tizen 2.3.1 release tizen_2.3.1 submit/tizen_2.3.1/20150915.081105 tizen_2.3.1_release
authorjk7744.park <jk7744.park@samsung.com>
Tue, 8 Sep 2015 13:25:59 +0000 (22:25 +0900)
committerjk7744.park <jk7744.park@samsung.com>
Tue, 8 Sep 2015 13:25:59 +0000 (22:25 +0900)
271 files changed:
AUTHORS
CMakeLists.txt
LICENSE [deleted file]
LICENSE.APLv2 [new file with mode: 0755]
NOTICE [new file with mode: 0755]
SLP_MessagingFW_PG.h [deleted file]
config/alert_on_call.mp3 [deleted file]
config/message_tone/Sherbet.wav [deleted file]
config/msg-service-db.CDMA.sql [new file with mode: 0755]
config/msg-service-db.sql [new file with mode: 0755]
config/plugin.cfg [deleted file]
config/sysinfo-message.xml [new file with mode: 0755]
doc/msg_service_doc.h [new file with mode: 0644]
externals/CMakeLists.txt [new file with mode: 0755]
externals/MsgAlarm.cpp [new file with mode: 0755]
externals/MsgDevicedWrapper.cpp [new file with mode: 0644]
externals/MsgLbs.cpp [new file with mode: 0755]
externals/MsgNotificationWrapper.cpp [new file with mode: 0755]
externals/MsgSensorWrapper.cpp [moved from msg_helper/MsgSensorWrapper.cpp with 66% similarity]
externals/MsgSoundPlayer.cpp [new file with mode: 0755]
externals/MsgSpamFilter.cpp [new file with mode: 0755]
framework/CMakeLists.txt
framework/deliver-handler/MsgDeliverHandler.cpp
framework/main.cpp
framework/plugin-manager/MsgPluginConfig.cpp [deleted file]
framework/plugin-manager/MsgPluginManager.cpp
framework/setting-handler/MsgSettingHandler.cpp
framework/storage-handler/MsgStorageFilter.cpp
framework/storage-handler/MsgStorageFolder.cpp
framework/storage-handler/MsgStorageManager.cpp
framework/storage-handler/MsgStorageMessage.cpp
framework/storage-handler/MsgStorageMms.cpp
framework/storage-handler/MsgStorageSim.cpp
framework/storage-handler/MsgStorageUtil.cpp
framework/submit-handler/MsgSubmitHandler.cpp
framework/transaction-manager/MsgCmdHandlerFilter.cpp
framework/transaction-manager/MsgCmdHandlerSetting.cpp
framework/transaction-manager/MsgCmdHandlerStorage.cpp
framework/transaction-manager/MsgCmdHandlerTransport.cpp
framework/transaction-manager/MsgTransManager.cpp
image/messaging_image001.png [deleted file]
include/common/MsgCmdTypes.h
include/common/MsgCppTypes.h
include/common/MsgFilterTypes.h
include/common/MsgInternalTypes.h
include/common/MsgMmsTypes.h
include/common/MsgPluginInterface.h
include/common/MsgQueue.h
include/common/MsgSettingTypes.h
include/common/MsgSmil.h [new file with mode: 0755]
include/common/MsgStorageTypes.h
include/common/MsgThread.h
include/common/MsgTransportTypes.h
include/common/MsgTypes.h
include/externals/MsgAlarm.h [new file with mode: 0755]
include/externals/MsgDevicedWrapper.h [new file with mode: 0644]
include/externals/MsgLbs.h [new file with mode: 0755]
include/externals/MsgNotificationWrapper.h [new file with mode: 0755]
include/externals/MsgSensorWrapper.h [new file with mode: 0755]
include/externals/MsgSoundPlayer.h [new file with mode: 0755]
include/externals/MsgSpamFilter.h [moved from include/utils/MsgSpamFilter.h with 56% similarity]
include/framework/MsgCmdHandler.h
include/framework/MsgDeliverHandler.h
include/framework/MsgPluginConfig.h [deleted file]
include/framework/MsgPluginManager.h
include/framework/MsgSettingHandler.h
include/framework/MsgStorageHandler.h
include/framework/MsgSubmitHandler.h
include/framework/MsgTransManager.h
include/mapi/msg.h
include/mapi/msg_private.h
include/mapi/msg_storage.h
include/mapi/msg_storage_types.h
include/mapi/msg_transport.h
include/mapi/msg_transport_types.h
include/mapi/msg_types.h
include/msg_helper/MsgHelper.h [deleted file]
include/proxy/MsgHandle.h
include/proxy/MsgProxyListener.h
include/utils/MsgContact.h
include/utils/MsgDebug.h
include/utils/MsgDrmWrapper.h
include/utils/MsgException.h
include/utils/MsgGconfWrapper.h
include/utils/MsgIpcSocket.h
include/utils/MsgJsonParser.h [new file with mode: 0755]
include/utils/MsgMemory.h
include/utils/MsgMmsMessage.h
include/utils/MsgMutex.h
include/utils/MsgNotificationWrapper.h [deleted file]
include/utils/MsgSerialize.h [new file with mode: 0755]
include/utils/MsgSoundPlayer.h [deleted file]
include/utils/MsgSqliteWrapper.h
include/utils/MsgTextConvert.h [moved from plugin/sms_plugin/include/SmsPluginTextConvert.h with 82% similarity]
include/utils/MsgUtilFile.h
include/utils/MsgUtilFunction.h
include/utils/MsgUtilStorage.h
include/utils/MsgVMessage.h [new file with mode: 0755]
mapi/CMakeLists.txt
mapi/msg_control.cpp
mapi/msg_filter.cpp
mapi/msg_message.cpp
mapi/msg_mms.cpp
mapi/msg_setting.cpp
mapi/msg_storage.cpp
mapi/msg_svc.cpp
mapi/msg_transport.cpp
mms-plugin.manifest [new file with mode: 0755]
msg-server
msg-service-tools.manifest [new file with mode: 0755]
msg-service.manifest [new file with mode: 0755]
msg-service.rule [new file with mode: 0755]
msg_helper/CMakeLists.txt [deleted file]
msg_helper/MsgSoundPlayer.cpp [deleted file]
msg_helper/main.cpp [deleted file]
packaging/msg-server.service [new file with mode: 0755]
packaging/msg-service.spec
plugin/mms_plugin/CMakeLists.txt
plugin/mms_plugin/LanguagePack/MmsPluginWmLngLatinUni.cpp [deleted file]
plugin/mms_plugin/LanguagePack/MmsPluginWmLngString.cpp [deleted file]
plugin/mms_plugin/LanguagePack/MmsPluginWmLngUTF8Uni.cpp [deleted file]
plugin/mms_plugin/LanguagePack/MmsPluginWmLngUniUTF8.cpp [deleted file]
plugin/mms_plugin/MmsPluginAppBase.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginAvCodec.cpp [deleted file]
plugin/mms_plugin/MmsPluginCodec.cpp [deleted file]
plugin/mms_plugin/MmsPluginCodecCommon.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginComposer.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginConnManWrapper.cpp
plugin/mms_plugin/MmsPluginContentCodec.cpp [deleted file]
plugin/mms_plugin/MmsPluginDebug.cpp [deleted file]
plugin/mms_plugin/MmsPluginDecode.cpp
plugin/mms_plugin/MmsPluginDrm.cpp
plugin/mms_plugin/MmsPluginEncode.cpp
plugin/mms_plugin/MmsPluginEventHandler.cpp
plugin/mms_plugin/MmsPluginHttp.cpp
plugin/mms_plugin/MmsPluginInternal.cpp
plugin/mms_plugin/MmsPluginMIME.cpp
plugin/mms_plugin/MmsPluginMain.cpp
plugin/mms_plugin/MmsPluginMessage.cpp
plugin/mms_plugin/MmsPluginSMILValidate.cpp
plugin/mms_plugin/MmsPluginSmil.cpp [deleted file]
plugin/mms_plugin/MmsPluginStorage.cpp
plugin/mms_plugin/MmsPluginTcs.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginTextConvert.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginTransport.cpp
plugin/mms_plugin/MmsPluginUserAgent.cpp
plugin/mms_plugin/MmsPluginUtil.cpp [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginAppBase.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginAvCodec.h [deleted file]
plugin/mms_plugin/include/MmsPluginCodec.h
plugin/mms_plugin/include/MmsPluginCodecCommon.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginCodecTypes.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginComposer.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginConnManWrapper.h
plugin/mms_plugin/include/MmsPluginData.h [deleted file]
plugin/mms_plugin/include/MmsPluginDebug.h
plugin/mms_plugin/include/MmsPluginDecode.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginDrm.h
plugin/mms_plugin/include/MmsPluginEncode.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginEventHandler.h
plugin/mms_plugin/include/MmsPluginHttp.h
plugin/mms_plugin/include/MmsPluginInternal.h
plugin/mms_plugin/include/MmsPluginMIME.h
plugin/mms_plugin/include/MmsPluginMain.h
plugin/mms_plugin/include/MmsPluginMessage.h
plugin/mms_plugin/include/MmsPluginSMILValidate.h [deleted file]
plugin/mms_plugin/include/MmsPluginSetup.h [deleted file]
plugin/mms_plugin/include/MmsPluginSmil.h [deleted file]
plugin/mms_plugin/include/MmsPluginStorage.h
plugin/mms_plugin/include/MmsPluginTcs.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginTextConvert.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginTransport.h
plugin/mms_plugin/include/MmsPluginTypes.h
plugin/mms_plugin/include/MmsPluginUserAgent.h
plugin/mms_plugin/include/MmsPluginUtil.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginWmLngPack.h [deleted file]
plugin/sms_cdma_plugin/CMakeLists.txt [new file with mode: 0755]
plugin/sms_cdma_plugin/SmsCdmaPluginCallback.cpp [new file with mode: 0755]
plugin/sms_cdma_plugin/SmsCdmaPluginCodec.cpp [new file with mode: 0755]
plugin/sms_cdma_plugin/SmsCdmaPluginEventHandler.cpp [new file with mode: 0755]
plugin/sms_cdma_plugin/SmsCdmaPluginMain.cpp [new file with mode: 0755]
plugin/sms_cdma_plugin/SmsCdmaPluginParamCodec.cpp [new file with mode: 0755]
plugin/sms_cdma_plugin/SmsCdmaPluginSetting.cpp [new file with mode: 0755]
plugin/sms_cdma_plugin/SmsCdmaPluginStorage.cpp [new file with mode: 0755]
plugin/sms_cdma_plugin/SmsCdmaPluginTransport.cpp [new file with mode: 0755]
plugin/sms_cdma_plugin/SmsCdmaPluginUAManager.cpp [new file with mode: 0755]
plugin/sms_cdma_plugin/SmsCdmaPluginWapPushHandler.cpp [new file with mode: 0755]
plugin/sms_cdma_plugin/include/SmsCdmaPluginCallback.h [new file with mode: 0755]
plugin/sms_cdma_plugin/include/SmsCdmaPluginCodec.h [new file with mode: 0755]
plugin/sms_cdma_plugin/include/SmsCdmaPluginEventHandler.h [new file with mode: 0755]
plugin/sms_cdma_plugin/include/SmsCdmaPluginMain.h [new file with mode: 0755]
plugin/sms_cdma_plugin/include/SmsCdmaPluginParamCodec.h [new file with mode: 0755]
plugin/sms_cdma_plugin/include/SmsCdmaPluginSetting.h [new file with mode: 0755]
plugin/sms_cdma_plugin/include/SmsCdmaPluginStorage.h [new file with mode: 0755]
plugin/sms_cdma_plugin/include/SmsCdmaPluginTransport.h [new file with mode: 0755]
plugin/sms_cdma_plugin/include/SmsCdmaPluginTypes.h [new file with mode: 0755]
plugin/sms_cdma_plugin/include/SmsCdmaPluginUAManager.h [new file with mode: 0755]
plugin/sms_cdma_plugin/include/SmsCdmaPluginWapPushHandler.h [new file with mode: 0755]
plugin/sms_plugin/CMakeLists.txt
plugin/sms_plugin/SmsPluginCallback.cpp
plugin/sms_plugin/SmsPluginCbMsgHandler.cpp
plugin/sms_plugin/SmsPluginConcatHandler.cpp
plugin/sms_plugin/SmsPluginDSHandler.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginEventHandler.cpp
plugin/sms_plugin/SmsPluginMain.cpp
plugin/sms_plugin/SmsPluginParamCodec.cpp
plugin/sms_plugin/SmsPluginSatHandler.cpp
plugin/sms_plugin/SmsPluginSetting.cpp
plugin/sms_plugin/SmsPluginSimMsg.cpp
plugin/sms_plugin/SmsPluginStorage.cpp
plugin/sms_plugin/SmsPluginTextConvert.cpp [deleted file]
plugin/sms_plugin/SmsPluginTpduCodec.cpp
plugin/sms_plugin/SmsPluginTransport.cpp
plugin/sms_plugin/SmsPluginUAManager.cpp
plugin/sms_plugin/SmsPluginUDCodec.cpp
plugin/sms_plugin/SmsPluginWapPushHandler.cpp
plugin/sms_plugin/include/SmsPluginCallback.h
plugin/sms_plugin/include/SmsPluginCbMsgHandler.h
plugin/sms_plugin/include/SmsPluginConcatHandler.h
plugin/sms_plugin/include/SmsPluginDSHandler.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginEventHandler.h
plugin/sms_plugin/include/SmsPluginMain.h
plugin/sms_plugin/include/SmsPluginParamCodec.h
plugin/sms_plugin/include/SmsPluginSatHandler.h
plugin/sms_plugin/include/SmsPluginSetting.h
plugin/sms_plugin/include/SmsPluginSimMsg.h
plugin/sms_plugin/include/SmsPluginStorage.h
plugin/sms_plugin/include/SmsPluginTpduCodec.h
plugin/sms_plugin/include/SmsPluginTransport.h
plugin/sms_plugin/include/SmsPluginTypes.h
plugin/sms_plugin/include/SmsPluginUAManager.h
plugin/sms_plugin/include/SmsPluginUDCodec.h
plugin/sms_plugin/include/SmsPluginWapPushHandler.h
proxy/CMakeLists.txt
proxy/MsgHandleControl.cpp
proxy/MsgHandleFilter.cpp
proxy/MsgHandleSetting.cpp
proxy/MsgHandleStorage.cpp
proxy/MsgHandleTransport.cpp
proxy/MsgProxyListener.cpp
sms-plugin.manifest [new file with mode: 0755]
utils/CMakeLists.txt
utils/MsgContact.cpp
utils/MsgDebug.cpp
utils/MsgDrmWrapper.cpp
utils/MsgException.cpp
utils/MsgGconfWrapper.cpp
utils/MsgIpcSocket.cpp
utils/MsgJsonParser.cpp [new file with mode: 0755]
utils/MsgMemory.cpp
utils/MsgMmsMessage.cpp
utils/MsgMutex.cpp
utils/MsgNotificationWrapper.cpp [deleted file]
utils/MsgSerialize.cpp [new file with mode: 0755]
utils/MsgSmil.cpp [new file with mode: 0755]
utils/MsgSoundPlayer.cpp [deleted file]
utils/MsgSpamFilter.cpp [deleted file]
utils/MsgSqliteWrapper.cpp
utils/MsgTextConvert.cpp [new file with mode: 0755]
utils/MsgUtilFile.cpp
utils/MsgUtilFunction.cpp
utils/MsgUtilStorage.cpp
utils/MsgVMessage.cpp [new file with mode: 0755]
vobject-engine/CMakeLists.txt [new file with mode: 0755]
vobject-engine/VCard.c [new file with mode: 0755]
vobject-engine/VCardCalUtil.c [new file with mode: 0755]
vobject-engine/VMessage.c [new file with mode: 0755]
vobject-engine/include/VCard.h [new file with mode: 0755]
vobject-engine/include/VMessage.h [new file with mode: 0755]
vobject-engine/include/VTypes.h [new file with mode: 0755]
vobject-engine/include/vobject.h [new file with mode: 0755]

diff --git a/AUTHORS b/AUTHORS
index fd16fcc..2ebd567 100755 (executable)
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,4 +1,4 @@
-Chang-Seok Oh <seok.oh@samsung.com>\r
-Sangkoo Kim <sangkoo.kim@samsung.com>\r
-Seunghwan Lee <sh.cat.lee@samsung.com>\r
-KeeBum Kim <keebum.kim@samsung.com>
\ No newline at end of file
+Sanghun Chung <sanghun.chung@samsung.com>
+Sangkoo Kim <sangkoo.kim@samsung.com>
+
+
index d6b9892..f4d7bdb 100755 (executable)
@@ -1,8 +1,12 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+include(CheckCXXCompilerFlag)
 
 ##########################################################
 # Set Variables
 ##########################################################
+SET(VOBJECT-LIB msg_vobject)
 SET(UTILS-LIB msg_utils)
+SET(EXTERNALS-LIB msg_externals)
 SET(PLUGIN-MANAGER-LIB msg_plugin_manager)
 SET(FW-HANDLER-LIB msg_framework_handler)
 SET(TRANS-MANAGER-LIB msg_transaction_manager)
@@ -10,19 +14,42 @@ SET(TRANS-PROXY-LIB msg_transaction_proxy)
 SET(MAPI-LIB msg_mapi)
 SET(SMS-PLUGIN-LIB msg_sms_plugin)
 SET(MMS-PLUGIN-LIB msg_mms_plugin)
-SET(MMS-LANGUAGE-PACK-LIB msg_mms_language_pack)
+
+IF(_FEATURE_SMS_CDMA)
+       ADD_DEFINITIONS("-DFEATURE_SMS_CDMA")
+ENDIF(_FEATURE_SMS_CDMA)
+
+IF(_MSG_WEARABLE_PROFILE)
+       ADD_DEFINITIONS("-DMSG_WEARABLE_PROFILE")
+ENDIF(_MSG_WEARABLE_PROFILE)
+
+ADD_DEFINITIONS("-D_FILE_OFFSET_BITS=64")
+
+CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
+CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
+IF(COMPILER_SUPPORTS_CXX11)
+    SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
+ELSEIF(COMPILER_SUPPORTS_CXX0X)
+    SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
+ELSE()
+    MESSAGE(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
+ENDIF()
 
 ##########################################################
 # Add Subdirectories
 ##########################################################
+ADD_SUBDIRECTORY(vobject-engine)
 ADD_SUBDIRECTORY(utils)
+ADD_SUBDIRECTORY(externals)
 ADD_SUBDIRECTORY(framework)
 ADD_SUBDIRECTORY(proxy)
 ADD_SUBDIRECTORY(mapi)
+IF(_FEATURE_SMS_CDMA)
+ADD_SUBDIRECTORY(plugin/sms_cdma_plugin)
+ELSE(_FEATURE_SMS_CDMA)
 ADD_SUBDIRECTORY(plugin/sms_plugin)
+ENDIF(_FEATURE_SMS_CDMA)
 ADD_SUBDIRECTORY(plugin/mms_plugin)
-ADD_SUBDIRECTORY(msg_helper)
-
 
 ##########################################################
 # Install Header Files
@@ -34,7 +61,7 @@ SET(MAPI-HEADERS
        ${CMAKE_CURRENT_SOURCE_DIR}/include/mapi/msg_storage_types.h
        ${CMAKE_CURRENT_SOURCE_DIR}/include/mapi/msg_transport.h
        ${CMAKE_CURRENT_SOURCE_DIR}/include/mapi/msg_transport_types.h
-       ${CMAKE_CURRENT_SOURCE_DIR}/SLP_MessagingFW_PG.h )
+       )
 INSTALL(FILES ${MAPI-HEADERS} DESTINATION include/msg-service)
 
 
@@ -42,13 +69,7 @@ INSTALL(FILES ${MAPI-HEADERS} DESTINATION include/msg-service)
 # Install etc Files
 ##########################################################
 
-INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config/plugin.cfg DESTINATION /usr/share/msg-service)
-
-SET(RINGTONE-FILES
-       ${CMAKE_CURRENT_SOURCE_DIR}/config/message_tone/Sherbet.wav
-)
-
-INSTALL(FILES ${RINGTONE-FILES} DESTINATION /usr/share/media/)
+#INSTALL(FILES ${MMS-FILES} DESTINATION /opt/etc/msg-service)
 
 CONFIGURE_FILE(msg-service.pc.in msg-service.pc @ONLY)
 INSTALL(FILES ${CMAKE_BINARY_DIR}/msg-service.pc DESTINATION lib/pkgconfig)
@@ -56,3 +77,18 @@ INSTALL(FILES ${CMAKE_BINARY_DIR}/msg-service.pc DESTINATION lib/pkgconfig)
 SET(RC_LOCAL_SCRIPT msg-server)
 INSTALL(PROGRAMS ${RC_LOCAL_SCRIPT} DESTINATION /etc/rc.d/init.d)
 
+# systemd
+INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/packaging/msg-server.service DESTINATION /usr/lib/systemd/system)
+
+# LICENSE file
+INSTALL(FILES ${CMAKE_SOURCE_DIR}/LICENSE.APLv2 DESTINATION /usr/share/license/msg-service)
+INSTALL(FILES ${CMAKE_SOURCE_DIR}/msg-service.rule DESTINATION /etc/smack/accesses.d/)
+
+#Install sysinfo file to provide which features are supported.
+IF(_FEATURE_SMS_CDMA)
+       INSTALL(FILES ${CMAKE_SOURCE_DIR}/config/msg-service-db.CDMA.sql DESTINATION /usr/share/msg-service RENAME msg-service-db.sql)
+       INSTALL(FILES ${CMAKE_SOURCE_DIR}/config/sysinfo-message.xml DESTINATION /etc/config)
+ELSE(_FEATURE_SMS_CDMA)
+       INSTALL(FILES ${CMAKE_SOURCE_DIR}/config/msg-service-db.sql DESTINATION /usr/share/msg-service RENAME msg-service-db.sql)
+       INSTALL(FILES ${CMAKE_SOURCE_DIR}/config/sysinfo-message.xml DESTINATION /etc/config)
+ENDIF(_FEATURE_SMS_CDMA)
diff --git a/LICENSE b/LICENSE
deleted file mode 100755 (executable)
index 7ccb5b5..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,75 +0,0 @@
-Flora License
-
-Version 1.0, May, 2012
-
-http://www.tizenopensource.org/license
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
-
-"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
-
-"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
-
-"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
-
-"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
-
-"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
-
-"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
-
-"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
-
-"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
-
-"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
-
-"Tizen Certified Platform" shall mean a software platform that complies with the standards set forth in the Compatibility Definition Document and passes the Compatibility Test Suite as defined from time to time by the Tizen Technical Steering Group and certified by the Tizen Association or its designated agent.
-
-2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
-
-3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work solely as incorporated into a Tizen Certified Platform, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work solely as incorporated into a Tizen Certified Platform to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
-
-4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof pursuant to the copyright license above, in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
-
-  1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
-
-  2. You must cause any modified files to carry prominent notices stating that You changed the files; and
-
-  3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
-
-  4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
-
-5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
-
-6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
-
-APPENDIX: How to apply the Flora License to your work
-
-To apply the Flora License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
-
-   Copyright [yyyy] [name of copyright owner]
-
-   Licensed under the Flora License, Version 1.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.tizenopensource.org/license
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
diff --git a/LICENSE.APLv2 b/LICENSE.APLv2
new file mode 100755 (executable)
index 0000000..74f474e
--- /dev/null
@@ -0,0 +1,203 @@
+Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/NOTICE b/NOTICE
new file mode 100755 (executable)
index 0000000..a718085
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,3 @@
+Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+Except as noted, this software is licensed under Apache License, Version 2.
+Please, see the LICENSE.APLv2 file for Apache License, Version 2 terms and conditions.
diff --git a/SLP_MessagingFW_PG.h b/SLP_MessagingFW_PG.h
deleted file mode 100755 (executable)
index ecff3d7..0000000
+++ /dev/null
@@ -1,869 +0,0 @@
-/**
- *
- * @ingroup   SLP_PG
- * @defgroup   MESSAGE MessagingFW
-@{
-<h1 class="pg">Introduction</h1>
-       <h2 class="pg">Purpose</h2>
-The purpose of this document is to describe how applications can use the Messaging Framework APIs to send and receive SMS and MMS messages. This document gives programming guidelines to application engineers.
-
-       <h2 class="pg">Scope</h2>
-The scope of this document is limited to Messaging Framework APIs usage.
-
-       <h2 class="pg">Abbreviations</h2>
-<table>
-<tr><td>API</td><td>Application Programming Interface</td></tr>
-</table>
-@}
-
-@defgroup Message_Architecture 1.Archtecture
-@ingroup MESSAGE
-@{
-<h1>Messaging Framework Architecture</h1>
-The Messaging framework supports various messaging services such as SMS, MMS, Cell Broadcast, WAP Push, and Provisioning message. The Messaging framework architecture consists of a Messaging daemon and a library. The messaging library works on application process and provides various APIs to support transport, control, storage, filter and setting services for application. The messaging daemon has three components (transaction manager, transaction handler, and plug-in manager) to provide message services. The socket IPC is used to communicate (request & event) between Messaging daemon and library.
-@image html messaging_image001.png
-
-- Transaction Manager
-       - Receive the IPC message (request) on socket.
-       - Manage list of pairs (request ID, transaction proxy) for synchronous return.
-       - Determine the transaction flow based on request/event information. (Mapping the request to one of the handlers)
-       - Store the transaction information for asynchronous events (Find which transaction proxy want to receive SMS)
-- Transaction Handler
-       - Submit handler deals with submit requests.
-       - Deliver handler deals with the incoming message from plug-ins.
-       - Storage handler deals with the messages, accounts and folder requests
-       - Filter handler deals with the filter requests
-       - Setting handler deals with the service-specific attributes
-- Plug-in Manager
-       - Initialize all plug-ins after loading plug-in configuration files
-       - Holding the list of plug-ins and the state of plug-ins
-       - Providing the interface between handlers and plug-ins
-- Transaction Handlers
-       - Initialize all plug-ins after loading plug-in configuration files
-       - Receiving IPC messages from messaging daemon.
-       - Handling synchronous calls
-               - Condition variable is used for waiting the return from msg. server)
-       - Handling asynchronous calls or events
-               - Proxy listener is a component of transaction proxy
-               - Proxy listener is waiting for the event
-               - Invoking callback function in the msg. handle list
-               - i.e. calling incoming callback function of MSG APP handle, when incoming msg
-       - Holding list of message handles
-               - Message handle is created by MsgOpenMsgHandle(msgHandle)
-               - Message handle holds some info such as callback func
-- Message API
-       - Transport & control API
-       - Storage API
-       - Filter API
-       - Setting API
-@}
-
-@defgroup Message_Feature 2.Feature
-@ingroup MESSAGE
-@{
-       <h2 class="pg">Messaging Framework Features</h2>
--# Message Control Features:
-       -# Open/Close message handle
--# Message Transport Features:
-       -# Submit request to send, forward, reply, retrieve message.
-       -# Register callback functions to listen to invoked events from messaging daemon. (message status callback, incoming message callback)
--# Message Storage Features:
-       -# Add / Update / Move / Delete / Count / Get message or message list.
-       -# Add / Update / Delete / Get folder or folder list.
--# Message Filter Features:
-       -# Add / Update / Delete filter or filter list.
--# Message Setting Features:
-       -# Set / Get various message setting (i.e. whether to send read/delivery report or not)
-@}
-
-@defgroup MESSAGE_USECASES_1 Initialize/Finalization
-@ingroup MESSAGE_USECASES
-@{
-       <h2 class="pg">Messaging Framework Functions</h2>
-
-               <h3 class="pg">Initialization / Finalization to use Messaging Service </h3>
-- int msg_open_msg_handle(MSG_HANDLE_T *handle);
-@n msg_open_msg_handle() should be called before using the messaging service. This function opens a channel between the application and the messaging framework.
-- int msg_close_msg_handle(MSG_HANDLE_T *handle);
-@n msg_close_msg_handle() should be called after using the messaging service. This function closes a channel between the application and the messaging framework.
-- int msg_reg_sent_status_callback(MSG_HANDLE_T handle, msg_sent_status_cb cb);
-@n Application should implement a msg_sent_status_cb function and register it into message handle. If the application sends a message, this callback function will be called to report its sending status. msg_reg_set_status_callback function should be called after creation of message handle.
-- int msg_reg_sms_message_callback(MSG_HANDLE_T handle, msg_sms_incoming_cb cb, unsigned short port);
-@n Application should implement a msg_sms_incoming_cb function and register it into message handle. It’s used to listen to the SMS incoming event invoked by messaging daemon. The incoming message information structure (MSG_MESSAGE_S) can be delivered as a parameter of the callback function.
-- int msg_reg_mms_conf_message_callback(MSG_HANDLE_T handle, msg_mms_conf_msg_incoming_cb cb, char *app_id);
-@n Application should implement a msg_mms_conf_msg_incoming_cb function and register it into message handle. It’s used to listen to the MMS incoming event invoked by messaging daemon. The incoming message information structure (MSG_MESSAGE_S) can be delivered as a parameter of the callback function.
-@code
-#include <stdio.h>
-#include <glib.h>
-#include <MapiControl.h>
-#include <MapiTransport.h>
-
-void sentStatusCB(MSG_HANDLE_T hMsgHandle, MSG_SENT_STATUS_S *pMsgStatus, void *user_param)
-{
-       // Application can handle message sent status event
-}
-
-void incomingSmsMessageCB (MSG_HANDLE_T hMsgHandle, msg_message_t msg, void *user_param)
-{
-       // Application can handle SMS incoming message.
-}
-
-void incomingMmsConfMessageCB(MSG_HANDLE_T hMsgHandle, msg_message_t msg, void *user_param)
-{
-       // Application can handle MMS incoming message.
-}
-
-int main(void)
-{
-       MSG_HANDLE_T msgHandle = NULL;
-
-       err = msg_open_msg_handle(&msgHandle);
-
-       if (err != MSG_SUCCESS)
-       {
-               printf("msg_open_msg_handle() Fail [%d]", err);
-               return err;
-       }
-
-       // Register sent status handler
-       err = msg_reg_sent_status_callback(msgHandle, &sentStatusCB, NULL);
-
-       if (err != MSG_SUCCESS)
-       {
-               printf("msg_reg_sent_status_callback() Fail [%d]", err);
-               return err;
-       }
-
-       // Register SMS incoming message handler
-       err = msg_reg_sms_message_callback(msgHandle, &incomingSmsMessageCB, 0, NULL);
-
-       if (err != MSG_SUCCESS)
-       {
-               printf("msg_reg_sms_message_callback() Fail [%d]", err);
-               return err;
-       }
-
-       // Register MMS incoming message handler
-       err = msg_reg_mms_conf_message_callback(msgHandle, &incomingMmsConfMessageCB, NULL, NULL);
-
-       if (err != MSG_SUCCESS)
-       {
-               printf("msg_reg_mms_conf_message_callback() Fail [%d]", err);
-               return err;
-       }
-
-       // g_main_loop should be used to listen CB event from messaging daemon
-       mainloop = g_main_loop_new(NULL, FALSE);
-       g_main_loop_run(mainloop);
-
-       msg_close_msg_handle(&msgHandle);
-
-       return err;
-}
-@endcode
-@}
-
-@defgroup MESSAGE_USECASES_2 Adding a SMS Message
-@ingroup MESSAGE_USECASES
-@{
-               <h3 class="pg">Adding a SMS Message</h3>
-- msg_message_t msg_new_message();
-@n msg_new_message() is a function to create a message object which can store the message information. You should call this function to set the message that you want to add or send.
-- int msg_set_message_type(msg_message_t msg, MSG_MESSAGE_TYPE_T msg_type);
-@n msg_set_message_type() is a function to set the message type such as SMS or MMS. The first parameter is the message object which is created by msg_new_message(). The second parameter is the message type you want to set. It should be one of enum type ( _MSG_MESSAGE_TYPE_E). If setting is successful, the function returns MSG_SUCCESS. Otherwise it returns an error in enum type (_MSG_ERROR_E).
-- int msg_sms_set_message_body(msg_message_t msg, const char* mdata, int size);
-@n msg_sms_set_message_body() is a function to set the SMS body data. The first parameter is the message object which is created by msg_new_message(). The second parameter is the SMS body data you want to set. The third parameter is the length of SMS body data. If setting is successful, the function returns MSG_SUCCESS. Otherwise it returns an error in enum type (_MSG_ERROR_E).
-- int msg_add_address(msg_message_t msg, const char* phone_num_list, MSG_RECIPIENT_TYPE_T to_type);
-@n msg_add_address() is a function to add the phone numbers for the message. The first parameter is the message object which is created by msg_new_message(). The second parameter is the list of phone number you want to set. You can add several phone numbers at once. The phone numbers should be separated by ','. The third parameter is the recipient type of phone number. It should be one of enum type (_MSG_RECIPIENT_TYPE_E). If setting is successful, the function returns MSG_SUCCESS. Otherwise it returns an error in enum type (_MSG_ERROR_E).
-- int msg_add_message(MSG_HANDLE_T handle, const msg_message_t msg, const MSG_SENDINGOPT_S *send_opt);
-@n msg_add_message() is a function to add a composed message into the database of messaging framework. Before calling this function, the application should set the message object and the sending option structure and then pass them as parameters. If you don't want to change the current sending option, set the variable 'bSetting' to false. If saving a message is successful, the function returns MSG_SUCCESS. Otherwise it returns an error in enum type (_MSG_ERROR_E).
-- int msg_release_message(msg_message_t *msg);
-@n msg_release_message() is a function to free the memory of a message object which is create by msg_new_message(). If freeing the memory is successful, the function returns MSG_SUCCESS. Otherwise it returns an error in enum type (_MSG_ERROR_E).
-@code
-#include <string.h>
-#include <MapiStorage.h>
-#include <MapiMessage.h>
-
-void test_add_sms_message(MSG_HANDLE_T hMsgHandle)
-{
-       MSG_ERROR_T err = MSG_SUCCESS;
-
-       MSG_SENDINGOPT_S sendOpt = {0, };
-       sendOpt.bSetting = false;
-
-       msg_message_t msgInfo = msg_new_message();
-
-       // Set Message Type
-       err = msg_set_message_type(msgInfo, MSG_TYPE_SMS);
-
-       if (err != MSG_SUCCESS) goto free_memory;
-
-       char msgText[1024];
-
-       memset(msgText, 0x00, 1024);
-       strncpy(msgText, "Test SMS Message", sizeof(msgText)-1);
-       int dataSize = strlen(msgText);
-
-       // Set SMS text
-       err = msg_sms_set_message_body(msgInfo, msgText, dataSize);
-
-       if (err != MSG_SUCCESS) goto free_memory;
-
-       char number[MAX_ADDRESS_VAL_LEN];
-
-       memset(number, 0x00, MAX_ADDRESS_VAL_LEN);
-       strncpy(number, "+821030011234", sizeof(number)-1);
-
-       // Set Recipient Address
-       err = msg_add_address(msgInfo, number, MSG_RECIPIENTS_TYPE_TO);
-
-       if (err != MSG_SUCCESS) goto free_memory;
-
-       err = msg_add_message(hMsgHandle, msgInfo, &sendOpt);
-
-       if (err == MSG_SUCCESS)
-               printf("Saving Message is OK!");
-       else
-               printf("Saving Message is failed!");
-
-free_memory:
-       msg_release_message(&msgInfo);
-}
-@endcode
-@}
-
-@defgroup MESSAGE_USECASES_3 Adding a MMS Message
-@ingroup MESSAGE_USECASES
-@{
-               <h3 class="pg">Adding a MMS Message</h3>
-- int msg_set_subject(msg_message_t msg, const char* subject);
-@n msg_set_subject() is a function to set the subject of MMS. The first parameter is the message object which is created by msg_new_message(). The second parameter is the subject you want to set. If setting is successful, the function returns MSG_SUCCESS. Otherwise it returns an error in enum type (_MSG_ERROR_E).
-
-- MMS_MESSAGE_DATA_S* msg_mms_create_message(void);
-@n msg_mms_create_message() allocates a MMS_MESSAGE_DATA_S structure and returns it’s address. MMS_MESSAGE_DATA_S is needed to represent mms specific data and transfer it to the messaging daemon in the pData parameter of the MSG_MESSAGE_S structure.
-
-- MMS_SMIL_ROOTLAYOUT* msg_mms_set_rootlayout(MMS_MESSAGE_DATA_S* msg, const int width, const int height, const int bgcolor);
-@n msg_mms_set_rootlayout() is a function to set smil root layout. The parameters representing the size and background color of smil root layout should be set.
-
-- MMS_SMIL_REGION* msg_mms_add_region(MMS_MESSAGE_DATA_S *msg_data, const char* szID, const int x, const int y, const int width, const int height, const int bgcolor);
-@n msg_mms_add_region() is a function to add a smil region. Smil region is needed to display text message, image, and video data (Each content has its own region). This function is called to allocate a region for each contents.
-
-- MMS_PAGE_S* msg_mms_add_page(MMS_MESSAGE_DATA_S *msg_data, const int duration);
-@n msg_mms_add_page() is a function to add a smil page.
-
-- MMS_MEDIA_S* msg_mms_add_media(MMS_PAGE_S *page, const MmsSmilMediaType mediatype, const char* regionid, char* filepath);
-@n msg_mms_add_media() is a function to add multimedia content to a mms message. If some content should be played with smil player, this function can be used.
-
-- MMS_ATTACH_S* msg_mms_add_attachment(MMS_MESSAGE_DATA_S *msg_data, char *filepath);
-@n msg_mms_add_attachment() is a function to add a content as an attached file. With this function a content might be attached as a multipart mixed type.
-
-- int msg_mms_set_message_body(msg_message_t msg, const MMS_MESSAGE_DATA_S *msg_data);
-@n msg_mms_set_message_body() is a function to set the MMS body data. The first parameter is the message object which is created by msg_new_message(). The second parameter is the structure which is allocated by msg_mms_create_message() and is set by the APIs for MMS.
-
-- int msg_mms_destroy_message(MMS_MESSAGE_DATA_S* msg);
-@n msg_mms_destroy_message() should be called to deallocate the MMS_MESSAGE_DATA_S structure and internal region, page, media, and attach list.
-@code
-#include <string.h>
-#include <MapiStorage.h>
-#include <MapiMessage.h>
-
-void test_add_mms_message(MSG_HANDLE_T hMsgHandle)
-{
-       MSG_ERROR_T err = MSG_SUCCESS;
-
-       MSG_SENDINGOPT_S sendOpt = {0, };
-       sendOpt.bSetting = false;
-
-       msg_message_t msgInfo = msg_new_message();
-
-       // Set Message Type
-       err = msg_set_message_type(msgInfo, MSG_TYPE_MMS);
-
-       if (err != MSG_SUCCESS) goto free_memory;
-
-       MMS_MESSAGE_DATA_S* data;
-       MMS_PAGE_S* page;
-       MMS_MEDIA_S* media[3];
-       MMS_ATTACH_S* attach;
-       int nSize = 0;
-
-       // Set MMS subject
-       char subject[MAX_SUBJECT_LEN];
-
-       memset(subject, 0x00, MAX_SUBJECT_LEN);
-       strncpy(subject, "hello mms", sizeof(subject)-1);
-
-       err = msg_set_subject(msgInfo, subject);
-
-       if (err != MSG_SUCCESS) goto free_memory;
-
-       // Set MMS Body data
-       data = msg_mms_create_message();
-       msg_mms_set_rootlayout(data, 100, 100, 0xffffff);
-       msg_mms_add_region(data, "Image", 0, 50, 100, 50, 0xffffff);
-       msg_mms_add_region(data, "Text", 0, 0, 100, 50, 0xffffff);
-       page = msg_mms_add_page(data, 5000);
-       media[0] = msg_mms_add_media(page, MMS_SMIL_MEDIA_IMG, "Image", "/tmp/image.jpg");
-       media[1] = msg_mms_add_media(page, MMS_SMIL_MEDIA_AUDIO, NULL, "/tmp/audio.amr");
-       media[2] = msg_mms_add_media(page, MMS_SMIL_MEDIA_TEXT, "Text", "/tmp/message.txt");
-       attach = msg_mms_add_attachment(data, "attachment.3gp");
-
-       err = msg_mms_set_message_body(msgInfo, data);
-
-       if (err != MSG_SUCCESS)
-       {
-               msg_mms_destroy_message(data);
-               goto free_memory;
-       }
-
-       msg_mms_destroy_message(data);
-
-       // Set Recipient Address
-       char number[MAX_ADDRESS_VAL_LEN];
-
-       memset(number, 0x00, MAX_ADDRESS_VAL_LEN);
-       strncpy(number, "+821030011234", sizeof(number)-1);
-
-       err = msg_add_address(msgInfo, number, MSG_RECIPIENTS_TYPE_TO);
-
-       if (err != MSG_SUCCESS) goto free_memory;
-
-       err = msg_add_message(hMsgHandle, msgInfo, &sendOpt);
-
-       if (err == MSG_SUCCESS)
-               printf("Saving Message is OK!");
-       else
-               printf("Saving Message is failed!");
-
-free_memory:
-       msg_release_message(&msgInfo);
-}
-@endcode
-@}
-
-@defgroup MESSAGE_USECASES_4 Sending a SMS/MMS Message
-@ingroup MESSAGE_USECASES
-@{
-               <h3 class="pg">Sending a SMS/MMS Message</h3>
-
-- bool msg_is_sms(msg_message_t msg);
-@n msg_is_sms() is a function to check whether the message type of message object is SMS or not. The first parameter is the message object which is created by msg_new_message(). The function returns true if the message object is a SMS message. Otherwise, it returns false.
-
-- bool msg_is_mms(msg_message_t msg);
-@n msg_is_mms() is a function to check whether the message type of message object is MMS or not. The first parameter is the message object which is created by msg_new_message(). The function returns true if the message object is a MMS message. Otherwise, it returns false.
-
-- int msg_sms_send_message(MSG_HANDLE_T handle, MSG_REQUEST_S* req);
-@n msg_sms_send_message() is a function to send SMS through messaging framework. The first parameter is the handle which is created by msg_open_msg_handle (). The second parameter is the structure that includes the message information to send. You can get the result of sending on sent status callback.
-
-- int msg_mms_send_message(MSG_HANDLE_T handle, MSG_REQUEST_S* req);
-@n msg_sms_send_message() is a function to send SMS through messaging framework. The first parameter is the handle which is created by msg_open_msg_handle (). The second parameter is the structure that includes the message information to send. You can get the result of sending on sent status callback.
-@code
-#include <MapiTransport.h>
-#include <MapiMessage.h>
-
-int MsgTestSendMsg(MSG_HANDLE_T hMsgHandle, msg_message_t pMsg)
-{
-       if (hMsgHandle == NULL)
-       {
-               printf("Handle is NULL\n");
-               return MSG_ERR_NULL_MSGHANDLE;
-       }
-
-       MSG_ERROR_T err = MSG_SUCCESS;
-
-       MSG_REQUEST_S req = {0};
-
-       if (pMsg == NULL)
-       {
-               printf("Message is NULL\n");
-               return MSG_ERR_NULL_MESSAGE;
-       }
-
-       req.msg = pMsg;
-
-       if (msg_is_sms(req.msg))
-               err = msg_sms_send_message(hMsgHandle, &req);
-       else if (msg_is_mms(req.msg))
-               err = msg_mms_send_message(hMsgHandle, &req);
-
-       if (err == MSG_SUCCESS)
-               printf("Request to Send Message is successful!!!");
-       else
-               printf("Request to Send Message is failed!!!");
-
-       return err;
-}
-@endcode
-@}
-
-@defgroup MESSAGE_USECASES_5 Sending Simple SMS Message
-@ingroup MESSAGE_USECASES
-@{
-               <h3 class="pg">Simple SMS Sending</h3>
-- int msg_sms_send(const char *phone_num_list, const char *sms_text, msg_simple_sent_status_cb cb, void *user_param);
-@n msg_sms_send() is a simple function to send an SMS message. Without this API, in order to send a message the application should allocate a channel with messaging daemon for IPC, register sent-status callback function to monitor the sending result, and fulfill many member variables of MSG_MESSAGE_S. This function implicitly makes a connection with messaging daemon and registers the callback function. In addition, member variables of the MSG_MESSAGE_S structure are filled with default values except for the recipient phone_number and sms_text.
-@code
-#include <stdio.h>
-#include <string.h>
-#include <glib.h>
-#include <MapiTransport.h>
-
-GMainLoop *mainloop;
-
-typedef struct {
-       char number[256];
-       char text[256];
-       char userdata[256];
-} send_data;
-
-void sent_status_cb(MSG_SENT_STATUS_S *pMsgStatus, void *userData)
-{
-       if (pMsgStatus->status == MSG_NETWORK_SEND_SUCCESS)
-               printf("reqId : %d  MSG SENT SUCCESS !!!\n", pMsgStatus->reqId);
-       else
-               printf("reqId : %d  MSG SENT FAIL !!! [%d]\n", pMsgStatus->reqId, pMsgStatus->status);
-}
-
-// count from here
-gboolean send_func(gpointer data)
-{
-       send_data* sms_input = (send_data*)data;
-
-       printf("Begin to send [%s] to [%s]\n", sms_input->number, sms_input->text);
-       MSG_ERROR_T err = msg_sms_send(sms_input->number, sms_input->text, &sent_status_cb, (void*)sms_input->userdata);
-
-       if (err != MSG_SUCCESS)
-               printf("Send failed [%d]\n", err);
-
-       return FALSE;
-}
-// end
-
-int main(int argc, char* argv[])
-{
-       if (argc != 3 && argc != 4)
-       {
-               printf("Usage: %s  {phone_num_list} {sms_text} [user_data]\n", argv[0]);
-               printf("phone_num_list: phone_num1, phone_num2, ..., phone_numN\n");
-               return 0;
-       }
-
-       // Set sms input parameters : phone numbers and text
-       send_data sms_input = {};
-       strncpy(sms_input.number, argv[1], sizeof(sms_input.number)-1);
-       strncpy(sms_input.text, argv[2], sizeof(sms_input.text)-1);
-       if (argc == 4)
-               strncpy(sms_input.userdata, argv[3], sizeof(sms_input.userdata)-1);
-
-       // Add Sending Function to GMainLoop
-       g_idle_add(&send_func, (gpointer) &sms_input);
-
-       // start GMainLoop
-       mainloop = g_main_loop_new(NULL, FALSE);
-
-       printf("Entering GMain Loop to Receive Notifications in Thread...\n");
-
-       g_main_loop_run(mainloop);
-
-       printf("==== End Test App. Bye...===\n");
-
-       return 0;
-}
-@endcode
-@}
-
-@defgroup MESSAGE_USECASES_6 Retrieving a MMS Message
-@ingroup MESSAGE_USECASES
-@{
-               <h3 class="pg">Retrieving a MMS Message</h3>
-- int msg_mms_retrieve_message(MSG_HANDLE_T handle, MSG_REQUEST_S* req);
-@n msg_mms_retrieve_message() is a function to submit a retrieve MMS request.
-@code
-void MsgTestRetrieveMessage(MSG_HANDLE_T hMsgHandle, MSG_MESSAGE_ID_T nMsgId)
-{
-       if (hMsgHandle == NULL)
-       {
-               printf("Handle is NULL");
-               return;
-       }
-
-       MSG_ERROR_T err = MSG_SUCCESS;
-
-       msg_message_t msg = msg_new_message();
-       MSG_SENDINGOPT_S sendOpt = {0, };
-
-       err = msg_get_message(hMsgHandle, (MSG_MESSAGE_ID_T)nMsgId, msg, &sendOpt);
-
-       if (err != MSG_SUCCESS)
-               printf("Get Message Failed!");
-
-       MSG_REQUEST_S req = {0, msg, sendOpt};
-
-       err = msg_mms_retrieve_message(hMsgHandle, &req);
-
-       if (err != MSG_SUCCESS)
-               printf("Retrieve MMS Message Failed!");
-
-       msg_release_message(&msg);
-}
-@endcode
-@}
-
-@defgroup MESSAGE_USECASES_7 Getting a SMS Message
-@ingroup MESSAGE_USECASES
-@{
-               <h3 class="pg">Getting a SMS Message</h3>
-- int msg_get_message(MSG_HANDLE_T handle, MSG_MESSAGE_ID_T msg_id, msg_message_t msg, MSG_SENDINGOPT_S *send_opt);
-@n msg_get_message() is a function to get a message. The first parameter is the handle which is created by msg_open_msg_handle (). The second parameter is the message ID you want to get. The third parameter is the message object to receive the message information. The last parameter is the structure to receive the message sending options.
-
-- int msg_get_message_id(msg_message_t msg);
-@n msg_get_message_id() is a function to get the message ID. The parameter is the message object. If the function is successful, it returns the message ID. Otherwise it returns an error in enum type (_MSG_ERROR_E).
-
-- int msg_get_folder_id(msg_message_t msg);
-@n msg_get_folder_id() is a function to get the ID of the folder  that the message is saved within. The parameter is the message object. If the function is successful, it returns one of the enum type in (_MSG_FOLDER_ID_E) . Otherwise it returns an error in enum type (_MSG_ERROR_E).
-
-- int msg_get_message_type(msg_message_t msg);
-@n msg_get_message_type() is a function to get the message type. The parameter is the message object. If the function is successful, it returns one of the enum type in (_MSG_MESSAGE_TYPE_E). Otherwise it returns an error in enum type (_MSG_ERROR_E).
-
-- int msg_get_address_count(msg_message_t msg);
-@n msg_get_address_count() is a function to get the number of addresses. The parameter is the message object. If the function is successful, it returns the number of addresses. Otherwise it returns an error in enum type (_MSG_ERROR_E).
-
-- const char* msg_get_ith_address(msg_message_t msg, int ith);
-@n msg_get_ith_address() is a function to get the ith address of message. The first parameter is the message object. The second parameter is the index of address you want to get. If the function is successful, it returns the address string. Otherwise it returns NULL.
-
-- time_t* msg_get_time(msg_message_t msg);
-@n msg_get_time() is a function to get the time value of message. The parameter is the message object. If the function is successful, it returns the time value. Otherwise it returns NULL.
-
-- int msg_get_network_status(msg_message_t msg);
-@n msg_get_network_status() is a function to get the network status of message. The parameter is the message object. If the function is successful, it returns one of the enum type in (_MSG_NETWORK_STATUS_E). Otherwise it returns an error in enum type (_MSG_ERROR_E).
-
-- bool msg_is_read(msg_message_t msg);
-@n msg_is_read() is a function to check whether the message was read or not. The parameter is the message object. If the message was read, it returns true. Otherwise it returns false.
-
-- bool msg_is_protected(msg_message_t msg);
-@n msg_is_protected() is a function to check whether the message is protected or not. The parameter is the message object. If the the message was protected, it returns true. Otherwise it returns false.
-
-- int msg_get_message_body_size(msg_message_t msg);
-@n msg_get_message_body_size() is a function to get the byte size of message. The parameter is the message object. If the function is successful, it returns the byte size of message. Otherwise it returns an error in enum type (_MSG_ERROR_E).
-
-- const char* msg_sms_get_message_body(msg_message_t msg);
-@n msg_sms_get_message_body() is a function to get the body data of message. The first parameter is the message object. If the function is successful, it returns the body data. Otherwise it returns NULL.
-@code
-void MsgTestGetSmsMessage(MSG_HANDLE_T hMsgHandle, int MsgId)
-{
-       if (hMsgHandle == NULL)
-       {
-               printf("Handle is NULL\n");
-               return;
-       }
-
-       MSG_ERROR_T err = MSG_SUCCESS;
-
-       msg_message_t msg = msg_new_message();
-       MSG_SENDINGOPT_S sendOpt = {0, };
-
-       // Get Message
-       err = msg_get_message(hMsgHandle, (MSG_MESSAGE_ID_T)MsgId, msg, &sendOpt);
-
-       if (err != MSG_SUCCESS) goto free_memory;
-
-       printf("msgId = %d\n", msg_get_message_id(msg));
-       printf("folderId = %d\n", msg_get_folder_id(msg));
-       printf("msgType = %d\n", msg_get_message_type(msg));
-       printf("phone number = %s\n", msg_get_ith_address(msg, 0));
-       printf("displayTime = %s\n", ctime(msg_get_time(msg)));
-       printf("networkStatus = %d\n", msg_get_network_status(msg));
-       printf("bRead = %d\n", msg_is_read(msg));
-       printf("bProtected = %d\n", msg_is_protected(msg));
-       printf("dataSize = %d\n", msg_get_message_body_size(msg));
-       printf("msgData = %s\n", msg_sms_get_message_body(msg));
-
-free_memory:
-       msg_release_message(&msg);
-}
-@endcode
-@}
-
-@defgroup MESSAGE_USECASES_8 Getting a MMS Message
-@ingroup MESSAGE_USECASES
-@{
-               <h3 class="pg">Getting a MMS Message</h3>
-- int msg_mms_get_message_body(msg_message_t msg, MMS_MESSAGE_DATA_S *body);
-@n msg_get_address_count. The parameter is the message object. The second parameter is the structure to receive MMS data as output. If the function is successful, it returns MSG_SUCCESS. Otherwise it returns an error in enum type (_MSG_ERROR_E).
-- MMS_SMIL_REGION* msg_mms_get_smil_region(MMS_MESSAGE_DATA_S msgBody, int region_idx);
-@n msg_mms_get_smil_region() is a function to get a SMIL region information. The first parameter is the structure of MMS data. The second parameter is the index of SMIL region you want to get. If the function is successful, it returns the structure which contains the SMIL region information. Otherwise it returns NULL.
-- MMS_PAGE_S* msg_mms_get_page(MMS_MESSAGE_DATA_S msgBody, int page_idx);
-@n msg_mms_get_page() is a function to get a SMIL page information. The first parameter is the structure of MMS data. The second parameter is the index of SMIL page you want to get. If the function is successful, it returns the structure which contains the SMIL page information. Otherwise it returns NULL.
-- MMS_MEDIA_S* msg_mms_get_media(MMS_PAGE_S *page, int media_idx);
-@n msg_mms_get_media() is a function to get a media information in a SMIL page. The first parameter is the structure of SMIL page you want to get the media from. The second parameter is the index of media you want to get. If the function is successful, it returns the structure which contains the media information. Otherwise it returns NULL.
-- MMS_ATTACH_S* msg_mms_get_attachment(MMS_MESSAGE_DATA_S msgBody, int attach_idx);
-@n msg_mms_get_attachment() is a function to get the file information of  an attachment. The first parameter is the structure of MMS data. The second parameter is the index of attachment you want to get. If the function is successful, it returns the structure which contains the attachment file information. Otherwise it returns NULL.
-- const char* msg_get_subject(msg_message_t msg);
-@n msg_get_subject() is a function to get the subject of MMS. The parameter is the message object. If the function is successful, it returns the subject string. Otherwise it returns NULL.
-@code
-void MsgTestGetMmsMessage(MSG_HANDLE_T hMsgHandle, int MsgId)
-{
-       if (hMsgHandle == NULL)
-       {
-               printf("Handle is NULL\n");
-               return;
-       }
-
-       MSG_ERROR_T err = MSG_SUCCESS;
-
-       msg_message_t msg = msg_new_message();
-       MSG_SENDINGOPT_S sendOpt = {0, };
-
-       // Get Message
-       err = msg_get_message(hMsgHandle, (MSG_MESSAGE_ID_T)MsgId, msg, &sendOpt);
-
-       if (err != MSG_SUCCESS) goto free_memory;
-
-       if (msg_is_mms(msg) == false)
-       {
-               printf("It is not MMS Message!");
-               goto free_memory;
-       }
-
-       MMS_MESSAGE_DATA_S* msgBody = msg_mms_create_message();
-
-       // Get MMS Body Data
-       msg_mms_get_message_body(msg, msgBody);
-
-       //Print root-layout info
-       printf("width: %d \n
-               height: %d \n
-               nbgColor:%x \n",
-               msgBody->rootlayout.width.value,
-               msgBody->rootlayout.height.value,
-               msgBody->rootlayout.bgColor);
-
-       // Print Region Info
-       for (int i = 0; i < msgBody->regionCnt; ++i)
-       {
-               MMS_SMIL_REGION* pRegion = msg_mms_get_smil_region(msgBody, i);
-
-               printf("region id: %s\n
-                       region left : %d\n
-                       region top : %d\n
-                       region width : %d\n
-                       region height : %d\n
-                       region bgColor : %x\n
-                       region fit : %d\n",
-                       pRegion->szID,pRegion->nLeft.value,
-                       pRegion->nTop.value,pRegion->width.value,
-                       pRegion->height.value, pRegion->bgColor,
-                       pRegion->fit);
-       }
-
-       // Print Page info
-       for (int i = 0; i< msgBody->pageCnt; ++i)
-       {
-               MMS_PAGE_S* pPage = msg_mms_get_page(msgBody, i);
-
-               printf("page's duration: %d msec\n
-                       page's media count: %d\n",
-                       pPage->nDur, pPage->mediaCnt);
-
-               // Print Contents Info
-               for(int j = 0; j < pPage->mediaCnt; ++j)
-               {
-                       MMS_MEDIA_S* pMedia = msg_mms_get_media(pPage, j);
-                       printf("media's filename: %s\n
-                               media's filepath: %s\n
-                               media's regionId: %s\n
-                               Bold: %d Italic: %d\n",
-                               pMedia->szFileName,
-                               pMedia->szFilePath,
-                               pMedia->regionId,
-                               pMedia->sMedia.sText.bBold,
-                               pMedia->sMedia.sText.bItalic);
-
-                       if(pMedia->drmType != MSG_DRM_TYPE_NONE)
-                       {
-                               printf("media's drmtype: %d\n
-                                       media's drmpath: %s\n",
-                                       pMedia->drmType, pMedia->szDrm2FullPath);
-                       }
-               }
-       }
-
-       for (int i = 0; i < msgBody->attachCnt; ++i)
-       {
-               MMS_ATTACH_S* pAttach = msg_mms_get_attachment(msgBody, i);
-
-               printf("Attachment file Name: %s\n
-                       Attachment file Path: %s\n
-                       Attached file size: %d\n",
-                       pAttach->szFileName,
-                       pAttach->szFilePath,
-                       pAttach->fileSize);
-
-               if(pAttach->drmType != MSG_DRM_TYPE_NONE)
-                       printf("media's drmtype: %d\n
-                               media's drmpath: %s\n",
-                               pAttach->drmType, pAttach->szDrm2FullPath);
-       }
-
-       printf("Subject: %s\n", msg_get_subject(pMsg));
-
-       printf("msgId = %d", msg_get_message_id(msg));
-       printf("folderId = %d", msg_get_folder_id(msg));
-       printf("phone number = %s", msg_get_ith_address(msg, 0));
-       printf("displayTime = %s", ctime(msg_get_time(msg)));
-       printf("networkStatus = %d", msg_get_network_status(msg));
-       printf("bRead = %d", msg_is_read(msg));
-       printf("bProtected = %d", msg_is_protected(msg));
-
-free_memory:
-       msg_mms_destroy_message(msgBody);
-
-       msg_release_message(&msg);
-}
-@endcode
-@}
-
-@defgroup MESSAGE_USECASES_9 Delete a Message
-@ingroup MESSAGE_USECASES
-@{
-               <h3 class="pg">Delete a Message</h3>
-- int msg_delete_message(MSG_HANDLE_T handle, MSG_MESSAGE_ID_T msg_id);
-@n msg_delete_message() is a function to delete a message from message box by msg_id.
-@code
-void MsgTestDeleteMessage(MSG_HANDLE_T hMsgHandle, MSG_MESSAGE_ID_T nMsgId)
-{
-       MSG_ERROR_T err;
-
-       if (msg_delete_message(hMsgHandle, nMsgId) != MSG_SUCCESS)
-               printf("Failed to delete Message");
-
-}
-@endcode
-@}
-
-@defgroup MESSAGE_USECASES_10 Set/Get Message Setting
-@ingroup MESSAGE_USECASES
-@{
-               <h3 class="pg">Set / Get Message setting</h3>
-msg_set_config() and msg_get_cofig() is used to set or to get the message setting options. MSG_SETTING_S structure includes various setting information and is shared between message application and messaging daemon.
-
-- int msg_set_config(MSG_HANDLE_T handle, const MSG_SETTING_S *setting);
-@n msg_set_config() sets a message option.
-- int msg_get_config(MSG_HANDLE_T handle, MSG_SETTING_S *setting);
-@n msg_get_config() gets a message option.
-@code
-void MsgTestSetGeneralOpt(MSG_HANDLE_T hMsgHandle)
-{
-       MSG_ERROR_T err = MSG_SUCCESS;
-       MSG_SETTING_S setting = {0, };
-
-       setting.type = MSG_GENERAL_OPT;
-
-       setting.option.generalOpt.bKeepCopy = true;
-       setting.option.generalOpt.alertTone = MSG_ALERT_TONE_ONCE;
-
-       err = msg_set_config(hMsgHandle, &setting);
-
-       if (err == MSG_SUCCESS)
-               printf("Setting Config Data is OK!");
-       else
-               printf("Setting Config Data is failed!");
-}
-
-void MsgTestGetGeneralOpt(MSG_HANDLE_T hMsgHandle)
-{
-       MSG_ERROR_T err = MSG_SUCCESS;
-       MSG_SETTING_S setting = {0, };
-
-       err = msg_get_config(hMsgHandle, &setting);
-
-       if (err == MSG_SUCCESS)
-       {
-               printf("Setting Config Data is OK!\n");
-               printf("bKeepCopy : [%d], AlertTone : [%d]\n", setting.option.generalOpt.bKeepCopy, setting.option.generalOpt.alertTone);
-       }
-       else
-               printf("Setting Config Data is failed!\n");
-}
-@endcode
-@}
-
-@defgroup MESSAGE_USECASES_11 Filtering a Message
-@ingroup MESSAGE_USECASES
-@{
-               <h3 class="pg">Filtering a Message</h3>
-Messaging framework provides a filtering function for incoming message. New incoming message can be blocked (Move to spam-box or discard) by adding a filtering rule. A incoming message can be blocked by its originating address or by subject matching. If address matching filter rule is applied, only messages with exactly the same phone number can be blocked. Whereas, if a subject matching filter rule is applied, all messages that include the registered subject string might be blocked. An application can add or remove a filtering rule by calling msg_add_filter() or msg_delete_filter().
-
-- int msg_add_filter(MSG_HANDLE_T handle, const MSG_FILTER_S *filter);
-@n msg_add_filter() inserts a filtering rule to filter list and returns filter id.
-- int msg_delete_filter(MSG_HANDLE_T handle, MSG_FILTER_ID_T filter_id);
-@n msg_delete_filter()removes a filtering rule from filter list by filter id
-@code
-void MsgTestAddFilter(MSG_HANDLE_T hMsgHandle)
-{
-       if (hMsgHandle == NULL)
-       {
-               printf("Handle is NULL");
-               return;
-       }
-
-       MSG_ERROR_T err = MSG_SUCCESS;
-       MSG_FILTER_S filter[2]= {0, };
-
-       // Add filter by address
-       filter[0].filterType = MSG_FILTER_BY_ADDRESS;
-       strncpy(filter[0].filterValue, "+821234567890", MAX_FILTER_VALUE_LEN);
-
-       err = msg_add_filter(hMsgHandle, &filter[0]);
-
-       if (err == MSG_SUCCESS)
-               printf("msg_add_filter success");
-       else
-               printf("msg_add_filter fail - err [%d]", err);
-
-       // Add filter by subject
-       filter[1].filterType = MSG_FILTER_BY_SUBJECT;
-       strncpy(filter[1].filterValue, "test filter", MAX_FILTER_VALUE_LEN);
-
-       err = msg_add_filter(hMsgHandle, &filter[1]);
-
-       if (err == MSG_SUCCESS)
-               printf("msg_add_filter success");
-       else
-               printf("msg_add_filter fail - err [%d]", err);
-
-       return;
-}
-
-void MsgTestDeleteFilter(MSG_HANDLE_T hMsgHandle, MSG_FILTER_ID_T filterId)
-{
-       if (hMsgHandle == NULL)
-       {
-               printf("Handle is NULL");
-               return;
-       }
-
-       MSG_ERROR_T err = MSG_SUCCESS;
-       err = msg_delete_filter(hMsgHandle, filterId);
-
-       if (MSG_SUCCESS == err)
-       {
-               printf("msg_delete_filter success");
-       }
-       else
-       {
-               printf("msg_delete_filter fail - err [%d]", err);
-       }
-
-       return;
-}
-@endcode
-@}
-*/
-
-/**
-@addtogroup MESSAGE
-@{
-       @defgroup MESSAGE_USECASES Use Cases
-@}
-*/
diff --git a/config/alert_on_call.mp3 b/config/alert_on_call.mp3
deleted file mode 100755 (executable)
index c7c77d1..0000000
Binary files a/config/alert_on_call.mp3 and /dev/null differ
diff --git a/config/message_tone/Sherbet.wav b/config/message_tone/Sherbet.wav
deleted file mode 100755 (executable)
index 3d352e4..0000000
Binary files a/config/message_tone/Sherbet.wav and /dev/null differ
diff --git a/config/msg-service-db.CDMA.sql b/config/msg-service-db.CDMA.sql
new file mode 100755 (executable)
index 0000000..6f22520
--- /dev/null
@@ -0,0 +1,327 @@
+PRAGMA user_version=1;
+
+CREATE TABLE MSG_CONVERSATION_TABLE
+(
+       CONV_ID INTEGER PRIMARY KEY ,
+       UNREAD_CNT INTEGER DEFAULT 0 ,
+       SMS_CNT INTEGER DEFAULT 0 ,
+       MMS_CNT INTEGER DEFAULT 0 ,
+       MAIN_TYPE INTEGER DEFAULT 0 ,
+       SUB_TYPE INTEGER DEFAULT 0 ,
+       MSG_DIRECTION INTEGER DEFAULT 0 ,
+       DISPLAY_TIME DATETIME ,
+       DISPLAY_NAME TEXT NOT NULL DEFAULT '' ,
+       MSG_TEXT TEXT NOT NULL DEFAULT '' ,
+       TRANSLATION INTEGER DEFAULT 0,
+       SENDER_LANG INTEGER DEFAULT 0,
+       RECEIVER_LANG INTEGER DEFAULT 0,
+       ONLY_RECEIVE INTEGER DEFAULT 0,
+       INCLUDE_ORGMSG INTEGER DEFAULT 0,
+       LAST_MSG_ID INTEGER DEFAULT 0
+);
+
+CREATE TABLE MSG_ADDRESS_TABLE
+(
+       ADDRESS_ID INTEGER PRIMARY KEY ,
+       CONV_ID INTEGER  NOT NULL ,
+       ADDRESS_TYPE INTEGER ,
+       RECIPIENT_TYPE INTEGER ,
+       ADDRESS_VAL TEXT NOT NULL DEFAULT '' ,
+       CONTACT_ID INTEGER ,
+       ADDR_BOOK_ID INTEGER ,
+       FIRST_NAME TEXT NOT NULL DEFAULT '' ,
+       LAST_NAME TEXT NOT NULL DEFAULT '' ,
+       MIDDLE_NAME TEXT NOT NULL DEFAULT '' ,
+       PREFIX TEXT NOT NULL DEFAULT '' ,
+       SUFFIX TEXT NOT NULL DEFAULT '' ,
+       IMAGE_PATH TEXT NOT NULL DEFAULT '' ,
+       SYNC_TIME DATETIME ,
+
+       FOREIGN KEY (CONV_ID) REFERENCES MSG_CONVERSATION_TABLE (CONV_ID)
+);
+
+CREATE TABLE MSG_FOLDER_TABLE
+(
+       FOLDER_ID INTEGER PRIMARY KEY ,
+       FOLDER_NAME TEXT NOT NULL ,
+       FOLDER_TYPE INTEGER DEFAULT 0
+);
+
+CREATE TABLE MSG_MESSAGE_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       CONV_ID INTEGER NOT NULL ,
+       FOLDER_ID INTEGER NOT NULL ,
+       STORAGE_ID INTEGER NOT NULL ,
+       MAIN_TYPE INTEGER NOT NULL ,
+       SUB_TYPE INTEGER NOT NULL ,
+       DISPLAY_TIME DATETIME ,
+       DATA_SIZE INTEGER DEFAULT 0 ,
+       NETWORK_STATUS INTEGER DEFAULT 0 ,
+       READ_STATUS INTEGER DEFAULT 0 ,
+       PROTECTED INTEGER DEFAULT 0 ,
+       PRIORITY INTEGER DEFAULT 0 ,
+       MSG_DIRECTION INTEGER NOT NULL ,
+       SCHEDULED_TIME DATETIME ,
+       BACKUP INTEGER DEFAULT 0 ,
+       SUBJECT TEXT NOT NULL DEFAULT '' ,
+       MSG_DATA TEXT NOT NULL DEFAULT '' ,
+       THUMB_PATH TEXT NOT NULL DEFAULT '' ,
+       MSG_TEXT TEXT NOT NULL DEFAULT '' ,
+       ATTACHMENT_COUNT INTEGER DEFAULT 0 ,
+
+       FOREIGN KEY (CONV_ID) REFERENCES MSG_CONVERSATION_TABLE (CONV_ID) ,
+       FOREIGN KEY (FOLDER_ID) REFERENCES MSG_FOLDER_TABLE (FOLDER_ID)
+);
+
+CREATE TABLE MSG_SIM_TABLE
+(
+       SIM_ID INTEGER PRIMARY KEY ,
+       MSG_ID INTEGER NOT NULL ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_PUSH_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       ACTION INTEGER ,
+       CREATED INTEGER ,
+       EXPIRES INTEGER ,
+       ID TEXT NOT NULL DEFAULT '' ,
+       HREF TEXT NOT NULL DEFAULT '' ,
+       CONTENT TEXT NOT NULL DEFAULT '' ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_CBMSG_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       CB_MSG_ID INTEGER NOT NULL ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_SYNCML_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       EXT_ID INTEGER NOT NULL ,
+       PINCODE INTEGER NOT NULL ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_SCHEDULED_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       ALARM_ID INTEGER NOT NULL ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_SMS_SENDOPT_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       DELREP_REQ INTEGER NOT NULL ,
+       KEEP_COPY INTEGER NOT NULL ,
+       REPLY_PATH INTEGER NOT NULL ,
+       ENCODE_TYPE INTEGER NOT NULL ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_FILTER_TABLE
+(
+       FILTER_ID INTEGER PRIMARY KEY ,
+       FILTER_TYPE INTEGER NOT NULL ,
+       FILTER_VALUE TEXT NOT NULL ,
+       FILTER_ACTIVE INTEGER DEFAULT 0
+);
+
+CREATE TABLE MSG_MMS_MESSAGE_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       TRANSACTION_ID TEXT NOT NULL DEFAULT '' ,
+       MESSAGE_ID TEXT NOT NULL DEFAULT '' ,
+       FWD_MESSAGE_ID TEXT NOT NULL DEFAULT '' ,
+       CONTENTS_LOCATION TEXT NOT NULL DEFAULT '' ,
+       FILE_PATH TEXT NOT NULL DEFAULT '' ,
+       VERSION INTEGER NOT NULL ,
+       DATA_TYPE INTEGER DEFAULT -1 ,
+       DATE DATETIME ,
+       HIDE_ADDRESS INTEGER DEFAULT 0 ,
+       ASK_DELIVERY_REPORT INTEGER DEFAULT 0 ,
+       REPORT_ALLOWED INTEGER DEFAULT 0 ,
+       READ_REPORT_ALLOWED_TYPE INTEGER DEFAULT 0 ,
+       ASK_READ_REPLY INTEGER DEFAULT 0 ,
+       READ INTEGER DEFAULT 0 ,
+       READ_REPORT_SEND_STATUS INTEGER DEFAULT 0 ,
+       READ_REPORT_SENT INTEGER DEFAULT 0 ,
+       PRIORITY INTEGER DEFAULT 0 ,
+       KEEP_COPY INTEGER DEFAULT 0 ,
+       MSG_SIZE INTEGER NOT NULL ,
+       MSG_CLASS INTEGER DEFAULT -1 ,
+       EXPIRY_TIME DATETIME ,
+       CUSTOM_DELIVERY_TIME INTEGER DEFAULT 0 ,
+       DELIVERY_TIME DATETIME ,
+       MSG_STATUS INTEGER DEFAULT -1 ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_MMS_PREVIEW_INFO_TABLE
+(
+       MSG_ID INTEGER NOT NULL ,
+       TYPE INTEGER,
+       VALUE TEXT,
+       COUNT INTEGER,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_SMS_REPORT_TABLE
+(
+       MSG_ID INTEGER NOT NULL ,
+       ADDRESS_VAL TEXT NOT NULL DEFAULT '' ,
+       MSG_REF INTEGER ,
+       STATUS_TYPE INTEGER ,
+       STATUS INTEGER DEFAULT 0 ,
+       TIME DATETIME
+);
+
+CREATE TABLE MSG_REPORT_TABLE
+(
+       MSG_ID INTEGER NOT NULL ,
+       ADDRESS_VAL TEXT NOT NULL DEFAULT '' ,
+       STATUS_TYPE INTEGER ,
+       STATUS INTEGER DEFAULT 0 ,
+       TIME DATETIME
+);
+
+CREATE TABLE MSG_PUSHCFG_TABLE
+(
+       PUSH_ID INTEGER PRIMARY KEY ,
+       CONTENT_TYPE TEXT NOT NULL DEFAULT '' ,
+       APP_ID TEXT NOT NULL DEFAULT '' ,
+       PKG_NAME TEXT NOT NULL DEFAULT '' ,
+       LAUNCH INTEGER,
+       APPCODE INTEGER,
+       SECURE INTEGER
+);
+
+CREATE TABLE MSG_TMP_MSGID_TABLE
+(
+       MSG_ID INTEGER
+);
+
+CREATE TABLE MSG_CB_CHANNEL_INFO_TABLE
+(
+       CHANNEL_ID INTEGER PRIMARY KEY ,
+       CHANNEL_ACTIVATION INTEGER DEFAULT 0,
+       CHANNEL_FROM INTEGER DEFAULT 0,
+       CHANNEL_TO INTEGER DEFAULT 0,
+       CHANNEL_NAME TEXT NOT NULL DEFAULT ''
+);
+
+CREATE TABLE MSG_MULTIPART_TABLE
+(
+       _ID INTEGER PRIMARY KEY AUTOINCREMENT,
+       MSG_ID INTEGER NOT NULL ,
+       SEQ INTEGER DEFAULT 0,
+       CONTENT_TYPE TEXT,
+       NAME TEXT,
+       CHARSET INTEGER,
+       CONTENT_ID TEXT,
+       CONTENT_LOCATION TEXT,
+       FILE_PATH TEXT,
+       TEXT TEXT,
+       TCS_LEVEL INTEGER DEFAULT -1,
+       MALWARE_ALLOW INTEGER DEFAULT 0,
+       THUMB_FILE_PATH TEXT,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_CDMA_CB_CHANNEL_INFO_TABLE
+(
+       CHANNEL_ID INTEGER PRIMARY KEY,
+       CHANNEL_ACTIVATION INTEGER DEFAULT 0,
+       CHANNEL_CATEGORY INTEGER DEFAULT 0,
+       CHANNEL_LANGUAGE INTEGER DEFAULT 0,
+       CHANNEL_NAME TEXT NOT NULL DEFAULT ''
+);
+
+CREATE TABLE MSG_UNIQUENESS_INFO_TABLE
+(
+       MSG_ID INTEGER NOT NULL,
+       TELE_MSG_ID INTEGER NOT NULL,
+       ADDRESS TEXT DEFAULT '',
+       SUB_ADDRESS TEXT DEFAULT '',
+       TIME_STAMP TEXT DEFAULT '',
+       TELESVC_ID INTEGER NOT NULL,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_ADDRESS_TEMP_TABLE
+(
+       ADDRESS_VAL TEXT NOT NULL DEFAULT ''
+);
+
+CREATE INDEX MSG_CONVERSATION_INDEX ON MSG_CONVERSATION_TABLE(CONV_ID);
+CREATE INDEX MSG_FOLDER_INDEX ON MSG_FOLDER_TABLE(FOLDER_ID);
+CREATE INDEX MSG_MESSAGE_INDEX ON MSG_MESSAGE_TABLE(MSG_ID, CONV_ID, FOLDER_ID);
+
+INSERT INTO MSG_FOLDER_TABLE VALUES (1, 'INBOX', 1);
+INSERT INTO MSG_FOLDER_TABLE VALUES (2, 'OUTBOX', 2);
+INSERT INTO MSG_FOLDER_TABLE VALUES (3, 'SENTBOX', 2);
+INSERT INTO MSG_FOLDER_TABLE VALUES (4, 'DRAFT', 3);
+INSERT INTO MSG_FOLDER_TABLE VALUES (5, 'CBMSGBOX', 1);
+INSERT INTO MSG_FOLDER_TABLE VALUES (6, 'SPAMBOX', 4);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (1, 'text/vnd.wap.si', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 1, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (2, 'application/vnd.wap.sic', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 2, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (3, 'text/vnd.wap.sl', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 3, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (4, 'application/vnd.wap.slc', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 4, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (5, 'text/vnd.wap.co', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 5, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (6, 'application/vnd.wap.coc', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 6, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (7, 'application/vnd.wap.mms-message', 'X-Wap-Application-Id: x-wap-application:mms.ua', '', 0, 7, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (8, 'application/vnd.wap.sia', 'X-Wap-Application-Id: x-wap-application:push.sia', '', 0, 8, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (9, 'application/vnd.syncml.dm+wbxml', 'X-Wap-Application-Id: x-wap-application:push.syncml.dm', '', 0, 9, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (10, 'application/vnd.syncml.dm+xml', 'X-Wap-Application-Id: x-wap-application:push.syncml.dm', '', 0, 10, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (11, 'application/vnd.syncml.notification', 'X-Wap-Application-Id: x-wap-application:push.syncml.dm', '', 0, 11, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (12, 'application/vnd.syncml.ds.notification', 'X-Wap-Application-Id: x-wap-application:push.syncml.ds', '', 0, 12, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (13, 'application/vnd.syncml+wbxml', 'X-Wap-Application-Id:x-wap-application:push.syncml', '', 0, 13, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (14, 'application/vnd.wap.locc+wbxml', 'X-Wap-Application-Id: x-wap-application:loc.ua', '', 0, 14, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (15, 'application/vnd.wap.loc+xml', 'X-Wap-Application-Id: x-wap-application:loc.ua', '', 0, 15, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (16, 'application/vnd.oma.dd+xml', 'X-Wap-Application-Id: x-wap-application:loc.ua', '', 0, 16, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (17, 'application/vnd.oma.drm.message', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 17, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (18, 'application/vnd.oma.drm.content', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 18, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (19, 'application/vnd.oma.drm.rights+xml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 19, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (20, 'application/vnd.oma.drm.rights+wbxml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 20, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (21, 'application/vnd.oma.drm.ro+xml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 21, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (22, 'application/vnd.oma.drm.roap-pdu+xml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 22, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (23, 'application/vnd.oma.drm.roap-trigger+xml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 23, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (24, 'application/vnd.oma.drm.roap-trigger+wbxml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 24, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (25, 'text/vnd.wap.connectivity-xml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 26, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (26, 'application/vnd.wap.connectivity-wbxml', 'X-Wap-Application-Id: x-wap-samsung:provisioning.ua', '', 0, 27, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (27, 'application/x-wap-prov.browser-settings', 'X-Wap-Application-Id: x-wap-samsung:provisioning.ua', '', 0, 28, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (28, 'application/x-wap-prov.browser-bookmarks', 'X-Wap-Application-Id: x-wap-samsung:provisioning.ua', '', 0, 29, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (29, 'application/x-wap-prov.syncset+xml', 'X-Wap-Application-Id: x-wap-samsung:provisioning.ua', '', 0, 30, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (30, 'application/x-wap-prov.syncset+wbxml', 'X-Wap-Application-Id: x-wap-samsung:provisioning.ua', '', 0, 31, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (33, 'application/vnd.wv.csp.cir', 'X-Wap-Application-Id: x-wap-application:wv.ua', '', 0, 34, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (34, 'application/vnd.omaloc-supl-init', 'X-Wap-Application-Id: x-oma-application:ulp.ua', '', 0, 44, 0);
+
+INSERT INTO MSG_CDMA_CB_CHANNEL_INFO_TABLE VALUES (0, 1, 4096, 1, 'Presidential');
+INSERT INTO MSG_CDMA_CB_CHANNEL_INFO_TABLE VALUES (1, 1, 4097, 1, 'Extreme');
+INSERT INTO MSG_CDMA_CB_CHANNEL_INFO_TABLE VALUES (2, 1, 4098, 1, 'Severe');
+INSERT INTO MSG_CDMA_CB_CHANNEL_INFO_TABLE VALUES (3, 1, 4099, 1, 'Amber');
+INSERT INTO MSG_CDMA_CB_CHANNEL_INFO_TABLE VALUES (4, 0, 4100, 1, 'Test');
diff --git a/config/msg-service-db.sql b/config/msg-service-db.sql
new file mode 100755 (executable)
index 0000000..a508b79
--- /dev/null
@@ -0,0 +1,301 @@
+PRAGMA user_version=1;
+
+CREATE TABLE MSG_CONVERSATION_TABLE
+(
+       CONV_ID INTEGER PRIMARY KEY ,
+       UNREAD_CNT INTEGER DEFAULT 0 ,
+       SMS_CNT INTEGER DEFAULT 0 ,
+       MMS_CNT INTEGER DEFAULT 0 ,
+       MAIN_TYPE INTEGER DEFAULT 0 ,
+       SUB_TYPE INTEGER DEFAULT 0 ,
+       MSG_DIRECTION INTEGER DEFAULT 0 ,
+       DISPLAY_TIME DATETIME ,
+       DISPLAY_NAME TEXT NOT NULL DEFAULT '' ,
+       MSG_TEXT TEXT NOT NULL DEFAULT ''
+);
+
+CREATE TABLE MSG_ADDRESS_TABLE
+(
+       ADDRESS_ID INTEGER PRIMARY KEY ,
+       CONV_ID INTEGER  NOT NULL ,
+       ADDRESS_TYPE INTEGER ,
+       RECIPIENT_TYPE INTEGER ,
+       ADDRESS_VAL TEXT NOT NULL DEFAULT '' ,
+       CONTACT_ID INTEGER ,
+       ADDR_BOOK_ID INTEGER ,
+       FIRST_NAME TEXT NOT NULL DEFAULT '' ,
+       LAST_NAME TEXT NOT NULL DEFAULT '' ,
+       MIDDLE_NAME TEXT NOT NULL DEFAULT '' ,
+       PREFIX TEXT NOT NULL DEFAULT '' ,
+       SUFFIX TEXT NOT NULL DEFAULT '' ,
+       IMAGE_PATH TEXT NOT NULL DEFAULT '' ,
+       SYNC_TIME DATETIME ,
+
+       FOREIGN KEY (CONV_ID) REFERENCES MSG_CONVERSATION_TABLE (CONV_ID)
+);
+
+CREATE TABLE MSG_FOLDER_TABLE
+(
+       FOLDER_ID INTEGER PRIMARY KEY ,
+       FOLDER_NAME TEXT NOT NULL ,
+       FOLDER_TYPE INTEGER DEFAULT 0
+);
+
+CREATE TABLE MSG_MESSAGE_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       CONV_ID INTEGER NOT NULL ,
+       FOLDER_ID INTEGER NOT NULL ,
+       STORAGE_ID INTEGER NOT NULL ,
+       MAIN_TYPE INTEGER NOT NULL ,
+       SUB_TYPE INTEGER NOT NULL ,
+       DISPLAY_TIME DATETIME ,
+       DATA_SIZE INTEGER DEFAULT 0 ,
+       NETWORK_STATUS INTEGER DEFAULT 0 ,
+       READ_STATUS INTEGER DEFAULT 0 ,
+       PROTECTED INTEGER DEFAULT 0 ,
+       PRIORITY INTEGER DEFAULT 0 ,
+       MSG_DIRECTION INTEGER NOT NULL ,
+       SCHEDULED_TIME DATETIME ,
+       BACKUP INTEGER DEFAULT 0 ,
+       SUBJECT TEXT NOT NULL DEFAULT '' ,
+       MSG_DATA TEXT NOT NULL DEFAULT '' ,
+       THUMB_PATH TEXT NOT NULL DEFAULT '' ,
+       MSG_TEXT TEXT NOT NULL DEFAULT '' ,
+       ATTACHMENT_COUNT INTEGER DEFAULT 0 ,
+       SIM_INDEX INTEGER DEFAULT 0 ,
+       SIM_IMSI TEXT ,
+
+       FOREIGN KEY (CONV_ID) REFERENCES MSG_CONVERSATION_TABLE (CONV_ID) ,
+       FOREIGN KEY (FOLDER_ID) REFERENCES MSG_FOLDER_TABLE (FOLDER_ID)
+);
+
+CREATE TABLE MSG_SIM_TABLE
+(
+       SIM_SLOT_ID INTEGER ,
+       SIM_ID INTEGER ,
+       MSG_ID INTEGER NOT NULL ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_PUSH_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       ACTION INTEGER ,
+       CREATED INTEGER ,
+       EXPIRES INTEGER ,
+       ID TEXT NOT NULL DEFAULT '' ,
+       HREF TEXT NOT NULL DEFAULT '' ,
+       CONTENT TEXT NOT NULL DEFAULT '' ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_CBMSG_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       CB_MSG_ID INTEGER NOT NULL ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_SYNCML_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       EXT_ID INTEGER NOT NULL ,
+       PINCODE INTEGER NOT NULL ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_SCHEDULED_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       ALARM_ID INTEGER NOT NULL ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_SMS_SENDOPT_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       DELREP_REQ INTEGER NOT NULL ,
+       KEEP_COPY INTEGER NOT NULL ,
+       REPLY_PATH INTEGER NOT NULL ,
+       ENCODE_TYPE INTEGER NOT NULL ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_FILTER_TABLE
+(
+       FILTER_ID INTEGER PRIMARY KEY ,
+       FILTER_TYPE INTEGER NOT NULL ,
+       FILTER_VALUE TEXT NOT NULL ,
+       FILTER_ACTIVE INTEGER DEFAULT 0
+);
+
+CREATE TABLE MSG_MMS_MESSAGE_TABLE
+(
+       MSG_ID INTEGER PRIMARY KEY ,
+       TRANSACTION_ID TEXT NOT NULL DEFAULT '' ,
+       MESSAGE_ID TEXT NOT NULL DEFAULT '' ,
+       FWD_MESSAGE_ID TEXT NOT NULL DEFAULT '' ,
+       CONTENTS_LOCATION TEXT NOT NULL DEFAULT '' ,
+       FILE_PATH TEXT NOT NULL DEFAULT '' ,
+       VERSION INTEGER NOT NULL ,
+       DATA_TYPE INTEGER DEFAULT -1 ,
+       DATE DATETIME ,
+       HIDE_ADDRESS INTEGER DEFAULT 0 ,
+       ASK_DELIVERY_REPORT INTEGER DEFAULT 0 ,
+       REPORT_ALLOWED INTEGER DEFAULT 0 ,
+       READ_REPORT_ALLOWED_TYPE INTEGER DEFAULT 0 ,
+       ASK_READ_REPLY INTEGER DEFAULT 0 ,
+       READ INTEGER DEFAULT 0 ,
+       READ_REPORT_SEND_STATUS INTEGER DEFAULT 0 ,
+       READ_REPORT_SENT INTEGER DEFAULT 0 ,
+       PRIORITY INTEGER DEFAULT 0 ,
+       KEEP_COPY INTEGER DEFAULT 0 ,
+       MSG_SIZE INTEGER NOT NULL ,
+       MSG_CLASS INTEGER DEFAULT -1 ,
+       EXPIRY_TIME DATETIME ,
+       CUSTOM_DELIVERY_TIME INTEGER DEFAULT 0 ,
+       DELIVERY_TIME DATETIME ,
+       MSG_STATUS INTEGER DEFAULT -1 ,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_MMS_PREVIEW_INFO_TABLE
+(
+       MSG_ID INTEGER NOT NULL ,
+       TYPE INTEGER,
+       VALUE TEXT,
+       COUNT INTEGER,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_SMS_REPORT_TABLE
+(
+       MSG_ID INTEGER NOT NULL ,
+       ADDRESS_VAL TEXT NOT NULL DEFAULT '' ,
+       MSG_REF INTEGER ,
+       STATUS_TYPE INTEGER ,
+       STATUS INTEGER DEFAULT 0 ,
+       TIME DATETIME
+);
+
+CREATE TABLE MSG_REPORT_TABLE
+(
+       MSG_ID INTEGER NOT NULL ,
+       ADDRESS_VAL TEXT NOT NULL DEFAULT '' ,
+       STATUS_TYPE INTEGER ,
+       STATUS INTEGER DEFAULT 0 ,
+       TIME DATETIME
+);
+
+CREATE TABLE MSG_PUSHCFG_TABLE
+(
+       PUSH_ID INTEGER PRIMARY KEY ,
+       CONTENT_TYPE TEXT NOT NULL DEFAULT '' ,
+       APP_ID TEXT NOT NULL DEFAULT '' ,
+       PKG_NAME TEXT NOT NULL DEFAULT '' ,
+       LAUNCH INTEGER,
+       APPCODE INTEGER,
+       SECURE INTEGER
+);
+
+CREATE TABLE MSG_TMP_MSGID_TABLE
+(
+       MSG_ID INTEGER
+);
+
+CREATE TABLE MSG_CB_CHANNEL_INFO_TABLE
+(
+       CHANNEL_ID INTEGER PRIMARY KEY AUTOINCREMENT,
+       CHANNEL_ACTIVATION INTEGER DEFAULT 0,
+       CHANNEL_FROM INTEGER DEFAULT 0,
+       CHANNEL_TO INTEGER DEFAULT 0,
+       CHANNEL_NAME TEXT NOT NULL DEFAULT '',
+       SIM_INDEX INTEGER DEFAULT 0
+);
+
+CREATE TABLE MSG_MULTIPART_TABLE
+(
+       _ID INTEGER PRIMARY KEY AUTOINCREMENT,
+       MSG_ID INTEGER NOT NULL ,
+       SEQ INTEGER DEFAULT 0,
+       CONTENT_TYPE TEXT,
+       NAME TEXT,
+       CHARSET INTEGER,
+       CONTENT_ID TEXT,
+       CONTENT_LOCATION TEXT,
+       FILE_PATH TEXT,
+       TEXT TEXT,
+       TCS_LEVEL INTEGER DEFAULT -1,
+       MALWARE_ALLOW INTEGER DEFAULT 0,
+       THUMB_FILE_PATH TEXT,
+
+       FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID)
+);
+
+CREATE TABLE MSG_ADDRESS_TEMP_TABLE
+(
+       ADDRESS_VAL TEXT NOT NULL DEFAULT ''
+);
+
+CREATE INDEX MSG_CONVERSATION_INDEX ON MSG_CONVERSATION_TABLE(CONV_ID);
+CREATE INDEX MSG_FOLDER_INDEX ON MSG_FOLDER_TABLE(FOLDER_ID);
+CREATE INDEX MSG_MESSAGE_INDEX ON MSG_MESSAGE_TABLE(MSG_ID, CONV_ID, FOLDER_ID);
+
+INSERT INTO MSG_FOLDER_TABLE VALUES (1, 'INBOX', 1);
+INSERT INTO MSG_FOLDER_TABLE VALUES (2, 'OUTBOX', 2);
+INSERT INTO MSG_FOLDER_TABLE VALUES (3, 'SENTBOX', 2);
+INSERT INTO MSG_FOLDER_TABLE VALUES (4, 'DRAFT', 3);
+INSERT INTO MSG_FOLDER_TABLE VALUES (5, 'CBMSGBOX', 1);
+INSERT INTO MSG_FOLDER_TABLE VALUES (6, 'SPAMBOX', 4);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (1, 'text/vnd.wap.si', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 1, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (2, 'application/vnd.wap.sic', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 2, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (3, 'text/vnd.wap.sl', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 3, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (4, 'application/vnd.wap.slc', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 4, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (5, 'text/vnd.wap.co', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 5, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (6, 'application/vnd.wap.coc', 'X-Wap-Application-Id: x-wap-application:wml.ua', '', 0, 6, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (7, 'application/vnd.wap.mms-message', 'X-Wap-Application-Id: x-wap-application:mms.ua', '', 0, 7, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (8, 'application/vnd.wap.sia', 'X-Wap-Application-Id: x-wap-application:push.sia', '', 0, 8, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (9, 'application/vnd.syncml.dm+wbxml', 'X-Wap-Application-Id: x-wap-application:push.syncml.dm', '', 0, 9, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (10, 'application/vnd.syncml.dm+xml', 'X-Wap-Application-Id: x-wap-application:push.syncml.dm', '', 0, 10, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (11, 'application/vnd.syncml.notification', 'X-Wap-Application-Id: x-wap-application:push.syncml.dm', '', 0, 11, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (12, 'application/vnd.syncml.ds.notification', 'X-Wap-Application-Id: x-wap-application:push.syncml.ds', '', 0, 12, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (13, 'application/vnd.syncml+wbxml', 'X-Wap-Application-Id:x-wap-application:push.syncml', '', 0, 13, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (14, 'application/vnd.wap.locc+wbxml', 'X-Wap-Application-Id: x-wap-application:loc.ua', '', 0, 14, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (15, 'application/vnd.wap.loc+xml', 'X-Wap-Application-Id: x-wap-application:loc.ua', '', 0, 15, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (16, 'application/vnd.oma.dd+xml', 'X-Wap-Application-Id: x-wap-application:loc.ua', '', 0, 16, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (17, 'application/vnd.oma.drm.message', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 17, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (18, 'application/vnd.oma.drm.content', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 18, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (19, 'application/vnd.oma.drm.rights+xml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 19, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (20, 'application/vnd.oma.drm.rights+wbxml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 20, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (21, 'application/vnd.oma.drm.ro+xml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 21, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (22, 'application/vnd.oma.drm.roap-pdu+xml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 22, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (23, 'application/vnd.oma.drm.roap-trigger+xml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 23, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (24, 'application/vnd.oma.drm.roap-trigger+wbxml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 24, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (25, 'text/vnd.wap.connectivity-xml', 'X-Wap-Application-Id: x-wap-application:drm.ua', '', 0, 26, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (26, 'application/vnd.wap.connectivity-wbxml', 'X-Wap-Application-Id: x-wap-samsung:provisioning.ua', '', 0, 27, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (27, 'application/x-wap-prov.browser-settings', 'X-Wap-Application-Id: x-wap-samsung:provisioning.ua', '', 0, 28, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (28, 'application/x-wap-prov.browser-bookmarks', 'X-Wap-Application-Id: x-wap-samsung:provisioning.ua', '', 0, 29, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (29, 'application/x-wap-prov.syncset+xml', 'X-Wap-Application-Id: x-wap-samsung:provisioning.ua', '', 0, 30, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (30, 'application/x-wap-prov.syncset+wbxml', 'X-Wap-Application-Id: x-wap-samsung:provisioning.ua', '', 0, 31, 0);
+
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (33, 'application/vnd.wv.csp.cir', 'X-Wap-Application-Id: x-wap-application:wv.ua', '', 0, 34, 0);
+INSERT INTO MSG_PUSHCFG_TABLE VALUES (34, 'application/vnd.omaloc-supl-init', 'X-Wap-Application-Id: x-oma-application:ulp.ua', '', 0, 44, 0);
+
+INSERT INTO MSG_CB_CHANNEL_INFO_TABLE VALUES (0, 1, 0, 65535, '', 1);
+INSERT INTO MSG_CB_CHANNEL_INFO_TABLE VALUES (1, 1, 0, 65535, '', 2);
diff --git a/config/plugin.cfg b/config/plugin.cfg
deleted file mode 100755 (executable)
index 498d80d..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-[sms-plugin]
-type=sms
-path=/usr/lib/libmsg_sms_plugin.so
-
-[mms-plugin]
-type=mms
-path=/usr/lib/libmsg_mms_plugin.so
diff --git a/config/sysinfo-message.xml b/config/sysinfo-message.xml
new file mode 100755 (executable)
index 0000000..be1ef51
--- /dev/null
@@ -0,0 +1,8 @@
+<?xml version="1.0"?>
+<sys-info>
+       <default>
+               <key id="sms-support" string="true"/>
+               <key id="mms-support" string="true"/>
+               <key id="cbs-support" string="true"/>
+       </default>
+</sys-info>
diff --git a/doc/msg_service_doc.h b/doc/msg_service_doc.h
new file mode 100644 (file)
index 0000000..6617947
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+
+#ifndef __MSG_SERVICE_DOC_H__
+#define __MSG_SERVICE_DOC_H__
+
+
+/**
+ * @internal
+ * @ingroup CAPI_MESSAGING_FRAMEWORK
+ * @defgroup MSG_SERVICE_FRAMEWORK msg-service
+ * @brief The @ref MSG_SERVICE_FRAMEWORK API provides functions to create, set properties and send or receive a SMS/MMS message.
+ *
+ * @addtogroup MSG_SERVICE_FRAMEWORK
+ *
+ * @section MSG_SERVICE_FRAMEWORK_OVERVIEW Overview
+ *
+ * The Messages API provides the following functionalities:
+ *
+ * - Creating a message
+ * - Setting the message properties
+ * - Sending a message
+ * - Getting a message information(s)
+ * - Searching for messages
+ * - Registering/Unregistering a callback function to check whether a message is sent successfully or not
+ * - Registering/Unregistering a callback function to receive notifications when an incoming message is received
+ *
+ * <BR>
+ *
+ */
+
+
+#endif /* __MSG_SERVICE_DOC_H__ */
diff --git a/externals/CMakeLists.txt b/externals/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..10c4638
--- /dev/null
@@ -0,0 +1,54 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT(msg-server CXX)
+
+SET(CMAKE_SKIP_BUILD_RPATH TRUE)
+
+IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+       SET(CMAKE_BUILD_TYPE "Debug")
+ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+MESSAGE("Build type: ${CMAKE_BUILD_TYPE}")
+
+SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
+
+##########################################################
+# Define Framework Utils
+##########################################################
+
+SET(EXTERNALS-SRCS
+       ${CMAKE_SOURCE_DIR}/externals/MsgSoundPlayer.cpp
+       ${CMAKE_SOURCE_DIR}/externals/MsgNotificationWrapper.cpp
+       ${CMAKE_SOURCE_DIR}/externals/MsgSpamFilter.cpp
+       ${CMAKE_SOURCE_DIR}/externals/MsgLbs.cpp
+       ${CMAKE_SOURCE_DIR}/externals/MsgSensorWrapper.cpp
+       ${CMAKE_SOURCE_DIR}/externals/MsgAlarm.cpp
+       ${CMAKE_SOURCE_DIR}/externals/MsgDevicedWrapper.cpp
+)
+
+INCLUDE_DIRECTORIES(
+       ${CMAKE_SOURCE_DIR}/include/mapi
+       ${CMAKE_SOURCE_DIR}/include/common
+       ${CMAKE_SOURCE_DIR}/include/utils
+       ${CMAKE_SOURCE_DIR}/include/externals
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(externals_pkgs REQUIRED glib-2.0 deviced mm-session alarm-service notification badge iniparser capi-appfw-application lbs-dbus mm-fileinfo mm-player mm-sound sensor feedback db-util)
+
+FOREACH(flag ${externals_pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
+ADD_DEFINITIONS("-DFEATURE_JAVA_MMS")
+IF(_TIZEN_I586_ENABLED)
+ADD_DEFINITIONS("-DTIZEN_I586_ENABLED")
+ENDIF(_TIZEN_I586_ENABLED)
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+ADD_LIBRARY(${EXTERNALS-LIB} SHARED ${EXTERNALS-SRCS})
+TARGET_LINK_LIBRARIES(${EXTERNALS-LIB} ${externals_pkgs_LDFLAGS} rt ${UTILS-LIB} ${VOBJECT-LIB})
+
+INSTALL(TARGETS ${EXTERNALS-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
+
diff --git a/externals/MsgAlarm.cpp b/externals/MsgAlarm.cpp
new file mode 100755 (executable)
index 0000000..1c53a3f
--- /dev/null
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+
+#include <map>
+
+#include "MsgDebug.h"
+#include "MsgAlarm.h"
+
+#include <alarm.h>
+
+
+/*==================================================================================================
+                                     DEFINES
+==================================================================================================*/
+typedef std::map<int, msg_alarm_cb> callBackMap;
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+bool alarmInit = false;
+callBackMap alarmCBMap;
+
+/*==================================================================================================
+                            INTERNAL FUNCTION IMPLEMENTATION
+==================================================================================================*/
+int MsgAlarmCB(int alarmId, void *pUserParam)
+{
+       MSG_DEBUG("MsgAlarmCB is called. alarmId [%d]", alarmId);
+
+       callBackMap::iterator it = alarmCBMap.find(alarmId);
+
+       if (it == alarmCBMap.end()) {
+               MSG_DEBUG("alarmId is not found.");
+       } else {
+               msg_alarm_cb alarmCBfunction = it->second;
+               if (alarmCBfunction)
+                       alarmCBfunction(alarmId);
+
+               alarmCBMap.erase(it);
+       }
+
+       return 0;
+}
+
+
+msg_error_t MsgAlarmInit()
+{
+       MSG_BEGIN();
+
+       alarmCBMap.clear();
+
+       int retval = alarmmgr_init("msg-service-tools");
+       if (retval != ALARMMGR_RESULT_SUCCESS) {
+               MSG_DEBUG("alarmmgr_init error [%d]", retval);
+               return MSG_ERR_UNKNOWN;
+       }
+
+       retval = alarmmgr_set_cb(MsgAlarmCB, NULL);
+       if (retval != ALARMMGR_RESULT_SUCCESS) MSG_DEBUG("alarmmgr_set_cb() [%d]", retval);
+
+       alarmInit = true;
+
+       MSG_END();
+       return MSG_SUCCESS;
+}
+
+/*==================================================================================================
+                            FUNCTION IMPLEMENTATION
+==================================================================================================*/
+msg_error_t MsgAlarmRegistration(struct tm *timeInfo, msg_alarm_cb userCB, int *alarmId)
+{
+       MSG_BEGIN();
+
+       if (!alarmInit) {
+               MSG_DEBUG("alarm manager is not initialized. Retry once.");
+               MsgAlarmInit();
+               if (!alarmInit) {
+                       MSG_DEBUG("alarm manager is still not initialized. So return error.");
+                       return MSG_ERR_UNKNOWN;
+               }
+       }
+
+       if (timeInfo == NULL || alarmId == NULL) {
+               MSG_DEBUG("(timeInfo == NULL || alarmId == NULL)");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       *alarmId = 0;
+       alarm_info_t* alarm_info = NULL;
+       alarm_id_t      alarm_id = -1;
+       alarm_date_t    target_time;
+
+       int retval = ALARMMGR_RESULT_SUCCESS;
+
+       alarm_info = alarmmgr_create_alarm();
+       if (alarm_info == NULL) {
+               MSG_DEBUG("alarmmgr_create_alarm error.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       target_time.year = timeInfo->tm_year + 1900;
+       target_time.month = timeInfo->tm_mon + 1;
+       target_time.day = timeInfo->tm_mday;
+       target_time.hour = timeInfo->tm_hour;
+       target_time.min = timeInfo->tm_min;
+       target_time.sec = timeInfo->tm_sec;
+
+       MSG_DEBUG( "Alarm Time : [%d-%d-%d %d:%d:%d] ",
+                       target_time.year, target_time.month, target_time.day,
+                       target_time.hour, target_time.min, target_time.sec);
+
+       retval = alarmmgr_set_time(alarm_info, target_time);
+       if (retval != ALARMMGR_RESULT_SUCCESS) MSG_DEBUG("alarmmgr_set_time ret[%d]", retval);
+       retval = alarmmgr_set_repeat_mode(alarm_info, ALARM_REPEAT_MODE_ONCE, 0);
+       if (retval != ALARMMGR_RESULT_SUCCESS) MSG_DEBUG("alarmmgr_set_repeat_mode ret[%d]", retval);
+       retval = alarmmgr_set_type(alarm_info, ALARM_TYPE_DEFAULT);
+       if (retval != ALARMMGR_RESULT_SUCCESS) MSG_DEBUG("alarmmgr_set_type ret[%d]", retval);
+       retval = alarmmgr_add_alarm_with_localtime(alarm_info, NULL, &alarm_id);
+       MSG_DEBUG("alarmmgr_add_alarm_with_localtime ret[%d], alarm_id[%d]", retval, alarm_id);
+
+       retval = alarmmgr_free_alarm(alarm_info);
+       if (retval != ALARMMGR_RESULT_SUCCESS) MSG_DEBUG("alarmmgr_free_alarm ret[%d]", retval);
+
+       *alarmId = (int)alarm_id;
+
+       alarmCBMap[*alarmId] = userCB;
+
+       MSG_END();
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgAlarmRemove(int alarmId)
+{
+       MSG_BEGIN();
+
+       if (!alarmInit) {
+               MSG_DEBUG("alarm manager is not initialized. Retry once.");
+               MsgAlarmInit();
+               if (!alarmInit) {
+                       MSG_DEBUG("alarm manager is still not initialized. So return error.");
+                       return MSG_ERR_UNKNOWN;
+               }
+       }
+
+       if (alarmmgr_remove_alarm(alarmId) != ALARMMGR_RESULT_SUCCESS) {
+               MSG_DEBUG("alarmmgr_remove_alarm faild.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       MSG_END();
+       return MSG_SUCCESS;
+}
diff --git a/externals/MsgDevicedWrapper.cpp b/externals/MsgDevicedWrapper.cpp
new file mode 100644 (file)
index 0000000..005aa77
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+
+#include <dd-display.h>
+
+#include "MsgDebug.h"
+#include "MsgMutex.h"
+#include "MsgGconfWrapper.h"
+#include "MsgDevicedWrapper.h"
+
+int g_lock_cnt = 0;
+Mutex mx;
+
+void MsgDisplayLock()
+{
+       MSG_BEGIN();
+
+       int ret = 0;
+
+       mx.lock();
+
+       if (g_lock_cnt <= 0) {
+               ret = display_lock_state(LCD_OFF, STAY_CUR_STATE, 0);
+               if (ret < 0) {
+                       MSG_DEBUG("display_lock_state() is failed [%d]", ret);
+               }
+       }
+
+       g_lock_cnt++;
+
+       mx.unlock();
+
+       MSG_DEBUG("Display lock count = [%d]", g_lock_cnt);
+
+       MSG_END();
+}
+
+
+void MsgDisplayUnlock()
+{
+       MSG_BEGIN();
+
+       int ret = 0;
+
+       mx.lock();
+
+       g_lock_cnt--;
+
+       MSG_DEBUG("Display lock count = [%d]", g_lock_cnt);
+
+       if (g_lock_cnt <= 0) {
+               ret = display_unlock_state(LCD_OFF, PM_RESET_TIMER);
+               if (ret < 0) {
+                       MSG_DEBUG("display_lock_state() is failed [%d]", ret);
+               }
+       }
+
+       mx.unlock();
+
+       MSG_END();
+}
+
+
+void MsgChangePmState()
+{
+       MSG_BEGIN();
+       int callStatus = 0;
+
+       callStatus = MsgSettingGetInt(VCONFKEY_CALL_STATE);
+       MSG_DEBUG("Call Status = %d", callStatus);
+
+       if (callStatus > VCONFKEY_CALL_OFF && callStatus < VCONFKEY_CALL_STATE_MAX) {
+               MSG_DEBUG("Call is activated. Do not turn on the lcd.");
+       } else {
+               MSG_DEBUG("Call is not activated. Turn on the lcd.");
+               display_change_state(LCD_NORMAL);
+       }
+
+       MSG_END();
+}
diff --git a/externals/MsgLbs.cpp b/externals/MsgLbs.cpp
new file mode 100755 (executable)
index 0000000..7ffe63d
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+
+#include "MsgDebug.h"
+
+extern "C"
+{
+       #include <lbs_agps.h>
+}
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+
+
+void MsgLbsSms(const char *msgBody, int msgSize) {
+
+       int ret = LBS_AGPS_ERROR_NONE;
+
+       ret = lbs_agps_sms(msgBody, msgSize);
+
+       if (ret != LBS_AGPS_ERROR_NONE)
+               MSG_DEBUG("lbs_agps_sms failed. [%d]", ret);
+}
+
+
+void MsgLbsWapPush(const char *pushHeader, const char *pushBody, int pushBodySize) {
+
+       int ret = LBS_AGPS_ERROR_NONE;
+
+       ret = lbs_agps_wap_push(pushHeader, pushBody, pushBodySize);
+
+       if (ret != LBS_AGPS_ERROR_NONE)
+               MSG_DEBUG("lbs_agps_wap_push failed. [%d]", ret);
+}
diff --git a/externals/MsgNotificationWrapper.cpp b/externals/MsgNotificationWrapper.cpp
new file mode 100755 (executable)
index 0000000..01e781e
--- /dev/null
@@ -0,0 +1,2839 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+
+#include "MsgDebug.h"
+#include "MsgCppTypes.h"
+#include "MsgDrmWrapper.h"
+#include "MsgContact.h"
+#include "MsgStorageTypes.h"
+#include "MsgUtilFile.h"
+#include "MsgUtilFunction.h"
+#include "MsgUtilStorage.h"
+#include "MsgAlarm.h"
+#include "MsgGconfWrapper.h"
+#include "MsgNotificationWrapper.h"
+#include "MsgSoundPlayer.h"
+#include "MsgDevicedWrapper.h"
+#include <libintl.h>
+#include <locale.h>
+#include <stdarg.h>
+
+extern "C"
+{
+#include <app_control.h>
+#include <notification.h>
+#include <notification_internal.h>
+#include <feedback.h>
+#include <badge.h>
+}
+
+
+/*======================================================================================*/
+/*                                                             VARIABLES AND STRUCTURES                                                                */
+/*======================================================================================*/
+
+int g_alarmId = 0;
+bool bFeedbackInit;
+
+GList *msg_report_notification_list;
+
+
+typedef struct _msg_noti_info_s
+{
+       msg_notification_type_t                 type;
+       int                     id;
+       int                     layout;
+       int                     count;
+       time_t          time;
+       char            sender[MSG_NOTI_TEXT_LEN_S];
+       char            text[MSG_NOTI_TEXT_LEN];
+       char            number[MSG_NOTI_TEXT_LEN_S];
+       char            imagePath[MAX_IMAGE_PATH_LEN + 1];              /**< Indicates the image path of contact. */
+       int                     applist;
+       app_control_h           svc_h;
+       msg_message_id_t        msg_id;
+       unsigned char           extra_data;
+       int             sim_idx;
+}MSG_NOTI_INFO_S;
+
+typedef struct _report_notification_s
+{
+       int priv_id;
+       char addressVal[MAX_ADDRESS_VAL_LEN+1];
+}report_notification_s;
+
+/*======================================================================================*/
+/*                                                                     FUNCTION DEFINE                                                                         */
+/*======================================================================================*/
+
+notification_h getHandle(int *noti_id);
+
+int getPrivId(msg_notification_type_t noti_type, int sim_idx);
+void updatePrivId(msg_notification_type_t noti_type, int noti_id, int sim_idx);
+
+void createInfoData(MSG_NOTI_INFO_S *noti_info, MSG_MESSAGE_INFO_S *msg_info); // For addNoti()
+void createInfoData(MSG_NOTI_INFO_S *noti_info, bool bTicker); // For refreshNoti()
+void clearInfoData(notification_h noti_h, MSG_NOTI_INFO_S *noti_info);
+
+msg_error_t getLatestMsgInfo(MSG_NOTI_INFO_S *noti_info, bool isForInstantMessage);
+
+void setProperty(notification_h noti_h, MSG_NOTI_INFO_S *noti_info);
+void setTextDomain(notification_h noti_h, msg_notification_type_t noti_type);
+void setText(notification_h noti_h, MSG_NOTI_INFO_S *noti_info);
+void setIcon(notification_h noti_h, MSG_NOTI_INFO_S *noti_info);
+void setPkgName(notification_h noti_h, msg_notification_type_t noti_type);
+void setSoundAndVibration(notification_h noti_h, char *addressVal, bool bVoiceMail);
+
+void setNotification(notification_h noti_h, MSG_NOTI_INFO_S *noti_info, bool bFeedback);
+
+void MsgDeleteNotiCb(void *data);
+void MsgRefreshNotiCb(void *data);
+
+bool isExistAddressInReportTable(const char *addr);
+
+// Wrapper
+void createServiceHandle(app_control_h *svc_h);
+void setServiceAppId(app_control_h svc_h, const char* app_id);
+void setServiceOperation(app_control_h svc_h, const char* operation);
+void addServiceExtraData(app_control_h svc_h, const char* bundle_key, const char* bundle_val);
+void addServiceExtraData(app_control_h svc_h, const char* bundle_key, int bundle_val);
+void setServicePackageName(app_control_h svc_h, const char* pkg_name);
+void sendServicelaunchRequest(app_control_h svc_h, app_control_reply_cb callback, void *user_data);
+
+void setNotiTextDomain(notification_h noti_h, const char *pkg_name, const char *loc_dir);
+void setNotiText(notification_h noti_h, notification_text_type_e type, const char *text, const char *key);
+void setNotiTimeToText(notification_h noti_h, notification_text_type_e type, time_t time);
+void setNotiTime(notification_h noti_h, time_t time);
+void setNotiImage(notification_h noti_h, notification_image_type_e type, const char *image_path);
+void setNotiSound(notification_h noti_h, notification_sound_type_e type, const char *path);
+void setNotiVibration(notification_h noti_h, notification_vibration_type_e type, const char *path);
+void setFlashNoti(void);
+
+
+// Alarm
+void MsgNotiSoundRepeatAlarmCB(int alarmId);
+void MsgSoundCreateRepeatAlarm(int RepeatTime);
+void MsgSoundSetRepeatAlarm();
+
+void sendMsgReplyPopup(MSG_NOTI_INFO_S *noti_info);
+
+/*======================================================================================*/
+/*                                                             FUNCTION IMPLEMENTATION                                                                 */
+/*======================================================================================*/
+
+
+msg_error_t MsgInsertNotification(MSG_MESSAGE_INFO_S *msg_info)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+#ifndef MSG_WEARABLE_PROFILE
+
+       msg_notification_type_t noti_type;
+
+       switch (msg_info->msgType.subType)
+       {
+#ifdef MSG_NOTI_INTEGRATION
+               case MSG_NORMAL_SMS :
+               case MSG_CB_SMS :
+                       {
+                               if (msg_info->msgType.classType == MSG_CLASS_0) {
+                                       noti_type = MSG_NOTI_TYPE_CLASS0;
+                               } else {
+                                       noti_type = MSG_NOTI_TYPE_NORMAL;
+                               }
+                       }
+                       break;
+#else
+               case MSG_NORMAL_SMS :
+                       {
+                               if (msg_info->msgType.classType == MSG_CLASS_0) {
+                                       noti_type = MSG_NOTI_TYPE_CLASS0;
+                               } else if (msg_info->msgType.classType == MSG_CLASS_2) {
+                                       noti_type = MSG_NOTI_TYPE_SIM;
+                               } else {
+                                       noti_type = MSG_NOTI_TYPE_NORMAL;
+                               }
+                       }
+                       break;
+               case MSG_CB_SMS :
+                       noti_type = MSG_NOTI_TYPE_CB;
+                       break;
+#endif
+               case MSG_MWI_FAX_SMS :
+               case MSG_MWI_EMAIL_SMS :
+               case MSG_MWI_OTHER_SMS :
+                       noti_type = MSG_NOTI_TYPE_MWI;
+                       break;
+               case MSG_MWI_VOICE_SMS :
+                       noti_type = MSG_NOTI_TYPE_VOICE_1;
+                       break;
+               case MSG_MWI_VOICE2_SMS :
+                       noti_type = MSG_NOTI_TYPE_VOICE_2;
+                       break;
+               case MSG_STATUS_REPORT_SMS :
+                       noti_type = MSG_NOTI_TYPE_SMS_DELIVERY_REPORT;
+                       break;
+               case MSG_DELIVERYIND_MMS :
+                       noti_type = MSG_NOTI_TYPE_MMS_DELIVERY_REPORT;
+                       break;
+               case MSG_READORGIND_MMS :
+                       noti_type = MSG_NOTI_TYPE_MMS_READ_REPORT;
+                       break;
+               default :
+               {
+#ifdef MSG_NOTI_INTEGRATION
+                       noti_type = MSG_NOTI_TYPE_NORMAL;
+#else
+                       if (msg_info->msgType.classType == MSG_CLASS_2) {
+                               noti_type = MSG_NOTI_TYPE_SIM;
+                       } else {
+                               noti_type = MSG_NOTI_TYPE_NORMAL;
+                       }
+#endif
+               }
+               break;
+       }
+
+       MSG_DEBUG("Notification type = [%d]", noti_type);
+
+       switch (noti_type)
+       {
+               case MSG_NOTI_TYPE_NORMAL :
+               case MSG_NOTI_TYPE_SIM :
+               case MSG_NOTI_TYPE_CB :
+                       err = MsgRefreshNotification(noti_type, true, true);
+                       break;
+               case MSG_NOTI_TYPE_SMS_DELIVERY_REPORT :
+               case MSG_NOTI_TYPE_MMS_DELIVERY_REPORT :
+               case MSG_NOTI_TYPE_MMS_READ_REPORT :
+                       err = MsgAddReportNotification(noti_type, msg_info);
+                       break;
+               case MSG_NOTI_TYPE_VOICE_1 :
+               case MSG_NOTI_TYPE_VOICE_2 :
+               case MSG_NOTI_TYPE_MWI :
+               case MSG_NOTI_TYPE_CLASS0 :
+                       err = MsgAddNotification(noti_type, msg_info);
+                       break;
+               default :
+                       MSG_DEBUG("No matching type [%d]");
+                       break;
+       }
+
+#endif // MSG_WEARABLE_PROFILE
+
+       MSG_END();
+
+       return err;
+
+}
+
+msg_error_t MsgDeleteReportNotification(const char *addr)
+{
+       MSG_BEGIN();
+
+       msg_error_t msg_err = MSG_SUCCESS;
+
+#ifndef MSG_WEARABLE_PROFILE
+
+       notification_h noti_h = NULL;
+       bool bNotification = true;
+
+       MSG_NOTI_INFO_S noti_info;
+       memset(&noti_info, 0x00, sizeof(MSG_NOTI_INFO_S));
+
+       if (MsgSettingGetBool(MSG_SETTING_NOTIFICATION, &bNotification) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgSettingGetBool is failed.");
+       }
+
+       if (bNotification == false) {
+               MSG_DEBUG("Msg Alert notification is off.");
+               return msg_err;
+       }
+
+       char normalAddr[MAX_ADDRESS_VAL_LEN+1];
+       unsigned int list_length = g_list_length(msg_report_notification_list);
+       bool isDelete = false;
+
+       MSG_DEBUG("list length [%d]", list_length);
+
+       if (list_length > 0) {
+               GList *iter = g_list_first(msg_report_notification_list);
+
+               while (iter != NULL)
+               {
+                       isDelete = false;
+                       report_notification_s *info = (report_notification_s*)(iter->data);
+                       if (info == NULL) {
+                               MSG_DEBUG("info is NULL!");
+                               return MSG_ERR_UNKNOWN;
+                       }
+
+                       MSG_SEC_DEBUG("list data = [priv_id = %d address = %s]", info->priv_id, info->addressVal);
+
+                       noti_h = notification_load(NULL, info->priv_id);
+                       if (noti_h == NULL)
+                       {
+                               MSG_DEBUG("notification with priv_id [%d] is NULL", info->priv_id);
+                               isDelete = true;
+                       } else {
+                               memset(normalAddr, 0x00, sizeof(normalAddr));
+                               MsgConvertNumber(info->addressVal, normalAddr, sizeof(normalAddr));
+                               MSG_SEC_DEBUG("normalized number = %s", normalAddr);
+
+                               if (g_str_has_suffix(addr, normalAddr)) {
+                                       if (notification_delete(noti_h) == NOTIFICATION_ERROR_NONE) {
+                                               MSG_SEC_DEBUG("delete report notification address [%s]", info->addressVal);
+                                               isDelete = true;
+                                       }
+                                       else {
+                                               MSG_DEBUG("delete notification failed");
+                                       }
+                               }
+
+                               notification_free(noti_h);
+                               noti_h = NULL;
+                       }
+
+                       iter = g_list_next(iter);
+
+                       if (isDelete) {
+                               msg_report_notification_list = g_list_remove(msg_report_notification_list, (void *)info);
+                               if(info) {
+                                       delete info;
+                                       info = NULL;
+                               }
+                       }
+               }
+       }
+
+#endif // MSG_WEARABLE_PROFILE
+
+       MSG_END();
+
+       return msg_err;
+}
+
+msg_error_t MsgAddReportNotification(msg_notification_type_t noti_type, MSG_MESSAGE_INFO_S *msg_info)
+{
+       msg_error_t msg_err = MSG_SUCCESS;
+#ifndef MSG_WEARABLE_PROFILE
+       notification_h noti_h = NULL;
+
+       MSG_NOTI_INFO_S noti_info;
+       memset(&noti_info, 0x00, sizeof(MSG_NOTI_INFO_S));
+
+       report_notification_s *info = new report_notification_s;
+       memset(info, 0x00, sizeof(report_notification_s));
+
+       noti_info.type = noti_type;
+
+       createInfoData(&noti_info, msg_info);
+
+       noti_h = getHandle(&noti_info.id);
+
+       if (noti_h == NULL) {
+               MSG_DEBUG("Notification handle is NULL");
+               msg_err = MSG_ERR_NULL_POINTER;
+               goto __END_OF_REFRESH_NOTI;
+       }
+
+       setNotification(noti_h, &noti_info, true);
+
+       info->priv_id = noti_info.id;
+       snprintf(info->addressVal, sizeof(info->addressVal), "%s", msg_info->addressList->addressVal);
+       msg_report_notification_list = g_list_append(msg_report_notification_list, (void *)info);
+       MSG_SEC_DEBUG("appended list data = [priv_id = %d address = %s]", info->priv_id, info->addressVal);
+
+__END_OF_REFRESH_NOTI :
+       clearInfoData(noti_h, &noti_info);
+#endif // MSG_WEARABLE_PROFILE
+       return msg_err;
+}
+
+msg_error_t MsgRefreshNotification(msg_notification_type_t noti_type, bool bFeedback, bool bTicker)
+{
+
+       msg_error_t msg_err = MSG_SUCCESS;
+#ifndef MSG_WEARABLE_PROFILE
+       notification_h noti_h = NULL;
+       bool bNotification = true;
+       bool bReplyPopup = false;
+
+       MSG_NOTI_INFO_S noti_info;
+       memset(&noti_info, 0x00, sizeof(MSG_NOTI_INFO_S));
+
+       noti_info.type = noti_type;
+
+       noti_info.id = getPrivId(noti_info.type, -1);
+
+       msg_err = getLatestMsgInfo(&noti_info, false);
+
+       if (msg_err != MSG_SUCCESS) {
+               MSG_DEBUG("getLatestMsgInfo() err = [%d]", msg_err);
+               goto __END_OF_REFRESH_NOTI;
+       }
+
+       if (bTicker) {
+               msg_err = MsgInsertInstantMessage(noti_type);
+
+               if (msg_err != MSG_SUCCESS) {
+                       MSG_DEBUG(" MsgInsertInstantMessage() err = [%d]", msg_err);
+                       goto __END_OF_REFRESH_NOTI;
+               }
+       }
+
+       if (MsgSettingGetBool(MSG_SETTING_NOTIFICATION, &bNotification) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgSettingGetBool is failed.");
+       }
+
+       if (bNotification == false) {
+               MSG_DEBUG("Msg Alert notification is off.");
+               return msg_err;
+       }
+
+       createInfoData(&noti_info, bTicker);
+
+       noti_h = getHandle(&noti_info.id);
+
+       if (noti_h == NULL) {
+               MSG_DEBUG("Notification handle is NULL");
+               msg_err = MSG_ERR_NULL_POINTER;
+               goto __END_OF_REFRESH_NOTI;
+       }
+
+       setNotification(noti_h, &noti_info, bFeedback);
+
+       if (MsgSettingGetBool(VCONFKEY_MESSAGE_POPUP_DISPLAY_ENABLE , &bReplyPopup) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgSettingGetBool is failed.");
+       }
+
+       if (bReplyPopup == true && bFeedback == true && noti_info.type == MSG_NOTI_TYPE_NORMAL) {
+               MSG_DEBUG("Msg reply popup is on.");
+               sendMsgReplyPopup(&noti_info);
+       }
+
+__END_OF_REFRESH_NOTI :
+       clearInfoData(noti_h, &noti_info);
+#endif // MSG_WEARABLE_PROFILE
+       return msg_err;
+}
+
+
+msg_error_t MsgAddNotification(msg_notification_type_t noti_type, MSG_MESSAGE_INFO_S *msg_info)
+{
+       msg_error_t msg_err = MSG_SUCCESS;
+#ifndef MSG_WEARABLE_PROFILE
+       notification_h noti_h = NULL;
+
+       MSG_NOTI_INFO_S noti_info = {0,};
+
+       noti_info.type = noti_type;
+
+       createInfoData(&noti_info, msg_info);
+
+       noti_h = getHandle(&noti_info.id);
+
+       if (noti_h == NULL) {
+               MSG_DEBUG("Notification handle is NULL");
+               msg_err = MSG_ERR_NULL_POINTER;
+               goto __END_OF_ADD_NOTI;
+       }
+
+       setNotification(noti_h, &noti_info, true);
+
+__END_OF_ADD_NOTI :
+       clearInfoData(noti_h, &noti_info);
+#endif // MSG_WEARABLE_PROFILE
+       return msg_err;
+}
+
+
+void MsgRefreshAllNotification(bool bWithSimNoti, bool bFeedback, bool bTickerNoti)
+{
+       MSG_BEGIN();
+
+#ifndef MSG_WEARABLE_PROFILE
+       msg_error_t err = MSG_SUCCESS;
+
+//     MsgDeleteNotification(MSG_NOTI_TYPE_SIM);
+
+#ifdef MSG_NOTI_INTEGRATION
+       err = MsgRefreshNotification(MSG_NOTI_TYPE_NORMAL, bFeedback, bTickerNoti);
+       if (err != MSG_SUCCESS)
+               MSG_DEBUG("refreshNoti is failed, [type=%d, err=%d]", MSG_NOTI_TYPE_NORMAL, err);
+#else
+       err = MsgRefreshNotification(MSG_NOTI_TYPE_NORMAL, bFeedback, bTickerNoti);
+       if (err != MSG_SUCCESS)
+               MSG_DEBUG("refreshNoti is failed, [type=%d, err=%d]", MSG_NOTI_TYPE_NORMAL, err);
+
+       err = MsgRefreshNotification(MSG_NOTI_TYPE_CB, bFeedback, bTickerNoti);
+       if (err != MSG_SUCCESS)
+               MSG_DEBUG("refreshNoti is failed, [type=%d, err=%d]", MSG_NOTI_TYPE_CB, err);
+
+       if (bWithSimNoti) {
+               err = MsgRefreshNotification(MSG_NOTI_TYPE_SIM, bFeedback, bTickerNoti);
+               if (err != MSG_SUCCESS)
+                       MSG_DEBUG("refreshNoti is failed, [type=%d, err=%d]", MSG_NOTI_TYPE_SIM, err);
+       }
+#endif
+
+       err = MsgRefreshNotification(MSG_NOTI_TYPE_FAILED, bFeedback, bTickerNoti);
+       if (err != MSG_SUCCESS)
+               MSG_DEBUG("refreshNoti is failed, [type=%d, err=%d]", MSG_NOTI_TYPE_FAILED, err);
+
+#endif // MSG_WEARABLE_PROFILE
+       MSG_END();
+}
+
+
+void MsgDeleteNotification(msg_notification_type_t noti_type, int simIndex)
+{
+#ifndef MSG_WEARABLE_PROFILE
+       int noti_err = NOTIFICATION_ERROR_NONE;
+
+       if (noti_type == MSG_NOTI_TYPE_ALL) {
+
+               noti_err = notification_delete_all_by_type(MSG_DEFAULT_APP_ID, NOTIFICATION_TYPE_NOTI);
+
+       } else if (noti_type == MSG_NOTI_TYPE_VOICE_1 || noti_type == MSG_NOTI_TYPE_VOICE_2 || noti_type == MSG_NOTI_TYPE_SIM) {
+               int notiId = 0;
+
+               notiId = getPrivId(noti_type, simIndex);
+               MSG_DEBUG("deleted notification ID = [%d] Type = [%d]", notiId, noti_type);
+
+               if (notiId > 0)
+                       noti_err = notification_delete_by_priv_id(NULL, NOTIFICATION_TYPE_NOTI, notiId);
+
+       } else {
+               MSG_DEBUG("No matching type [%d]", noti_type);
+       }
+
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_delete_all_by_type noti_err [%d]", noti_err);
+       }
+
+       updatePrivId(noti_type, 0, simIndex);
+#endif // MSG_WEARABLE_PROFILE
+}
+
+
+bool isExistAddressInReportTable(const char *addr)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+       char normalAddr[MAX_ADDRESS_VAL_LEN+1];
+       MsgDbHandler *dbHandle = getDbHandle();
+       int rowCnt = 0;
+
+       memset(normalAddr, 0x00, sizeof(normalAddr));
+       MsgConvertNumber(addr, normalAddr, sizeof(normalAddr));
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT * FROM %s WHERE ADDRESS_VAL LIKE '%%%%%s'", MSGFW_SMS_REPORT_TABLE_NAME, normalAddr);
+       if (dbHandle->getTable(sqlQuery, &rowCnt, NULL) == MSG_SUCCESS) {
+               dbHandle->freeTable();
+               return true;
+       }
+
+       dbHandle->freeTable();
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT * FROM %s WHERE ADDRESS_VAL LIKE '%%%%%s'", MSGFW_REPORT_TABLE_NAME, normalAddr);
+       if (dbHandle->getTable(sqlQuery, &rowCnt, NULL) == MSG_SUCCESS) {
+               dbHandle->freeTable();
+               return true;
+       }
+
+       dbHandle->freeTable();
+
+       return false;
+}
+
+
+void MsgInitReportNotiList()
+{
+       MSG_BEGIN();
+#ifndef MSG_WEARABLE_PROFILE
+       msg_report_notification_list = NULL;
+
+       notification_h noti = NULL;
+       notification_list_h noti_list = NULL;
+       notification_list_h head_noti_list = NULL;
+       int noti_err = NOTIFICATION_ERROR_NONE;
+       bundle *b = NULL;
+
+       noti_err = notification_get_list(NOTIFICATION_TYPE_NONE, -1, &noti_list);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("notification_get_list() is failed!!");
+               return;
+       }
+
+       head_noti_list = noti_list;
+
+       while (noti_list != NULL) {
+               noti = notification_list_get_data(noti_list);
+
+               char tempAddr[MAX_ADDRESS_VAL_LEN+1];
+               memset(tempAddr, 0x00, sizeof(tempAddr));
+
+               noti_err  = notification_get_execute_option(noti, NOTIFICATION_EXECUTE_TYPE_SINGLE_LAUNCH, NULL, &b);
+               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                       MSG_DEBUG("notification_get_excute_option() failed!!");
+                       break;
+               }
+
+               const char *bundle_addr = bundle_get_val(b, "address");
+
+               if (bundle_addr != NULL) {
+                       if (isExistAddressInReportTable(bundle_addr)) {
+                               report_notification_s *info = new report_notification_s;
+                               memset(info, 0x00, sizeof(report_notification_s));
+
+                               notification_get_id(noti, NULL, &(info->priv_id));
+                               snprintf(info->addressVal, sizeof(info->addressVal), "%s", bundle_addr);
+
+                               msg_report_notification_list = g_list_append(msg_report_notification_list, (void *)info);
+                               MSG_SEC_DEBUG("appended list data = [priv_id = %d address = %s]", info->priv_id, info->addressVal);
+                       }
+               }
+
+               noti_list = notification_list_get_next(noti_list);
+       }
+
+       if (head_noti_list)
+               notification_free_list(head_noti_list);
+
+#endif // MSG_WEARABLE_PROFILE
+       MSG_END();
+}
+
+
+msg_error_t MsgInitNoti()
+{
+#ifndef MSG_WEARABLE_PROFILE
+       bool bNotiSvcReady = false;
+
+       bNotiSvcReady = notification_is_service_ready();
+
+       if (bNotiSvcReady == true) {
+               MSG_DEBUG("Notification server is available");
+#ifndef MSG_NOTI_INTEGRATION
+               MsgDeleteNotification(MSG_NOTI_TYPE_SIM, -1);
+#endif
+               MsgRefreshAllNotification(false, true, true);           // On Booting
+               MsgInitReportNotiList();
+       }
+       else {
+               MSG_DEBUG("Notification server is not available. Init is defered");
+#ifndef MSG_NOTI_INTEGRATION
+               MSG_NOTI_INFO_S *delNotiInfo = (MSG_NOTI_INFO_S *)calloc(1, sizeof(MSG_NOTI_INFO_S));
+               if (delNotiInfo) {
+                       delNotiInfo->type = MSG_NOTI_TYPE_SIM;
+                       delNotiInfo->sim_idx = -1;
+               }
+               notification_add_deferred_task(MsgDeleteNotiCb, (void *)delNotiInfo);
+#endif
+               notification_add_deferred_task(MsgRefreshNotiCb, (void *)NULL);
+       }
+
+#endif // MSG_WEARABLE_PROFILE
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgDeleteNoti(msg_notification_type_t noti_type, int simIndex)
+{
+#ifndef MSG_WEARABLE_PROFILE
+       bool bNotiSvcReady = false;
+
+       MSG_NOTI_INFO_S *delNotiInfo = (MSG_NOTI_INFO_S *)calloc(1, sizeof(MSG_NOTI_INFO_S));
+
+       if (delNotiInfo) {
+               delNotiInfo->type = noti_type;
+               delNotiInfo->sim_idx = simIndex;
+       }
+
+       bNotiSvcReady = notification_is_service_ready();
+
+       if (bNotiSvcReady == true) {
+               MSG_DEBUG("Notification server is available");
+               MsgDeleteNotiCb((void *)delNotiInfo);
+       } else {
+               MSG_DEBUG("Notification server is not available. Delete is defered");
+               notification_add_deferred_task(MsgDeleteNotiCb, (void *)delNotiInfo);
+       }
+#endif // MSG_WEARABLE_PROFILE
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgInsertTicker(const char* pTickerMsg, const char* pLocaleTickerMsg, bool bPlayFeedback, int msgId)
+{
+#ifndef MSG_WEARABLE_PROFILE
+       MSG_DEBUG("pTickerMsg=[%s], pLocaleTickerMsg=[%s]", pTickerMsg, pLocaleTickerMsg);
+       MSG_DEBUG("play feedback=[%d], msgId=[%d]", bPlayFeedback, msgId);
+
+       MsgChangePmState();
+
+       char *notiMsg = NULL;
+       bool bTicker = false;
+
+       notiMsg = getTranslateText(MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR, pLocaleTickerMsg);
+       MSG_DEBUG("notiMsg %s", notiMsg);
+
+       if (g_strcmp0(pLocaleTickerMsg, SMS_MESSAGE_SENDING_FAIL) != 0 &&
+               g_strcmp0(pLocaleTickerMsg, SENDING_MULTIMEDIA_MESSAGE_FAILED) != 0 &&
+               g_strcmp0(pLocaleTickerMsg, MESSAGE_RETRIEVED) != 0) {
+               if (g_strcmp0(pLocaleTickerMsg, notiMsg) == 0) {
+                       notification_status_message_post(pTickerMsg);
+               } else {
+                       notification_status_message_post(notiMsg);
+               }
+       } else {
+               //Show ticker popup for sending failed msg.
+               bTicker = true;
+       }
+
+       if (notiMsg) {
+               free(notiMsg);
+               notiMsg = NULL;
+       }
+
+       if (bPlayFeedback) {
+               if (msgId > 0 && \
+                       (g_strcmp0(pLocaleTickerMsg, SMS_MESSAGE_SENDING_FAIL) == 0 || g_strcmp0(pLocaleTickerMsg, SENDING_MULTIMEDIA_MESSAGE_FAILED) == 0))
+               {
+                       msg_error_t err = MSG_SUCCESS;
+                       err = MsgRefreshNotification(MSG_NOTI_TYPE_FAILED, true, bTicker);
+                       if (err != MSG_SUCCESS) {
+                               MSG_DEBUG("MsgRefreshFailedNoti err=[%d]", err);
+                       }
+               } else if (g_strcmp0(pLocaleTickerMsg, SMS_MESSAGE_SIM_MESSAGE_FULL) == 0) {
+                       msg_error_t err = MSG_SUCCESS;
+                       err = MsgRefreshNotification(MSG_NOTI_TYPE_SIM_FULL, true, false);
+                       if (err != MSG_SUCCESS) {
+                               MSG_DEBUG("MsgRefreshSimFullNoti err=[%d]", err);
+                       }
+               }
+               else {
+                       MsgSoundPlayer::instance()->MsgSoundPlayStart(NULL, MSG_SOUND_PLAY_DEFAULT);
+               }
+       }
+#endif // MSG_WEARABLE_PROFILE
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgInsertBadge(unsigned int unreadMsgCnt)
+{
+#ifndef MSG_WEARABLE_PROFILE
+       MSG_DEBUG("Start to set badge to [%d].", unreadMsgCnt);
+
+       int err = BADGE_ERROR_NONE;
+       bool exist = false;
+
+       err = badge_is_existing(MSG_DEFAULT_APP_ID, &exist);
+
+       if (err != BADGE_ERROR_NONE) {
+               MSG_DEBUG("Fail to badge_is_existing : %d", err);
+               return MSG_ERR_UNKNOWN;
+       }
+
+       if (!exist) {
+               /* create badge */
+               err = badge_new(MSG_DEFAULT_APP_ID);
+               if (err != BADGE_ERROR_NONE) {
+                       MSG_DEBUG("Fail to badge_new : %d", err);
+                       return MSG_ERR_UNKNOWN;
+               }
+       }
+
+       err = badge_set_count(MSG_DEFAULT_APP_ID, unreadMsgCnt);
+
+       if (err != BADGE_ERROR_NONE) {
+               MSG_DEBUG("Fail to badge_set_count : %d", err);
+               return MSG_ERR_UNKNOWN;
+       }
+
+#endif // MSG_WEARABLE_PROFILE
+       return MSG_SUCCESS;
+}
+
+
+void MsgRefreshNotiCb(void *data)
+{
+       MsgRefreshAllNotification(false, true, true);
+       MsgInitReportNotiList();
+
+       if (data) {
+               free(data);
+               data = NULL;
+       }
+
+       return;
+}
+
+
+void MsgDeleteNotiCb(void *data)
+{
+       if (data) {
+               MSG_NOTI_INFO_S *delNotiInfo = (MSG_NOTI_INFO_S *)data;
+
+               MsgDeleteNotification(delNotiInfo->type, delNotiInfo->sim_idx);
+
+               free(data);
+               data = NULL;
+       }
+
+       return;
+}
+
+
+notification_h getHandle(int *noti_id)
+{
+       notification_h noti_h = NULL;
+
+       if (*noti_id > 0) {
+               MSG_DEBUG("Notification load");
+               noti_h = notification_load(NULL, *noti_id);
+               if (noti_h == NULL)
+                       MSG_DEBUG("notification_load is failed.");
+       }
+
+       if (noti_h == NULL) {
+               MSG_DEBUG("Notification create");
+               noti_h = notification_create(NOTIFICATION_TYPE_NOTI);
+               if (noti_h == NULL) {
+                       MSG_DEBUG("notification_create is failed.");
+                       return NULL;
+               }
+
+               *noti_id = 0;
+       }
+
+       return noti_h;
+}
+
+
+int getPrivId(msg_notification_type_t noti_type, int sim_idx)
+{
+       MSG_BEGIN();
+
+       int noti_id = 0;
+
+       switch (noti_type)
+       {
+#ifdef MSG_NOTI_INTEGRATION
+               case MSG_NOTI_TYPE_NORMAL :
+               case MSG_NOTI_TYPE_SIM :
+               case MSG_NOTI_TYPE_CB :
+                       noti_id = MsgSettingGetInt(NOTIFICATION_PRIV_ID);
+                       break;
+#else
+               case MSG_NOTI_TYPE_NORMAL :
+                       noti_id = MsgSettingGetInt(NOTIFICATION_PRIV_ID);
+                       break;
+               case MSG_NOTI_TYPE_SIM :
+                       noti_id = MsgSettingGetInt(SIM_MSG_NOTI_PRIV_ID);
+                       break;
+               case MSG_NOTI_TYPE_CB :
+                       noti_id = MsgSettingGetInt(CB_NOTI_PRIV_ID);
+                       break;
+#endif
+               case MSG_NOTI_TYPE_FAILED :
+                       noti_id = MsgSettingGetInt(MSG_SENTFAIL_NOTI_ID);
+                       break;
+               case MSG_NOTI_TYPE_VOICE_1 :
+                       {
+                               char keyName[MAX_VCONFKEY_NAME_LEN] = {0,};
+                               snprintf(keyName, sizeof(keyName), "%s/%d", VOICE_NOTI_ID_1, sim_idx);
+                               noti_id = MsgSettingGetInt(keyName);
+                       }
+                       break;
+               case MSG_NOTI_TYPE_VOICE_2 :
+                       {
+                               char keyName[MAX_VCONFKEY_NAME_LEN] = {0,};
+                               snprintf(keyName, sizeof(keyName), "%s/%d", VOICE_NOTI_ID_2, sim_idx);
+                               noti_id = MsgSettingGetInt(keyName);
+                       }
+                       break;
+               case MSG_NOTI_TYPE_SIM_FULL :
+                       noti_id = MsgSettingGetInt(SIM_FULL_NOTI_PRIV_ID);
+                       break;
+               default :
+                       MSG_DEBUG("No matching noti type [%d]", noti_type);
+                       break;
+       }
+
+       MSG_DEBUG("Get noti type = %d, id = %d, sim_idx:%d", noti_type, noti_id, sim_idx);
+
+       MSG_END();
+
+       return noti_id;
+}
+
+
+void updatePrivId(msg_notification_type_t noti_type, int noti_id, int sim_idx)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       MSG_DEBUG("Update noti type = %d, id = %d, sim_idx = %d", noti_type, noti_id, sim_idx);
+
+       switch (noti_type)
+       {
+#ifdef MSG_NOTI_INTEGRATION
+               case MSG_NOTI_TYPE_NORMAL :
+               case MSG_NOTI_TYPE_SIM :
+               case MSG_NOTI_TYPE_CB :
+                       err = MsgSettingSetInt(NOTIFICATION_PRIV_ID, noti_id);
+                       break;
+#else
+               case MSG_NOTI_TYPE_NORMAL :
+                       err = MsgSettingSetInt(NOTIFICATION_PRIV_ID, noti_id);
+                       break;
+               case MSG_NOTI_TYPE_SIM :
+                       err = MsgSettingSetInt(SIM_MSG_NOTI_PRIV_ID, noti_id);
+                       break;
+               case MSG_NOTI_TYPE_CB :
+                       err = MsgSettingSetInt(CB_NOTI_PRIV_ID, noti_id);
+                       break;
+#endif
+               case MSG_NOTI_TYPE_FAILED :
+                       err = MsgSettingSetInt(MSG_SENTFAIL_NOTI_ID, noti_id);
+                       break;
+               case MSG_NOTI_TYPE_VOICE_1 :
+                       {
+                               char keyName[MAX_VCONFKEY_NAME_LEN] = {0,};
+                               snprintf(keyName, sizeof(keyName), "%s/%d", VOICE_NOTI_ID_1, sim_idx);
+                               err = MsgSettingSetInt(keyName, noti_id);
+                       }
+                       break;
+               case MSG_NOTI_TYPE_VOICE_2 :
+                       {
+                               char keyName[MAX_VCONFKEY_NAME_LEN] = {0,};
+                               snprintf(keyName, sizeof(keyName), "%s/%d", VOICE_NOTI_ID_2, sim_idx);
+                               err = MsgSettingSetInt(keyName, noti_id);
+                       }
+                       break;
+               case MSG_NOTI_TYPE_SIM_FULL :
+                       err = MsgSettingSetInt(SIM_FULL_NOTI_PRIV_ID, noti_id);
+                       break;
+               default:
+                       MSG_DEBUG("No matching type [%d]", noti_type);
+                       break;
+       }
+
+       if (err != MSG_SUCCESS)
+               MSG_INFO("MsgSettingSetInt fail : noti type = %d, id = %d, sim_idx = %d", noti_type, noti_id, sim_idx);
+
+       MSG_END();
+}
+
+
+void createInfoData(MSG_NOTI_INFO_S *noti_info, bool bTicker)
+{
+       MSG_BEGIN();
+
+       createServiceHandle(&noti_info->svc_h);
+
+       switch (noti_info->type)
+       {
+               case MSG_NOTI_TYPE_NORMAL :
+                       {
+                               if (noti_info->count > 1) {
+                                       noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_MULTIPLE;
+                               } else {
+                                       noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_SINGLE;
+                               }
+
+                               setServiceAppId(noti_info->svc_h, MSG_DEFAULT_APP_ID);
+                               addServiceExtraData(noti_info->svc_h, "type", "new_msg");
+                               addServiceExtraData(noti_info->svc_h, "msgId", noti_info->msg_id);
+                               addServiceExtraData(noti_info->svc_h, "http://tizen.org/appcontrol/data/notification", "new_message");
+
+                               bool bReplyPopup = false;
+                               if (MsgSettingGetBool(VCONFKEY_MESSAGE_POPUP_DISPLAY_ENABLE , &bReplyPopup) != MSG_SUCCESS) {
+                                       MSG_DEBUG("MsgSettingGetBool is failed.");
+                               }
+
+                               noti_info->applist = NOTIFICATION_DISPLAY_APP_ALL^NOTIFICATION_DISPLAY_APP_TICKER;
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_CB :
+                       {
+                               if (noti_info->count > 1) {
+                                       noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_MULTIPLE;
+                               } else {
+                                       noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_SINGLE;
+                               }
+
+                               setServiceAppId(noti_info->svc_h, MSG_DEFAULT_APP_ID);
+                               addServiceExtraData(noti_info->svc_h, "type", "new_msg");
+                               addServiceExtraData(noti_info->svc_h, "msgId", noti_info->msg_id);
+
+                               if (bTicker)
+                                       noti_info->applist = NOTIFICATION_DISPLAY_APP_ALL^NOTIFICATION_DISPLAY_APP_LOCK;
+                               else
+                                       noti_info->applist = NOTIFICATION_DISPLAY_APP_NOTIFICATION_TRAY|NOTIFICATION_DISPLAY_APP_INDICATOR;
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_SIM :
+                       {
+                               if (noti_info->count > 1) {
+                                       noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_MULTIPLE;
+                               } else {
+                                       noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_SINGLE;
+                               }
+
+                               setServiceAppId(noti_info->svc_h, MSG_DEFAULT_APP_ID);
+                               addServiceExtraData(noti_info->svc_h, "type", "new_msg");
+                               addServiceExtraData(noti_info->svc_h, "msgId", noti_info->msg_id);
+
+                               if (bTicker)
+                                       noti_info->applist = NOTIFICATION_DISPLAY_APP_ALL^NOTIFICATION_DISPLAY_APP_LOCK;
+                               else
+                                       noti_info->applist = NOTIFICATION_DISPLAY_APP_NOTIFICATION_TRAY|NOTIFICATION_DISPLAY_APP_INDICATOR;
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_FAILED :
+                       {
+                               noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_SINGLE;
+
+                               setServiceAppId(noti_info->svc_h, MSG_DEFAULT_APP_ID);
+                               addServiceExtraData(noti_info->svc_h, "type", "send_failed_msg");
+                               addServiceExtraData(noti_info->svc_h, "msgId", noti_info->msg_id);
+
+                               noti_info->applist = NOTIFICATION_DISPLAY_APP_ALL^NOTIFICATION_DISPLAY_APP_TICKER^NOTIFICATION_DISPLAY_APP_LOCK;
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_SIM_FULL :
+                       {
+                               noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_SINGLE;
+
+                               setServiceAppId(noti_info->svc_h, MSG_DEFAULT_APP_ID);
+                               addServiceExtraData(noti_info->svc_h, "sim_list_show", "sim_setting");
+
+                               noti_info->applist = NOTIFICATION_DISPLAY_APP_NOTIFICATION_TRAY|NOTIFICATION_DISPLAY_APP_INDICATOR;
+                       }
+               break;
+
+               default :
+                       break;
+       }
+
+       MSG_END();
+}
+
+
+void createInfoData(MSG_NOTI_INFO_S *noti_info, MSG_MESSAGE_INFO_S *msg_info)
+{
+       MSG_BEGIN();
+
+       if (msg_info) {
+               noti_info->id = getPrivId(noti_info->type, msg_info->sim_idx);
+               noti_info->msg_id = msg_info->msgId;
+       } else {
+               MSG_DEBUG("msg_info is NULL");
+               return;
+       }
+
+       noti_info->sim_idx = msg_info->sim_idx;
+
+       createServiceHandle(&noti_info->svc_h);
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+
+       switch (noti_info->type)
+       {
+               case MSG_NOTI_TYPE_VOICE_1 :
+               case MSG_NOTI_TYPE_VOICE_2 :
+                       {
+                               memset(keyName, 0x00, sizeof(keyName));
+                               snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_COUNT, msg_info->sim_idx);
+                               noti_info->count = MsgSettingGetInt(keyName);
+                               noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_SINGLE;
+                               noti_info->time = msg_info->displayTime;
+
+                               memset(keyName, 0x00, sizeof(keyName));
+                               snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_NUMBER, msg_info->sim_idx);
+                               char *voiceNumber = MsgSettingGetString(keyName);
+                               memset(keyName, 0x00, sizeof(keyName));
+                               snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_ALPHA_ID, msg_info->sim_idx);
+                               char *voiceAlphaId = MsgSettingGetString(keyName);
+                               char *dialNumber = NULL;
+
+                               MSG_SEC_DEBUG("Voice mail server - alpha id = [%s], default num = [%s]", voiceAlphaId, voiceNumber);
+
+                               if (voiceNumber && strlen(voiceNumber))
+                                       dialNumber = voiceNumber;
+
+                               if (voiceAlphaId && strlen(voiceAlphaId) > 0) {
+                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s", voiceAlphaId);
+                               } else if(dialNumber && strlen(dialNumber) > 0){
+                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s", dialNumber);
+                               }
+
+                               if (dialNumber && strlen(dialNumber) > 0)
+                                       snprintf(noti_info->number, sizeof(noti_info->number), "%s", dialNumber);
+
+                               setServiceAppId(noti_info->svc_h, "org.tizen.call");
+
+                               addServiceExtraData(noti_info->svc_h, "launch-type", "MO");
+
+                               addServiceExtraData(noti_info->svc_h, "number", "VOICEMAIL");
+
+                               char slot_id[5] = {0,};
+                               snprintf(slot_id, sizeof(slot_id), "%d", msg_info->sim_idx - 1);
+                               addServiceExtraData(noti_info->svc_h, "slot_id", slot_id);
+
+                               MSG_FREE(voiceNumber);
+                               MSG_FREE(voiceAlphaId);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_MWI :
+               case MSG_NOTI_TYPE_CLASS0 :
+                       {
+                               noti_info->count = 1;
+                               noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_SINGLE;
+                               noti_info->time = msg_info->displayTime;
+
+                               if (msg_info->addressList[0].displayName[0] == '\0')
+                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s", msg_info->addressList[0].addressVal);
+                               else
+                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s", msg_info->addressList[0].displayName);
+
+                               snprintf(noti_info->number, sizeof(noti_info->number), "%s", msg_info->addressList[0].addressVal);
+
+                               snprintf(noti_info->text, sizeof(noti_info->text), "%s", msg_info->msgText);
+
+                               if (noti_info->type == MSG_NOTI_TYPE_MWI) {
+                                       setServiceAppId(noti_info->svc_h, "org.tizen.call");
+                                       addServiceExtraData(noti_info->svc_h, "launch-type", "MO");
+                                       addServiceExtraData(noti_info->svc_h, "number", "VOICEMAIL");
+
+                                       char slot_id[5] = {0,};
+                                       snprintf(slot_id, sizeof(slot_id), "%d", msg_info->sim_idx - 1);
+                                       addServiceExtraData(noti_info->svc_h, "slot_id", slot_id);
+
+                               } else {
+                                       setServiceAppId(noti_info->svc_h, "org.tizen.msg-ui-class0");
+                                       addServiceExtraData(noti_info->svc_h, "type", "new_msg");
+                                       addServiceExtraData(noti_info->svc_h, "msgId", noti_info->msg_id);
+                               }
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_SMS_DELIVERY_REPORT :
+                       {
+                               noti_info->count = 1;
+                               noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_SINGLE;
+                               noti_info->time = msg_info->displayTime;
+                               noti_info->extra_data = msg_info->networkStatus;
+
+                               MSG_CONTACT_INFO_S contactInfo;
+                               memset(&contactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+                               if (MsgGetContactInfo(&(msg_info->addressList[0]), &contactInfo) != MSG_SUCCESS) {
+                                       MSG_DEBUG("MsgGetContactInfo() fail.");
+                               }
+
+                               snprintf(msg_info->addressList[0].displayName, sizeof(msg_info->addressList[0].displayName), "%s", contactInfo.firstName);
+
+                               if (msg_info->addressList[0].displayName[0] == '\0')
+                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s",msg_info->addressList[0].addressVal);
+                               else
+                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s",msg_info->addressList[0].displayName);
+
+                               snprintf(noti_info->number, sizeof(noti_info->number), "%s", msg_info->addressList[0].addressVal);
+
+                               if (noti_info->msg_id > 0) {
+                                       setServiceAppId(noti_info->svc_h, MSG_DEFAULT_APP_ID);
+                                       addServiceExtraData(noti_info->svc_h, "type", "new_msg");
+                                       addServiceExtraData(noti_info->svc_h, "msgId", noti_info->msg_id);
+                                       addServiceExtraData(noti_info->svc_h, "address", msg_info->addressList[0].addressVal);
+                               }
+                       }
+                       break;
+               case MSG_NOTI_TYPE_MMS_READ_REPORT :
+               case MSG_NOTI_TYPE_MMS_DELIVERY_REPORT :
+                       {
+                               noti_info->count = 1;
+                               noti_info->layout = NOTIFICATION_LY_NOTI_EVENT_SINGLE;
+                               noti_info->time = msg_info->displayTime;
+
+                               MSG_CONTACT_INFO_S contactInfo;
+                               memset(&contactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+                               if (MsgGetContactInfo(&(msg_info->addressList[0]), &contactInfo) != MSG_SUCCESS) {
+                                       MSG_DEBUG("MsgGetContactInfo() fail.");
+                               }
+
+                               snprintf(msg_info->addressList[0].displayName, sizeof(msg_info->addressList[0].displayName), "%s", contactInfo.firstName);
+
+                               if (msg_info->addressList[0].displayName[0] == '\0')
+                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s",msg_info->addressList[0].addressVal);
+                               else
+                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s",msg_info->addressList[0].displayName);
+
+                               snprintf(noti_info->number, sizeof(noti_info->number), "%s",msg_info->addressList[0].addressVal);
+
+                               MsgDbHandler *dbhandler = getDbHandle();
+                               char sqlQuery[MAX_QUERY_LEN+1];
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+                               int report_status_type;
+                               int report_status_value;
+
+                               if (noti_info->type == MSG_NOTI_TYPE_MMS_READ_REPORT) {
+                                       report_status_type = MSG_REPORT_TYPE_READ;
+                               } else {
+                                       report_status_type = MSG_REPORT_TYPE_DELIVERY;
+                               }
+
+                               char *normalNum = NULL;
+                               if (msg_info->addressList[0].addressVal[0] != '\0') {
+                                       normalNum = msg_normalize_number(msg_info->addressList[0].addressVal);
+                               }
+
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                                               "STATUS "
+                                               "FROM %s "
+                                               "WHERE MSG_ID=%d AND STATUS_TYPE=%d AND ADDRESS_VAL LIKE '%%%s';",
+                                               MSGFW_REPORT_TABLE_NAME, msg_info->msgId, report_status_type, normalNum);
+
+                               MSG_DEBUG("sqlQuery = [%s]", sqlQuery);
+
+                               if (dbhandler->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                                       MSG_DEBUG("prepareQuery is failed");
+                                       return;
+                               }
+
+                               if (dbhandler->stepQuery() == MSG_ERR_DB_ROW) {
+                                       report_status_value = dbhandler->columnInt(0);
+                                       MSG_DEBUG("report status [type = %d, value = %d]", report_status_type, report_status_value);
+                               } else {
+                                       MSG_DEBUG("DB Query Result Fail");
+                                       dbhandler->finalizeQuery();
+                                       return;
+                               }
+
+                               dbhandler->finalizeQuery();
+
+                               if (noti_info->msg_id > 0) {
+                                       setServiceAppId(noti_info->svc_h, MSG_DEFAULT_APP_ID);
+                                       addServiceExtraData(noti_info->svc_h, "type", "new_msg");
+                                       addServiceExtraData(noti_info->svc_h, "msgId", noti_info->msg_id);
+                                       addServiceExtraData(noti_info->svc_h, "address", msg_info->addressList[0].addressVal);
+                               }
+
+                               noti_info->extra_data = (unsigned char)report_status_value;
+                       }
+                       break;
+
+               default:
+                       MSG_DEBUG("No matching type [%d]", noti_info->type);
+                       break;
+       }
+
+       noti_info->applist = NOTIFICATION_DISPLAY_APP_ALL^NOTIFICATION_DISPLAY_APP_LOCK;
+
+       MSG_END();
+}
+
+
+void clearInfoData(notification_h noti_h, MSG_NOTI_INFO_S *noti_info)
+{
+       MSG_BEGIN();
+
+       if (noti_h) {
+               notification_free(noti_h);
+               noti_h = NULL;
+       }
+
+       if (noti_info->svc_h) {
+               app_control_destroy(noti_info->svc_h);
+               noti_info->svc_h = NULL;
+       }
+
+       MSG_END();
+}
+
+
+void setProperty(notification_h noti_h, MSG_NOTI_INFO_S *noti_info)
+{
+       MSG_BEGIN();
+
+       int noti_err = NOTIFICATION_ERROR_NONE;
+
+       // set layout
+       noti_err = notification_set_layout(noti_h, (notification_ly_type_e)noti_info->layout);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_layout : %d", noti_err);
+       }
+
+       // set led
+       noti_err = notification_set_led(noti_h, NOTIFICATION_LED_OP_ON, 0x00);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_led.");
+       }
+
+       // set execute option
+       bundle *bundle_data = NULL;
+       bundle *reply_msg = NULL;
+
+       app_control_to_bundle(noti_info->svc_h, &bundle_data);
+
+       if (bundle_data == NULL) {
+               MSG_DEBUG("bundle is NULL");
+       }
+
+       // set execute option and property
+       switch (noti_info->type)
+       {
+               case MSG_NOTI_TYPE_NORMAL :
+                       {
+                               if (noti_info->count > 1) {
+                                       notification_set_execute_option(noti_h, NOTIFICATION_EXECUTE_TYPE_MULTI_LAUNCH, NULL, NULL, bundle_data);
+                                       notification_set_execute_option(noti_h, NOTIFICATION_EXECUTE_TYPE_RESPONDING, NULL, NULL, NULL);
+                               } else {
+                                       if (noti_info->svc_h){ // overwrite bundle key "type"
+                                               //addServiceExtraData(noti_info->svc_h, "type", "reply");
+                                               addServiceExtraData(noti_info->svc_h, "show_list", "list_show");
+
+                                               app_control_to_bundle(noti_info->svc_h, &reply_msg);
+                                       }
+                                       notification_set_execute_option(noti_h, NOTIFICATION_EXECUTE_TYPE_SINGLE_LAUNCH, NULL, NULL, bundle_data);
+                                       notification_set_execute_option(noti_h, NOTIFICATION_EXECUTE_TYPE_RESPONDING, NULL, NULL, reply_msg);
+                               }
+
+                               notification_set_property(noti_h, NOTIFICATION_PROP_DISABLE_AUTO_DELETE);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_CB :
+               case MSG_NOTI_TYPE_SIM :
+                       {
+                               if (noti_info->count > 1) {
+                                       notification_set_execute_option(noti_h, NOTIFICATION_EXECUTE_TYPE_MULTI_LAUNCH, NULL, NULL, bundle_data);
+                               } else {
+                                       notification_set_execute_option(noti_h, NOTIFICATION_EXECUTE_TYPE_SINGLE_LAUNCH, NULL, NULL, bundle_data);
+                               }
+
+                               notification_set_property(noti_h, NOTIFICATION_PROP_DISABLE_AUTO_DELETE|NOTIFICATION_PROP_VOLATILE_DISPLAY);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_FAILED :
+                       {
+                               notification_set_execute_option(noti_h, NOTIFICATION_EXECUTE_TYPE_SINGLE_LAUNCH, NULL, NULL, bundle_data);
+                               notification_set_property(noti_h, NOTIFICATION_PROP_DISABLE_AUTO_DELETE);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_SIM_FULL :
+                       {
+                               notification_set_execute_option(noti_h, NOTIFICATION_EXECUTE_TYPE_SINGLE_LAUNCH, NULL, NULL, bundle_data);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_VOICE_1 :
+               case MSG_NOTI_TYPE_VOICE_2 :
+               case MSG_NOTI_TYPE_MWI :
+               case MSG_NOTI_TYPE_CLASS0 :
+               case MSG_NOTI_TYPE_SMS_DELIVERY_REPORT :
+               case MSG_NOTI_TYPE_MMS_READ_REPORT :
+               case MSG_NOTI_TYPE_MMS_DELIVERY_REPORT :
+                       {
+                               notification_set_execute_option(noti_h, NOTIFICATION_EXECUTE_TYPE_SINGLE_LAUNCH, NULL, NULL, bundle_data);
+                       }
+                       break;
+               default:
+                       MSG_DEBUG("No matching type for notification_set_execute_option() [%d]", noti_info->type);
+                       break;
+       }
+
+       // set applist
+       noti_err = notification_set_display_applist(noti_h, noti_info->applist);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_display_applist");
+       }
+
+
+       MSG_END();
+}
+
+
+void setTextDomain(notification_h noti_h, msg_notification_type_t noti_type)
+{
+       MSG_BEGIN();
+
+       setNotiTextDomain(noti_h, MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR);
+       MSG_END();
+}
+
+
+void setText(notification_h noti_h, MSG_NOTI_INFO_S *noti_info)
+{
+       MSG_BEGIN();
+
+       char unreadMsgCntStr[10] = {0,};
+       bool bPreview;
+
+       if (MsgSettingGetBool(MSG_SETTING_PREVIEW, &bPreview) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgSettingGetBool is failed.");
+       }
+
+       // set title and content
+       switch (noti_info->type)
+       {
+#ifdef MSG_NOTI_INTEGRATION
+               case MSG_NOTI_TYPE_NORMAL :
+               case MSG_NOTI_TYPE_CB :
+               case MSG_NOTI_TYPE_SIM :
+                       {
+                               if (noti_info->count > 1) {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "New Messages", NEW_MESSAGES);
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+                                       setNotiTime(noti_h, noti_info->time);
+
+                                       snprintf(unreadMsgCntStr, sizeof(unreadMsgCntStr), "%d", noti_info->count);
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, unreadMsgCntStr, NULL);
+
+                               } else {
+                                       if (bPreview) {
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, noti_info->sender, NULL);
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->text, NULL);
+                                       } else {
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "New Message", NEW_MESSAGE);
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+                                       }
+                                       setNotiTime(noti_h, noti_info->time);
+                               }
+                       }
+                       break;
+#else
+               case MSG_NOTI_TYPE_NORMAL :
+                       {
+                               if (noti_info->count > 1) {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "New Messages", NEW_MESSAGES);
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+                                       setNotiTime(noti_h, noti_info->time);
+
+                                       snprintf(unreadMsgCntStr, sizeof(unreadMsgCntStr), "%d", noti_info->count);
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, unreadMsgCntStr, NULL);
+
+                               } else {
+                                       if (bPreview) {
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, noti_info->sender, NULL);
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->text, NULL);
+                                       } else {
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "New Message", NEW_MESSAGE);
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+                                       }
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, "1", NULL);
+                                       setNotiTime(noti_h, noti_info->time);
+                               }
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_CB :
+                       {
+                               if (noti_info->count > 1) {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "Broadcast message", CB_MESSAGE);
+                                       snprintf(unreadMsgCntStr, sizeof(unreadMsgCntStr), "%d", noti_info->count);
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, unreadMsgCntStr, NULL);
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+                                       setNotiTime(noti_h, noti_info->time);
+
+                               } else {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, "1", NULL);
+                                       setNotiTime(noti_h, noti_info->time);
+
+                                       if (bPreview) {
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, noti_info->sender, NULL);
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->text, NULL);
+                                       } else {
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "Broadcast message", CB_MESSAGE);
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+                                       }
+                               }
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_SIM :
+                       {
+                               if (noti_info->count > 1) {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "SIM card Message", SIM_CARD_MESSAGE);
+                                       snprintf(unreadMsgCntStr, sizeof(unreadMsgCntStr), "%d", noti_info->count);
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, unreadMsgCntStr, NULL);
+
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+                                       setNotiTime(noti_h, noti_info->time);
+                               } else {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, "1", NULL);
+                                       setNotiTime(noti_h, noti_info->time);
+
+                                       if (bPreview) {
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, noti_info->sender, NULL);
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->text, NULL);
+                                       } else {
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "SIM card Message", SIM_CARD_MESSAGE);
+                                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+                                       }
+                               }
+                       }
+                       break;
+#endif
+               case MSG_NOTI_TYPE_FAILED :
+                       {
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "Message", MSG_MESSAGE);
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, "Failed to send message.", FAILED_TO_SEND_MESSAGE);
+                               snprintf(unreadMsgCntStr, sizeof(unreadMsgCntStr), "%d", noti_info->count);
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, unreadMsgCntStr, NULL);
+                               setNotiTime(noti_h, noti_info->time);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_VOICE_1 :
+               case MSG_NOTI_TYPE_VOICE_2 :
+                       {
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "Voicemail", VOICE_MAIL);
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+                               setNotiTime(noti_h, noti_info->time);
+
+                               if (noti_info->count == 1) {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, "1", NULL);
+                               } else if (noti_info->count > 1) {
+                                       snprintf(unreadMsgCntStr, sizeof(unreadMsgCntStr), "%d", noti_info->count);
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, unreadMsgCntStr, NULL);
+                               } else {
+                                       MSG_DEBUG("Invalid notification count, [cnt = %d]", noti_info->count);
+                               }
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_MWI :
+                       {
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "MWI Message", NULL);
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+                               setNotiTime(noti_h, noti_info->time);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_CLASS0 :
+                       {
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "CLASS 0 Message", NULL);
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+                               setNotiTime(noti_h, noti_info->time);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_SMS_DELIVERY_REPORT :
+                       {
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "Delivery report", DELIVERY_MESSAGE);
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+
+                               if(noti_info->extra_data == MSG_NETWORK_DELIVER_SUCCESS) {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message delivered", DELIVERED_MESSAGE);
+                               } else if(noti_info->extra_data == MSG_NETWORK_DELIVER_EXPIRED) {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message expired", EXPIRED_MESSAGE);
+                               } else {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message deferred", DEFERRED_MESSAGE);
+                               }
+
+                               setNotiTime(noti_h, noti_info->time);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_MMS_READ_REPORT :
+                       {
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "Read Report", READ_REPORT_MESSAGE);
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+
+                               if (noti_info->extra_data == MSG_READ_REPORT_IS_DELETED) {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message deleted", READ_REPORT_DELETE);
+                               }
+                               //CID 45672: noti_info->extra_data in unsigned char but MSG_READ_REPORT_NONE is -1. So the expression is always false
+#if 0
+                               else if (noti_info->extra_data == MSG_READ_REPORT_NONE) {
+                                       //notification free
+                               }
+#endif
+                               else {
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message read", READ_REPORT_READ);
+                               }
+
+                               setNotiTime(noti_h, noti_info->time);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_MMS_DELIVERY_REPORT :
+                       {
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "Delivery Report", DELIVERY_MESSAGE);
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info->sender, NULL);
+
+                               if (noti_info->extra_data == MSG_DELIVERY_REPORT_EXPIRED)
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message expired", EXPIRED_MESSAGE);
+                               else if (noti_info->extra_data == MSG_DELIVERY_REPORT_REJECTED)
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message rejected", REJECTED_MESSAGE);
+                               else if (noti_info->extra_data == MSG_DELIVERY_REPORT_DEFERRED)
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message deferred", DEFERRED_MESSAGE);
+                               else if (noti_info->extra_data == MSG_DELIVERY_REPORT_UNRECOGNISED)
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message unrecognised", UNRECOGNISED_MESSAGE);
+                               else if (noti_info->extra_data == MSG_DELIVERY_REPORT_INDETERMINATE)
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message indeterminate", INDETEMINATE_MESSAGE);
+                               else if (noti_info->extra_data == MSG_DELIVERY_REPORT_FORWARDED)
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message forwarded", NULL);
+                               else if (noti_info->extra_data == MSG_DELIVERY_REPORT_UNREACHABLE)
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message unreachable", UNREACHABLE_MESSAGE);
+                               else if (noti_info->extra_data == MSG_DELIVERY_REPORT_ERROR)
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message error", NULL);
+
+                               //CID 45672: noti_info->extra_data in unsigned char but MSG_READ_REPORT_NONE is -1. So the expression is always false
+#if 0
+                               else if (noti_info->extra_data == MSG_DELIVERY_REPORT_NONE) {
+                                       //notification free
+                               }
+#endif
+                               else
+                                       setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_INFO_1, "Message delivered", DELIVERED_MESSAGE);
+
+                               setNotiTime(noti_h, noti_info->time);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_SIM_FULL :
+                       {
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_TITLE, "SIM card full", SMS_SIM_CARD_FULL);
+                               setNotiText(noti_h, NOTIFICATION_TEXT_TYPE_CONTENT, "Not enough memory. Delete some items.", SMS_MESSAGE_MEMORY_FULL);
+                       }
+                       break;
+               default:
+                       MSG_DEBUG("No matching type [%d]", noti_info->type);
+                       break;
+       }
+
+       MSG_END();
+
+}
+
+
+void setIcon(notification_h noti_h, MSG_NOTI_INFO_S *noti_info)
+{
+       MSG_BEGIN();
+
+       switch(noti_info->type)
+       {
+#ifdef MSG_NOTI_INTEGRATION
+               case MSG_NOTI_TYPE_NORMAL :
+               case MSG_NOTI_TYPE_CB :
+               case MSG_NOTI_TYPE_SIM :
+                       {
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, MSG_NORMAL_STATUS_ICON);
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_LOCK, MSG_NORMAL_ICON_PATH);
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_NORMAL_ICON_PATH);
+                       }
+                       break;
+#else
+               case MSG_NOTI_TYPE_NORMAL :
+                       {
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, MSG_NORMAL_STATUS_ICON);
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_LOCK, MSG_NORMAL_ICON_PATH);
+
+                               if (noti_info->count > 1) {
+                                       setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_NORMAL_ICON_PATH);
+                               } else {
+                                       setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_REPLY_ICON_PATH);
+                               }
+                       }
+                       break;
+               case MSG_NOTI_TYPE_CB :
+                       {
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_CB_ICON_PATH);
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, MSG_CB_ICON_PATH);
+                       }
+                       break;
+               case MSG_NOTI_TYPE_SIM :
+                       {
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_SIM_ICON_PATH);
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, MSG_SIM_ICON_PATH);
+                       }
+                       break;
+#endif
+               case MSG_NOTI_TYPE_FAILED :
+                       {
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_NORMAL_ICON_PATH);
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, MSG_NORMAL_STATUS_ICON);
+                       }
+                       break;
+               case MSG_NOTI_TYPE_VOICE_1 :
+               case MSG_NOTI_TYPE_VOICE_2 :
+               case MSG_NOTI_TYPE_MWI :
+                       {
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, MSG_VOICE_MSG_STATUS_ICON);
+                               setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_VOICE_ICON_PATH);
+                       }
+                       break;
+               case MSG_NOTI_TYPE_CLASS0 :
+                       setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_NORMAL_ICON_PATH);
+                       break;
+               case MSG_NOTI_TYPE_SMS_DELIVERY_REPORT :
+                       setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, MSG_NORMAL_STATUS_ICON);
+                       setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_NORMAL_ICON_PATH);
+                       break;
+               case MSG_NOTI_TYPE_MMS_READ_REPORT :
+                       setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, MSG_NORMAL_STATUS_ICON);
+                       setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_NORMAL_ICON_PATH);
+                       break;
+               case MSG_NOTI_TYPE_MMS_DELIVERY_REPORT :
+                       setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, MSG_NORMAL_STATUS_ICON);
+                       setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_NORMAL_ICON_PATH);
+                       break;
+               case MSG_NOTI_TYPE_SIM_FULL :
+                       setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON, MSG_NORMAL_ICON_PATH);
+                       setNotiImage(noti_h, NOTIFICATION_IMAGE_TYPE_ICON_FOR_INDICATOR, MSG_NORMAL_STATUS_ICON);
+                       break;
+               default:
+                       MSG_DEBUG("No matching type for MsgNotiSetImage [%d]", noti_info->type);
+                       break;
+       }
+
+       MSG_END();
+}
+
+msg_error_t MsgInsertInstantMessage(msg_notification_type_t noti_type)
+{
+       MSG_BEGIN();
+
+       msg_error_t msg_err = MSG_SUCCESS;
+       char *notiMsg = NULL;
+
+       notification_h noti = notification_create(NOTIFICATION_TYPE_NOTI);
+
+       setPkgName(noti, noti_type);
+
+       switch (noti_type)
+       {
+               case MSG_NOTI_TYPE_NORMAL :
+               case MSG_NOTI_TYPE_SIM :
+               case MSG_NOTI_TYPE_CB :
+               {
+                       MSG_NOTI_INFO_S noti_info;
+                       memset(&noti_info, 0x00, sizeof(MSG_NOTI_INFO_S));
+
+                       noti_info.type = noti_type;
+                       msg_err = getLatestMsgInfo(&noti_info, true);
+
+                       if (msg_err == MSG_SUCCESS) {
+                               MSG_DEBUG("Unread count [%d]", noti_info.count);
+                               if (noti_info.count == 1) {
+                                       MSG_SEC_DEBUG("noti_info.sender [%s]",noti_info.sender);
+                                       setNotiText(noti, NOTIFICATION_TEXT_TYPE_TITLE,  noti_info.sender, NULL);
+                                       setNotiText(noti, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info.text, NULL);
+                               } else if (noti_info.count  > 1) {
+                                       gchar *cnt_string = g_strdup_printf("%i", noti_info.count);
+
+                                       notiMsg = getTranslateText(MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR, NEW_MESSAGES);
+                                       gchar *outString = g_strconcat(cnt_string, " ", notiMsg, NULL);
+                                       setNotiText(noti, NOTIFICATION_TEXT_TYPE_TITLE, outString, NULL);
+                                       setNotiText(noti, NOTIFICATION_TEXT_TYPE_CONTENT, noti_info.sender, NULL);
+                                       g_free(outString);
+                                       g_free(cnt_string);
+                               }
+
+                               setNotiImage(noti, NOTIFICATION_IMAGE_TYPE_ICON, MSG_NORMAL_ICON_PATH);
+                       }
+               }
+               break;
+
+               case MSG_NOTI_TYPE_FAILED:
+               {
+                       notiMsg = getTranslateText(MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR, FAILED_TO_SEND_MESSAGE);
+                       setNotiText(noti, NOTIFICATION_TEXT_TYPE_TITLE, notiMsg, NULL);
+                       setNotiImage(noti, NOTIFICATION_IMAGE_TYPE_ICON, MSG_NORMAL_ICON_PATH);
+               }
+               break;
+
+               default:
+                       MSG_DEBUG("No matching type for MsgNotiType%d]", noti_type);
+                       goto _END_OF_INSTANT_NOTI;
+                       break;
+       }
+
+       if (notification_set_display_applist(noti, NOTIFICATION_DISPLAY_APP_TICKER) != NOTIFICATION_ERROR_NONE)
+               MSG_DEBUG("Fail to notification_set_display_applist");
+
+       if (notification_post(noti) != NOTIFICATION_ERROR_NONE)
+               MSG_DEBUG("Fail to notification_post");
+
+_END_OF_INSTANT_NOTI:
+
+       if (notification_delete(noti) != NOTIFICATION_ERROR_NONE)
+               MSG_DEBUG("Fail to notification_delete");
+       if (notiMsg) {
+               free(notiMsg);
+               notiMsg = NULL;
+       }
+
+       if (noti) {
+               if (notification_free(noti) != NOTIFICATION_ERROR_NONE)
+                       MSG_DEBUG("Fail to notification_free");
+               noti = NULL;
+       }
+
+       MSG_END();
+       return MSG_SUCCESS;
+}
+
+void setPkgName(notification_h noti_h, msg_notification_type_t noti_type)
+{
+       MSG_BEGIN();
+
+       int noti_err = NOTIFICATION_ERROR_NONE;
+
+       switch (noti_type)
+       {
+               case MSG_NOTI_TYPE_NORMAL :
+               case MSG_NOTI_TYPE_CB :
+               case MSG_NOTI_TYPE_SIM :
+               case MSG_NOTI_TYPE_FAILED :
+               case MSG_NOTI_TYPE_SMS_DELIVERY_REPORT :
+               case MSG_NOTI_TYPE_MMS_READ_REPORT :
+               case MSG_NOTI_TYPE_MMS_DELIVERY_REPORT :
+               case MSG_NOTI_TYPE_SIM_FULL :
+                       {
+                               noti_err = notification_set_pkgname(noti_h, MSG_DEFAULT_APP_ID);
+                               if (noti_err != NOTIFICATION_ERROR_NONE)
+                                       MSG_ERR("notification_set_pkgname() is failed, [%d]", noti_err);
+                       }
+                       break;
+               default:
+                       MSG_DEBUG("No matching type for notification_set_pkgname() [%d]", noti_type);
+                       break;
+       }
+
+       MSG_END();
+}
+
+
+void setSoundAndVibration(notification_h noti_h, char *addressVal, bool bVoiceMail)
+{
+       MSG_BEGIN();
+
+       bool bBlockingMode = false;
+
+       MSG_ADDRESS_INFO_S addrInfo;
+       memset(&addrInfo, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+       MSG_CONTACT_INFO_S contactInfo;
+       memset(&contactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+       if (addressVal != NULL) {
+               snprintf(addrInfo.addressVal, sizeof(addrInfo.addressVal), "%s", addressVal);
+               // Get Contact Info
+               if (MsgGetContactInfo(&addrInfo, &contactInfo) != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgGetContactInfo() fail.");
+               }
+               bBlockingMode = checkBlockingMode(addressVal, NULL);
+       } else {
+               MSG_DEBUG("addressVal is NULL.");
+       }
+
+       char *msg_tone_file_path = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&msg_tone_file_path, unique_ptr_deleter);
+
+       MsgSoundPlayer::instance()->MsgGetRingtonePath(contactInfo.alerttonePath, &msg_tone_file_path);
+
+       MSG_SEC_DEBUG("Sound File [%s]", msg_tone_file_path);
+
+       bool bPlaySound = false;
+       bool bPlayVibration = false;
+       bool bOnCall = false;
+
+       MsgSoundPlayer::instance()->MsgGetPlayStatus(bVoiceMail, &bPlaySound, &bPlayVibration, &bOnCall);
+
+       if (!bBlockingMode) { // check blocking mode.
+               if (bPlaySound) {
+                       if (msg_tone_file_path)
+                               setNotiSound(noti_h, NOTIFICATION_SOUND_TYPE_USER_DATA, msg_tone_file_path);
+                       else {
+                               MSG_RINGTONE_TYPE_T ringtoneType = (MSG_RINGTONE_TYPE_T)MsgSettingGetInt(MSG_SETTING_RINGTONE_TYPE);
+                               if (ringtoneType == MSG_RINGTONE_TYPE_SILENT)
+                                       setNotiSound(noti_h, NOTIFICATION_SOUND_TYPE_NONE, NULL);
+                               else
+                                       setNotiSound(noti_h, NOTIFICATION_SOUND_TYPE_DEFAULT, NULL);
+                       }
+               } else {
+                       setNotiSound(noti_h, NOTIFICATION_SOUND_TYPE_NONE, NULL);
+               }
+
+               if (bPlayVibration) {
+                       if (contactInfo.vibrationPath[0] == '\0')
+                               setNotiVibration(noti_h, NOTIFICATION_VIBRATION_TYPE_DEFAULT, NULL);
+                       else
+                               setNotiVibration(noti_h, NOTIFICATION_VIBRATION_TYPE_USER_DATA, contactInfo.vibrationPath);
+               } else {
+                       setNotiVibration(noti_h, NOTIFICATION_VIBRATION_TYPE_NONE, NULL);
+               }
+       } else {
+               setNotiSound(noti_h, NOTIFICATION_SOUND_TYPE_NONE, NULL);
+               setNotiVibration(noti_h, NOTIFICATION_VIBRATION_TYPE_NONE, NULL);
+       }
+       MSG_END();
+}
+
+
+void setNotification(notification_h noti_h, MSG_NOTI_INFO_S *noti_info, bool bFeedback)
+{
+       MSG_BEGIN();
+
+       int noti_err = NOTIFICATION_ERROR_NONE;
+
+       setPkgName(noti_h, noti_info->type);
+
+       setProperty(noti_h, noti_info);
+
+       setTextDomain(noti_h, noti_info->type);
+
+       setText(noti_h, noti_info);
+
+       setIcon(noti_h, noti_info);
+
+       if (bFeedback) {
+               setFlashNoti();
+
+               if (noti_info->type == MSG_NOTI_TYPE_VOICE_1 || noti_info->type == MSG_NOTI_TYPE_VOICE_2)
+                       setSoundAndVibration(noti_h, noti_info->number, true);
+               else
+                       setSoundAndVibration(noti_h, noti_info->number, false);
+
+       } else {
+               setNotiSound(noti_h, NOTIFICATION_SOUND_TYPE_NONE, NULL);
+               setNotiVibration(noti_h, NOTIFICATION_VIBRATION_TYPE_NONE, NULL);
+       }
+
+       if (noti_info->id > 0) {
+               MSG_DEBUG("Notification update");
+               noti_err = notification_update(noti_h);
+               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                       MSG_DEBUG("Fail to notification_update");
+               }
+       } else {
+               MSG_DEBUG("Notification insert");
+               noti_err = notification_insert(noti_h, &noti_info->id);
+               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                       MSG_DEBUG("Fail to notification_insert");
+               }
+
+               updatePrivId(noti_info->type, noti_info->id, noti_info->sim_idx);
+       }
+
+       MSG_END();
+}
+
+
+msg_error_t getLatestMsgInfo(MSG_NOTI_INFO_S *noti_info, bool isForInstantMessage)
+{
+       MSG_BEGIN();
+
+       MsgDbHandler *dbhandler = getDbHandle();
+       int noti_err = NOTIFICATION_ERROR_NONE;
+       msg_error_t msg_err = MSG_SUCCESS;
+
+       switch (noti_info->type)
+       {
+#ifdef MSG_NOTI_INTEGRATION
+               case MSG_NOTI_TYPE_NORMAL :
+               case MSG_NOTI_TYPE_CB :
+               case MSG_NOTI_TYPE_SIM :
+#else
+               case MSG_NOTI_TYPE_NORMAL :
+#endif
+                       {
+                               int smsUnreadCnt = 0;
+                               int mmsUnreadCnt = 0;
+
+                               char sqlQuery[MAX_QUERY_LEN+1];
+                               MSG_MAIN_TYPE_T mainType;
+                               MSG_SUB_TYPE_T subType;
+
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+#ifdef MSG_NOTI_INTEGRATION
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT "
+                                               "A.ADDRESS_VAL, "
+                                               "B.SUB_TYPE "
+                                               "FROM %s A, %s B "
+                                               "WHERE A.CONV_ID=B.CONV_ID "
+                                               "AND B.READ_STATUS=0 AND (B.FOLDER_ID=%d OR B.FOLDER_ID=%d) "
+                                               "AND B.STORAGE_ID = %d  "
+                                               "GROUP BY A.ADDRESS_VAL "
+                                               "ORDER BY B.DISPLAY_TIME DESC LIMIT 5;",
+                                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                                               MSG_INBOX_ID, MSG_CBMSGBOX_ID,
+                                               MSG_STORAGE_PHONE);
+#else
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT "
+                                               "A.ADDRESS_VAL, "
+                                               "B.SUB_TYPE "
+                                               "FROM %s A, %s B "
+                                               "WHERE A.CONV_ID=B.CONV_ID "
+                                               "AND B.READ_STATUS=0 AND B.FOLDER_ID=%d "
+                                               "AND B.STORAGE_ID = %d  "
+                                               "GROUP BY A.ADDRESS_VAL "
+                                               "ORDER BY B.DISPLAY_TIME DESC LIMIT 5;",
+                                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                                               MSG_INBOX_ID,
+                                               MSG_STORAGE_PHONE);
+#endif
+                               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+
+                               int rowCnt = 0, index = 0;
+
+                               msg_err = dbhandler->getTable(sqlQuery, &rowCnt, &index);
+                               MSG_DEBUG("getTable() ret=[%d], rowCnt=[%d]", msg_err, rowCnt);
+
+                               MSG_ADDRESS_INFO_S tmpAddressInfo;
+
+                               for (int i = 1; i <= rowCnt; i++) {
+                                       memset(&tmpAddressInfo, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+                                       char *address = dbhandler->getColumnToString(index++);
+                                       if (address) {
+                                               snprintf(tmpAddressInfo.addressVal, MAX_ADDRESS_VAL_LEN, "%s", address);
+                                               if (msg_is_valid_email(address)) {
+                                                       tmpAddressInfo.addressType = MSG_ADDRESS_TYPE_EMAIL;
+                                               } else {
+                                                       tmpAddressInfo.addressType = MSG_ADDRESS_TYPE_UNKNOWN;
+                                               }
+                                       }
+                                       subType = dbhandler->getColumnToInt(index++);
+
+                                       MSG_CONTACT_INFO_S tmpContact;
+                                       memset(&tmpContact, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+                                       MsgGetContactInfo(&tmpAddressInfo, &tmpContact);
+
+                                       if (rowCnt == 1) {
+                                               snprintf(noti_info->imagePath, sizeof(noti_info->imagePath), "%s", tmpContact.imagePath);
+                                       }
+
+                                       if (i > 1) {
+                                               g_strlcat(noti_info->sender, ", ", sizeof(noti_info->sender)-strlen(noti_info->sender));
+                                       }
+
+                                       if (tmpContact.firstName[0] != '\0')
+                                               g_strlcat(noti_info->sender, tmpContact.firstName, sizeof(noti_info->sender)-strlen(noti_info->sender));
+                                       else if (tmpAddressInfo.addressVal[0] == '\0') {
+                                               char *senderStr = NULL;
+                                               senderStr = getTranslateText(MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR, MSG_UNKNOWN_SENDER);
+                                               g_strlcat(noti_info->sender, senderStr, sizeof(noti_info->sender)-strlen(noti_info->sender));
+                                               if (senderStr) {
+                                                       free(senderStr);
+                                                       senderStr = NULL;
+                                               }
+                                       } else {
+                                               char *senderStr = NULL;
+                                               if (subType == MSG_CB_SMS) {
+                                                       senderStr = getTranslateText(MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR, CB_MESSAGE);
+                                                       g_strlcat(noti_info->sender, senderStr, sizeof(noti_info->sender)-strlen(noti_info->sender));
+                                               } else if (subType == MSG_WAP_SI_SMS || subType == MSG_WAP_SL_SMS) {
+                                                       senderStr = getTranslateText(MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR, PUSH_MESSAGE);
+                                                       g_strlcat(noti_info->sender, senderStr, sizeof(noti_info->sender)-strlen(noti_info->sender));
+                                               } else {
+                                                       g_strlcat(noti_info->sender, tmpAddressInfo.addressVal, sizeof(noti_info->sender)-strlen(noti_info->sender));
+                                               }
+                                               if (senderStr) {
+                                                       free(senderStr);
+                                                       senderStr = NULL;
+                                               }
+                                       }
+                               }
+
+                               dbhandler->freeTable();
+
+                               MSG_SEC_DEBUG("sender info = [%s]", noti_info->sender);
+
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+#ifdef MSG_NOTI_INTEGRATION
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                                               "A.ADDRESS_VAL, "
+                                               "B.DISPLAY_TIME, "
+                                               "B.MSG_ID, "
+                                               "B.SUBJECT, "
+                                               "B.MSG_TEXT, "
+                                               "B.MAIN_TYPE, "
+                                               "(COUNT(CASE WHEN B.MAIN_TYPE = %d THEN 1 END)) AS SMS_UNREAD_CNT, "
+                                               "(COUNT(CASE WHEN B.MAIN_TYPE = %d THEN 1 END)) AS MMS_UNREAD_CNT "
+                                               "FROM %s A, %s B "
+                                               "WHERE A.CONV_ID=B.CONV_ID "
+                                               "AND B.READ_STATUS=0 AND (B.FOLDER_ID=%d OR B.FOLDER_ID=%d) "
+                                               "AND B.STORAGE_ID = %d  "
+                                               "ORDER BY B.DISPLAY_TIME DESC;",
+                                               MSG_SMS_TYPE,
+                                               MSG_MMS_TYPE,
+                                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                                               MSG_INBOX_ID, MSG_CBMSGBOX_ID,
+                                               MSG_STORAGE_PHONE);
+#else
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                                               "A.ADDRESS_VAL, "
+                                               "B.DISPLAY_TIME, "
+                                               "B.MSG_ID, "
+                                               "B.SUBJECT, "
+                                               "B.MSG_TEXT, "
+                                               "B.MAIN_TYPE, "
+                                               "(COUNT(CASE WHEN B.MAIN_TYPE = %d THEN 1 END)) AS SMS_UNREAD_CNT, "
+                                               "(COUNT(CASE WHEN B.MAIN_TYPE = %d THEN 1 END)) AS MMS_UNREAD_CNT "
+                                               "FROM %s A, %s B "
+                                               "WHERE A.CONV_ID=B.CONV_ID "
+                                               "AND B.READ_STATUS=0 AND B.FOLDER_ID=%d "
+                                               "AND B.STORAGE_ID = %d  "
+                                               "ORDER BY B.DISPLAY_TIME DESC;",
+                                               MSG_SMS_TYPE,
+                                               MSG_MMS_TYPE,
+                                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                                               MSG_INBOX_ID,
+                                               MSG_STORAGE_PHONE);
+#endif
+                               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+
+                               if (dbhandler->prepareQuery(sqlQuery) != MSG_SUCCESS)
+                                       return MSG_ERR_DB_PREPARE;
+
+                               if (dbhandler->stepQuery() == MSG_ERR_DB_ROW) {
+
+                                       smsUnreadCnt = dbhandler->columnInt(6);
+                                       mmsUnreadCnt = dbhandler->columnInt(7);
+
+                                       noti_info->count = smsUnreadCnt + mmsUnreadCnt;
+
+                                       if (noti_info->count > 0) {
+                                               snprintf(noti_info->number, sizeof(noti_info->number), "%s", (char*)dbhandler->columnText(0));
+
+                                               noti_info->time = (time_t)dbhandler->columnInt(1);
+
+                                               noti_info->msg_id = (msg_message_id_t)dbhandler->columnInt(2);
+
+                                               mainType = (MSG_MAIN_TYPE_T)dbhandler->columnInt(5);
+
+                                               if (mainType == MSG_MMS_TYPE) {
+                                                       snprintf(noti_info->text, sizeof(noti_info->text), "%s", (char*)dbhandler->columnText(3));
+                                                       if (noti_info->text[0] == '\0') {
+                                                               char *noti_text = getTranslateText(MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR, MSG_NO_SUBJECT);
+                                                               snprintf(noti_info->text, sizeof(noti_info->text), "%s", noti_text);
+                                                               g_free(noti_text);
+                                                       }
+                                               } else {
+                                                       snprintf(noti_info->text, sizeof(noti_info->text), "%s", (char*)dbhandler->columnText(4));
+                                               }
+
+                                               MSG_DEBUG("unread message ID [%d].", noti_info->msg_id);
+
+                                               if (!isForInstantMessage) {
+                                                       if (noti_info->id > 0 && noti_info->count == 1 ) {
+                                                               noti_err = notification_delete_by_priv_id(MSG_DEFAULT_APP_ID, NOTIFICATION_TYPE_NOTI, noti_info->id);
+                                                               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                                                                       MSG_DEBUG("Fail to notification_delete_by_priv_id : %d", noti_err);
+                                                               }
+                                                               noti_info->id = 0;
+                                                               if (MsgSettingSetInt(NOTIFICATION_PRIV_ID, noti_info->id) != MSG_SUCCESS)
+                                                                       MSG_DEBUG("MsgSettingSetInt fail : NOTIFICATION_PRIV_ID");
+                                                       }
+                                                       MsgSettingHandleNewMsg(smsUnreadCnt, mmsUnreadCnt);
+                                                       MsgInsertBadge(noti_info->count);
+                                                       MsgSoundSetRepeatAlarm();
+                                               }
+                                       } else {
+
+                                               MSG_DEBUG("No unread message.");
+                                               MSG_DEBUG("notiPrivId [%d]", noti_info->id);
+
+                                               dbhandler->finalizeQuery();
+
+                                               if (!isForInstantMessage) {
+                                                       // No unread message.
+                                                       if (noti_info->id > 0) {
+                                                               noti_err = notification_delete_by_priv_id(MSG_DEFAULT_APP_ID, NOTIFICATION_TYPE_NOTI, noti_info->id);
+                                                               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                                                                       MSG_DEBUG("Fail to notification_delete_by_priv_id : %d", noti_err);
+                                                               }
+                                                       }
+
+                                                       noti_info->id = 0;
+
+                                                       if(MsgSettingSetInt(NOTIFICATION_PRIV_ID, noti_info->id) != MSG_SUCCESS)
+                                                               MSG_DEBUG("MsgSettingSetInt fail : NOTIFICATION_PRIV_ID");
+
+                                                       MsgSettingHandleNewMsg(0,0);
+                                                       MsgInsertBadge(0);
+                                                       MsgSoundSetRepeatAlarm();
+                                               }
+
+                                               return MSG_ERR_DB_STEP;
+                                       }
+                               } else {
+                                       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+                                       dbhandler->finalizeQuery();
+                                       return MSG_ERR_DB_STEP;
+                               }
+
+                               dbhandler->finalizeQuery();
+                       }
+                       break;
+
+#ifndef MSG_NOTI_INTEGRATION
+               case MSG_NOTI_TYPE_CB :
+                       {
+                               char sqlQuery[MAX_QUERY_LEN+1];
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                                               "A.ADDRESS_VAL, "
+                                               "B.DISPLAY_TIME, "
+                                               "B.MSG_ID, "
+                                               "B.MSG_TEXT "
+                                               "FROM %s A, %s B "
+                                               "WHERE A.CONV_ID=B.CONV_ID "
+                                               "AND B.READ_STATUS=0 "
+                                               "AND B.FOLDER_ID=%d "
+                                               "AND B.STORAGE_ID = %d "
+                                               "ORDER BY B.DISPLAY_TIME DESC;",
+                                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                                               MSG_CBMSGBOX_ID,
+                                               MSG_STORAGE_PHONE);
+
+                               if (dbhandler->prepareQuery(sqlQuery) != MSG_SUCCESS)
+                                       return MSG_ERR_DB_PREPARE;
+
+                               if (dbhandler->stepQuery() == MSG_ERR_DB_ROW) {
+                                       MSG_ADDRESS_INFO_S addrInfo;
+                                       memset(&addrInfo, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+                                       if (dbhandler->columnText(0) != NULL)
+                                               snprintf(addrInfo.addressVal, sizeof(addrInfo.addressVal), "%s", (char*)dbhandler->columnText(0));
+
+                                       MSG_CONTACT_INFO_S tmpContact;
+                                       memset(&tmpContact, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+                                       MsgGetContactInfo(&addrInfo, &tmpContact);
+
+                                       if (tmpContact.firstName[0] != '\0') {
+                                               snprintf(noti_info->sender, sizeof(noti_info->sender), "%s", tmpContact.firstName);
+                                       } else if (addrInfo.addressVal[0] == '\0') {
+                                               char *senderStr = NULL;
+                                               senderStr = getTranslateText(MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR, MSG_UNKNOWN_SENDER);
+                                               g_strlcat(noti_info->sender, senderStr, sizeof(noti_info->sender)-strlen(noti_info->sender));
+                                               if (senderStr) {
+                                                       free(senderStr);
+                                                       senderStr = NULL;
+                                               }
+                                       } else {
+                                               snprintf(noti_info->sender, sizeof(noti_info->sender), "%s", addrInfo.addressVal);
+                                       }
+
+                                       snprintf(noti_info->number, sizeof(noti_info->number), "%s", addrInfo.addressVal);
+
+                                       noti_info->time = (time_t)dbhandler->columnInt(1);
+
+                                       noti_info->msg_id = (msg_message_id_t)dbhandler->columnInt(2);
+
+                                       snprintf(noti_info->text, sizeof(noti_info->text), "%s", (char*)dbhandler->columnText(3));
+
+                                       MSG_DEBUG("unread CB message [%d].", noti_info->msg_id);
+                               } else {
+
+                                       MSG_DEBUG("No unread CB message.");
+                                       MSG_DEBUG("notiCbId [%d]", noti_info->id);
+
+                                       dbhandler->finalizeQuery();
+
+                                       if (!isForInstantMessage) {
+                                               // No unread message.
+                                               if (noti_info->id > 0) {
+                                                       noti_err = notification_delete_by_priv_id(NULL, NOTIFICATION_TYPE_NOTI, noti_info->id);
+                                                       if (noti_err != NOTIFICATION_ERROR_NONE) {
+                                                               MSG_DEBUG("Fail to notification_delete_by_priv_id : %d", noti_err);
+                                                       }
+                                               }
+
+                                               noti_info->id = 0;
+
+                                               if (MsgSettingSetInt(CB_NOTI_PRIV_ID, noti_info->id) != MSG_SUCCESS)
+                                                       MSG_DEBUG("MsgSettingSetInt fail : CB_NOTI_PRIV_ID");
+                                       }
+
+                                       return MSG_ERR_DB_STEP;
+                               }
+
+                               dbhandler->finalizeQuery();
+
+                               if (dbhandler->getTable(sqlQuery, &noti_info->count, NULL) != MSG_SUCCESS) {
+                                       MSG_DEBUG("getTable is failed");
+                                       dbhandler->freeTable();
+                                       return MSG_ERR_DB_GETTABLE;
+                               }
+
+                               dbhandler->freeTable();
+                               MSG_DEBUG("notiCbId [%d], unreadCbMsgCnt [%d]", noti_info->id, noti_info->count);
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_SIM :
+                       {
+                               char sqlQuery[MAX_QUERY_LEN+1];
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                                               "A.ADDRESS_VAL, "
+                                               "B.DISPLAY_TIME, "
+                                               "B.MSG_ID, "
+                                               "B.MSG_TEXT, "
+                                               "(COUNT(CASE WHEN B.MAIN_TYPE = %d THEN 1 END)) AS SMS_UNREAD_CNT "
+                                               "FROM %s A, %s B "
+                                               "WHERE A.CONV_ID=B.CONV_ID "
+                                               "AND B.READ_STATUS=0 AND B.FOLDER_ID=%d "
+                                               "AND B.STORAGE_ID = %d "
+                                               "ORDER BY B.DISPLAY_TIME DESC;",
+                                               MSG_SMS_TYPE,
+                                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                                               MSG_INBOX_ID,
+                                               MSG_STORAGE_SIM);
+
+                               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+
+                               if (dbhandler->prepareQuery(sqlQuery) != MSG_SUCCESS)
+                                       return MSG_ERR_DB_PREPARE;
+
+                               if (dbhandler->stepQuery() == MSG_ERR_DB_ROW) {
+
+                                       noti_info->count = dbhandler->columnInt(4);
+
+                                       if (noti_info->count > 0) {
+                                               MSG_ADDRESS_INFO_S addrInfo;
+                                               memset(&addrInfo, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+                                               if (dbhandler->columnText(0) != NULL)
+                                                       snprintf(addrInfo.addressVal, sizeof(addrInfo.addressVal), "%s", (char*)dbhandler->columnText(0));
+
+                                               MSG_CONTACT_INFO_S tmpContact;
+                                               memset(&tmpContact, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+                                               MsgGetContactInfo(&addrInfo, &tmpContact);
+
+                                               if (tmpContact.firstName[0] != '\0') {
+                                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s", tmpContact.firstName);
+                                               } else if (addrInfo.addressVal[0] == '\0') {
+                                                       char *senderStr = NULL;
+                                                       senderStr = getTranslateText(MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR, MSG_UNKNOWN_SENDER);
+                                                       g_strlcat(noti_info->sender, senderStr, sizeof(noti_info->sender)-strlen(noti_info->sender));
+                                                       if (senderStr) {
+                                                               free(senderStr);
+                                                               senderStr = NULL;
+                                                       }
+                                               } else {
+                                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s", addrInfo.addressVal);
+                                               }
+
+                                               snprintf(noti_info->number, sizeof(noti_info->number), "%s", addrInfo.addressVal);
+
+                                               noti_info->time = (time_t)dbhandler->columnInt(1);
+
+                                               noti_info->msg_id = (msg_message_id_t)dbhandler->columnInt(2);
+
+                                               snprintf(noti_info->text, sizeof(noti_info->text), "%s", (char*)dbhandler->columnText(3));
+
+                                               MSG_DEBUG("unread SIM message [%d].", noti_info->msg_id);
+                                       } else {
+
+                                               MSG_DEBUG("No unread SIM message.");
+                                               MSG_DEBUG("notiPrivId [%d]", noti_info->id);
+
+                                               dbhandler->finalizeQuery();
+
+                                               if (!isForInstantMessage) {
+                                                       // No unread message.
+                                                       if (noti_info->id > 0) {
+                                                               noti_err = notification_delete_by_priv_id(MSG_DEFAULT_APP_ID, NOTIFICATION_TYPE_NOTI, noti_info->id);
+                                                               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                                                                       MSG_DEBUG("Fail to notification_delete_by_priv_id : %d", noti_err);
+                                                               }
+                                                       }
+
+                                                       noti_info->id = 0;
+
+                                                       if (MsgSettingSetInt(SIM_MSG_NOTI_PRIV_ID, noti_info->id) != MSG_SUCCESS)
+                                                               MSG_DEBUG("MsgSettingSetInt fail : SIM_MSG_NOTI_PRIV_ID");
+                                               }
+
+                                               return MSG_ERR_DB_STEP;
+                                       }
+                               } else {
+                                       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+                                       dbhandler->finalizeQuery();
+                                       return MSG_ERR_DB_STEP;
+                               }
+
+                               dbhandler->finalizeQuery();
+                       }
+                       break;
+#endif
+               case MSG_NOTI_TYPE_FAILED :
+                       {
+                               MSG_MAIN_TYPE_T mainType;
+                               char sqlQuery[MAX_QUERY_LEN+1];
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                                               "A.ADDRESS_VAL, "
+                                               "B.DISPLAY_TIME, "
+                                               "B.MSG_ID, "
+                                               "B.MSG_TEXT, "
+                                               "B.SUBJECT, "
+                                               "B.MAIN_TYPE, "
+                                               "(COUNT(CASE WHEN B.NETWORK_STATUS = %d THEN 1 END)) AS SENT_FAILED_CNT "
+                                               "FROM %s A, %s B "
+                                               "WHERE A.CONV_ID=B.CONV_ID "
+                                               "AND B.READ_STATUS=0 AND B.FOLDER_ID=%d "
+                                               "AND B.STORAGE_ID = %d  "
+                                               "ORDER BY B.DISPLAY_TIME DESC;",
+                                               MSG_NETWORK_SEND_FAIL,
+                                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                                               MSG_OUTBOX_ID,
+                                               MSG_STORAGE_PHONE);
+
+                               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+
+                               if (dbhandler->prepareQuery(sqlQuery) != MSG_SUCCESS)
+                                       return MSG_ERR_DB_PREPARE;
+
+                               if (dbhandler->stepQuery() == MSG_ERR_DB_ROW) {
+
+                                       noti_info->count = dbhandler->columnInt(6);
+
+                                       if (noti_info->count > 0) {
+                                               MSG_ADDRESS_INFO_S addrInfo;
+                                               memset(&addrInfo, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+                                               if (dbhandler->columnText(0) != NULL)
+                                                       snprintf(addrInfo.addressVal, sizeof(addrInfo.addressVal), "%s", (char*)dbhandler->columnText(0));
+
+                                               MSG_CONTACT_INFO_S tmpContact;
+                                               memset(&tmpContact, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+                                               MsgGetContactInfo(&addrInfo, &tmpContact);
+
+                                               if (tmpContact.firstName[0] != '\0') {
+                                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s", tmpContact.firstName);
+                                               } else if (addrInfo.addressVal[0] == '\0') {
+                                                       char *senderStr = NULL;
+                                                       senderStr = getTranslateText(MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR, MSG_UNKNOWN_SENDER);
+                                                       g_strlcat(noti_info->sender, senderStr, sizeof(noti_info->sender)-strlen(noti_info->sender));
+                                                       if (senderStr) {
+                                                               free(senderStr);
+                                                               senderStr = NULL;
+                                                       }
+                                               } else {
+                                                       snprintf(noti_info->sender, sizeof(noti_info->sender), "%s", addrInfo.addressVal);
+                                               }
+
+                                               snprintf(noti_info->number, sizeof(noti_info->number), "%s", addrInfo.addressVal);
+
+                                               noti_info->time = (time_t)dbhandler->columnInt(1);
+
+                                               noti_info->msg_id = (msg_message_id_t)dbhandler->columnInt(2);
+
+                                               mainType = (MSG_MAIN_TYPE_T)dbhandler->columnInt(5);
+
+                                               if (mainType == MSG_TYPE_MMS)
+                                                       snprintf(noti_info->text, sizeof(noti_info->text), "%s", (char*)dbhandler->columnText(4));
+                                               else
+                                                       snprintf(noti_info->text, sizeof(noti_info->text), "%s", (char*)dbhandler->columnText(3));
+
+                                               MSG_DEBUG("Sent failed message ID [%d].", noti_info->msg_id);
+                                       } else {
+
+                                               MSG_DEBUG("No sent failed message.");
+                                               MSG_DEBUG("failedNotiId [%d]", noti_info->id);
+
+                                               dbhandler->finalizeQuery();
+
+                                               if (!isForInstantMessage) {
+                                                       // No unread message.
+                                                       if (noti_info->id > 0) {
+                                                               noti_err = notification_delete_by_priv_id(MSG_DEFAULT_APP_ID, NOTIFICATION_TYPE_NOTI, noti_info->id);
+                                                               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                                                                       MSG_DEBUG("Fail to notification_delete_by_priv_id : %d", noti_err);
+                                                               }
+                                                       }
+
+                                                       noti_info->id = 0;
+
+                                                       if (MsgSettingSetInt(MSG_SENTFAIL_NOTI_ID, noti_info->id) != MSG_SUCCESS)
+                                                               MSG_DEBUG("MsgSettingSetInt fail : MSG_SENTFAIL_NOTI_ID");
+                                               }
+
+                                               return MSG_ERR_DB_STEP;
+                                       }
+                               } else {
+                                       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+                                       dbhandler->finalizeQuery();
+                                       return MSG_ERR_DB_STEP;
+                               }
+
+                               dbhandler->finalizeQuery();
+                       }
+                       break;
+
+               case MSG_NOTI_TYPE_SIM_FULL :
+                       break;
+
+               default:
+                       {
+                               MSG_DEBUG("No matching type [%d]", noti_info->type);
+                               return MSG_ERR_UNKNOWN;
+                       }
+                       break;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+void setFlashNoti(void)
+{
+       MSG_BEGIN();
+
+       int ret = 0;
+
+       if (!bFeedbackInit) {
+               int ret = feedback_initialize();
+
+               if (ret != FEEDBACK_ERROR_NONE) {
+                       MSG_DEBUG("Fail to feedback_initialize : [%d]", ret);
+                       bFeedbackInit = false;
+                       return;
+               } else {
+                       MSG_DEBUG("Success to feedback_initialize.");
+                       bFeedbackInit = true;
+               }
+       }
+
+       ret = feedback_play_type(FEEDBACK_TYPE_LED, FEEDBACK_PATTERN_MESSAGE);
+       if (ret != FEEDBACK_ERROR_NONE)
+               MSG_DEBUG("Fail to feedback_play_type");
+
+       MSG_END();
+}
+
+
+void createServiceHandle(app_control_h *svc_h)
+{
+       int svc_err = APP_CONTROL_ERROR_NONE;
+
+       svc_err = app_control_create(svc_h);
+
+       if (svc_err != APP_CONTROL_ERROR_NONE)
+               MSG_DEBUG("app_control_create() is failed, [%d]", svc_err);
+}
+
+
+void setServiceAppId(app_control_h svc_h, const char* app_id)
+{
+       int svc_err = APP_CONTROL_ERROR_NONE;
+
+       svc_err = app_control_set_app_id(svc_h, app_id);
+
+       if (svc_err != APP_CONTROL_ERROR_NONE)
+               MSG_DEBUG("app_control_set_app_id() was failed, [%d]", svc_err);
+}
+
+
+void setServiceOperation(app_control_h svc_h, const char* operation)
+{
+       int svc_err = APP_CONTROL_ERROR_NONE;
+
+       svc_err = app_control_set_operation(svc_h, operation);
+
+       if (svc_err != APP_CONTROL_ERROR_NONE)
+               MSG_DEBUG("app_control_set_operation() was failed, [%d]", svc_err);
+}
+
+
+void addServiceExtraData(app_control_h svc_h, const char* bundle_key, const char* bundle_val)
+{
+       int svc_err = APP_CONTROL_ERROR_NONE;
+
+       svc_err = app_control_add_extra_data(svc_h, bundle_key, bundle_val);
+
+       if (svc_err != APP_CONTROL_ERROR_NONE)
+               MSG_DEBUG("app_control_add_extra_data() was failed, [%d]", svc_err);
+}
+
+
+void addServiceExtraData(app_control_h svc_h, const char* bundle_key, int bundle_val)
+{
+       int svc_err = APP_CONTROL_ERROR_NONE;
+
+       char tempId[10];
+       memset(&tempId, 0x00, sizeof(tempId));
+       snprintf(tempId, sizeof(tempId), "%d", bundle_val);
+
+       svc_err = app_control_add_extra_data(svc_h, bundle_key, (const char *)tempId);
+
+       if (svc_err != APP_CONTROL_ERROR_NONE)
+               MSG_DEBUG("app_control_add_extra_data() was failed, [%d]", svc_err);
+}
+
+
+void setServicePackageName(app_control_h svc_h, const char* pkg_name)
+{
+       int svc_err = APP_CONTROL_ERROR_NONE;
+
+       svc_err = app_control_set_app_id(svc_h, pkg_name);
+
+       if (svc_err != APP_CONTROL_ERROR_NONE)
+               MSG_DEBUG("app_control_set_app_id() was failed, [%d]", svc_err);
+}
+
+
+void sendServicelaunchRequest(app_control_h svc_h, app_control_reply_cb callback, void *user_data)
+{
+       int svc_err = APP_CONTROL_ERROR_NONE;
+
+       svc_err = app_control_send_launch_request(svc_h, callback, user_data);
+
+       if (svc_err != APP_CONTROL_ERROR_NONE)
+               MSG_DEBUG("app_control_send_launch_request() is failed : %d", svc_err);
+}
+
+
+void setNotiTextDomain(notification_h noti_h, const char *pkg_name, const char *loc_dir)
+{
+       int noti_err = NOTIFICATION_ERROR_NONE;
+
+       noti_err = notification_set_text_domain(noti_h, pkg_name, loc_dir);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("notification_set_text_domain() was failed. [%d]", noti_err);
+       }
+}
+
+
+void setNotiText(notification_h noti_h, notification_text_type_e type, const char *text, const char *key)
+{
+       int noti_err = NOTIFICATION_ERROR_NONE;
+
+       noti_err = notification_set_text(noti_h, type, text, key, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       if (noti_err != NOTIFICATION_ERROR_NONE)
+               MSG_DEBUG("notification_set_text() was failed. [%d]", noti_err);
+}
+
+
+void setNotiTimeToText(notification_h noti_h, notification_text_type_e type, time_t time)
+{
+       int noti_err = NOTIFICATION_ERROR_NONE;
+
+       noti_err = notification_set_time_to_text(noti_h, type, time);
+
+       if (noti_err != NOTIFICATION_ERROR_NONE)
+               MSG_DEBUG("notification_set_time_to_text() was failed. [%d]", noti_err);
+}
+
+
+void setNotiTime(notification_h noti_h, time_t time)
+{
+       int noti_err = NOTIFICATION_ERROR_NONE;
+
+       noti_err = notification_set_time(noti_h, time);
+
+       if (noti_err != NOTIFICATION_ERROR_NONE)
+               MSG_DEBUG("notification_set_time() was failed. [%d]", noti_err);
+}
+
+
+
+void setNotiImage(notification_h noti_h, notification_image_type_e type, const char *image_path)
+{
+       int noti_err = NOTIFICATION_ERROR_NONE;
+
+       noti_err = notification_set_image(noti_h, type, image_path);
+
+       if (noti_err != NOTIFICATION_ERROR_NONE)
+               MSG_DEBUG("notification_set_image() was failed. [%d]", noti_err);
+}
+
+
+void setNotiSound(notification_h noti_h, notification_sound_type_e type, const char *path)
+{
+       int noti_err = NOTIFICATION_ERROR_NONE;
+
+       noti_err = notification_set_sound(noti_h, type, path);
+
+       if (noti_err != NOTIFICATION_ERROR_NONE)
+               MSG_DEBUG("notification_set_sound() was failed. [%d]", noti_err);
+}
+
+
+void setNotiVibration(notification_h noti_h, notification_vibration_type_e type, const char *path)
+{
+       int noti_err = NOTIFICATION_ERROR_NONE;
+
+       noti_err = notification_set_vibration(noti_h, type, path);
+
+       if (noti_err != NOTIFICATION_ERROR_NONE)
+               MSG_DEBUG("notification_set_vibration() was failed. [%d]", noti_err);
+}
+
+
+char *getTranslateText(const char *pkg_name, const char *locale_dir, const char *text)
+{
+       char *notiMsg = NULL;
+       char *lang = NULL;
+
+       lang = vconf_get_str(VCONFKEY_LANGSET);
+
+       setlocale(LC_MESSAGES, lang);
+
+       bindtextdomain(pkg_name, locale_dir);
+
+       notiMsg = dgettext(pkg_name, text);
+
+       if (lang) {
+               free(lang);
+               lang = NULL;
+       }
+
+       return g_strdup(notiMsg);
+}
+
+void MsgNotiSoundRepeatAlarmCB(int alarmId)
+{
+       MSG_BEGIN();
+
+       MsgRefreshNotification(MSG_NOTI_TYPE_NORMAL, true, true);
+
+#ifndef MSG_NOTI_INTEGRATION
+       MsgRefreshNotification(MSG_NOTI_TYPE_SIM, true, true);
+       MsgRefreshNotification(MSG_NOTI_TYPE_CB, true, true);
+#endif
+
+       MSG_END();
+       return;
+}
+
+
+void MsgSoundCreateRepeatAlarm(int RepeatTime)
+{
+       MSG_BEGIN();
+
+       int tmpAlarmId = 0;
+       time_t tmp_time;
+       struct tm repeat_tm;
+
+       time(&tmp_time);
+
+       tmp_time += (RepeatTime*60);
+       tzset();
+       localtime_r(&tmp_time, &repeat_tm);
+
+       if (MsgAlarmRegistration(&repeat_tm, MsgNotiSoundRepeatAlarmCB, &tmpAlarmId) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgAlarmRegistration fail.");
+               return;
+       }
+
+       g_alarmId = tmpAlarmId;
+       MSG_DEBUG("Set alarmId to [%d]", g_alarmId);
+
+       MSG_END();
+
+       return;
+}
+
+
+void MsgSoundSetRepeatAlarm()
+{
+       int nRepeatValue = 0;
+       long    nRepeatTime = 0;
+
+       nRepeatValue = MsgSettingGetInt(MSG_ALERT_REP_TYPE);
+
+       switch (nRepeatValue)
+       {
+               case MSG_ALERT_TONE_ONCE:
+                       nRepeatTime = 0;
+                       break;
+
+               case MSG_ALERT_TONE_2MINS:
+                       nRepeatTime = 2;
+                       break;
+
+               case MSG_ALERT_TONE_5MINS:
+                       nRepeatTime = 5;
+                       break;
+
+               case MSG_ALERT_TONE_10MINS:
+                       nRepeatTime = 10;
+                       break;
+
+               default:
+                       MSG_DEBUG("Invalid Repetition time");
+                       break;
+       }
+
+       MSG_DEBUG("nRepeatTime = %d", nRepeatTime);
+
+       if (nRepeatTime > 0) {
+               if (g_alarmId > 0) {
+                       if (MsgAlarmRemove(g_alarmId) != MSG_SUCCESS) {
+                               MSG_FATAL("MsgAlarmRemove fail.");
+                       }
+                       g_alarmId = 0;
+               }
+               MsgSoundCreateRepeatAlarm(nRepeatTime);
+       }
+
+       return;
+}
+
+
+void sendMsgReplyPopup(MSG_NOTI_INFO_S *noti_info)
+{
+       app_control_h svc_h = NULL;
+
+       createServiceHandle(&svc_h);
+
+       if (svc_h) {
+               setServicePackageName(svc_h, "org.tizen.msg-ui-reply");
+
+               MSG_DEBUG("Reply-popup display - Msg Id = [%d]", noti_info->msg_id);
+               addServiceExtraData(svc_h, "msgId", noti_info->msg_id);
+
+               sendServicelaunchRequest(svc_h, NULL, NULL);
+
+               app_control_destroy(svc_h);
+       }
+}
similarity index 66%
rename from msg_helper/MsgSensorWrapper.cpp
rename to externals/MsgSensorWrapper.cpp
index 4e615ca..1dc502d 100755 (executable)
@@ -1,32 +1,33 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
+
 #include "MsgDebug.h"
 #include "MsgCppTypes.h"
 #include "MsgGconfWrapper.h"
-#include "MsgHelper.h"
+#include "MsgSensorWrapper.h"
 
-#include <sensor.h>
+#include <sensor_internal.h>
 
 /*==================================================================================================
                                      VARIABLES
 ==================================================================================================*/
 int sensorHandler = -1;
 
-msg_sensor_cb cbFunction = NULL;
+msg_sensor_cb SensorCBFunction = NULL;
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
@@ -42,8 +43,9 @@ void MsgSensorCB(unsigned int event_type, sensor_event_data_t *event_data , void
                if(*my_event_data == MOTION_ENGIEN_TOP_TO_BOTTOM_DETECTION) {
                        MSG_DEBUG("top to bottom event detected.");
                        if(MsgSettingGetInt(VCONFKEY_SETAPPL_MOTION_ACTIVATION))
-                               if(MsgSettingGetInt(VCONFKEY_SETAPPL_USE_TURN_OVER))
-                                       cbFunction();
+                               if(MsgSettingGetInt(VCONFKEY_SETAPPL_USE_TURN_OVER)) {
+                                       if(SensorCBFunction) SensorCBFunction();
+                               }
                }
 }
 
@@ -62,13 +64,20 @@ msg_error_t MsgSensorConnect()
 
 void MsgSensorDisconnect()
 {
-       if(cbFunction != NULL)
-               cbFunction = NULL;
+       if(SensorCBFunction != NULL)
+               SensorCBFunction = NULL;
 
        if (sensorHandler < 0)
                return;
 
-       sf_stop(sensorHandler);
+       try
+       {
+               sf_stop(sensorHandler);
+       }
+       catch(int exception)
+       {
+               MSG_FATAL("sf_stop error[%d]", exception);
+       }
        sf_disconnect(sensorHandler);
 }
 
@@ -84,7 +93,7 @@ msg_error_t MsgRegSensorCB(msg_sensor_cb cb)
 
        if(cb != NULL) {
                // regist cb.
-               cbFunction = cb;
+               SensorCBFunction = cb;
        } else {
                MSG_DEBUG("cb is NULL.");
                return MSG_ERR_UNKNOWN;
diff --git a/externals/MsgSoundPlayer.cpp b/externals/MsgSoundPlayer.cpp
new file mode 100755 (executable)
index 0000000..784f4e9
--- /dev/null
@@ -0,0 +1,793 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include <wait.h>
+
+#include "MsgDebug.h"
+#include "MsgCppTypes.h"
+#include "MsgGconfWrapper.h"
+#include "MsgSettingTypes.h"
+#include "MsgDrmWrapper.h"
+#include "MsgSensorWrapper.h"
+#include "MsgUtilFile.h"
+#include "MsgStorageTypes.h"
+#include "MsgContact.h"
+#include "MsgAlarm.h"
+#include "MsgNotificationWrapper.h"
+#include "MsgSoundPlayer.h"
+
+#include <mm_error.h>
+#include <mm_player.h>
+#include <mm_session_private.h>
+#include <mm_sound.h>
+
+#include <feedback.h>
+
+/*==================================================================================================
+                                    DEFINES
+==================================================================================================*/
+#define MAX_SOUND_FILE_LEN 1024
+
+#define DEFAULT_ALERT_FILE             "/opt/usr/share/settings/Alerts/notification_sdk.wav"
+
+#define HAPTIC_TEST_ITERATION 1
+#define MSG_VIBRATION_INTERVAL 3000
+#define MSG_SOUND_TIMEOUT 5500
+
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+MMHandleType hPlayerHandle = 0;
+
+pthread_mutex_t muMmPlay = PTHREAD_MUTEX_INITIALIZER;
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF Functions
+==================================================================================================*/
+void MsgSoundRepeatAlarmCB(int alarmId)
+{
+       MSG_BEGIN();
+
+       MsgSoundPlayer::instance()->MsgSoundInitRepeatAlarm();
+
+       MSG_END();
+       return;
+}
+
+
+void MsgSensorCBStop()
+{
+       MSG_BEGIN();
+
+#if 0
+       MsgSoundPlayer::instance()->MsgSoundPlayStop();
+#else
+       MsgDeleteNotification(MSG_NOTI_TYPE_ALL, -1);
+
+       MsgRefreshNotification(MSG_NOTI_TYPE_ALL, false, false);
+
+#ifndef MSG_NOTI_INTEGRATION
+       MsgRefreshNotification(MSG_NOTI_TYPE_SIM, false, false);
+#endif
+
+#endif
+
+       MSG_END();
+}
+
+
+//static gboolean MsgSoundMelodyTimeout(gpointer data)
+//{
+//     MSG_BEGIN();
+//
+//     MsgSoundPlayer::instance()->MsgSoundPlayStop();
+//
+//     MSG_END();
+//
+//     return FALSE;
+//}
+
+
+static int MsgSoundPlayCallback(int message, void *param, void *user_param)
+{
+       switch (message)
+       {
+               case MM_MESSAGE_BEGIN_OF_STREAM:
+                       MSG_DEBUG("Play is started.");
+                       break;
+               case MM_MESSAGE_END_OF_STREAM:
+               case MM_MESSAGE_STATE_INTERRUPTED:
+                       MSG_DEBUG("EOS or Interrupted.");
+                       MsgSoundPlayer::instance()->MsgSoundPlayStop();
+                       break;
+               case MM_MESSAGE_FILE_NOT_SUPPORTED:
+               case MM_MESSAGE_FILE_NOT_FOUND:
+               case MM_MESSAGE_DRM_NOT_AUTHORIZED:
+               case MM_MESSAGE_ERROR:
+                       MSG_DEBUG("message [%d] & play with default", message);
+                       MsgSoundPlayer::instance()->MsgSoundPlayStart(NULL, MSG_SOUND_PLAY_DEFAULT);
+                       break;
+               default:
+                       MSG_DEBUG("message [%d]", message);
+                       break;
+       }
+
+       return 1;
+}
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgSoundPlayer - Member Functions
+==================================================================================================*/
+MsgSoundPlayer* MsgSoundPlayer::pInstance = NULL;
+
+
+MsgSoundPlayer::MsgSoundPlayer()
+{
+       bPlaying = false;
+       bVibrating = false;
+       bFeedbackInit = false;
+       g_alarmId = 0;
+
+       defaultRingtonePath = NULL;
+
+       defaultRingtonePath = MsgSettingGetString(VCONFKEY_SETAPPL_NOTI_RINGTONE_DEFAULT_PATH_STR);
+
+       if (defaultRingtonePath == NULL || MsgGetFileSize(defaultRingtonePath) < 1) {
+               defaultRingtonePath = (char *)DEFAULT_ALERT_FILE;
+       }
+
+       MSG_DEBUG("defaultRingtonePath [%s]", defaultRingtonePath);
+
+       if (MsgSensorConnect() == MSG_SUCCESS) {
+               if (MsgRegSensorCB(&MsgSensorCBStop) != MSG_SUCCESS) {
+                       MSG_DEBUG("Fail to MsgRegSensorCB.");
+                       MsgSensorDisconnect();
+               }
+       } else {
+               MSG_DEBUG("Fail to MsgSensorConnect.");
+       }
+}
+
+
+MsgSoundPlayer::~MsgSoundPlayer()
+{
+
+}
+
+
+MsgSoundPlayer* MsgSoundPlayer::instance()
+{
+       if (!pInstance) {
+               MSG_DEBUG("pInstance is NULL. Now creating instance.");
+               pInstance = new MsgSoundPlayer();
+       }
+
+       return pInstance;
+}
+
+
+void MsgSoundPlayer::MsgGetRingtonePath(char *userRingtonePath, char **msg_tone_file_path_p)
+{
+       MSG_RINGTONE_TYPE_T ringtoneType = (MSG_RINGTONE_TYPE_T)MsgSettingGetInt(MSG_SETTING_RINGTONE_TYPE);
+
+       MSG_DEBUG("Ringtone type = [%d]", ringtoneType);
+
+       if (ringtoneType == MSG_RINGTONE_TYPE_SILENT) {
+               *msg_tone_file_path_p = NULL;
+               return;
+       }
+
+       char *tmpFilePath = NULL;
+       *msg_tone_file_path_p = new char[MSG_FILEPATH_LEN_MAX+1];
+
+       char *msg_tone_file_path = *msg_tone_file_path_p;
+
+       bool bUserRingtone = userRingtonePath && userRingtonePath[0] != '\0';
+       if (bUserRingtone) {
+               tmpFilePath = userRingtonePath;
+       } else {
+               if (ringtoneType == MSG_RINGTONE_TYPE_DEFAULT) {
+                       tmpFilePath = MsgSettingGetString(VCONFKEY_SETAPPL_NOTI_MSG_RINGTONE_PATH_STR);
+               } else {
+                       tmpFilePath = MsgSettingGetString(MSG_SETTING_RINGTONE_PATH);
+               }
+       }
+
+       memset(msg_tone_file_path, 0x00, sizeof(char)*(MSG_FILEPATH_LEN_MAX+1));
+
+       if ((tmpFilePath == NULL || MsgGetFileSize(tmpFilePath) < 1) || // wrong ringtone file path
+                       (MsgDrmIsDrmFile(tmpFilePath) && !MsgDrmCheckRingtone(tmpFilePath))) { // check DRM
+               if (tmpFilePath && (strcmp(tmpFilePath, "silent") == 0)) {
+                       MSG_DEBUG("Set ringtone to NONE(Silent)");
+                       msg_tone_file_path = NULL;
+               } else {
+                       MSG_DEBUG("Set ringtone to defaultRingtonePath.");
+                       strncpy(msg_tone_file_path, defaultRingtonePath, MSG_FILEPATH_LEN_MAX);
+               }
+       } else {
+               MSG_DEBUG("Set ringtone to tmpFilePath.");
+               snprintf(msg_tone_file_path, MSG_FILEPATH_LEN_MAX, "%s", tmpFilePath);
+       }
+
+       if (tmpFilePath && !bUserRingtone) {
+               free(tmpFilePath);
+               tmpFilePath = NULL;
+       }
+}
+
+
+bool MsgIsSoundPlayOnCall(void)
+{
+       bool bPlayOnCall = false;
+       int err = MM_ERROR_NONE;
+
+       mm_sound_device_in soundIn = MM_SOUND_DEVICE_IN_NONE;
+       mm_sound_device_out soundOut = MM_SOUND_DEVICE_OUT_NONE;
+
+       err = mm_sound_get_active_device(&soundIn, &soundOut);
+
+       if (err == MM_ERROR_NONE) {
+               if (soundOut & (MM_SOUND_DEVICE_OUT_RECEIVER|MM_SOUND_DEVICE_OUT_SPEAKER|MM_SOUND_DEVICE_OUT_BT_SCO))
+                       bPlayOnCall = true;
+               else
+                       bPlayOnCall = false;
+
+               MSG_DEBUG("mm_sound_device_out=[0x%04x],bPlayOnCall=[%d]", soundOut, bPlayOnCall);
+       } else {
+               MSG_DEBUG("mm_sound_get_active_device() err=[%d]", err);
+       }
+
+       return bPlayOnCall;
+}
+
+
+void MsgSoundPlayer::MsgGetPlayStatus(bool bVoiceMail, bool *bPlaySound, bool *bPlayVibration, bool *bOnCall)
+{
+       MSG_BEGIN();
+
+       if (!bPlaySound || !bPlayVibration || !bOnCall) {
+               MSG_DEBUG("IN parameter is NULL.");
+               return;
+       }
+
+       *bPlaySound = false;
+       *bPlayVibration = false;
+       *bOnCall = false;
+
+       /* Global setting */
+       bool bSoundOn = false; // sound setting on notification panel
+       bool bVibrationOn = false; // vibration setting on notification panel
+
+       /* Alert setting */
+#if 0  //not used value
+       bool bNotiVibrationOn = false; // alert vibration
+       MsgSettingGetBool(VCONFKEY_SETAPPL_VIBRATE_WHEN_NOTIFICATION_BOOL, &bNotiVibrationOn);
+#endif
+
+       bool bMsgSettingNoti = true; // Alert for message notification
+       bool bMsgSettingVibration = false; // vibration for message notification
+
+       MsgSettingGetBool(VCONFKEY_SETAPPL_SOUND_STATUS_BOOL, &bSoundOn);
+       MsgSettingGetBool(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, &bVibrationOn);
+
+       MsgSettingGetBool(MSG_SETTING_VIBRATION, &bMsgSettingVibration);
+       MsgSettingGetBool(MSG_SETTING_NOTIFICATION, &bMsgSettingNoti);
+
+       MSG_SEC_DEBUG("Sound status : Sound mode=[%d], Manner mode=[%d]", bSoundOn, bVibrationOn);
+       MSG_SEC_DEBUG("Msg Setting : Noti Alert=[%d], With vibration=[%d]", bMsgSettingNoti, bMsgSettingVibration);
+
+       int callStatus = 0;
+       int alertOnCall = 0;
+
+       callStatus = MsgSettingGetInt(VCONFKEY_CALL_STATE);
+       MSG_DEBUG("Call Status [%d]", callStatus);
+
+       /* Check call status */
+       if (callStatus > VCONFKEY_CALL_OFF && callStatus < VCONFKEY_CALL_STATE_MAX) {
+               /* 1. On Call */
+
+               *bOnCall = true; // set call status;
+
+               alertOnCall = MsgSettingGetInt(VCONFKEY_CISSAPPL_ALERT_ON_CALL_INT);
+               MSG_DEBUG("Alert On Call [%d]", alertOnCall);
+
+               if (alertOnCall == 0) {
+                       MSG_DEBUG("Call is active & Alert on Call - Off");
+               } else if (alertOnCall == 1) {
+                       /* set default value to true, while on Call  alert sound to be played  and vibration to be off. */
+                       bool bPlayOnCall = true;
+
+                       if (!bSoundOn) {
+                               /* check whther sound should be on when sound setting on notification panel is off */
+                               bPlayOnCall = MsgIsSoundPlayOnCall();
+                       }
+
+                       if (bVoiceMail) {       /* 1-1. Voice message */
+                               if (bPlayOnCall && bMsgSettingNoti) {
+                                       MSG_DEBUG("On call, Play sound - voice message");
+                                       *bPlaySound = true;
+                               } else {
+                                       MSG_DEBUG("On call, It doesn't play sound - voice message");
+                               }
+
+                               MSG_DEBUG("On call, It doesn't play vibration - voice message");
+                       } else {        /* 1-2. Normal message */
+                               if (bMsgSettingNoti) {
+                                       if (bPlayOnCall) {
+                                               MSG_DEBUG("On call, Play sound");
+                                               *bPlaySound = true;
+                                       } else {
+                                               MSG_DEBUG("On call, It doesn't play sound");
+                                       }
+
+                                       MSG_DEBUG("On call, It doesn't play vibration");
+                               }
+                       }
+               }
+       } else {
+               /* 2. Call is not active */
+
+               MSG_DEBUG("Call is not active.");
+               int voiceRecording = MsgSettingGetInt(VCONFKEY_VOICERECORDER_STATE);
+
+               if (bVoiceMail) {       /* 2-1. Voice message */
+                       if (bMsgSettingNoti) {
+                               if (bSoundOn || bVibrationOn) {
+                                       MSG_DEBUG("Play vibration - voice message.");
+                                       *bPlayVibration = true;
+                               } else {
+                                       MSG_DEBUG("It doesn't play vibration - voice message.");
+                               }
+
+                               MSG_DEBUG("Play sound - voice message.");
+                               *bPlaySound = true;
+
+                       } else {
+                               MSG_DEBUG("It doesn't play sound/vibration - voice message.");
+                       }
+               } else {        /* 2-1. Normal message */
+                       if (bMsgSettingNoti) {
+                               if (voiceRecording != VCONFKEY_VOICERECORDER_RECORDING) {
+                                       if (bSoundOn) {
+                                               MSG_DEBUG("Play sound.");
+                                               *bPlaySound = true;
+                                       } else {
+                                               MSG_DEBUG("It doesn't play vibration.");
+                                       }
+
+                                       if ((bSoundOn || bVibrationOn) && bMsgSettingVibration) {
+                                               MSG_DEBUG("Play vibration.");
+                                               *bPlayVibration = true;
+                                       } else {
+                                               MSG_DEBUG("It doesn't play vibration.");
+                                       }
+                               } else {
+                                       MSG_DEBUG("It doesn't play sound/vibration.");
+                               }
+                       } else {
+                               MSG_DEBUG("It doesn't play sound/vibration.");
+                       }
+               }
+       }
+
+       MSG_END();
+}
+
+
+void MsgSoundPlayer::MsgSoundPlayStart(const MSG_ADDRESS_INFO_S *pAddrInfo, MSG_SOUND_TYPE_T soundType)
+{
+       MSG_BEGIN();
+       MSG_DEBUG("soundType [%d]", soundType);
+
+       /* check camera state */
+       int cameraState = 0;    // camera recording state
+       cameraState = MsgSettingGetInt(VCONFKEY_CAMERA_STATE);
+       MSG_SEC_DEBUG("Camera state [%d]", cameraState);
+
+       if (cameraState == VCONFKEY_CAMERA_STATE_RECORDING) {
+               MSG_END();
+               return;
+       }
+
+       /* get contact information */
+       MSG_CONTACT_INFO_S contactInfo;
+       memset(&contactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+       if(pAddrInfo) {
+               // Get Contact Info
+               if (MsgGetContactInfo(pAddrInfo, &contactInfo) != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgGetContactInfo() fail.");
+               }
+       }
+
+       /* get ringtone file path */
+       char *msg_tone_file_path = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&msg_tone_file_path, unique_ptr_deleter);
+
+       if (soundType == MSG_SOUND_PLAY_EMERGENCY) {
+               msg_tone_file_path = new char[MAX_SOUND_FILE_LEN+1];
+               memset(msg_tone_file_path, 0x00, sizeof(char)*(MAX_SOUND_FILE_LEN+1));
+       } else if (soundType == MSG_SOUND_PLAY_DEFAULT) {
+               msg_tone_file_path = new char[MAX_SOUND_FILE_LEN+1];
+               memset(msg_tone_file_path, 0x00, sizeof(char)*(MAX_SOUND_FILE_LEN+1));
+               strncpy(msg_tone_file_path, DEFAULT_ALERT_FILE, MAX_SOUND_FILE_LEN);
+       } else {
+               MsgGetRingtonePath(contactInfo.alerttonePath, &msg_tone_file_path);
+       }
+
+       MSG_SEC_DEBUG("soundType [%d], Sound File [%s]", soundType, msg_tone_file_path);
+
+       /* get sound play status */
+       bool bPlaySound = false;
+       bool bPlayVibration = false;
+       bool bVoiceMsg = (soundType == MSG_SOUND_PLAY_VOICEMAIL)?true:false;
+       bool bOnCall = false;
+
+       MsgGetPlayStatus(bVoiceMsg, &bPlaySound, &bPlayVibration, &bOnCall);
+
+       MSG_SEC_DEBUG("sound=[%d], vibration=[%d], voice_msg?[%d], on_call?[%d]", \
+                       bPlaySound, bPlayVibration, bVoiceMsg, bOnCall);
+
+       /* play sound */
+       if (bPlaySound) {
+               int err = MM_ERROR_NONE;
+
+               if (soundType == MSG_SOUND_PLAY_EMERGENCY)
+                       err = mm_session_init(MM_SESSION_TYPE_EMERGENCY);
+               else
+                       err = mm_session_init(MM_SESSION_TYPE_NOTIFY);
+
+               if (err != MM_ERROR_NONE)
+                       MSG_DEBUG("MM Session Init Failed");
+               else
+                       MSG_DEBUG("MM Session Init Success : %d", err);
+
+
+               MsgSoundPlayMelody(msg_tone_file_path);
+
+               err = mm_session_finish();
+
+               if (err != MM_ERROR_NONE)
+                       MSG_DEBUG("MM Session Finish Failed.");
+               else
+                       MSG_DEBUG("MM Session Finish Success : %d", err);
+       }
+
+       /* play vibration */
+       if (bPlayVibration) {
+               MsgSoundPlayVibration(contactInfo.vibrationPath, bOnCall);
+       }
+
+       // For repeatition.
+//     MsgSoundSetRepeatAlarm();
+
+       MSG_END();
+}
+
+
+void MsgSoundPlayer::MsgSoundPlayStop()
+{
+       MSG_BEGIN();
+
+       pthread_mutex_lock(&muMmPlay);
+
+       if (bPlaying == true && hPlayerHandle != 0 ) {
+               MSG_DEBUG("stopping the player.");
+               /* Stop playing media contents */
+               int err = mm_player_stop(hPlayerHandle);
+
+               if (err != MM_ERROR_NONE) {
+                       MSG_DEBUG("stopping the player handle failed");
+               }
+
+       }
+
+       if (hPlayerHandle != 0) {
+               MSG_DEBUG("destroy the player.");
+
+               /* Uninitializing the player module */
+               mm_player_unrealize(hPlayerHandle);
+
+               /* Destroying the player handle */
+               mm_player_destroy(hPlayerHandle);
+       }
+
+       hPlayerHandle = 0;
+       bPlaying = false;
+
+       pthread_mutex_unlock(&muMmPlay);
+
+       MSG_END();
+}
+
+
+void MsgSoundPlayer::MsgSoundPlayMelody(char *pMsgToneFilePath)
+{
+       int err = MM_ERROR_NONE;
+
+       if (!pMsgToneFilePath) {
+               MSG_DEBUG("Ringtone path is NULL");
+               return;
+       }
+
+       pthread_mutex_lock(&muMmPlay);
+
+       if (hPlayerHandle != 0) {
+               mm_player_unrealize(hPlayerHandle);
+               mm_player_destroy(hPlayerHandle);
+               hPlayerHandle = 0;
+       }
+
+       err = mm_player_create(&hPlayerHandle);
+
+       pthread_mutex_unlock(&muMmPlay);
+
+       if (err != MM_ERROR_NONE) {
+               MSG_DEBUG("creating the player handle failed");
+               return;
+       }
+
+       /* Setting the call back function msg_callback */
+       mm_player_set_message_callback(hPlayerHandle, MsgSoundPlayCallback, NULL);
+
+       do {
+               /* Setting fade in/out, Volume */
+               err = mm_player_set_attribute(hPlayerHandle, NULL,
+                               "sound_volume_type", MM_SOUND_VOLUME_TYPE_NOTIFICATION,
+                               "profile_uri", pMsgToneFilePath, strlen(pMsgToneFilePath),
+                               "sound_priority", 2,
+                               NULL);
+
+               if (err != MM_ERROR_NONE) {
+                       MSG_DEBUG("error setting the profile attr [%d]", err);
+               }
+
+               err = mm_player_realize(hPlayerHandle);
+
+               if (err != MM_ERROR_NONE) {
+                       MSG_DEBUG("mm_player_realize() error : [%d]", err);
+                       if (pMsgToneFilePath != defaultRingtonePath) {
+                               pMsgToneFilePath = defaultRingtonePath;
+                       } else {
+                               return;
+                       }
+               }
+       } while(err != MM_ERROR_NONE);
+
+
+       pthread_mutex_lock(&muMmPlay);
+       MSG_DEBUG("mm_player_start with [%s]", pMsgToneFilePath);
+       err = mm_player_start(hPlayerHandle);
+
+       if (err != MM_ERROR_NONE) {
+               MSG_DEBUG("mm_player_start, FAIL [%x]", err);
+       } else {
+               /* Add Timer to stop playing after 5 sec. */
+//             int g_contact_timer = -1;
+//             g_contact_timer = g_timeout_add(MSG_SOUND_TIMEOUT, (GSourceFunc)MsgSoundMelodyTimeout, NULL);
+
+               bPlaying = true;
+       }
+       pthread_mutex_unlock(&muMmPlay);
+
+       return;
+}
+
+
+void MsgSoundPlayer::MsgSoundPlayVibration(char *vibrationPath, bool isOnCall)
+{
+       MSG_BEGIN();
+
+       int ret = 0;
+
+       if (!bFeedbackInit) {
+               int ret = feedback_initialize();
+
+               if (ret != FEEDBACK_ERROR_NONE) {
+                       MSG_DEBUG("Fail to feedback_initialize : [%d]", ret);
+                       bFeedbackInit = false;
+                       return;
+               } else {
+                       MSG_DEBUG("Success to feedback_initialize.");
+                       bFeedbackInit = true;
+               }
+       }
+
+       if(vibrationPath && strlen(vibrationPath))
+       {
+               MSG_DEBUG("vibrationPath: [%s]", vibrationPath);
+               ret = feedback_set_resource_path(FEEDBACK_TYPE_VIBRATION, FEEDBACK_PATTERN_MESSAGE, vibrationPath);
+               if (ret != FEEDBACK_ERROR_NONE)
+                       MSG_DEBUG("Fail to feedback_set_resource_path");
+               ret = feedback_play_type(FEEDBACK_TYPE_VIBRATION, FEEDBACK_PATTERN_MESSAGE);
+
+               if (ret != FEEDBACK_ERROR_NONE)
+                       MSG_DEBUG("Fail to feedback_play_type");
+       }
+       else
+       {
+               if (isOnCall)
+                       ret = feedback_play_type(FEEDBACK_TYPE_VIBRATION, FEEDBACK_PATTERN_MESSAGE_ON_CALL);
+               else
+               {
+                       ret = feedback_set_resource_path(FEEDBACK_TYPE_VIBRATION, FEEDBACK_PATTERN_MESSAGE, NULL);
+                       if (ret != FEEDBACK_ERROR_NONE)
+                               MSG_DEBUG("Fail to feedback_set_resource_path");
+                       ret = feedback_play_type(FEEDBACK_TYPE_VIBRATION, FEEDBACK_PATTERN_MESSAGE);
+               }
+
+               if (ret != FEEDBACK_ERROR_NONE)
+                       MSG_DEBUG("Fail to feedback_play_type");
+       }
+
+       MSG_END();
+}
+
+void MsgSoundPlayer::MsgSoundPlayDtmf()
+{
+       MSG_BEGIN();
+
+       int ret = 0;
+       int hToneHandle = 0;
+
+       ret = mm_sound_play_tone(MM_SOUND_TONE_PROP_BEEP2, VOLUME_TYPE_SYSTEM, 1.0, 300, &hToneHandle);
+
+       if(ret < 0) {
+               MSG_DEBUG("play tone failed.");
+       } else {
+               MSG_DEBUG("play tone success.");
+       }
+
+       MSG_END();
+}
+
+
+void MsgSoundPlayer::MsgSoundSetRepeatAlarm()
+{
+       int nRepeatValue = 0;
+       long    nRepeatTime = 0;
+
+       nRepeatValue = MsgSettingGetInt(MSG_ALERT_REP_TYPE);
+
+       switch (nRepeatValue)
+       {
+               case MSG_ALERT_TONE_ONCE:
+                       nRepeatTime = 0;
+               break;
+
+               case MSG_ALERT_TONE_2MINS:
+                       nRepeatTime = 2;
+               break;
+
+               case MSG_ALERT_TONE_5MINS:
+                       nRepeatTime = 5;
+               break;
+
+               case MSG_ALERT_TONE_10MINS:
+                       nRepeatTime = 10;
+               break;
+
+               default:
+                       MSG_DEBUG("Invalid Repetition time");
+               break;
+       }
+
+       MSG_DEBUG("nRepeatTime = %d", nRepeatTime);
+
+       if (nRepeatTime > 0) {
+               if (g_alarmId > 0) {
+                       if (MsgAlarmRemove(g_alarmId) != MSG_SUCCESS) {
+                               MSG_FATAL("MsgAlarmRemove fail.");
+                       }
+                       g_alarmId = 0;
+               }
+               MsgSoundCreateRepeatAlarm(nRepeatTime);
+       }
+
+       return;
+}
+
+
+void MsgSoundPlayer::MsgSoundCreateRepeatAlarm(int RepeatTime)
+{
+       MSG_BEGIN();
+
+       int alarmId = 0;
+       time_t tmp_time;
+       struct tm repeat_tm;
+
+       time(&tmp_time);
+
+       tmp_time += (RepeatTime*60);
+       tzset();
+       localtime_r(&tmp_time, &repeat_tm);
+
+       if (MsgAlarmRegistration(&repeat_tm, MsgSoundRepeatAlarmCB, &alarmId) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgAlarmRegistration fail.");
+               return;
+       }
+
+       g_alarmId = alarmId;
+       MSG_DEBUG("Set g_alarmId to [%d]", alarmId);
+
+       MSG_END();
+
+       return;
+}
+
+
+int MsgSoundPlayer::MsgSoundGetUnreadMsgCnt()
+{
+       int unreadCnt = 0;
+
+       // Get SMS Count
+       unreadCnt = MsgSettingGetInt(VCONFKEY_MESSAGE_RECV_SMS_STATE);
+
+       // Get MMS Count
+       unreadCnt += MsgSettingGetInt(VCONFKEY_MESSAGE_RECV_MMS_STATE);
+
+       MSG_DEBUG("unread count : [%d]", unreadCnt);
+
+       return unreadCnt;
+}
+
+void MsgSoundPlayer::MsgSoundInitRepeatAlarm()
+{
+       MSG_BEGIN();
+
+       int nRepeatValue = 0;
+       long    nRepeatTime = 0;
+
+       g_alarmId = 0;
+
+       if (MsgSoundGetUnreadMsgCnt() <= 0) {
+               MSG_DEBUG("no unread msg");
+               return;
+       }
+
+       nRepeatValue = MsgSettingGetInt(MSG_ALERT_REP_TYPE);
+
+       switch (nRepeatValue)
+       {
+               case MSG_ALERT_TONE_ONCE:
+                       nRepeatTime = 0;
+               break;
+
+               case MSG_ALERT_TONE_2MINS:
+                       nRepeatTime = 2;
+               break;
+
+               case MSG_ALERT_TONE_5MINS:
+                       nRepeatTime = 5;
+               break;
+
+               case MSG_ALERT_TONE_10MINS:
+                       nRepeatTime = 10;
+               break;
+
+               default:
+                       MSG_DEBUG("Invalid Repetition time");
+               break;
+       }
+
+       MSG_DEBUG("nRepeatTime = %d", nRepeatTime);
+
+       if (nRepeatTime > 0)
+               MsgSoundPlayStart(NULL, MSG_SOUND_PLAY_USER);
+
+       MSG_END();
+}
diff --git a/externals/MsgSpamFilter.cpp b/externals/MsgSpamFilter.cpp
new file mode 100755 (executable)
index 0000000..ec47690
--- /dev/null
@@ -0,0 +1,319 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include "MsgDebug.h"
+#include "MsgUtilFile.h"
+#include "MsgContact.h"
+#include "MsgCppTypes.h"
+#include "MsgGconfWrapper.h"
+#include "MsgSpamFilter.h"
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+msg_error_t MsgSetFilterOperation(bool bSetFlag)
+{
+       MSG_BEGIN();
+
+       if (MsgSettingSetBool(MSG_BLOCK_MESSAGE, bSetFlag) != MSG_SUCCESS) {
+               MSG_DEBUG("Error to set config data [%s]", MSG_BLOCK_MESSAGE);
+               return MSG_ERR_SET_SETTING;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgGetFilterOperation(bool *pSetFlag)
+{
+       MSG_BEGIN();
+
+       MsgSettingGetBool(MSG_BLOCK_MESSAGE, pSetFlag);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+bool MsgCheckFilter(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       // =======================================================================
+       // Check Unknown Sender
+       // =======================================================================
+       bool bBlockUnknown = false;
+
+       if (MsgSettingGetBool(MSG_BLOCK_UNKNOWN_MSG, &bBlockUnknown) == MSG_SUCCESS) {
+               if (bBlockUnknown == true && pMsgInfo->addressList[0].addressVal[0] == '\0') {
+                       MSG_DEBUG("Unknown sender message!!");
+                       return true;
+               }
+       }
+
+       // =======================================================================
+       // Check Filter Operation
+       // =======================================================================
+       bool filterFlag = false;
+
+       MsgGetFilterOperation(&filterFlag);
+
+       if (filterFlag == false) {
+               MSG_DEBUG("filter operation is not working");
+               return false;
+       }
+
+       // =======================================================================
+       // Check Filter by Address
+       // =======================================================================
+       int rowCnt = 0;
+
+       MSG_SEC_DEBUG("pMsg->addressList[0].addressVal [%s]", pMsgInfo->addressList[0].addressVal);
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILTER_ID FROM %s WHERE FILTER_TYPE = %d AND '%s' LIKE (CASE WHEN LENGTH(FILTER_VALUE)>%d-1 THEN '%%'||SUBSTR(FILTER_VALUE, LENGTH(FILTER_VALUE)-%d+1) ELSE FILTER_VALUE END) AND FILTER_ACTIVE = 1 \
+                       UNION SELECT FILTER_ID FROM %s WHERE FILTER_TYPE = %d AND '%s' LIKE SUBSTR(FILTER_VALUE,1)||'%%' AND FILTER_ACTIVE = 1 \
+                       UNION SELECT FILTER_ID FROM %s WHERE FILTER_TYPE = %d AND '%s' LIKE '%%'||SUBSTR(FILTER_VALUE,1)||'%%' AND FILTER_ACTIVE = 1 \
+                       UNION SELECT FILTER_ID FROM %s WHERE FILTER_TYPE = %d AND '%s' LIKE '%%'||SUBSTR(FILTER_VALUE,1) AND FILTER_ACTIVE = 1;",
+                       MSGFW_FILTER_TABLE_NAME, MSG_FILTER_BY_ADDRESS_SAME, pMsgInfo->addressList[0].addressVal, MsgContactGetMinMatchDigit(), MsgContactGetMinMatchDigit(),
+                       MSGFW_FILTER_TABLE_NAME, MSG_FILTER_BY_ADDRESS_START, pMsgInfo->addressList[0].addressVal,
+                       MSGFW_FILTER_TABLE_NAME, MSG_FILTER_BY_ADDRESS_INCLUDE, pMsgInfo->addressList[0].addressVal,
+                       MSGFW_FILTER_TABLE_NAME, MSG_FILTER_BY_ADDRESS_END, pMsgInfo->addressList[0].addressVal);
+
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+       if (rowCnt > 0) {
+               MSG_SEC_DEBUG("Msg is Filtered by Address : [%s]", pMsgInfo->addressList[0].addressVal);
+               pDbHandle->freeTable();
+               pMsgInfo->folderId = MSG_SPAMBOX_ID;
+               return true;
+       } else {
+               MSG_SEC_DEBUG("Msg is NOT Filtered by Address : [%s]", pMsgInfo->addressList[0].addressVal);
+               pDbHandle->freeTable();
+       }
+
+       // =======================================================================
+       // Check Filter by Subject
+       // =======================================================================
+       // Get Filter List
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILTER_VALUE FROM %s WHERE FILTER_TYPE = %d;",
+                       MSGFW_FILTER_TABLE_NAME, MSG_FILTER_BY_WORD);
+
+       rowCnt = 0;
+
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               pDbHandle->freeTable();
+               return false;
+       }
+
+       char filterValue[MAX_FILTER_VALUE_LEN+1];
+
+       char* pData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&pData, unique_ptr_deleter);
+
+       int fileSize = 0;
+       bool bFiltered = false;
+
+       for (int i = 1; i <= rowCnt; i++)
+       {
+               memset(filterValue, 0x00, sizeof(filterValue));
+
+               pDbHandle->getColumnToString(i, MAX_FILTER_VALUE_LEN, filterValue);
+
+               MSG_DEBUG("filterValue [%s]", filterValue);
+
+               if (strlen(filterValue) <= 0)
+                       continue;
+
+               if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE && pMsgInfo->msgType.subType == MSG_NORMAL_SMS) {
+                       if (pMsgInfo->bTextSms == false) {
+                               if (pData) {
+                                       delete[] pData;
+                                       pData = NULL;
+                               }
+
+                               if (MsgOpenAndReadFile(pMsgInfo->msgData, &pData, &fileSize) == false) {
+                                       pDbHandle->freeTable();
+                                       return false;
+                               }
+                               MSG_DEBUG("file data [%s]", pData);
+                       } else {
+                               if (pMsgInfo->dataSize > 0) {
+                                       if (pData) {
+                                               delete[] pData;
+                                               pData = NULL;
+                                       }
+
+                                       pData = new char[pMsgInfo->dataSize+1];
+
+                                       strncpy(pData, pMsgInfo->msgText, pMsgInfo->dataSize);
+                                       pData[strlen(pMsgInfo->msgText)] = '\0';
+                               }
+                       }
+               } else if(pMsgInfo->msgType.mainType == MSG_MMS_TYPE) {
+                       if (strlen(pMsgInfo->subject) > 0) {
+                               if (pData) {
+                                       delete[] pData;
+                                       pData = NULL;
+                               }
+
+                               pData = new char[strlen(pMsgInfo->subject)+1];
+
+                               strncpy(pData, pMsgInfo->subject, strlen(pMsgInfo->subject));
+                               pData[strlen(pMsgInfo->subject)] = '\0';
+                       }
+               }
+
+               // NULL value check
+               if (pData == NULL) {
+                       MSG_DEBUG("pData is NULL");
+
+                       bFiltered = false;
+                       break;
+               }
+
+               MSG_DEBUG("pData [%s]", pData);
+
+               if (strcasestr(pData, filterValue) != NULL) {
+#if 0
+                       MSG_CONTACT_INFO_S contactInfo;
+                       memset(&contactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+                       // Get Contact Info
+                       if (MsgGetContactInfo(&(pMsgInfo->addressList[0]), &contactInfo) == MSG_SUCCESS) {
+                               if (contactInfo.contactId > 0) {
+                                       MSG_SEC_DEBUG("Msg is Filtered by Subject [%s] Data [%s], but address is in contact. Skip.", filterValue, pData);
+                               } else {
+                                       MSG_DEBUG("Msg is Filtered by Subject [%s] Data [%s]", filterValue, pData);
+                                       bFiltered = true;
+                                       break;
+                               }
+                       } else {
+                               MSG_DEBUG("MsgGetContactInfo() fail.");
+                       }
+#else
+                       MSG_DEBUG("Msg is Filtered by Subject [%s] Data [%s]", filterValue, pData);
+                       bFiltered = true;
+                       break;
+#endif
+               }
+       }
+
+       pDbHandle->freeTable();
+
+       if (bFiltered == true) {
+               MSG_DEBUG("Msg is Filtered by Subject");
+
+               pMsgInfo->folderId = MSG_SPAMBOX_ID;
+
+               return true;
+       } else {
+               MSG_DEBUG("Msg is NOT Filtered by Subject");
+       }
+
+       MSG_END();
+
+       return false;
+}
+
+
+bool MsgCheckFilterByWord(MsgDbHandler *pDbHandle, const char *pMsgText)
+{
+       MSG_BEGIN();
+
+       if (!pMsgText) {
+               MSG_DEBUG("pMsgText is NULL");
+               return false;
+       }
+
+       msg_error_t err = MSG_SUCCESS;
+
+       // =======================================================================
+       // Check Filter Operation
+       // =======================================================================
+       bool filterFlag = false;
+
+       MsgGetFilterOperation(&filterFlag);
+
+       if (filterFlag == false) {
+               MSG_DEBUG("filter operation is not working");
+               return false;
+       }
+
+       int rowCnt = 0;
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+
+       // =======================================================================
+       // Check Filter by Word
+       // =======================================================================
+       // Get Filter List
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILTER_VALUE FROM %s WHERE FILTER_TYPE = %d;",
+                       MSGFW_FILTER_TABLE_NAME, MSG_FILTER_BY_WORD);
+
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               pDbHandle->freeTable();
+               return false;
+       }
+
+       char filterValue[MAX_FILTER_VALUE_LEN+1];
+       bool bFiltered = false;
+
+       for (int i = 1; i <= rowCnt; i++)
+       {
+               memset(filterValue, 0x00, sizeof(filterValue));
+
+               pDbHandle->getColumnToString(i, MAX_FILTER_VALUE_LEN, filterValue);
+
+               MSG_DEBUG("filterValue [%s]", filterValue);
+
+               if (strlen(filterValue) <= 0) continue;
+
+               if (strcasestr(pMsgText, filterValue) != NULL) {
+                       MSG_DEBUG("Msg is Filtered by Word [%s] ", filterValue);
+                       bFiltered = true;
+                       break;
+               }
+       }
+
+       pDbHandle->freeTable();
+
+       MSG_END();
+
+       return bFiltered;
+}
+
+
index 3494f19..596bba3 100755 (executable)
@@ -8,7 +8,7 @@ IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
 ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
 MESSAGE("Build type: ${CMAKE_BUILD_TYPE}")
 
-SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
+SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
 
 #########################################################
 # Define Plugin Manager
@@ -16,11 +16,10 @@ SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
 
 SET(PLUGIN-MANAGER-SRCS
        ${CMAKE_SOURCE_DIR}/framework/plugin-manager/MsgPluginManager.cpp
-       ${CMAKE_SOURCE_DIR}/framework/plugin-manager/MsgPluginConfig.cpp
 )
 
 INCLUDE_DIRECTORIES(
-    ${CMAKE_SOURCE_DIR}/include/mapi
+       ${CMAKE_SOURCE_DIR}/include/mapi
        ${CMAKE_SOURCE_DIR}/include/common
        ${CMAKE_SOURCE_DIR}/include/framework
        ${CMAKE_SOURCE_DIR}/include/utils
@@ -33,7 +32,7 @@ FOREACH(flag ${plugin_manager_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
 ENDFOREACH(flag)
 
-SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
 
 ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
 
@@ -62,27 +61,29 @@ SET(FW-HANDLER-SRCS
 )
 
 INCLUDE_DIRECTORIES(
-    ${CMAKE_SOURCE_DIR}/include/mapi
+       ${CMAKE_SOURCE_DIR}/include/mapi
        ${CMAKE_SOURCE_DIR}/include/common
        ${CMAKE_SOURCE_DIR}/include/framework
        ${CMAKE_SOURCE_DIR}/include/utils
+       ${CMAKE_SOURCE_DIR}/include/externals
+       ${CMAKE_SOURCE_DIR}/vobject-engine/include      
 )
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(fw_handler_pkgs REQUIRED glib-2.0 dlog vconf capi-appfw-application)
+pkg_check_modules(fw_handler_pkgs REQUIRED glib-2.0 gio-2.0 dlog vconf capi-appfw-application)
 
 FOREACH(flag ${fw_handler_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag} -std=c++0x")
 ENDFOREACH(flag)
 
-SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
 
 ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
 
 SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
 
 ADD_LIBRARY(${FW-HANDLER-LIB} SHARED ${FW-HANDLER-SRCS})
-TARGET_LINK_LIBRARIES(${FW-HANDLER-LIB} ${fw_handler_pkgs_LDFLAGS} ${UTILS-LIB} ${PLUGIN-MANAGER-LIB})
+TARGET_LINK_LIBRARIES(${FW-HANDLER-LIB} ${fw_handler_pkgs_LDFLAGS} ${UTILS-LIB} ${EXTERNALS-LIB} ${PLUGIN-MANAGER-LIB})
 
 INSTALL(TARGETS ${FW-HANDLER-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
 
@@ -99,9 +100,10 @@ SET(TRANS-MANAGER-SRCS
 )
 
 INCLUDE_DIRECTORIES(
-    ${CMAKE_SOURCE_DIR}/include/mapi
+       ${CMAKE_SOURCE_DIR}/include/mapi
        ${CMAKE_SOURCE_DIR}/include/common
        ${CMAKE_SOURCE_DIR}/include/framework
+       ${CMAKE_SOURCE_DIR}/include/externals
        ${CMAKE_SOURCE_DIR}/include/utils
 )
 
@@ -112,14 +114,14 @@ FOREACH(flag ${trans_manager_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
 ENDFOREACH(flag)
 
-SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
 
 ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
 
 SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
 
 ADD_LIBRARY(${TRANS-MANAGER-LIB} SHARED ${TRANS-MANAGER-SRCS})
-TARGET_LINK_LIBRARIES(${TRANS-MANAGER-LIB} ${trans_manager_pkgs_LDFLAGS} ${UTILS-LIB} ${FW-HANDLER-LIB})
+TARGET_LINK_LIBRARIES(${TRANS-MANAGER-LIB} ${trans_manager_pkgs_LDFLAGS} ${UTILS-LIB} ${EXTERNALS-LIB} ${FW-HANDLER-LIB})
 
 INSTALL(TARGETS ${TRANS-MANAGER-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
 
@@ -132,27 +134,31 @@ SET(MAIN-SRCS
 )
 
 INCLUDE_DIRECTORIES(
-    ${CMAKE_SOURCE_DIR}/include/mapi
+       ${CMAKE_SOURCE_DIR}/include/mapi
        ${CMAKE_SOURCE_DIR}/include/common
        ${CMAKE_SOURCE_DIR}/include/framework
+       ${CMAKE_SOURCE_DIR}/include/externals
        ${CMAKE_SOURCE_DIR}/include/utils
 )
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(main_pkgs REQUIRED glib-2.0 dbus-glib-1 dlog vconf)
+pkg_check_modules(main_pkgs REQUIRED glib-2.0 dlog vconf db-util)
 
 FOREACH(flag ${main_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
 ENDFOREACH(flag)
 
-SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
+SET(server_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIE")
 
 ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
 
-SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed -pie")
 
 ADD_EXECUTABLE(${PROJECT_NAME} ${MAIN-SRCS})
-TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${main_pkgs_LDFLAGS} ${UTILS-LIB} ${PLUGIN-MANAGER-LIB} ${TRANS-MANAGER-LIB} ${FW-HANDLER-LIB})
+TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${main_pkgs_LDFLAGS} ${UTILS-LIB} ${EXTERNALS-LIB} ${PLUGIN-MANAGER-LIB} ${TRANS-MANAGER-LIB} ${FW-HANDLER-LIB})
+
+SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "${server_CXX_FLAGS}")
 
 INSTALL(TARGETS ${PROJECT_NAME} DESTINATION bin)
 
index 8e0af31..0b4e336 100755 (executable)
@@ -1,21 +1,20 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-// for sl message browser launch
-#include <app_service.h>
+#include <app_control.h>
 
 #include "MsgDebug.h"
 #include "MsgUtilFile.h"
 #include "MsgStorageHandler.h"
 #include "MsgDeliverHandler.h"
 #include "MsgNotificationWrapper.h"
+#include "MsgDevicedWrapper.h"
 
 /*==================================================================================================
                                      VARIABLES
 ==================================================================================================*/
-extern MsgDbHandler dbHandle;
-
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
+
+void MsgPlayTTSMode(MSG_SUB_TYPE_T msgSubType, msg_message_id_t msgId, bool isFavorites)
+{
+       MSG_BEGIN();
+
+       bool bNotification = true;
+
+       if (MsgSettingGetBool(MSG_SETTING_NOTIFICATION, &bNotification) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgSettingGetBool is failed.");
+       }
+
+       if (bNotification == false) {
+               MSG_DEBUG("Msg Alert notification is off.");
+               return;
+       }
+
+       bool isTTSOn = false;
+       MsgSettingGetBool(VCONFKEY_SETAPPL_DRIVINGMODE_DRIVINGMODE, &isTTSOn);
+       MSG_DEBUG("VCONFKEY_SETAPPL_DRIVINGMODE_DRIVINGMODE [%d]", isTTSOn);
+
+       if(isTTSOn) {
+
+               bool isVoiceMail = false;
+
+               if (msgSubType == MSG_MWI_VOICE_SMS) {
+                       bool isVoiceMailOn = false;
+                       MsgSettingGetBool(VCONFKEY_SETAPPL_DRIVINGMODE_NEWVOICEMAILS, &isVoiceMailOn);
+                       MSG_DEBUG("VCONFKEY_SETAPPL_DRIVINGMODE_NEWVOICEMAILS [%d]", isVoiceMailOn);
+                       if (isVoiceMailOn) {
+                               isVoiceMail = true;
+                       } else {
+                               return;
+                       }
+               } else {
+                       bool isTTSMsgOn = false;
+                       MsgSettingGetBool(VCONFKEY_SETAPPL_DRIVINGMODE_MESSAGE, &isTTSMsgOn);
+                       MSG_DEBUG("VCONFKEY_SETAPPL_DRIVINGMODE_MESSAGE [%d]", isTTSMsgOn);
+                       if (!isTTSMsgOn || !isFavorites) {
+                               return;
+                       }
+               }
+
+               app_control_h svc_h;
+
+               int ret = APP_CONTROL_ERROR_NONE;
+
+               ret = app_control_create(&svc_h);
+               if (ret != APP_CONTROL_ERROR_NONE) {
+                       MSG_DEBUG("app_control_create() is failed : %d", ret);
+                       app_control_destroy(svc_h);
+                       return;
+               }
+
+               ret = app_control_set_app_id(svc_h, "org.tizen.msg-ui-tts-play");
+               if (ret != APP_CONTROL_ERROR_NONE) {
+                       MSG_DEBUG("app_control_set_app_id() is failed : %d", ret);
+                       app_control_destroy(svc_h);
+                       return;
+               }
+
+               if (isVoiceMail) {
+                       ret = app_control_add_extra_data(svc_h, "type", "voicemail");
+               } else {
+                       char tmpStrMsgId[10];
+                       memset(&tmpStrMsgId, 0x00, sizeof(tmpStrMsgId));
+                       snprintf(tmpStrMsgId, sizeof(tmpStrMsgId), "%d", msgId);
+                       MSG_DEBUG("tmpStrMsgId [%s]", tmpStrMsgId);
+                       ret = app_control_add_extra_data(svc_h, "msgId", tmpStrMsgId);
+               }
+
+               if (ret != APP_CONTROL_ERROR_NONE) {
+                       MSG_DEBUG("app_control_add_extra_data() is failed : %d", ret);
+                       app_control_destroy(svc_h);
+                       return;
+               }
+
+               ret = app_control_send_launch_request(svc_h, NULL, NULL);
+               if (ret != APP_CONTROL_ERROR_NONE) {
+                       MSG_DEBUG("app_control_send_launch_request() is failed : %d", ret);
+                       app_control_destroy(svc_h);
+                       return;
+               }
+
+               app_control_destroy(svc_h);
+       }
+
+       MsgChangePmState();
+
+       MSG_END();
+}
+
+
+void MsgLaunchClass0(msg_message_id_t msgId)
+{
+       MSG_BEGIN();
+
+       app_control_h svc_h;
+
+       int ret = APP_CONTROL_ERROR_NONE;
+
+       ret = app_control_create(&svc_h);
+       if (ret != APP_CONTROL_ERROR_NONE) {
+               MSG_DEBUG("app_control_create() is failed : %d", ret);
+               app_control_destroy(svc_h);
+               return;
+       }
+
+       ret = app_control_set_app_id(svc_h, "org.tizen.msg-ui-class0");
+       if (ret != APP_CONTROL_ERROR_NONE) {
+               MSG_DEBUG("app_control_set_app_id() is failed : %d", ret);
+               app_control_destroy(svc_h);
+               return;
+       }
+
+       ret = app_control_add_extra_data(svc_h, "type", "msg_id");
+       if (ret != APP_CONTROL_ERROR_NONE) {
+               MSG_DEBUG("app_control_add_extra_data() is failed : %d", ret);
+               app_control_destroy(svc_h);
+               return;
+       }
+
+       char tmpStrMsgId[10];
+       memset(&tmpStrMsgId, 0x00, sizeof(tmpStrMsgId));
+       snprintf(tmpStrMsgId, sizeof(tmpStrMsgId), "%d", msgId);
+       MSG_DEBUG("tmpStrMsgId [%s]", tmpStrMsgId);
+       ret = app_control_add_extra_data(svc_h, "msgId", tmpStrMsgId);
+       if (ret != APP_CONTROL_ERROR_NONE) {
+               MSG_DEBUG("app_control_add_extra_data() is failed : %d", ret);
+               app_control_destroy(svc_h);
+               return;
+       }
+
+       ret = app_control_send_launch_request(svc_h, NULL, NULL);
+       if (ret != APP_CONTROL_ERROR_NONE) {
+               MSG_DEBUG("app_control_send_launch_request() is failed : %d", ret);
+               app_control_destroy(svc_h);
+               return;
+       }
+
+       app_control_destroy(svc_h);
+
+       MSG_END();
+}
+
+
 msg_error_t MsgHandleMmsConfIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_request_id_t reqID)
 {
        MSG_BEGIN();
 
        msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
 
        MSG_DEBUG(" msgtype subtype is [%d]", pMsgInfo->msgType.subType);
 
        if (pMsgInfo->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || pMsgInfo->msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS) {
-               // keep origianl subType
+               // keep original subType
                MSG_SUB_TYPE_T subType = pMsgInfo->msgType.subType;
 
                /* If Retrieve Failed, Msg SubType is remained as Notification Ind */
-               if (pMsgInfo->networkStatus == MSG_NETWORK_RETRIEVE_FAIL)
+               if (pMsgInfo->networkStatus == MSG_NETWORK_RETRIEVE_FAIL) {
+                       pMsgInfo->folderId = MSG_INBOX_ID;
                        pMsgInfo->msgType.subType = MSG_NOTIFICATIONIND_MMS;
+               }
 
-               err = MsgStoUpdateMMSMessage(pMsgInfo);
-
-               if (err == MSG_SUCCESS)
-                       MSG_DEBUG("Command Handle Success : MsgStoUpdateMessage()");
+//             err = MsgStoUpdateMMSMessage(pMsgInfo);
+//
+//             if (err == MSG_SUCCESS)
+//                     MSG_DEBUG("Command Handle Success : MsgStoUpdateMessage()");
 
                if (pMsgInfo->networkStatus == MSG_NETWORK_RETRIEVE_SUCCESS) {
                        MSG_DEBUG("### MSG_NETWORK_RETRIEVE_SUCCESS ###");
@@ -65,6 +211,8 @@ msg_error_t MsgHandleMmsConfIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_reques
 
                        // MMS Received Ind Process Func
                        MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(pMsgInfo->msgType.mainType);
+                       if (plg == NULL)
+                               return MSG_ERR_NULL_POINTER;
 
                        //Contents of msg Data was removed and replaced to retrievedFilePath
                        // NOTICE:: now it was moved to handleEvent in MsgListnerThread
@@ -73,6 +221,12 @@ msg_error_t MsgHandleMmsConfIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_reques
                                return MSG_ERR_STORAGE_ERROR;
                }
 
+               err = MsgStoUpdateMMSMessage(pMsgInfo);//For Text Update
+
+               if (err == MSG_SUCCESS)
+                       MSG_DEBUG("Command Handle Success : MsgStoUpdateMessage()");
+
+
                MSG_DEBUG(" ######################### MESSAGE UPDATE COMPLETED!!! ######################");
 
                bool readStatus = false;
@@ -80,47 +234,46 @@ msg_error_t MsgHandleMmsConfIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_reques
                MsgStoGetReadStatus(pMsgInfo->msgId, &readStatus);
                MSG_DEBUG("### readStatus = %d ###", readStatus);
 
-               //Update Read Status to Unread beacaus Noti is Read
+               //Update Read Status to Unread because Noti is Read
                if (subType == MSG_RETRIEVE_MANUALCONF_MMS && pMsgInfo->networkStatus == MSG_NETWORK_RETRIEVE_SUCCESS) {
                        MSG_DEBUG("###2. subType = %d ###", pMsgInfo->msgType.subType);
 
-                       if (readStatus == true)
-                               MsgStoSetReadStatus(&dbHandle, pMsgInfo->msgId, false);
-               }
-
-               // update badge
-               if (subType == MSG_RETRIEVE_AUTOCONF_MMS || pMsgInfo->networkStatus == MSG_NETWORK_RETRIEVE_SUCCESS) {
-                       int smsCnt = 0;
-                       int mmsCnt = 0;
-
-                       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
-                       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
-
-                       MsgSettingHandleNewMsg(smsCnt, mmsCnt);
+                       if (readStatus == true) {
+                               MsgStoSetReadStatus(dbHandle, pMsgInfo->msgId, false);
+                               MsgRefreshNotification(MSG_NOTI_TYPE_NORMAL, false, false);
+                       }
                }
 
                if (subType == MSG_RETRIEVE_AUTOCONF_MMS) {
-                       // play message-tone when MMS retrieved
-                       MsgSoundPlayStart();
+                       bool isFavorites = false;
+                       if (!checkBlockingMode(pMsgInfo->addressList[0].addressVal, &isFavorites)) {
+                               MsgPlayTTSMode(subType, pMsgInfo->msgId, isFavorites);
+                       }
 
                        // add phone log
                        MSG_DEBUG("Enter MsgAddPhoneLog() for mms message.");
                        MsgAddPhoneLog(pMsgInfo);
 
-                       MsgInsertNoti(&dbHandle, pMsgInfo);
+                       if (pMsgInfo->folderId == MSG_INBOX_ID)
+                               MsgInsertNotification(pMsgInfo);
+
                }  else if (subType == MSG_RETRIEVE_MANUALCONF_MMS) {
                        if (pMsgInfo->networkStatus == MSG_NETWORK_RETRIEVE_SUCCESS) {
                                MSG_DEBUG("Manual success");
-                               MsgInsertTicker("Message Retrieved", MESSAGE_RETRIEVED);
+                               if (pMsgInfo->folderId == MSG_INBOX_ID)
+                                       MsgInsertTicker("Message Retrieved", MESSAGE_RETRIEVED, true, 0);
                        } else if (pMsgInfo->networkStatus == MSG_NETWORK_RETRIEVE_FAIL) {
                                MSG_DEBUG("Manual failed");
-                               MsgInsertTicker("Retrieving message failed", RETRIEVING_MESSAGE_FAILED);
+                               MsgInsertTicker("Retrieving message failed", RETRIEVING_MESSAGE_FAILED, true, pMsgInfo->msgId);
                        }
                }
        }
        else if (pMsgInfo->msgType.subType == MSG_SENDREQ_MMS || pMsgInfo->msgType.subType == MSG_SENDCONF_MMS)
        {
                MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(pMsgInfo->msgType.mainType);
+               if (plg == NULL)
+                       return MSG_ERR_NULL_POINTER;
+
                // change subType for storage update
                pMsgInfo->msgType.subType = MSG_SENDCONF_MMS;
 
@@ -133,7 +286,7 @@ msg_error_t MsgHandleMmsConfIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_reques
                        return MSG_ERR_STORAGE_ERROR;
 
                MSG_DEBUG("pMsg->networkStatus : %d", pMsgInfo->networkStatus);
-               err = MsgStoUpdateNetworkStatus(pMsgInfo, pMsgInfo->networkStatus);
+               err = MsgStoUpdateNetworkStatus(dbHandle, pMsgInfo, pMsgInfo->networkStatus);
                if (err != MSG_SUCCESS)
                        return MSG_ERR_STORAGE_ERROR;
 
@@ -158,21 +311,20 @@ msg_error_t MsgHandleIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti)
 
        msg_error_t err = MSG_SUCCESS;
 
-       if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE)
-       {
-               err = MsgHandleSMS(pMsgInfo, pSendNoti);
+       MsgDisplayLock();
 
-               if (err == MSG_SUCCESS && *pSendNoti == true)
-               {
-                       MsgSoundPlayStart();
+       if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE) {
 
-                       int smsCnt = 0, mmsCnt = 0;
+               bool bOnlyNoti = false;
 
-                       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
-                       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
+               err = MsgHandleSMS(pMsgInfo, pSendNoti, &bOnlyNoti);
 
-                       MsgSettingHandleNewMsg(smsCnt, mmsCnt);
-                       MsgInsertNoti(&dbHandle, pMsgInfo);
+               if (err == MSG_SUCCESS && ((*pSendNoti)||bOnlyNoti)) {
+                       bool isFavorites = false;
+                       if (!checkBlockingMode(pMsgInfo->addressList[0].addressVal, &isFavorites)) {
+                               MsgPlayTTSMode(pMsgInfo->msgType.subType, pMsgInfo->msgId, isFavorites);
+                       }
+                       MsgInsertNotification(pMsgInfo);
                }
        }
        else if (pMsgInfo->msgType.mainType == MSG_MMS_TYPE)
@@ -180,6 +332,8 @@ msg_error_t MsgHandleIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti)
                err = MsgHandleMMS(pMsgInfo, pSendNoti);
        }
 
+       MsgDisplayUnlock();
+
        //Add Phone Log Data
        if ((err == MSG_SUCCESS) &&
                (pMsgInfo->folderId == MSG_INBOX_ID || pMsgInfo->folderId == MSG_SPAMBOX_ID) &&
@@ -191,18 +345,123 @@ msg_error_t MsgHandleIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti)
                MsgAddPhoneLog(pMsgInfo);
        }
 
+       // Auto delete
+       //MsgStoAutoDeleteConversation(pMsgInfo->threadId);
+
        MSG_END();
 
        return err;
 }
 
 
-msg_error_t MsgHandleSMS(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti)
+msg_error_t MsgHandleSMS(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti, bool *bOnlyNoti)
 {
        msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       if (pMsgInfo->msgPort.valid == true) {
+               *pSendNoti = false;
+               *bOnlyNoti = false;
+               return MSG_SUCCESS;
+       }
+
+       // Add SMS message
+       MSG_SENDINGOPT_INFO_S send_opt;
+       memset(&send_opt, 0x00, sizeof(MSG_SENDINGOPT_INFO_S));
+
+       if (pMsgInfo->msgType.classType == MSG_CLASS_2) {
+#ifdef MSG_NOTI_INTEGRATION
+               MSG_DEBUG("Copy Class2 message to phone storage.");
+               pMsgInfo->msgType.classType = MSG_CLASS_NONE;
+               pMsgInfo->storageId = MSG_STORAGE_PHONE;
+               pMsgInfo->msgId = 0;
+#else
+               MSG_DEBUG("Class2 message is already added.");
+               return MSG_SUCCESS;
+#endif
+       }
+
+       if (pMsgInfo->msgType.subType == MSG_NORMAL_SMS) {
+               MSG_DEBUG("Add Normal Message");
+               err = MsgStoAddMessage(pMsgInfo, &send_opt);
+       } else if ((pMsgInfo->msgType.subType >= MSG_REPLACE_TYPE1_SMS) && (pMsgInfo->msgType.subType <= MSG_REPLACE_TYPE7_SMS)) {
+               MSG_DEBUG("Add Replace Message");
+
+               pMsgInfo->msgId = 0;
+               MsgStoGetReplaceMsgId(pMsgInfo);
+
+               if (pMsgInfo->msgId > 0) {
+                       err = MsgStoUpdateMessage(pMsgInfo, &send_opt);
+               } else {
+                       err = MsgStoAddMessage(pMsgInfo, &send_opt);
+                       pMsgInfo->msgType.subType = MSG_NORMAL_SMS; // To make 'insert' type for storage change callback.
+               }
+       } else if ((pMsgInfo->msgType.subType == MSG_WAP_SI_SMS) || (pMsgInfo->msgType.subType == MSG_WAP_CO_SMS) || (pMsgInfo->msgType.subType == MSG_WAP_SL_SMS)) {
+               MSG_DEBUG("Add WAP Push Message");
+               switch (pMsgInfo->msgType.subType)
+               {
+                       case MSG_WAP_SI_SMS:
+                       case MSG_WAP_SL_SMS:
+                               err = MsgStoAddWAPMsg(pMsgInfo);
+                               break;
+                       case MSG_WAP_CO_SMS:
+                               err = MsgStoAddCOWAPMsg(pMsgInfo);
+                               break;
+                       default :
+                               break;
+               }
+       } else if ((pMsgInfo->msgType.subType == MSG_CB_SMS) || (pMsgInfo->msgType.subType == MSG_JAVACB_SMS)) {
+               /** check add message option */
+       }
+       else if (pMsgInfo->msgType.subType == MSG_STATUS_REPORT_SMS) {
+               MSG_DEBUG("Add Report Message");
+       }
+       else if (pMsgInfo->msgType.subType >= MSG_MWI_VOICE_SMS && pMsgInfo->msgType.subType <= MSG_MWI_OTHER_SMS) {
+               char keyName[MAX_VCONFKEY_NAME_LEN];
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_NUMBER, pMsgInfo->sim_idx);
+               char *number = MsgSettingGetString(keyName);
+               int addrSize = strlen(pMsgInfo->addressList[0].addressVal);
+               char newPhoneNum[addrSize+1];
+               memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
+               MsgConvertNumber(pMsgInfo->addressList[0].addressVal, newPhoneNum, addrSize);
+
+               if (g_str_has_suffix(number, newPhoneNum)) {
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_ALPHA_ID, pMsgInfo->sim_idx);
+                       char *alphaId = MsgSettingGetString(keyName);
+                       if (alphaId) {
+                               memset(pMsgInfo->addressList->displayName, 0x00, sizeof(pMsgInfo->addressList->displayName));
+                               memcpy(pMsgInfo->addressList->displayName, alphaId, sizeof(pMsgInfo->addressList->displayName)-1);
+                               g_free(alphaId);
+                               alphaId = NULL;
+                       }
+               }
+
+               if(number)
+               {
+                       g_free(number);
+                       number = NULL;
+               }
+
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_COUNT, pMsgInfo->sim_idx);
+               int voicecnt = MsgSettingGetInt(keyName);
+               memset(pMsgInfo->msgText, 0x00, sizeof(pMsgInfo->msgText));
+               snprintf(pMsgInfo->msgText, sizeof(pMsgInfo->msgText), "%d", voicecnt);
+               pMsgInfo->dataSize = strlen(pMsgInfo->msgText);
+               MSG_DEBUG("Add Voice or other Message");
+       }
+       else {
+               MSG_DEBUG("No matching type [%d]", pMsgInfo->msgType.subType);
+               return err;
+       }
+
+       if (err != MSG_SUCCESS)
+               MSG_DEBUG("Add message - Error : [%d]", err);
 
        if (pMsgInfo->msgType.subType == MSG_NORMAL_SMS) {
-               if (MsgCheckFilter(&dbHandle, pMsgInfo) == true) {
+               if (MsgCheckFilter(dbHandle, pMsgInfo) == true) {
                        // Move to SpamBox
                        err = MsgStoMoveMessageToFolder(pMsgInfo->msgId, MSG_SPAMBOX_ID);
 
@@ -212,27 +471,31 @@ msg_error_t MsgHandleSMS(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti)
                                pMsgInfo->folderId = MSG_SPAMBOX_ID;
                        }
 
-                       // Update Conversation table
-                       err = MsgStoUpdateConversation(&dbHandle, pMsgInfo->threadId);
-
-                       if (err != MSG_SUCCESS)
-                               MSG_DEBUG("MsgStoUpdateConversation() Error : [%d]", err);
-
                        *pSendNoti = false;
+                       *bOnlyNoti = false;
+               } else if (pMsgInfo->msgType.classType == MSG_CLASS_0) {
+                       MsgLaunchClass0(pMsgInfo->msgId);
+                       bool isFavorites = false;
+                       if (!checkBlockingMode(pMsgInfo->addressList[0].addressVal, &isFavorites)) {
+                               MsgPlayTTSMode(pMsgInfo->msgType.subType, pMsgInfo->msgId, isFavorites);
+                               MsgSoundPlayer::instance()->MsgSoundPlayStart(&(pMsgInfo->addressList[0]), MSG_SOUND_PLAY_USER);
+                       }
+                       *pSendNoti = false;
+                       *bOnlyNoti = false;
                }
        } else if ((pMsgInfo->msgType.subType >= MSG_WAP_SI_SMS) && (pMsgInfo->msgType.subType <= MSG_WAP_CO_SMS)) {
                MSG_DEBUG("Starting WAP Message Incoming.");
 
                MSG_PUSH_SERVICE_TYPE_T serviceType = (MSG_PUSH_SERVICE_TYPE_T)MsgSettingGetInt(PUSH_SERVICE_TYPE);
-               service_h svc_handle = NULL;
+               app_control_h svc_handle = NULL;
 
                switch (pMsgInfo->msgType.subType) {
                        case MSG_WAP_SL_SMS:
                        {
-                               *pSendNoti = false;
+                               *pSendNoti = true;
 
                                if (serviceType == MSG_PUSH_SERVICE_ALWAYS) {
-                                       if (service_create(&svc_handle) < 0) {
+                                       if (app_control_create(&svc_handle) < 0) {
                                                MSG_DEBUG("Fail to create service handle");
                                                break;
                                        }
@@ -240,58 +503,103 @@ msg_error_t MsgHandleSMS(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti)
                                                MSG_DEBUG("Service handle is NULL");
                                                break;
                                        }
-                                       if (service_set_operation(svc_handle, SERVICE_OPERATION_VIEW) < 0) {
+                                       if (app_control_set_operation(svc_handle, APP_CONTROL_OPERATION_VIEW) < 0) {
                                                MSG_DEBUG("Fail to create service handle");
-                                               service_destroy(svc_handle);
+                                               app_control_destroy(svc_handle);
                                                break;
                                        }
-                                       if (service_set_uri(svc_handle, pMsgInfo->msgText) < 0) {
+                                       if (app_control_set_uri(svc_handle, pMsgInfo->msgText) < 0) {
                                                MSG_DEBUG("Fail to set uri");
-                                               service_destroy(svc_handle);
+                                               app_control_destroy(svc_handle);
                                                break;
                                        }
-                                       if (service_set_package(svc_handle, MSG_SVC_PKG_NAME_BROWSER) < 0) {
+                                       if (app_control_set_app_id(svc_handle, MSG_SVC_PKG_NAME_BROWSER) < 0) {
                                                MSG_DEBUG("Fail to set package");
-                                               service_destroy(svc_handle);
+                                               app_control_destroy(svc_handle);
                                                break;
                                        }
-                                       if (service_send_launch_request(svc_handle, NULL, NULL) < 0) {
+                                       if (app_control_send_launch_request(svc_handle, NULL, NULL) < 0) {
                                                MSG_DEBUG("Fail to launch browser");
-                                               service_destroy(svc_handle);
+                                               app_control_destroy(svc_handle);
                                                break;
                                        }
 
-                                       service_destroy(svc_handle);
+                                       app_control_destroy(svc_handle);
 
                                } else if (serviceType == MSG_PUSH_SERVICE_PROMPT) {
-                                       char urlString[MAX_COMMAND_LEN+1];
-                                       memset(urlString, 0x00, sizeof(urlString));
 
-                                       snprintf(urlString, MAX_COMMAND_LEN, "/opt/apps/org.tizen.message/bin/message-dialog -m PUSH_MSG_ALWAYS_ASK -u %s &", pMsgInfo->msgText);
+                                       MSG_DEBUG("WAP Message SL(Always Ask) start.");
 
-                                       system(urlString);
-                               }
+                                       app_control_h svc_h;
+                                       int ret = APP_CONTROL_ERROR_NONE;
+
+                                       ret = app_control_create(&svc_h);
+                                       if (ret != APP_CONTROL_ERROR_NONE) {
+                                               MSG_DEBUG("app_control_create() is failed : %d", ret);
+                                               break;
+                                       }
+
+                                       ret = app_control_set_app_id(svc_h, "org.tizen.message-dialog");
+                                       if (ret != APP_CONTROL_ERROR_NONE) {
+                                               MSG_DEBUG("app_control_set_app_id() is failed : %d", ret);
+                                               app_control_destroy(svc_h);
+                                               break;
+                                       }
+
+                                       ret = app_control_add_extra_data(svc_h, "mode", "WAP_PUSH_SL");
+                                       if (ret != APP_CONTROL_ERROR_NONE) {
+                                               MSG_DEBUG("app_control_add_extra_data() is failed : %d", ret);
+                                               app_control_destroy(svc_h);
+                                               break;
+                                       }
 
+                                       ret = app_control_add_extra_data(svc_h, "url", pMsgInfo->msgText);
+                                       if (ret != APP_CONTROL_ERROR_NONE) {
+                                               MSG_DEBUG("app_control_add_extra_data() is failed : %d", ret);
+                                               app_control_destroy(svc_h);
+                                               break;
+                                       }
+
+                                       ret = app_control_add_extra_data(svc_h, "address", pMsgInfo->addressList[0].addressVal);
+                                       if (ret != APP_CONTROL_ERROR_NONE) {
+                                               MSG_DEBUG("app_control_add_extra_data() is failed : %d", ret);
+                                               app_control_destroy(svc_h);
+                                               break;
+                                       }
+
+                                       ret = app_control_send_launch_request(svc_h, NULL, NULL);
+                                       if (ret != APP_CONTROL_ERROR_NONE) {
+                                               MSG_DEBUG("app_control_send_launch_request() is failed : %d", ret);
+                                       }
+
+                                       app_control_destroy(svc_h);
+                                       MSG_DEBUG("app_control_destroy() returns : %d", ret);
+                               }
                        }
                        break;
 
                        case MSG_WAP_SI_SMS:
+                               *pSendNoti = true;
+                               break;
                        case MSG_WAP_CO_SMS:
-                       {
                                *pSendNoti = false;
-                       }
-                       break;
+                               break;
                }
        } else if (pMsgInfo->msgType.subType == MSG_STATUS_REPORT_SMS) {
-               msg_thread_id_t convId = 0;
-
-               // Get Address ID
-               MsgExistAddress(&dbHandle, pMsgInfo, &convId);
+               *pSendNoti = false;
+               *bOnlyNoti = true;
+       } else if (pMsgInfo->msgType.subType >= MSG_MWI_VOICE_SMS && pMsgInfo->msgType.subType <= MSG_MWI_OTHER_SMS) {
+               if (pMsgInfo->bStore == false) {
+                       *pSendNoti = false;
+                       *bOnlyNoti = true;
+               }
+       }
 
-               MSG_DEBUG("Conversation ID : [%d], Value : [%s]", convId, pMsgInfo->addressList[0].addressVal);
+       // Update Conversation table
+       err = MsgStoUpdateConversation(dbHandle, pMsgInfo->threadId);
 
-               pMsgInfo->threadId = convId;
-       }
+       if (err != MSG_SUCCESS)
+               MSG_DEBUG("MsgStoUpdateConversation() Error : [%d]", err);
 
        return err;
 }
@@ -300,7 +608,7 @@ msg_error_t MsgHandleSMS(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti)
 msg_error_t MsgHandleMMS(MSG_MESSAGE_INFO_S *pMsgInfo,  bool *pSendNoti)
 {
        msg_error_t err = MSG_SUCCESS;
-
+       MsgDbHandler *dbHandle = getDbHandle();
        MSG_REQUEST_INFO_S request = {0};
        bool bReject = false;
        bool bFiltered = false;
@@ -309,6 +617,32 @@ msg_error_t MsgHandleMMS(MSG_MESSAGE_INFO_S *pMsgInfo,  bool *pSendNoti)
        MSG_MAIN_TYPE_T msgMainType = pMsgInfo->msgType.mainType;
        MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(msgMainType);
 
+       if (plg == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       // Read the default network SIM
+       MsgPlugin *sms_plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
+
+       if (sms_plg == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       int defaultNetworkSimId = 0;
+
+       err = sms_plg->getDefaultNetworkSimId(&defaultNetworkSimId);
+
+       MSG_DEBUG("######defaultNetworkSimId = %d, err = %d", defaultNetworkSimId, err);
+
+       if (err != MSG_SUCCESS) {
+               MSG_ERR("getDefaultNetworkSimId is failed=[%d]", err);
+               return err;
+       }
+
+       err = MsgSettingSetInt(MSG_NETWORK_SIM, (int)defaultNetworkSimId);
+       if (err != MSG_SUCCESS) {
+               MSG_ERR("Error to set config data [%s], err = %d", MSG_NETWORK_SIM, err);
+               return err;
+       }
+
        // Need to process m-delivery-ind, m-notification-ind, m-read-orig-ind
        err = plg->processReceivedInd(pMsgInfo, &request, &bReject);
 
@@ -316,16 +650,35 @@ msg_error_t MsgHandleMMS(MSG_MESSAGE_INFO_S *pMsgInfo,  bool *pSendNoti)
                MSG_DEBUG("Process Message Success : processReceivedInd(), btextsms %d", pMsgInfo->bTextSms);
        } else {
                MSG_DEBUG("Process Message Fail : processReceivedInd()");
+               *pSendNoti = false;
                return err;
        }
 
        // Add into DB
        if ((pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS) && bReject == false) {
-               bFiltered = MsgCheckFilter(&dbHandle, pMsgInfo);
+               //bFiltered = MsgCheckFilter(dbHandle, pMsgInfo);
+               if (pMsgInfo->folderId == MSG_SPAMBOX_ID) {
+                       bFiltered = true;
+               }
 
                if (bFiltered == true) {
+                       err = MsgStoMoveMessageToFolder(pMsgInfo->msgId, MSG_SPAMBOX_ID);
+
+                       if (err != MSG_SUCCESS) {
+                               MSG_DEBUG("MsgStoMoveMessageToFolder() Error : [%d]", err);
+                       } else {
+                               pMsgInfo->folderId = MSG_SPAMBOX_ID;
+                       }
+
                        pMsgInfo->networkStatus = MSG_NETWORK_RETRIEVE_FAIL;
                        *pSendNoti = false;
+               } else {/* If it is not SPAM message, it should be check whether filter option is enable or not. */
+                       bool filterFlag = false;
+                       MsgGetFilterOperation(&filterFlag);
+                       if (filterFlag == true && request.msgInfo.msgType.subType == MSG_GET_MMS) {
+                                /* Not to show MMS notification msg until it retrieves. */
+                               pMsgInfo->folderId = MSG_IOSBOX_ID;
+                       }
                }
 
                err = MsgStoAddMessage(pMsgInfo, NULL);
@@ -335,35 +688,55 @@ msg_error_t MsgHandleMMS(MSG_MESSAGE_INFO_S *pMsgInfo,  bool *pSendNoti)
                        return err;
                }
        } else if (pMsgInfo->msgType.subType == MSG_READORGIND_MMS || pMsgInfo->msgType.subType == MSG_DELIVERYIND_MMS) {
-               MsgSoundPlayStart();
-               *pSendNoti = false;
+               if (MsgInsertNotification(pMsgInfo) == MSG_SUCCESS) {
+                       bool isFavorites = false;
+                       if (!checkBlockingMode(pMsgInfo->addressList[0].addressVal, &isFavorites)) {
+                               MsgPlayTTSMode(pMsgInfo->msgType.subType, pMsgInfo->msgId, isFavorites);
+                       }
+                       *pSendNoti = false;
+               }
        }
 
+#if 0
+       if (pMsgInfo->bTextSms == false) {
+               MsgDeleteFile(pMsgInfo->msgData); //ipc
+               memset(pMsgInfo->msgData, 0x00, sizeof(pMsgInfo->msgData));
+       }
+#endif
        //In the case of m-notification-ind, we should decide whether to send m-notify-response-ind or http 'Get'
        //submit request
-       if (pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS && bFiltered == false) {
-               if (request.msgInfo.msgType.subType == MSG_NOTIFYRESPIND_MMS && bReject == false) {
-                       MsgSoundPlayStart();
+       if (pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS) {
+               if (request.msgInfo.msgType.subType == MSG_NOTIFYRESPIND_MMS && bReject == false && bFiltered == false) {
+                       bool isFavorites = false;
+                       if (!checkBlockingMode(pMsgInfo->addressList[0].addressVal, &isFavorites)) {
+                               MsgPlayTTSMode(pMsgInfo->msgType.subType, pMsgInfo->msgId, isFavorites);
+                       }
 
-                       int smsCnt = 0;
-                       int mmsCnt = 0;
+                       MsgInsertNotification(pMsgInfo);
+               } else {
+                       *pSendNoti = false;
+               }
 
-                       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
-                       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
+               MSG_DEBUG("default_sim = %d, pMsgInfo->sim_idx = %d", defaultNetworkSimId, pMsgInfo->sim_idx);
 
-                       MsgSettingHandleNewMsg(smsCnt, mmsCnt);
-                       MsgInsertNoti(&dbHandle, pMsgInfo);
-               }
+               if (defaultNetworkSimId == pMsgInfo->sim_idx) {
+                       request.msgInfo.msgId = pMsgInfo->msgId;
 
-               request.msgInfo.msgId = pMsgInfo->msgId;
+                       MSG_DEBUG("-=====================[[[ %s ]]]] =========================", request.msgInfo.msgData);
+                       err = plg->submitReq(&request);
 
-               MSG_DEBUG("-=====================[[[ %s ]]]] =========================", pMsgInfo->msgData);
-               err = plg->submitReq(&request);
+                       if (err == MSG_SUCCESS) {
+                               MSG_DEBUG("Process Message Success : processReceivedInd()");
+
+                               if (request.msgInfo.msgType.subType == MSG_GET_MMS) {
+                                       MSG_DEBUG("Auto Retrieve Mode : update network status retrieving");
+                                       MsgStoUpdateNetworkStatus(dbHandle, &(request.msgInfo), MSG_NETWORK_RETRIEVING);
+                               }
+
+                       } else {
+                               MSG_DEBUG("Process Message Fail : processReceivedInd()");
+                       }
 
-               if (err == MSG_SUCCESS) {
-                       MSG_DEBUG("Process Message Success : processReceivedInd()");
-               } else {
-                       MSG_DEBUG("Process Message Fail : processReceivedInd()");
                }
        }
 
index 02c6ba4..cfd57d5 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 /*==================================================================================================
 #include "MsgTransManager.h"
 #include "MsgStorageTypes.h"
 #include "MsgSoundPlayer.h"
+#include "MsgCmdHandler.h"
+#include "MsgUtilFile.h"
+#include "MsgUtilStorage.h"
+#include "MsgNotificationWrapper.h"
 
 #include <errno.h>
 #include <glib.h>
-#include <dbus/dbus-glib.h>
+#include <glib-object.h>
 #include <sys/stat.h>
 #include <wait.h>
 
 static GMainLoop* mainloop = NULL;
 
-
-/*==================================================================================================
-                                     DEFINES
-==================================================================================================*/
-#define MSG_MOBILE_TRACKER_MSG "Mobile Tracker Alert"
-
-
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
+
 msg_error_t InitMmsDir()
 {
        if (mkdir(MSG_DATA_ROOT_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0)
@@ -68,11 +66,11 @@ msg_error_t InitMmsDir()
        {
                if (errno == EEXIST)
                {
-                       MSG_DEBUG("The %s already exists", MSG_SMIL_FILE_PATH);
+                       MSG_SEC_DEBUG("The %s already exists", MSG_SMIL_FILE_PATH);
                }
                else
                {
-                       MSG_DEBUG("Error while mkdir %s", MSG_SMIL_FILE_PATH);
+                       MSG_SEC_DEBUG("Error while mkdir %s", MSG_SMIL_FILE_PATH);
                        return MSG_ERR_DB_MAKE_DIR;
                }
        }
@@ -104,11 +102,8 @@ msg_error_t InitMmsDir()
                if (errno == EEXIST)
                {
                        MSG_DEBUG("The %s already exists", MSG_IPC_DATA_PATH);
-
                        // if IPC data path is already exist, clear all files in folder.
-                       char exeStr[1024];
-                       snprintf(exeStr, 1024, "rm %s*.DATA", MSG_IPC_DATA_PATH);
-                       system(exeStr);
+                       MsgRmRf((char *)MSG_IPC_DATA_PATH);
                }
                else
                {
@@ -117,153 +112,47 @@ msg_error_t InitMmsDir()
                }
        }
 
-       chmod( MSG_IPC_DATA_PATH, S_IRWXU | S_IRWXG ); //public shared file: pass data by file
-       chown( MSG_IPC_DATA_PATH, 0, 6502 );
-
-       return MSG_SUCCESS;
-}
-
-
-void SendMobileTrackerMsg()
-{
-       MSG_BEGIN();
-
-       bool bEnabled = false;
-
-       if (MsgSettingGetBool(VCONFKEY_SETAPPL_FIND_MY_MOBILE_SIM_CHANGE_ALERT_BOOL, &bEnabled) < 0)
-       {
-               MSG_DEBUG("Can't read VCONFKEY_SETAPPL_FIND_MY_MOBILE_SIM_CHANGE_ALERT_BOOL");
-               return;
+       if (MsgChmod( MSG_IPC_DATA_PATH, S_IRWXU | S_IRWXG) == 0) { //public shared file: pass data by file
+               MSG_DEBUG("Fail to chmod [%s].", MSG_IPC_DATA_PATH);
        }
-
-       if (bEnabled == false)
-       {
-               MSG_DEBUG("Mobile Tracker Option [%d]", bEnabled);
-               return;
+       if (MsgChown(MSG_DATA_ROOT_PATH, 0, 5000) == 0) {
+               MSG_DEBUG("Fail to chown [%s].", MSG_DATA_ROOT_PATH);
        }
-       // to wait modem init
-       // temporary code.
-       else
-       {
-               MSG_DEBUG("Waiting for modem ready, 22 sec.");
-               sleep(22);
+       if (MsgChown(MSG_DATA_PATH, 0, 5000) == 0) {
+               MSG_DEBUG("Fail to chown [%s].", MSG_DATA_PATH);
        }
-
-       MSG_REQUEST_INFO_S req = {0};
-
-       req.sendOptInfo.bSetting = false;
-
-       req.msgInfo.msgId = 0;
-       req.msgInfo.threadId = 0;
-       req.msgInfo.folderId = MSG_DRAFT_ID;
-       req.msgInfo.msgType.mainType = MSG_SMS_TYPE;
-       req.msgInfo.msgType.subType = MSG_NORMAL_SMS;
-       req.msgInfo.msgType.classType = MSG_CLASS_NONE;
-       req.msgInfo.storageId = MSG_STORAGE_PHONE;
-       req.msgInfo.displayTime = 0;
-       req.msgInfo.networkStatus = MSG_NETWORK_NOT_SEND;
-       req.msgInfo.encodeType = MSG_ENCODE_AUTO;
-       req.msgInfo.bRead = false;
-       req.msgInfo.bProtected = false;
-       req.msgInfo.priority = MSG_MESSAGE_PRIORITY_NORMAL;
-       req.msgInfo.direction = MSG_DIRECTION_TYPE_MO;
-       req.msgInfo.msgPort.valid = false;
-       req.msgInfo.bTextSms = true;
-
-       // Get Message Text
-       char* msgText = NULL;
-
-       msgText = MsgSettingGetString(VCONFKEY_SETAPPL_FIND_MY_MOBILE_MESSAGE_STR);
-
-       if (msgText == NULL)
-       {
-               MSG_DEBUG("Assign Default Msg");
-               msgText = strdup(MSG_MOBILE_TRACKER_MSG);
+       if (MsgChown(MSG_SMIL_FILE_PATH, 0, 5000) == 0) {
+               MSG_DEBUG("Fail to chown [%s].", MSG_SMIL_FILE_PATH);
        }
-
-       MSG_DEBUG("mobile tracker msg : [%s]", msgText);
-
-       req.msgInfo.dataSize = strlen(msgText);
-       strncpy(req.msgInfo.msgText, msgText, req.msgInfo.dataSize);
-
-       // Get Address List
-       char *orgRecipientList = NULL;
-
-       orgRecipientList = MsgSettingGetString(VCONFKEY_SETAPPL_FIND_MY_MOBILE_RECIPIENTS_STR);
-
-       if (orgRecipientList == NULL)
-       {
-               MSG_DEBUG("recipient list is NULL");
-               return;
+       if (MsgChown(MSG_IPC_DATA_PATH, 0, 5000) == 0) {
+               MSG_DEBUG("Fail to chown [%s].", MSG_IPC_DATA_PATH);
+       }
+       if (MsgChown(MSG_THUMBNAIL_PATH, 0, 5000) == 0) {
+               MSG_DEBUG("Fail to chown [%s].", MSG_THUMBNAIL_PATH);
        }
 
-       int len = strlen(orgRecipientList);
-       char recipientList[len + 1];
-
-       memset(recipientList, 0, len + 1);
-       memcpy(recipientList, orgRecipientList, len);
-
-       MSG_DEBUG("recipient list : [%s]", recipientList);
-
-       req.msgInfo.nAddressCnt = 1;
-
-       char *token;
-
-       token = strtok(recipientList, "|");
+       return MSG_SUCCESS;
+}
 
-       MSG_MAIN_TYPE_T mainType = MSG_SMS_TYPE;
-       MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(mainType);
 
+void* InitMsgServer(void*)
+{
        msg_error_t err = MSG_SUCCESS;
+       MSG_DEBUG("Start InitMsgServer.");
 
-       while (token)
+       //CID 356902: Moving try block up to include MsgStoInitDB which also throws MsgException
+       try
        {
-               req.msgInfo.addressList[0].addressType = MSG_ADDRESS_TYPE_PLMN;
-               req.msgInfo.addressList[0].recipientType = MSG_RECIPIENTS_TYPE_TO;
-
-               memset(req.msgInfo.addressList[0].addressVal, 0x00, MAX_ADDRESS_VAL_LEN);
-               strncpy(req.msgInfo.addressList[0].addressVal, token, MAX_ADDRESS_VAL_LEN);
-
-               MSG_DEBUG("address : [%s]", req.msgInfo.addressList[0].addressVal);
-
-               if (plg != NULL)
-               {
-                       MSG_DEBUG("mobile tracker msg : [%s]", msgText);
-
-                       err = plg->submitReq(&req);
-
-                       if (err != MSG_SUCCESS)
-                       {
-                               MSG_DEBUG("fail to send mobile tracker msg : [%d]", err);
-                               break;
-                       }
+               // storage handler initialize
+               err = MsgStoInitDB(false);
+               if (err != MSG_SUCCESS) {
+                       MSG_ERR("FAIL TO INITIALIZE STORAGE HANDLER [%d]", err);
                }
 
-               token = strtok(NULL, "|");
-       }
-
-       if (msgText) {
-               free(msgText);
-               msgText = NULL;
-       }
-
-       if (orgRecipientList) {
-               free(orgRecipientList);
-               orgRecipientList = NULL;
-       }
-
+               MsgInitNoti();
 
-       MSG_END();
-
-       return;
-}
-
-
-void* StartMsgServer(void*)
-{
-       try
-       {
-               MsgTransactionManager::instance()->run();
+               // plugin manager initialize
+               MsgPluginManager::instance()->initialize();
        }
        catch (MsgException& e)
        {
@@ -274,21 +163,23 @@ void* StartMsgServer(void*)
                MSG_FATAL("%s", e.what());
        }
 
-       if (g_main_loop_is_running(mainloop))
-               g_main_loop_quit(mainloop);
+
+//     MsgSoundPlayer::instance()->MsgSoundInitRepeatAlarm();
+
+       MsgStoDisconnectDB();
+
+       MsgReleaseMemory();
+       MSG_DEBUG("End InitMsgServer.");
 
        return (void*)0;
 }
 
 
-void* InitMsgServer(void*)
+void* StartMsgServer(void*)
 {
-       msg_error_t err = MSG_SUCCESS;
-
        try
        {
-               // plugin manager initialize
-               MsgPluginManager::instance()->initialize();
+               MsgTransactionManager::instance()->run();
        }
        catch (MsgException& e)
        {
@@ -299,152 +190,53 @@ void* InitMsgServer(void*)
                MSG_FATAL("%s", e.what());
        }
 
-       MSG_MAIN_TYPE_T mainType = MSG_SMS_TYPE;
-       MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(mainType);
-
-       // storage handler initialize
-       err = MsgStoInitDB(false);
-
-       if (err != MSG_SUCCESS) {
-               MSG_DEBUG("FAIL TO INITIALIZE STORAGE HANDLER [%d]", err);
-       }
-
-       // Set Msg FW Ready Flag
-       MsgSettingSetBool(VCONFKEY_MSG_SERVER_READY, true);
-       MSG_DEBUG("### VCONFKEY_MSG_SERVER_READY ###");
-
-       if (plg == NULL) {
-               MSG_DEBUG("No plugin for %d type", mainType);
-
-               MsgReleaseMemory();
-               return (void*)0;
-       }
-
-       MSG_SIM_STATUS_T simStatus = MSG_SIM_STATUS_NORMAL;
-
-       // Check Sim Status
-       if (plg->checkSimStatus(&simStatus) == MSG_SUCCESS) {
-
-               // Add the change of SIM to vconf
-               if (MsgSettingSetInt(MSG_SIM_CHANGED, (int)simStatus) != MSG_SUCCESS) {
-                       MSG_DEBUG("Error to set config data [%s]", MSG_SIM_CHANGED);
-               }
-
-               if (simStatus != MSG_SIM_STATUS_NOT_FOUND) {
-                       // Check Device Status
-                       if (plg->checkDeviceStatus() != MSG_SUCCESS) {
-                               MSG_DEBUG("checkDeviceStatus() error");
-
-                               MsgReleaseMemory();
-
-                               return (void*)0;
-                       }
-               }
-
-               // Init SIM Message
-               if (MsgInitSimMessage(simStatus) != MSG_SUCCESS) {
-                       MSG_DEBUG("Fail to Initialize SIM Message");
-               }
-
-               // Init SIM Configuration
-               if (MsgInitSimConfig(simStatus) != MSG_SUCCESS) {
-                       MSG_DEBUG("Fail to Initialize SIM Configuration");
-               }
-
-               // Add SendMobileTrackerMsg() to GMainLoop
-               if (simStatus == MSG_SIM_STATUS_CHANGED) {
-                       MSG_DEBUG("Send Mobile Tracker Message");
-
-                       SendMobileTrackerMsg();
-               }
-       } else {
-               MSG_DEBUG("checkSimStatus() error");
-       }
-
-       MsgReleaseMemory();
-
-       // Try to connect contact server  if it is not opened.
-       MsgOpenContactSvc();
-
-       // Register Callback to get the change of contact
-       MsgInitContactSvc(&MsgContactChangedCallback);
-
-       MsgSoundInitRepeatAlarm();
+       if (g_main_loop_is_running(mainloop))
+               g_main_loop_quit(mainloop);
 
        return (void*)0;
 }
 
 
-static gboolean InitThreadFunc(void* pData)
-{
-       MSG_BEGIN();
-
-       pthread_t initThreadId;
-
-       // initialize msg fw
-       if (pthread_create(&initThreadId, NULL, InitMsgServer, NULL) != 0)
-       {
-               MSG_DEBUG("InitMsgFw not invoked: %s", strerror(errno));
-               return -1;
-       }
-
-       pthread_detach(initThreadId);
-
-       MSG_END();
-
-       return FALSE;
-}
-
-
 int main(void)
 {
 #if !GLIB_CHECK_VERSION(2, 31, 0)
        g_thread_init(NULL);
 #endif
-       dbus_g_thread_init();
-
-////////////////////////////////////
-
-/// set to ignore child process terminated signal.
-signal( SIGCHLD, SIG_IGN );
-
-////////////////////////////////////
+       /* set to ignore child process terminated signal */
+       signal(SIGCHLD, SIG_IGN);
 
+       MSG_INFO("===========START MESSAGING FRAMEWORK==========");
 
-       MSG_DEBUG("===========START MESSAGING FRAMEWORK==========");
-
+#if !GLIB_CHECK_VERSION(2, 36, 0)
+       g_type_init();
+#endif
        // Reset message server ready flag
-       MsgSettingSetBool(VCONFKEY_MSG_SERVER_READY, false);
+       if(MsgSettingSetBool(VCONFKEY_MSG_SERVER_READY, false) != MSG_SUCCESS)
+               MSG_DEBUG("MsgSettingSetBool FAIL: VCONFKEY_MSG_SERVER_READY");
 
        // Connect to DB
        //      MsgStoConnectDB();
 
-       // Open Contact Service
-       MsgOpenContactSvc();
-
        // Clean up mms dir
        InitMmsDir();
 
-       // Regist vconf CB.
-       MsgSettingRegVconfCB();
+       // init server
+       InitMsgServer(NULL);
 
        pthread_t startThreadId;
 
        // start transaction manager
        if (pthread_create(&startThreadId, NULL, StartMsgServer, NULL) != 0)
        {
-               MSG_DEBUG("StartMsgServer not invoked: %s", strerror(errno));
+               MSG_DEBUG("StartMsgServer not invoked: %s", g_strerror(errno));
                return -1;
        }
 
-       MsgTransactionManager::instance()->getTMStatus();
+       // Regist vconf CB.
+       MsgSettingRegVconfCB();
 
        mainloop = g_main_loop_new(NULL, FALSE);
 
-       g_type_init();
-
-       g_idle_add(InitThreadFunc, NULL);
-
        if (mainloop != NULL)
        {
                MSG_DEBUG("Start Messaging Framework!!!");
@@ -457,6 +249,9 @@ signal( SIGCHLD, SIG_IGN );
                MSG_DEBUG("Fail to start Messaging Framework!!!");
        }
 
+       // free MmapMutex
+       MsgfreeMmapMutex();
+
        // Remove vconf CB
        MsgSettingRemoveVconfCB();
 
diff --git a/framework/plugin-manager/MsgPluginConfig.cpp b/framework/plugin-manager/MsgPluginConfig.cpp
deleted file mode 100755 (executable)
index 057498b..0000000
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include "MsgPluginConfig.h"
-#include "MsgException.h"
-
-
-/*==================================================================================================
-                                     IMPLEMENTATION OF MsgPlgToken - Member Functions
-==================================================================================================*/
-int MsgPlgToken::tokenize(char *pStr)
-{
-       MSG_BEGIN();
-
-       if (pStr == NULL)
-               THROW(MsgException::INVALID_PARAM, "pstr is NULL");
-
-       char *pFirst = index(pStr, '[');
-
-       if (pFirst) // title is enclosed by [ ]
-       {
-               pFirst++; // excluding '['
-
-               char *pEnd = index(pStr, ']');
-
-               if (pEnd)
-               {
-                       pEnd--;
-
-                       tokenType = TOK_PLG_TITLE;
-                       int len = pEnd-pFirst+1;
-
-                       memcpy(tokenVal, pFirst, len);
-                       tokenVal[len] = '\0';
-
-                       MSG_DEBUG("%s", tokenVal);
-               }
-               else
-                       THROW(MsgException::INVALID_RESULT, "']' not found");
-       }
-       else // (attribute, value) pair
-       {
-               char tokStr[strlen(pStr)+1];
-               strncpy(tokStr, pStr, strlen(pStr));
-
-               char *attr = strtok(tokStr, "=");
-               char *val = strtok(NULL, "=");
-
-               if (!attr || !val)
-               {
-                       tokenType = TOK_UNDEFINED;
-               }
-               else
-               {
-                       // trimming enter key
-                       char *tmp = index(val,'\n');
-
-                       if (tmp)
-                               *tmp = '\0';
-
-                       MSG_DEBUG("attr \"%s\", val \"%s\" ", attr, val);
-
-                       // classifying the attribute
-                       if (strcmp(attr, "type") == 0)
-                       {
-                               tokenType = TOK_PLG_TYPE;
-                               strncpy(tokenVal, val, 255);
-                       }
-                       else if (strcmp(attr, "path") == 0)
-                       {
-                               tokenType = TOK_PLG_PATH;
-                               strncpy(tokenVal, val, 255);
-                       }
-                       else
-                       {
-                               tokenType = TOK_UNDEFINED;
-                       }
-               }
-       }
-
-       MSG_END();
-
-       return tokenType;
-}
-
-
-/*==================================================================================================
-                                     IMPLEMENTATION OF MsgPlgConfig - Member Functions
-==================================================================================================*/
-MsgPlgConfig::MsgPlgConfig(FILE* fp)
-{
-       MSG_BEGIN();
-
-       if (fp == NULL)
-               THROW(MsgException::INVALID_PARAM, "fp is NULL");
-
-       MsgPlgToken tokTitle, tokMsgType, tokLibPath;
-
-       char str[256];
-       memset(str, 0x00, sizeof(str));
-
-       MsgPlgToken tok = MsgPlgToken();
-
-       while (fgets(str, 255, fp))
-       {
-               tok.tokenize(str); // parsing the line into tokens
-
-               switch ( tok.getType() )
-               {
-                       case MsgPlgToken::TOK_PLG_TITLE:
-                               // processing previous items
-                               if( tokTitle && tokMsgType && tokLibPath )
-                               {
-                                       insert(tokTitle, tokMsgType, tokLibPath);
-                               }
-
-                               tokTitle = tok;
-                               tokMsgType.reset();
-                               tokLibPath.reset();
-
-                               break;
-
-                       case MsgPlgToken::TOK_PLG_TYPE:
-                               tokMsgType = tok;
-                               break;
-
-                       case MsgPlgToken::TOK_PLG_PATH:
-                               tokLibPath = tok;
-                               break;
-
-                       default:
-                               MSG_DEBUG("the line \"%s\" is not accecpted", str);
-                               break;
-               }
-       }
-
-       if (tokTitle && tokMsgType && tokLibPath)
-       {
-               insert(tokTitle, tokMsgType, tokLibPath);
-       }
-
-       MSG_END();
-}
-
-
-void MsgPlgConfig::insert(const MsgPlgToken& tokTitle, const MsgPlgToken& tokMsgType, const MsgPlgToken& tokLibPath)
-{
-       MSG_BEGIN();
-
-       MsgPlgTokenVec item2add;
-       item2add.push_back(tokMsgType);
-       item2add.push_back(tokLibPath);
-
-       CharVector titleVec;
-       tokTitle.getVal(titleVec);
-       MsgConfigMap::iterator it=configMap.find(titleVec);
-
-       if (it == configMap.end())
-               configMap.insert(std::make_pair(titleVec, item2add));
-       else
-               THROW(MsgException::PLUGIN_ERROR, "duplicated plugin title");
-
-       MSG_DEBUG("item inserted");
-       MSG_DEBUG("token:%d,value:%s", tokTitle.getType(), tokTitle.getVal());
-       MSG_DEBUG("token:%d,value:%s", tokMsgType.getType(), tokMsgType.getVal());
-       MSG_DEBUG("token:%d,value:%s", tokLibPath.getType(), tokLibPath.getVal());
-
-       MSG_END();
-}
-
-
-const CharVector& MsgPlgConfig::title(unsigned int pos)
-{
-       if (pos >= configMap.size())
-               THROW(MsgException::OUT_OF_RANGE, "Input Parameter is not valid [%d]", pos);
-
-       MsgConfigMap::iterator it = configMap.begin();
-
-       unsigned int i=0;
-
-       while (it != configMap.end())
-       {
-               if (i++ == pos) break;
-               it++;
-       }
-
-       if (it == configMap.end())
-               THROW(MsgException::INVALID_RESULT, "no title");
-
-       MSG_DEBUG("searched title:%s", &(it->first)[0]);
-
-       return it->first;
-}
-
-
-void MsgPlgConfig::token(const CharVector& key, unsigned int pos, MsgPlgToken& retTok)
-{
-       MsgConfigMap::iterator it = configMap.find(key);
-
-       if (it != configMap.end()) //found
-       {
-               MSG_DEBUG("searched title:%s", &(it->first)[0]);
-
-               MsgPlgTokenVec tokVec = it->second;
-               retTok = tokVec[pos];
-
-               MSG_DEBUG("searched token:%d,value:%s", retTok.getType(), retTok.getVal());
-       }
-       else
-       {
-               THROW(MsgException::INVALID_RESULT, "no title");
-       }
-}
-
-
-void MsgPlgConfig::token(int i, unsigned int pos, MsgPlgToken& retTok)
-{
-       const CharVector& key = title(i);
-
-       token(key, pos, retTok);
-
-       MSG_DEBUG("returned token:%d,value:%s", retTok.getType(), retTok.getVal());
-}
-
index 7c5bf38..3b5f174 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
@@ -21,6 +21,7 @@
 #include "MsgUtilFile.h"
 #include "MsgException.h"
 #include "MsgIpcSocket.h"
+#include "MsgUtilFunction.h"
 #include "MsgCmdTypes.h"
 #include "MsgGconfWrapper.h"
 #include "MsgPluginManager.h"
@@ -38,7 +39,17 @@ void MsgSentStatusListener(MSG_SENT_STATUS_S *pSentStatus)
 
        // establish connection to msgfw daemon
        MsgIpcClientSocket client;
-       client.connect(MSG_SOCKET_PATH);
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+
+
 
        // composing command
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_SENT_STATUS_S); // cmd type, MSG_SENT_STATUS
@@ -62,8 +73,8 @@ void MsgSentStatusListener(MSG_SENT_STATUS_S *pSentStatus)
        MSG_DEBUG("Waiting result for SENT STATUS");
 
        char *temp = NULL;
-       AutoPtr<char> wrap(&temp);
-       int len;
+       unique_ptr<char*, void(*)(char**)> wrap(&temp, unique_ptr_deleter);
+       unsigned int len;
        client.read(&temp, &len);
 
        // close connection to msgfw daemon
@@ -81,7 +92,15 @@ void MsgStorageChangeListener(msg_storage_change_type_t storageChangeType, MSG_M
 
        // establish connection to msgfw daemon
        MsgIpcClientSocket client;
+       try
+       {
        client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
 
        // composing command
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_MESSAGE_INFO_S) + sizeof(msg_storage_change_type_t);
@@ -106,8 +125,8 @@ void MsgStorageChangeListener(msg_storage_change_type_t storageChangeType, MSG_M
        MSG_DEBUG("Waiting result for STORAGE CHANGE");
 
        char *temp = NULL;
-       AutoPtr<char> wrap(&temp);
-       int len;
+       unique_ptr<char*, void(*)(char**)> wrap(&temp, unique_ptr_deleter);
+       unsigned int len;
        client.read(&temp, &len);
 
        // close connection to msgfw daemon
@@ -123,7 +142,15 @@ msg_error_t MsgIncomingMessageListener(MSG_MESSAGE_INFO_S *pMsg)
 
        // establish connection to msgfw daemon
        MsgIpcClientSocket client;
-       client.connect(MSG_SOCKET_PATH);
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_UNKNOWN;
+       }
 
        // Check Invalid Message Structure
        if (pMsg == NULL)
@@ -133,8 +160,13 @@ msg_error_t MsgIncomingMessageListener(MSG_MESSAGE_INFO_S *pMsg)
                return MSG_ERR_NULL_MESSAGE;
        }
 
+       // Allocate Memory to Command Data
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+       int dataSize = MsgEncodeMsgInfo(pMsg, &encodedData);
+
        // composing command
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_MESSAGE_INFO_S); // cmd type, MSG_MESSAGE_INFO_S
+       int cmdSize = sizeof(MSG_CMD_S) + dataSize; // cmd type, MSG_MESSAGE_INFO_S
 
        MSG_DEBUG("cmdSize: %d", cmdSize);
 
@@ -148,14 +180,14 @@ msg_error_t MsgIncomingMessageListener(MSG_MESSAGE_INFO_S *pMsg)
 
        memset(pCmd->cmdCookie, 0x00, MAX_COOKIE_LEN);
 
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pMsg, sizeof(MSG_MESSAGE_INFO_S));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), encodedData, dataSize);
 
        // Send Command to Messaging FW
        client.write(cmdBuf, cmdSize);
 
        char* retBuf = NULL;
-       AutoPtr<char> wrap(&retBuf);
-       int retSize;
+       unique_ptr<char*, void(*)(char**)> wrap(&retBuf, unique_ptr_deleter);
+       unsigned int retSize;
 
        client.read(&retBuf, &retSize);
 
@@ -167,7 +199,12 @@ msg_error_t MsgIncomingMessageListener(MSG_MESSAGE_INFO_S *pMsg)
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)retBuf;
 
        if (pEvent->eventType != MSG_EVENT_PLG_INCOMING_MSG_IND)
-               THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               MSG_FATAL("Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               //THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+
+#ifdef FEATURE_SMS_CDMA
+       memcpy(&(pMsg->msgId), pEvent->data, sizeof(msg_message_id_t));
+#endif
 
        MSG_END();
 
@@ -181,7 +218,15 @@ msg_error_t MsgIncomingSyncMLMessageListener(MSG_SYNCML_MESSAGE_DATA_S *pSyncMLD
 
        // establish connection to msgfw daemon
        MsgIpcClientSocket client;
-       client.connect(MSG_SOCKET_PATH);
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_UNKNOWN;
+       }
 
        // composing command
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_SYNCML_MESSAGE_DATA_S); // cmd type, MSG_SYNCML_MESSAGE_DATA_S
@@ -204,8 +249,8 @@ msg_error_t MsgIncomingSyncMLMessageListener(MSG_SYNCML_MESSAGE_DATA_S *pSyncMLD
 
        // Receive result from Transaction Manager
        char* retBuf = NULL;
-       AutoPtr<char> wrap(&retBuf);
-       int retSize;
+       unique_ptr<char*, void(*)(char**)> wrap(&retBuf, unique_ptr_deleter);
+       unsigned int retSize;
        client.read(&retBuf, &retSize);
 
        // close connection to msgfw daemon
@@ -216,7 +261,144 @@ msg_error_t MsgIncomingSyncMLMessageListener(MSG_SYNCML_MESSAGE_DATA_S *pSyncMLD
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)retBuf;
 
        if (pEvent->eventType != MSG_EVENT_PLG_INCOMING_SYNCML_MSG_IND)
-               THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               MSG_FATAL("Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               //THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+
+       MSG_END();
+
+       return (pEvent->result);
+}
+
+msg_error_t MsgIncomingPushMessageListener(MSG_PUSH_MESSAGE_DATA_S *pPushData)
+{
+       MSG_BEGIN();
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_UNKNOWN;
+       }
+
+       // composing command
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_PUSH_MESSAGE_DATA_S); // cmd type, MSG_SYNCML_MESSAGE_DATA_S
+
+       MSG_DEBUG("cmdSize: %d", cmdSize);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_PLG_INCOMING_PUSH_IND;
+
+       memset(pCmd->cmdCookie, 0x00, MAX_COOKIE_LEN);
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pPushData, sizeof(MSG_PUSH_MESSAGE_DATA_S));
+
+       // Send Command to Messaging FW
+       client.write(cmdBuf, cmdSize);
+
+       // Receive result from Transaction Manager
+       char* retBuf = NULL;
+       unique_ptr<char*, void(*)(char**)> wrap(&retBuf, unique_ptr_deleter);
+       unsigned int retSize;
+       client.read(&retBuf, &retSize);
+
+       // close connection to msgfw daemon
+       client.close();
+
+       // Decoding the result from FW and Returning it to plugin
+       // the result is used for making delivery report
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)retBuf;
+
+       if (pEvent->eventType != MSG_EVENT_PLG_INCOMING_PUSH_MSG_IND)
+               MSG_FATAL("Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               //THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+
+       MSG_END();
+
+       return (pEvent->result);
+}
+
+
+msg_error_t MsgIncomingCBMessageListener(MSG_CB_MSG_S *pCbMsg, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_UNKNOWN;
+       }
+
+       // Check Invalid Message Structure
+       if (pCbMsg == NULL)
+       {
+               MSG_DEBUG("pMsg is NULL !!");
+
+               return MSG_ERR_NULL_MESSAGE;
+       }
+       int cmdSize = 0;
+
+       // Allocate Memory to Command Data
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+       int dataSize = MsgEncodeMsgInfo(pMsgInfo, &encodedData);
+
+       // composing command
+       if(pCbMsg->type == MSG_ETWS_SMS)
+               cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_CB_MSG_S); // cmd type, MSG_CB_MSG_S
+       else
+               cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_CB_MSG_S) + dataSize; // cmd type, MSG_CB_MSG_S
+
+       MSG_DEBUG("cmdSize: %d", cmdSize);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_PLG_INCOMING_CB_IND;
+
+       memset(pCmd->cmdCookie, 0x00, MAX_COOKIE_LEN);
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pCbMsg, sizeof(MSG_CB_MSG_S));
+
+       if(pCbMsg->type != MSG_ETWS_SMS)
+               memcpy((void*)((char*)pCmd + sizeof(MSG_CMD_TYPE_T)+ MAX_COOKIE_LEN + sizeof(MSG_CB_MSG_S)), encodedData, dataSize);
+
+       // Send Command to Messaging FW
+       client.write(cmdBuf, cmdSize);
+
+       char* retBuf = NULL;
+       unique_ptr<char*, void(*)(char**)> wrap(&retBuf, unique_ptr_deleter);
+       unsigned int retSize;
+
+       client.read(&retBuf, &retSize);
+
+       // close connection to msgfw daemon
+       client.close();
+
+       // Decoding the result from FW and Returning it to plugin
+       // the result is used for making delivery report
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)retBuf;
+
+       if (pEvent->eventType != MSG_EVENT_PLG_INCOMING_CB_MSG_IND)
+               MSG_FATAL("Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               //THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
 
        MSG_END();
 
@@ -230,7 +412,15 @@ msg_error_t MsgIncomingLBSMessageListener(MSG_LBS_MESSAGE_DATA_S *pLBSData)
 
        // establish connection to msgfw daemon
        MsgIpcClientSocket client;
-       client.connect(MSG_SOCKET_PATH);
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_UNKNOWN;
+       }
 
        // composing command
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_LBS_MESSAGE_DATA_S); // cmd type, MSG_LBS_MESSAGE_DATA_S
@@ -253,8 +443,8 @@ msg_error_t MsgIncomingLBSMessageListener(MSG_LBS_MESSAGE_DATA_S *pLBSData)
 
        // Receive result from Transaction Manager
        char* retBuf = NULL;
-       AutoPtr<char> wrap(&retBuf);
-       int retSize;
+       unique_ptr<char*, void(*)(char**)> wrap(&retBuf, unique_ptr_deleter);
+       unsigned int retSize;
        client.read(&retBuf, &retSize);
 
        // close connection to msgfw daemon
@@ -265,7 +455,8 @@ msg_error_t MsgIncomingLBSMessageListener(MSG_LBS_MESSAGE_DATA_S *pLBSData)
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)retBuf;
 
        if (pEvent->eventType != MSG_EVENT_PLG_INCOMING_LBS_MSG_IND)
-               THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               MSG_FATAL("Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               //THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
 
        MSG_END();
 
@@ -279,7 +470,15 @@ msg_error_t MsgInitSimBySatListener()
 
        // establish connection to msgfw daemon
        MsgIpcClientSocket client;
-       client.connect(MSG_SOCKET_PATH);
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_UNKNOWN;
+       }
 
        // composing command
        int cmdSize = sizeof(MSG_CMD_S);
@@ -297,8 +496,8 @@ msg_error_t MsgInitSimBySatListener()
 
        // Receive result from Transaction Manager
        char* retBuf = NULL;
-       AutoPtr<char> wrap(&retBuf);
-       int retSize;
+       unique_ptr<char*, void(*)(char**)> wrap(&retBuf, unique_ptr_deleter);
+       unsigned int retSize;
        client.read(&retBuf, &retSize);
 
        // close connection to msgfw daemon
@@ -308,7 +507,8 @@ msg_error_t MsgInitSimBySatListener()
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)retBuf;
 
        if (pEvent->eventType != MSG_EVENT_PLG_INIT_SIM_BY_SAT)
-               THROW(MsgException::INVALID_RESULT, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               MSG_FATAL("Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               //THROW(MsgException::INVALID_RESULT, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
 
        MSG_END();
 
@@ -319,14 +519,27 @@ msg_error_t MsgInitSimBySatListener()
 msg_error_t MsgMmsConfIncomingListener(MSG_MESSAGE_INFO_S *pMsg, msg_request_id_t *pReqId)
 {
        MSG_BEGIN();
-       MSG_DEBUG("pMsg = %s, pReqId = %d ", pMsg->msgData, *pReqId);
+       MSG_SEC_DEBUG("pMsg = %s, pReqId = %d ", pMsg->msgData, *pReqId);
 
        // establish connection to msgfw daemon
        MsgIpcClientSocket client;
-       client.connect(MSG_SOCKET_PATH);
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_UNKNOWN;
+       }
+
+       // Allocate Memory to Command Data
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+       int dataSize = MsgEncodeMsgInfo(pMsg, &encodedData);
 
        // composing command
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_MESSAGE_INFO_S) + sizeof(msg_request_id_t); // cmd type, MSG_MESSAGE_INFO_S, msg_request_id_t
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_request_id_t) + dataSize; // cmd type, MSG_MESSAGE_INFO_S, msg_request_id_t
        MSG_DEBUG("cmdSize : %d", cmdSize);
 
        char cmdBuf[cmdSize];
@@ -340,27 +553,320 @@ msg_error_t MsgMmsConfIncomingListener(MSG_MESSAGE_INFO_S *pMsg, msg_request_id_
        memset(pCmd->cmdCookie, 0x00, MAX_COOKIE_LEN); // cmd cookie
 
        // cmd data
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pMsg, sizeof(MSG_MESSAGE_INFO_S));
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_MESSAGE_INFO_S)), pReqId, sizeof(msg_request_id_t));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pReqId, sizeof(msg_request_id_t));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN + sizeof(msg_request_id_t)), encodedData, dataSize);
 
        // Send Command to Messaging FW
        client.write(cmdBuf, cmdSize);
 
        // Receive result from Transaction Manager
        char *retBuf = NULL;
-       AutoPtr<char> wrap(&retBuf);
-       int retSize = 0;
+       unique_ptr<char*, void(*)(char**)> wrap(&retBuf, unique_ptr_deleter);
+       unsigned int retSize = 0;
        client.read(&retBuf, &retSize);
 
        // close connection to msgfw daemon
        client.close();
 
-       //Decoding the result from FW and Returning it to plugin
-       // the result is used for making delivery report
+       // Decoding the result from FW and Returning it to plugin
        MSG_EVENT_S *pEvent = (MSG_EVENT_S *)retBuf;
 
-       if(pEvent->eventType != MSG_EVENT_PLG_INCOMING_MMS_CONF && pEvent->eventType != MSG_EVENT_PLG_SENT_STATUS_CNF)
-               THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+       if(pEvent->eventType != MSG_EVENT_PLG_INCOMING_MMS_CONF)
+               MSG_FATAL("Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               //THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+
+       MSG_END();
+
+       return (pEvent->result);
+}
+
+
+msg_error_t MsgSimMessageListener(MSG_MESSAGE_INFO_S *pMsg, int *simIdList, msg_message_id_t *retMsgId, int size)
+{
+       MSG_BEGIN();
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_UNKNOWN;
+       }
+
+       // Check Invalid Message Structure
+       if (pMsg == NULL)
+       {
+               MSG_DEBUG("pMsg is NULL !!");
+
+               return MSG_ERR_NULL_MESSAGE;
+       }
+
+       // Allocate Memory to Command Data
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+       int dataSize = MsgEncodeMsgInfo(pMsg, &encodedData);
+
+       char* encodedData2 = NULL;
+       unique_ptr<char*, void(*)(char**)> buf2(&encodedData2, unique_ptr_deleter);
+       encodedData2 = (char*)new char[dataSize + sizeof(int) + (sizeof(int)*size) + 1];
+
+       char *offset = NULL;
+       memcpy(encodedData2, encodedData, dataSize);
+       offset = encodedData2+dataSize;
+
+       memcpy(offset, &size, sizeof(int));
+       offset += sizeof(int);
+       MSG_DEBUG("size [%d]", size);
+
+       memcpy(offset, simIdList, (sizeof(int)*size));
+
+       MSG_DEBUG("simIdList[0] [%d]", simIdList[0]);
+
+       dataSize += ((sizeof(int)*size) + 1);
+
+       // composing command
+       int cmdSize = sizeof(MSG_CMD_S) + dataSize; // cmd type, MSG_MESSAGE_INFO_S
+
+       MSG_DEBUG("cmdSize: %d", cmdSize);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_ADD_SIM_MSG;
+
+       memset(pCmd->cmdCookie, 0x00, MAX_COOKIE_LEN);
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), encodedData2, dataSize);
+
+       // Send Command to Messaging FW
+       client.write(cmdBuf, cmdSize);
+
+       char* retBuf = NULL;
+       unique_ptr<char*, void(*)(char**)> wrap(&retBuf, unique_ptr_deleter);
+       unsigned int retSize;
+
+       client.read(&retBuf, &retSize);
+
+       // close connection to msgfw daemon
+       client.close();
+
+       // Decoding the result from FW and Returning it to plugin
+       // the result is used for making delivery report
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)retBuf;
+
+       if (pEvent->eventType != MSG_EVENT_ADD_SIM_MSG)
+               MSG_FATAL("Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               //THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+
+       //CID 48645: pEvent->data is an array hence null check is not required on it.
+       if (retMsgId) {
+               memcpy(retMsgId, pEvent->data, sizeof(msg_message_id_t));
+               MSG_DEBUG("Saved SIM message ID = [%d]", *retMsgId);
+       }
+
+       MSG_END();
+
+       return (pEvent->result);
+}
+
+msg_error_t MsgResendMessageListener(void)
+{
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_UNKNOWN;
+       }
+
+       // composing command
+       int cmdSize = sizeof(MSG_CMD_S);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_PLG_RESEND_MESSAGE;
+
+       // Send Command to Transaction Manager
+       client.write(cmdBuf, cmdSize);
+
+       // Receive result from Transaction Manager
+       char* retBuf = NULL;
+       unique_ptr<char*, void(*)(char**)> wrap(&retBuf, unique_ptr_deleter);
+       unsigned int retSize;
+       client.read(&retBuf, &retSize);
+
+       // close connection to msgfw daemon
+       client.close();
+
+       // Decoding the result from FW and Returning it to plugin
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)retBuf;
+
+       if (pEvent->eventType != MSG_EVENT_PLG_RESEND_MESSAGE)
+               MSG_FATAL("Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               //THROW(MsgException::INVALID_RESULT, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+
+       MSG_END();
+
+       return (pEvent->result);
+}
+
+#ifdef FEATURE_SMS_CDMA
+bool MsgCheckUniquenessListener(MSG_UNIQUE_INDEX_S *p_msg, msg_message_id_t msgId, bool bInsert)
+{
+       MSG_BEGIN();
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_UNKNOWN;
+       }
+
+       // Check Invalid Message Structure
+       if (p_msg == NULL)
+       {
+               MSG_DEBUG("p_msg is NULL !!");
+
+               return MSG_ERR_NULL_MESSAGE;
+       }
+
+       // Allocate Memory to Command Data
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+
+       int dataSize = sizeof(bool) + sizeof(msg_message_id_t) + sizeof(MSG_UNIQUE_INDEX_S);
+
+       encodedData = (char*)new char[dataSize];
+
+       MSG_DEBUG("Encoded Teleservice Msg Id = [%d]", p_msg->tele_msgId);
+       MSG_DEBUG("Encoded Address = [%s]", p_msg->address);
+       MSG_DEBUG("Encoded Sub Address = [%s]", p_msg->sub_address);
+
+       void* p = (void*)encodedData;
+
+       memcpy(p, &(bInsert), sizeof(bool));
+       p = (void*)((char*)p + sizeof(bool));
+
+       memcpy(p, &(msgId), sizeof(msg_message_id_t));
+       p = (void*)((char*)p + sizeof(msg_message_id_t));
+
+       memcpy(p, p_msg, sizeof(MSG_UNIQUE_INDEX_S));
+       p = (void*)((char*)p + sizeof(MSG_UNIQUE_INDEX_S));
+
+       // composing command
+       int cmdSize = sizeof(MSG_CMD_S) + dataSize; // cmd type, MSG_MESSAGE_INFO_S
+
+       MSG_DEBUG("cmdSize: %d", cmdSize);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_PLG_CHECK_UNIQUENESS;
+
+       memset(pCmd->cmdCookie, 0x00, MAX_COOKIE_LEN);
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), encodedData, dataSize);
+
+       // Send Command to Messaging FW
+       client.write(cmdBuf, cmdSize);
+
+       char* retBuf = NULL;
+       unique_ptr<char*, void(*)(char**)> wrap(&retBuf, unique_ptr_deleter);
+       unsigned int retSize;
+
+       client.read(&retBuf, &retSize);
+
+       // close connection to msgfw daemon
+       client.close();
+
+       // Decoding the result from FW and Returning it to plugin
+       // the result is used for making delivery report
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)retBuf;
+
+       if (pEvent->eventType != MSG_EVENT_PLG_CHECK_UNIQUENESS)
+               MSG_FATAL("Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               //THROW(MsgException::INCOMING_MSG_ERROR, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+
+       MSG_END();
+
+       if (pEvent->result == MSG_SUCCESS)
+               return true;
+       else
+               return false;
+}
+#endif
+
+msg_error_t MsgSimImsiListener(int sim_idx)
+{
+       MSG_BEGIN();
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       try
+       {
+               client.connect(MSG_SOCKET_PATH);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_UNKNOWN;
+       }
+
+       // composing command
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(int);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_UPDATE_IMSI;
+
+       memset(pCmd->cmdCookie, 0x00, MAX_COOKIE_LEN);
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), (const void *)&sim_idx, sizeof(int));
+
+       // Send Command to Transaction Manager
+       client.write(cmdBuf, cmdSize);
+
+       // Receive result from Transaction Manager
+       char* retBuf = NULL;
+       unique_ptr<char*, void(*)(char**)> wrap(&retBuf, unique_ptr_deleter);
+       unsigned int retSize;
+       client.read(&retBuf, &retSize);
+
+       // close connection to msgfw daemon
+       client.close();
+
+       // Decoding the result from FW and Returning it to plugin
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)retBuf;
+
+       if (pEvent->eventType != MSG_EVENT_UPDATE_IMSI)
+               MSG_FATAL("Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+               //THROW(MsgException::INVALID_RESULT, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
 
        MSG_END();
 
@@ -379,11 +885,11 @@ MsgPlugin::MsgPlugin(MSG_MAIN_TYPE_T mainType, const char *libPath): mSupportedM
        if (libPath == NULL)
                THROW(MsgException::INVALID_PARAM, "libPath NULL");
 
-        void* libHandle = NULL;
+       mLibHandler = NULL;
 
-       libHandle = dlopen(libPath, RTLD_NOW);
+       mLibHandler = dlopen(libPath, RTLD_NOW);
 
-       if (!libHandle)
+       if (!mLibHandler)
                THROW(MsgException::PLUGIN_ERROR, "ERROR dlopen library : [%s] [%s]", libPath, dlerror());
 
        // Clear Error
@@ -392,40 +898,48 @@ MsgPlugin::MsgPlugin(MSG_MAIN_TYPE_T mainType, const char *libPath): mSupportedM
        // assign the c function pointers
        msg_error_t(*pFunc)(MSG_PLUGIN_HANDLER_S*) = NULL;
 
-       pFunc = (msg_error_t(*)(MSG_PLUGIN_HANDLER_S*))dlsym(libHandle, "MsgPlgCreateHandle");
+       pFunc = (msg_error_t(*)(MSG_PLUGIN_HANDLER_S*))dlsym(mLibHandler, "MsgPlgCreateHandle");
 
        char *error = dlerror();
 
        if (error != NULL)
-               THROW(MsgException::PLUGIN_ERROR, "ERROR dlsym library : [%s]", dlerror());
+               THROW(MsgException::PLUGIN_ERROR, "ERROR dlsym library : [%s]", error);
 
-       if ((*pFunc)(&mPlgHandler) != MSG_SUCCESS)
+       if (pFunc && (*pFunc)(&mPlgHandler) != MSG_SUCCESS)
                THROW(MsgException::PLUGIN_ERROR, "ERROR to create plugin handle");
 
-       // Initialize Plug-in
-       if (initialize() != MSG_SUCCESS)
-               THROW(MsgException::PLUGIN_ERROR, "ERROR to initialize plugin");
-
        MSG_PLUGIN_LISTENER_S fwListener = {0};
-       fwListener.pfSentStatusCb                       = &MsgSentStatusListener;
-       fwListener.pfStorageChangeCb            = &MsgStorageChangeListener;
-       fwListener.pfMsgIncomingCb              = &MsgIncomingMessageListener;
-       fwListener.pfInitSimBySatCb                     = &MsgInitSimBySatListener;
+       fwListener.pfSentStatusCb                                       = &MsgSentStatusListener;
+       fwListener.pfStorageChangeCb                    = &MsgStorageChangeListener;
+       fwListener.pfMsgIncomingCb                              = &MsgIncomingMessageListener;
+       fwListener.pfInitSimBySatCb                             = &MsgInitSimBySatListener;
        fwListener.pfSyncMLMsgIncomingCb        = &MsgIncomingSyncMLMessageListener;
        fwListener.pfLBSMsgIncomingCb           = &MsgIncomingLBSMessageListener;
-       fwListener.pfMmsConfIncomingCb = &MsgMmsConfIncomingListener;
+       fwListener.pfMmsConfIncomingCb          = &MsgMmsConfIncomingListener;
+       fwListener.pfPushMsgIncomingCb          = &MsgIncomingPushMessageListener;
+       fwListener.pfCBMsgIncomingCb                    = &MsgIncomingCBMessageListener;
+       fwListener.pfSimMsgIncomingCb           = &MsgSimMessageListener;
+       fwListener.pfResendMessageCb            = &MsgResendMessageListener;
+#ifdef FEATURE_SMS_CDMA
+       fwListener.pfCheckUniquenessCb          = &MsgCheckUniquenessListener;
+#endif
+       fwListener.pfSimInitImsiCb              = &MsgSimImsiListener;
 
        if (registerListener(&fwListener) != MSG_SUCCESS)
                THROW(MsgException::PLUGIN_ERROR, "ERROR to register listener");
 
-//     dlclose(libHandle);
+       // Initialize Plug-in
+       if (initialize() != MSG_SUCCESS)
+               THROW(MsgException::PLUGIN_ERROR, "ERROR to initialize plugin");
 }
 
 
 MsgPlugin::~MsgPlugin()
 {
-
-
+       this->finalize();
+       // close mLibHandler.
+       if (mLibHandler != NULL)
+               dlclose(mLibHandler);
 }
 
 
@@ -463,42 +977,41 @@ msg_error_t MsgPlugin::registerListener(MSG_PLUGIN_LISTENER_S *pListener)
 }
 
 
-msg_error_t MsgPlugin::checkSimStatus(MSG_SIM_STATUS_T *pStatus)
+msg_error_t MsgPlugin::saveSimMessage(MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList)
 {
-       if (mPlgHandler.pfRegisterListener != NULL)
-               return mPlgHandler.pfCheckSimStatus(pStatus);
+       if (mPlgHandler.pfSaveSimMessage != NULL)
+               return mPlgHandler.pfSaveSimMessage(pMsgInfo, pSimIdList);
        else
                return MSG_ERR_INVALID_PLUGIN_HANDLE;
 }
 
-
-msg_error_t MsgPlugin::checkDeviceStatus()
+#ifndef FEATURE_SMS_CDMA
+msg_error_t MsgPlugin::deleteSimMessage(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId)
 {
-       if (mPlgHandler.pfRegisterListener != NULL)
-               return mPlgHandler.pfCheckDeviceStatus();
+       if (mPlgHandler.pfDeleteSimMessage != NULL)
+               return mPlgHandler.pfDeleteSimMessage(sim_idx, SimMsgId);
        else
                return MSG_ERR_INVALID_PLUGIN_HANDLE;
 }
 
 
-msg_error_t MsgPlugin::initSimMessage()
+msg_error_t MsgPlugin::setReadStatus(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId)
 {
-       if (mPlgHandler.pfInitSimMessage != NULL)
-               return mPlgHandler.pfInitSimMessage();
+       if (mPlgHandler.pfSetReadStatus != NULL)
+               return mPlgHandler.pfSetReadStatus(sim_idx, SimMsgId);
        else
                return MSG_ERR_INVALID_PLUGIN_HANDLE;
 }
 
 
-msg_error_t MsgPlugin::saveSimMessage(MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList)
+msg_error_t MsgPlugin::setMemoryStatus(msg_sim_slot_id_t sim_idx, msg_error_t Error)
 {
-       if (mPlgHandler.pfSaveSimMessage != NULL)
-               return mPlgHandler.pfSaveSimMessage(pMsgInfo, pSimIdList);
+       if (mPlgHandler.pfSetMemoryStatus != NULL)
+               return mPlgHandler.pfSetMemoryStatus(sim_idx, Error);
        else
                return MSG_ERR_INVALID_PLUGIN_HANDLE;
 }
-
-
+#else
 msg_error_t MsgPlugin::deleteSimMessage(msg_sim_id_t SimMsgId)
 {
        if (mPlgHandler.pfDeleteSimMessage != NULL)
@@ -524,17 +1037,7 @@ msg_error_t MsgPlugin::setMemoryStatus(msg_error_t Error)
        else
                return MSG_ERR_INVALID_PLUGIN_HANDLE;
 }
-
-
-msg_error_t MsgPlugin::initConfigData(MSG_SIM_STATUS_T SimStatus)
-{
-       if (mPlgHandler.pfInitConfigData != NULL)
-               return mPlgHandler.pfInitConfigData(SimStatus);
-       else
-               return MSG_ERR_INVALID_PLUGIN_HANDLE;
-}
-
-
+#endif
 msg_error_t MsgPlugin::setConfigData(const MSG_SETTING_S *pSetting)
 {
        if (mPlgHandler.pfSetConfigData != NULL)
@@ -581,10 +1084,10 @@ msg_error_t MsgPlugin::processReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQU
 }
 
 
-msg_error_t MsgPlugin::getMmsMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo,  MMS_MESSAGE_DATA_S *pMmsMsg, char **pDestMsg)
+msg_error_t MsgPlugin::getMmsMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char **pDestMsg)
 {
        if (mPlgHandler.pfGetMmsMessage != NULL) {
-               return mPlgHandler.pfGetMmsMessage(pMsg, pSendOptInfo, pMmsMsg, pDestMsg);
+               return mPlgHandler.pfGetMmsMessage(pMsg, pSendOptInfo, pDestMsg);
        } else {
                return MSG_ERR_INVALID_PLUGIN_HANDLE;
        }
@@ -619,6 +1122,14 @@ msg_error_t MsgPlugin::restoreMsg(MSG_MESSAGE_INFO_S *pMsgInfo, char* pRecvBody,
                return MSG_ERR_INVALID_PLUGIN_HANDLE;
 }
 
+msg_error_t MsgPlugin::getDefaultNetworkSimId(int *SimId)
+{
+       if (mPlgHandler.pfGetDefaultNetworkSimId != NULL)
+               return mPlgHandler.pfGetDefaultNetworkSimId(SimId);
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
 
 /*==================================================================================================
                                      IMPLEMENTATION OF MsgPluginManager - Member Functions
@@ -643,12 +1154,31 @@ MsgPluginManager::MsgPluginManager()
 
 void MsgPluginManager::initialize()
 {
-       char path[64];
-
-       memset(path, 0x00, sizeof(path));
-       snprintf(path, sizeof(path), "%s%s", MSG_PLUGIN_CFG_PATH, MSG_PLUGIN_CFG_NAME);
+       int plg_len = sizeof(__msg_plg_items)/sizeof(MSG_PLG_TABLE_T);
+       for (int i=0; i < plg_len; i++) {
+               MsgPlugin* pDupPlgCheck = checkPlugin(__msg_plg_items[i].type);
+
+               if (pDupPlgCheck) {
+                       MSG_DEBUG("Plugin for type %d is duplicated", __msg_plg_items[i].type);
+                       continue;
+               }
+
+               MsgPlugin *newPlg = NULL;
+
+               try
+               {
+                       newPlg = new MsgPlugin(__msg_plg_items[i].type, __msg_plg_items[i].path);
+               }
+               catch (MsgException& e)
+               {
+                       MSG_FATAL("%s", e.what());
+                       continue;
+               }
+
+               if (newPlg)
+                       plgMap.insert(make_pair(__msg_plg_items[i].type, newPlg));
 
-       loadPlugins(path);
+       }
 }
 
 
@@ -658,56 +1188,37 @@ void MsgPluginManager::finalize()
 
        for (it = plgMap.begin(); it != plgMap.end(); it++)
        {
-               MsgPlugin temp = it->second;
-               temp.finalize();
+               MsgPlugin *temp = it->second;
+               delete temp;
        }
 
        plgMap.clear();
 }
 
 
-void MsgPluginManager::loadPlugins(const char* path)
+MsgPlugin* MsgPluginManager::checkPlugin(MSG_MAIN_TYPE_T mainType)
 {
-       /* read plugins from configuration file */
-       FILE* fp = MsgOpenFile(path, "rt");
-
-       MsgPlgConfig plgConf = MsgPlgConfig(fp);
-
-       for (int i=0; i < plgConf.titleCount(); i++)
-       {
-               MsgPlgToken tok;
-
-               plgConf.token(i, 0, tok);
-               const char* content = tok.getVal();
-
-               MSG_MAIN_TYPE_T mainType = strstr(content,"sms")? MSG_SMS_TYPE:
-                                                       (strstr(content,"mms")? MSG_MMS_TYPE: MSG_UNKNOWN_TYPE);
-
-               plgConf.token(i, 1, tok);
-               const char* libPath = tok.getVal();
-
-               MsgPlugin* pDupPlgCheck = getPlugin(mainType);
-
-               if (pDupPlgCheck)
-                       THROW(MsgException::PLUGIN_ERROR, "Plugin for type %d is duplicated", mainType);
-
-               MsgPlugin newPlg(mainType, libPath);
+       /* Implementing the content */
+       MsgPluginMap::iterator it = plgMap.find(mainType);
 
-               plgMap.insert(make_pair(mainType, newPlg));
-       }
+       if (it == plgMap.end())
+               return NULL;
 
-       MsgCloseFile(fp);
+       return it->second;
 }
 
 
 MsgPlugin* MsgPluginManager::getPlugin(MSG_MAIN_TYPE_T mainType)
 {
-       /* Implementing the content */
-       MsgPluginMap::iterator it = plgMap.find(mainType);
+       MsgPlugin *plugin = NULL;
 
-       if (it == plgMap.end())
-               return NULL;
+       if (plgMap.size() == 0) {
+               MSG_INFO("Msg plugin is initializing again");
+               initialize();
+       }
+
+       plugin = checkPlugin(mainType);
 
-       return &(it->second);
+       return plugin;
 }
 
index 247dd89..f805bab 100755 (executable)
@@ -1,23 +1,26 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
 #include "MsgPluginManager.h"
 #include "MsgSettingHandler.h"
 #include "MsgGconfWrapper.h"
+#include "MsgUtilFunction.h"
+#include "MsgSqliteWrapper.h"
+#include "MsgUtilStorage.h"
 
 
 #define DEF_BUF_LEN    128
 /*==================================================================================================
                                                                STATIC FUNCTION PROTOTYPES
 ==================================================================================================*/
-static char* msg_clean_country_code(char *src);
-static char* msg_normalize_number(char *src);
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
-msg_error_t MsgInitSimConfig(MSG_SIM_STATUS_T SimStatus)
-{
-       MSG_DEBUG("Start to initialize SIM Configuration");
-
-       msg_error_t err = MSG_SUCCESS;
-
-       if (SimStatus != MSG_SIM_STATUS_NOT_FOUND)
-       {
-               MSG_MAIN_TYPE_T mainType = MSG_SMS_TYPE;
-               MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(mainType);
-
-               if (plg == NULL)
-               {
-                       MSG_DEBUG("No plugin for %d type", mainType);
-                       return MSG_ERR_INVALID_PLUGIN_HANDLE;
-               }
-
-               // Check SIM Status
-               MSG_DEBUG(" ** SIM is available - status : [%d] ** ", SimStatus);
-
-               err = plg->initConfigData(SimStatus);
-       }
-
-       return err;
-}
-
-
 msg_error_t MsgSetConfigData(const MSG_SETTING_S *pSetting)
 {
        msg_error_t err = MSG_SUCCESS;
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       memset(keyName, 0x00, sizeof(keyName));
+       MSG_SIM_STATUS_T simStatus = MSG_SIM_STATUS_NOT_FOUND;
 
 #ifdef USE_GCONF
        err = MsgGconfGetClient();
@@ -82,9 +59,19 @@ msg_error_t MsgSetConfigData(const MSG_SETTING_S *pSetting)
                case MSG_SMS_SENDOPT :
                        err = MsgSetSMSSendOpt(pSetting);
                        break;
+#ifndef FEATURE_SMS_CDMA
                case MSG_SMSC_LIST :
+                       // Check SIM is present or not
+                       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, pSetting->option.smscList.simIndex);
+                       simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
+
+                       if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
+                               MSG_DEBUG("SIM is not present..");
+                               return MSG_ERR_NO_SIM;
+                       }
                        err = MsgSetSMSCList(pSetting, true);
                        break;
+#endif
                case MSG_MMS_SENDOPT :
                        err = MsgSetMMSSendOpt(pSetting);
                        break;
@@ -98,10 +85,28 @@ msg_error_t MsgSetConfigData(const MSG_SETTING_S *pSetting)
                        err = MsgSetPushMsgOpt(pSetting);
                        break;
                case MSG_CBMSG_OPT :
+                       if (pSetting->option.cbMsgOpt.simIndex != 0) {
+                               // Check SIM is present or not
+                               snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, pSetting->option.cbMsgOpt.simIndex);
+                               simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
+
+                               if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
+                                       MSG_DEBUG("SIM is not present..");
+                                       return MSG_ERR_NO_SIM;
+                               }
+                       }
                        err = MsgSetCBMsgOpt(pSetting, true);
                        break;
                case MSG_VOICEMAIL_OPT :
-                       err = MsgSetVoiceMailOpt(pSetting);
+                       // Check SIM is present or not
+                       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, pSetting->option.voiceMailOpt.simIndex);
+                       simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
+
+                       if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
+                               MSG_DEBUG("SIM is not present..");
+                               return MSG_ERR_NO_SIM;
+                       }
+                       err = MsgSetVoiceMailOpt(pSetting, true);
                        break;
                case MSG_MSGSIZE_OPT:
                        err = MsgSetMsgSizeOpt(pSetting);
@@ -129,9 +134,8 @@ msg_error_t MsgGetConfigData(MSG_SETTING_S *pSetting)
                return MSG_ERR_NULL_POINTER;
        }
 #endif
-
-       // Check SIM is present or not
-       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
+       char keyName[MAX_VCONFKEY_NAME_LEN] = {0,};
+       MSG_SIM_STATUS_T simStatus = MSG_SIM_STATUS_NOT_FOUND;
 
        switch (pSetting->type)
        {
@@ -143,6 +147,10 @@ msg_error_t MsgGetConfigData(MSG_SETTING_S *pSetting)
                        break;
                case MSG_SMSC_LIST :
                {
+                       // Check SIM is present or not
+                       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, pSetting->option.smscList.simIndex);
+                       simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
+
                        if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
                                MSG_DEBUG("SIM is not present..");
                                return MSG_ERR_NO_SIM;
@@ -164,6 +172,10 @@ msg_error_t MsgGetConfigData(MSG_SETTING_S *pSetting)
                        break;
                case MSG_CBMSG_OPT :
                {
+                       // Check SIM is present or not
+                       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, pSetting->option.cbMsgOpt.simIndex);
+                       simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
+
                        if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
                                MSG_DEBUG("SIM is not present..");
                                return MSG_ERR_NO_SIM;
@@ -172,6 +184,19 @@ msg_error_t MsgGetConfigData(MSG_SETTING_S *pSetting)
                }
                break;
                case MSG_VOICEMAIL_OPT :
+                       // Check SIM is present or not
+                       if (pSetting->option.voiceMailOpt.simIndex == 0) {
+                               MSG_DEBUG("Invalid SIM Index [%d]", pSetting->option.voiceMailOpt.simIndex);
+                               return MSG_ERR_INVALID_PARAMETER;
+                       }
+
+                       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, pSetting->option.voiceMailOpt.simIndex);
+                       simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
+
+                       if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
+                               MSG_DEBUG("SIM is not present..");
+                               return MSG_ERR_NO_SIM;
+                       }
                        MsgGetVoiceMailOpt(pSetting);
                        break;
                case MSG_MSGSIZE_OPT :
@@ -194,6 +219,8 @@ msg_error_t MsgSetGeneralOpt(const MSG_SETTING_S *pSetting)
 {
        MSG_GENERAL_OPT_S generalOpt;
        bool bValue = false;
+       int iValue = 0;
+       char *strValue = NULL;
 
        memcpy(&generalOpt, &(pSetting->option.generalOpt), sizeof(MSG_GENERAL_OPT_S));
 
@@ -213,6 +240,100 @@ msg_error_t MsgSetGeneralOpt(const MSG_SETTING_S *pSetting)
                }
        }
 
+       MsgSettingGetBool(MSG_BLOCK_UNKNOWN_MSG, &bValue);
+       if (bValue != generalOpt.bBlockUnknownMsg) {
+               if (MsgSettingSetBool(MSG_BLOCK_UNKNOWN_MSG, generalOpt.bBlockUnknownMsg) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_BLOCK_UNKNOWN_MSG);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MSG_SMS_LIMIT);
+       if (iValue != (int)generalOpt.smsLimitCnt) {
+               if (MsgSettingSetInt(MSG_SMS_LIMIT, (int)generalOpt.smsLimitCnt) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_SMS_LIMIT);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MSG_MMS_LIMIT);
+       if (iValue != (int)generalOpt.mmsLimitCnt) {
+               if (MsgSettingSetInt(MSG_MMS_LIMIT, (int)generalOpt.mmsLimitCnt) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_MMS_LIMIT);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MSG_SETTING_NOTIFICATION, &bValue);
+       if (bValue != generalOpt.bNotification) {
+               if (MsgSettingSetBool(MSG_SETTING_NOTIFICATION, generalOpt.bNotification) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_SETTING_NOTIFICATION);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MSG_SETTING_VIBRATION, &bValue);
+       if (bValue != generalOpt.bVibration) {
+               if (MsgSettingSetBool(MSG_SETTING_VIBRATION, generalOpt.bVibration) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_SETTING_VIBRATION);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MSG_SETTING_PREVIEW, &bValue);
+       if (bValue != generalOpt.bPreview) {
+               if (MsgSettingSetBool(MSG_SETTING_PREVIEW, generalOpt.bPreview) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_SETTING_PREVIEW);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MSG_SETTING_RINGTONE_TYPE);
+       if (iValue != generalOpt.ringtoneType) {
+               if (MsgSettingSetInt(MSG_SETTING_RINGTONE_TYPE, generalOpt.ringtoneType) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_SETTING_RINGTONE_TYPE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       if (generalOpt.ringtoneType == MSG_RINGTONE_TYPE_SILENT) {
+               if (MsgSettingSetString(MSG_SETTING_RINGTONE_PATH, "") != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_SETTING_RINGTONE_PATH);
+                       return MSG_ERR_SET_SETTING;
+               }
+       } else {
+               strValue = MsgSettingGetString(MSG_SETTING_RINGTONE_PATH);
+               MSG_DEBUG("strValue=[%s], ringtone=[%s]", strValue, generalOpt.ringtonePath);
+
+               if (g_strcmp0(strValue, generalOpt.ringtonePath) != 0) {
+                       if (MsgSettingSetString(MSG_SETTING_RINGTONE_PATH, generalOpt.ringtonePath) != MSG_SUCCESS) {
+                               MSG_DEBUG("Error to set config data [%s]", MSG_SETTING_RINGTONE_PATH);
+                               return MSG_ERR_SET_SETTING;
+                       }
+               }
+       }
+
+       if (strValue) {
+               free(strValue);
+               strValue = NULL;
+       }
+
+       iValue = MsgSettingGetInt(MSG_ALERT_REP_TYPE);
+       if (iValue != (int)generalOpt.alertTone) {
+               if (MsgSettingSetInt(MSG_ALERT_REP_TYPE, (int)generalOpt.alertTone) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_ALERT_REP_TYPE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MSG_SEARCH_TAGS);
+       if (iValue != (int)generalOpt.searchTags) {
+               if (MsgSettingSetInt(MSG_SEARCH_TAGS, (int)generalOpt.searchTags) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_SEARCH_TAGS);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
        return MSG_SUCCESS;
 }
 
@@ -273,96 +394,46 @@ msg_error_t MsgSetSMSCList(const MSG_SETTING_S *pSetting, bool bSetSim)
 {
        msg_error_t err = MSG_SUCCESS;
 
-       for (int index = 0; index < pSetting->option.smscList.totalCnt; index++)
-       {
-               if(strlen(pSetting->option.smscList.smscData[index].smscAddr.address) > SMSC_ADDR_MAX)
-               {
-                       MSG_DEBUG("SMSC address is too long [%d]", strlen(pSetting->option.smscList.smscData[index].smscAddr.address));
-                       return MSG_ERR_SET_SIM_SET;
-               }
-       }
-
-       if (bSetSim == true)
-       {
-               err = MsgSetConfigInSim(pSetting);
-
-               if (err != MSG_SUCCESS)
-               {
-                       MSG_DEBUG("Error to set config data in sim [%d]", err);
-                       return err;
-               }
-       }
-
-       MSG_SMSC_LIST_S smscList;
+       int addrLen = 0;
+       int index = 0;
 
+       MSG_SMSC_LIST_S smscList = {0,};
        memcpy(&smscList, &(pSetting->option.smscList), sizeof(MSG_SMSC_LIST_S));
 
-       char keyName[DEF_BUF_LEN] = {0, };
+//     int sel_id = smscList.selected;
 
-       // No selected SMSC Info. in SIM.
-       if (bSetSim == true)
-       {
-               if (MsgSettingSetInt(SMSC_SELECTED, smscList.selected) != MSG_SUCCESS)
-               {
-                       MSG_DEBUG("Error to set config data [%s]", SMSC_SELECTED);
-                       return MSG_ERR_SET_SETTING;
-               }
-       }
+       index = smscList.index;
 
-       if (MsgSettingSetInt(SMSC_TOTAL_COUNT, smscList.totalCnt) != MSG_SUCCESS)
-       {
-               MSG_DEBUG("Error to set config data [%s]", SMSC_TOTAL_COUNT);
-               return MSG_ERR_SET_SETTING;
+       if (index < 0 || index >= smscList.totalCnt) {
+               MSG_DEBUG("Update SMSC index is invalid [id=%d]", index);
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
-       for (int i = 0; i < smscList.totalCnt; i++)
-       {
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_PID, i);
-
-               if ((err = MsgSettingSetInt(keyName, (int)smscList.smscData[i].pid)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_VAL_PERIOD, i);
-
-               if ((err = MsgSettingSetInt(keyName, (int)smscList.smscData[i].valPeriod)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_NAME, i);
-
-               if ((err = MsgSettingSetString(keyName, smscList.smscData[i].name)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_TON, i);
-
-               if (smscList.smscData[i].smscAddr.address[0] == '+')
-                       smscList.smscData[i].smscAddr.ton = MSG_TON_INTERNATIONAL;
-               else
-                       smscList.smscData[i].smscAddr.ton = MSG_TON_NATIONAL;
-
-               if ((err = MsgSettingSetInt(keyName, (int)smscList.smscData[i].smscAddr.ton)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_NPI, i);
-
-               smscList.smscData[i].smscAddr.npi = MSG_NPI_ISDN; // app cannot set this value
-
-               if ((err = MsgSettingSetInt(keyName, (int)smscList.smscData[i].smscAddr.npi)) != MSG_SUCCESS)
-                       break;
+       if (pSetting->option.smscList.smscData[index].smscAddr.address[0] == '+')
+               addrLen = strlen(pSetting->option.smscList.smscData[index].smscAddr.address) - 1;
+       else
+               addrLen = strlen(pSetting->option.smscList.smscData[index].smscAddr.address);
 
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_ADDRESS, i);
+       if(addrLen > SMSC_ADDR_MAX) {
+               MSG_DEBUG("SMSC address is too long [%d]", strlen(pSetting->option.smscList.smscData[index].smscAddr.address));
+               return MSG_ERR_SET_SIM_SET;
+       } else if(addrLen < 2) {
+               MSG_DEBUG("SMSC address is too short [%d]", addrLen);
+               return MSG_ERR_SET_SIM_SET;
+       }
 
-               if ((err = MsgSettingSetString(keyName, smscList.smscData[i].smscAddr.address)) != MSG_SUCCESS)
-                       break;
+       if (pSetting->option.smscList.simIndex == 0) {
+               MSG_DEBUG("SIM Index for Setting SMSC List = 0");
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
-       if (err != MSG_SUCCESS)
-       {
-               MSG_DEBUG("Error to set config data [%s]", keyName);
+       if (bSetSim == true) {
+               err = MsgSetConfigInSim(pSetting);
+
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data in sim [%d]", err);
+                       return err;
+               }
        }
 
        return err;
@@ -440,6 +511,13 @@ msg_error_t MsgSetMMSSendOpt(const MSG_SETTING_S *pSetting)
                        return MSG_ERR_SET_SETTING;
                }
        }
+#ifdef __NOT_USED_BY_DESIGN_CHANGE__
+       if (MsgSettingSetBool(MMS_SEND_KEEP_COPY, sendOpt.bKeepCopy) != MSG_SUCCESS)
+       {
+               MSG_DEBUG("Error to set config data [%s]", MMS_SEND_KEEP_COPY);
+               return MSG_ERR_SET_SETTING;
+       }
+#endif /* __NOT_USED_BY_DESIGN_CHANGE__ */
 
        MsgSettingGetBool(MMS_SEND_BODY_REPLYING, &bValue);
        if (bValue != sendOpt.bBodyReplying) {
@@ -720,17 +798,28 @@ msg_error_t MsgSetCBMsgOpt(const MSG_SETTING_S *pSetting, bool bSetSim)
        MSG_CBMSG_OPT_S cbOpt;
        int iValue = 0;
        bool bValue = false;
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       msg_sim_slot_id_t simIndex;
 
        memcpy(&cbOpt, &(pSetting->option.cbMsgOpt), sizeof(MSG_CBMSG_OPT_S));
 
-       if (bSetSim == true) {
-               cbOpt.maxSimCnt = MsgSettingGetInt(CB_MAX_SIM_COUNT);
+       simIndex = cbOpt.simIndex;
 
-               if (cbOpt.channelData.channelCnt > cbOpt.maxSimCnt) {
-                       MSG_DEBUG("Channel Count is over Max SIM Count [%d]", cbOpt.channelData.channelCnt);
-                       return MSG_ERR_SET_SIM_SET;
-               }
+       MSG_DEBUG("SIM Index = [%d]", simIndex);
+
+       if (bSetSim == true) {//if (bSetSim == true && simIndex != 0) {
+#ifndef FEATURE_SMS_CDMA
+               if (simIndex != 0) {
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", CB_MAX_SIM_COUNT, simIndex);
+                       cbOpt.maxSimCnt = MsgSettingGetInt(keyName);
 
+                       if (cbOpt.channelData.channelCnt > cbOpt.maxSimCnt) {
+                               MSG_DEBUG("Channel Count [%d] is over Max SIM Count [%d]", cbOpt.channelData.channelCnt,cbOpt.maxSimCnt);
+                               return MSG_ERR_SET_SIM_SET;
+                       }
+               }
+#endif
                err = MsgSetConfigInSim(pSetting);
                if (err != MSG_SUCCESS) {
                        MSG_DEBUG("Error to set config data in sim [%d]", err);
@@ -738,58 +827,43 @@ msg_error_t MsgSetCBMsgOpt(const MSG_SETTING_S *pSetting, bool bSetSim)
                }
        }
 
-       MsgSettingGetBool(CB_RECEIVE, &bValue);
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", CB_RECEIVE, simIndex);
+       MsgSettingGetBool(keyName, &bValue);
        if (bValue != cbOpt.bReceive) {
-               if (MsgSettingSetBool(CB_RECEIVE, cbOpt.bReceive) != MSG_SUCCESS) {
-                       MSG_DEBUG("Error to set config data [%s]", CB_RECEIVE);
+               if (MsgSettingSetBool(keyName, cbOpt.bReceive) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", keyName);
                        return MSG_ERR_SET_SETTING;
                }
        }
 
-       iValue = MsgSettingGetInt(CB_MAX_SIM_COUNT);
-       if (iValue != cbOpt.maxSimCnt) {
-               if (MsgSettingSetInt(CB_MAX_SIM_COUNT, cbOpt.maxSimCnt) != MSG_SUCCESS) {
-                       MSG_DEBUG("Error to set config data [%s]", CB_MAX_SIM_COUNT);
-                       return MSG_ERR_SET_SETTING;
-               }
+#ifndef FEATURE_SMS_CDMA
+       if (simIndex == 0) {
+               MSG_DEBUG("SIM Index for Setting CB Option = 0, Setting for CB_RECEIVE success");
+               return MSG_SUCCESS;
        }
 
-       iValue = MsgSettingGetInt(CB_CHANNEL_COUNT);
-       if (iValue != cbOpt.channelData.channelCnt) {
-               if (MsgSettingSetInt(CB_CHANNEL_COUNT, cbOpt.channelData.channelCnt) != MSG_SUCCESS) {
-                       MSG_DEBUG("Error to set config data [%s]", CB_CHANNEL_COUNT);
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", CB_MAX_SIM_COUNT, simIndex);
+       iValue = MsgSettingGetInt(keyName);
+       if (iValue != cbOpt.maxSimCnt) {
+               if (MsgSettingSetInt(keyName, cbOpt.maxSimCnt) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", keyName);
                        return MSG_ERR_SET_SETTING;
                }
        }
+#endif
 
-       char keyName[DEF_BUF_LEN] = {0, };
-
-       for (int i = 0; i < cbOpt.channelData.channelCnt; i++)
-       {
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", CB_CHANNEL_ACTIVATE, i);
-
-               if ((err = MsgSettingSetBool(keyName, cbOpt.channelData.channelInfo[i].bActivate)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", CB_CHANNEL_ID_FROM, i);
-
-               if ((err = MsgSettingSetInt(keyName, cbOpt.channelData.channelInfo[i].from)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", CB_CHANNEL_ID_TO, i);
-
-               if ((err = MsgSettingSetInt(keyName, cbOpt.channelData.channelInfo[i].to)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", CB_CHANNEL_NAME, i);
+       MsgDbHandler *dbHandle = getDbHandle();
 
-               if ((err = MsgSettingSetString(keyName, cbOpt.channelData.channelInfo[i].name)) != MSG_SUCCESS)
-                       break;
-       }
+#ifdef FEATURE_SMS_CDMA
+       err = MsgStoAddCBChannelInfo(dbHandle, &cbOpt.channelData);
+#else
+       err = MsgStoAddCBChannelInfo(dbHandle, &cbOpt.channelData, simIndex);
+#endif
+       MSG_DEBUG("MsgStoAddCBChannelInfo : err=[%d]", err);
 
+#ifndef FEATURE_SMS_CDMA
        if (bSetSim == true)
        {
                for (int i = MSG_CBLANG_TYPE_ALL; i < MSG_CBLANG_TYPE_MAX; i++)
@@ -804,39 +878,59 @@ msg_error_t MsgSetCBMsgOpt(const MSG_SETTING_S *pSetting, bool bSetSim)
                        }
                }
        }
+#endif
 
        return err;
 }
 
-msg_error_t MsgSetVoiceMailOpt(const MSG_SETTING_S *pSetting)
+
+msg_error_t MsgSetVoiceMailOpt(const MSG_SETTING_S *pSetting, bool bSetSim)
 {
        MSG_VOICEMAIL_OPT_S voiceMailOpt;
        char *pValue = NULL;
+       char keyName[DEF_BUF_LEN];
+       msg_sim_slot_id_t simIndex = 0;
+       msg_error_t err = MSG_SUCCESS;
 
        memcpy(&voiceMailOpt, &(pSetting->option.voiceMailOpt), sizeof(MSG_VOICEMAIL_OPT_S));
 
-       pValue = MsgSettingGetString(VOICEMAIL_NUMBER);
+       simIndex = pSetting->option.voiceMailOpt.simIndex;
+
+       if (simIndex == 0) {
+               MSG_DEBUG("SIM Index for Setting Voicemail Option = 0");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_NUMBER, simIndex);
+
+       pValue = MsgSettingGetString(keyName);
+
        if (pValue != NULL && strcmp(pValue, voiceMailOpt.mailNumber) == 0) {
                /* Value is same with previous one. Therefore, we don't need to save it. */
        } else {
-               if (MsgSettingSetString(VOICEMAIL_NUMBER, voiceMailOpt.mailNumber) != MSG_SUCCESS) {
-                       MSG_DEBUG("Error to set config data [%s]", VOICEMAIL_NUMBER);
-
-                       if (pValue != NULL) {
-                               free(pValue);
-                               pValue = NULL;
-                       }
+               if (bSetSim == true) {
+                       err = MsgSetConfigInSim(pSetting);
+                       /* Even if err is not Success, no need to return error. */
+                       MSG_DEBUG("MsgSetConfigInSim return [%d]", err);
+               }
 
-                       return MSG_ERR_SET_SETTING;
+               if (err != MSG_SUCCESS) {
+                       goto _END_OF_SET_VOICE_OPT;
                }
+
+               err = MsgSettingSetString(keyName, voiceMailOpt.mailNumber);
+               if (err != MSG_SUCCESS)
+                       MSG_ERR("Error to set config data [%s]", keyName);
        }
 
+_END_OF_SET_VOICE_OPT:
        if (pValue != NULL) {
                free(pValue);
                pValue = NULL;
        }
 
-       return MSG_SUCCESS;
+       return err;
 }
 
 
@@ -861,85 +955,65 @@ msg_error_t MsgSetMsgSizeOpt(const MSG_SETTING_S *pSetting)
 
 void MsgGetGeneralOpt(MSG_SETTING_S *pSetting)
 {
+       char *tmpValue = NULL;
+
        memset(&(pSetting->option.generalOpt), 0x00, sizeof(MSG_GENERAL_OPT_S));
 
        MsgSettingGetBool(MSG_KEEP_COPY, &pSetting->option.generalOpt.bKeepCopy);
-}
 
+       MsgSettingGetBool(MSG_BLOCK_UNKNOWN_MSG, &pSetting->option.generalOpt.bBlockUnknownMsg);
 
-void MsgGetSMSSendOpt(MSG_SETTING_S *pSetting)
-{
-       memset(&(pSetting->option.smsSendOpt), 0x00, sizeof(MSG_SMS_SENDOPT_S));
+       pSetting->option.generalOpt.smsLimitCnt = MsgSettingGetInt(MSG_SMS_LIMIT);
 
-       pSetting->option.smsSendOpt.dcs = (msg_encode_type_t)MsgSettingGetInt(SMS_SEND_DCS);
+       pSetting->option.generalOpt.mmsLimitCnt = MsgSettingGetInt(MSG_MMS_LIMIT);
 
-       pSetting->option.smsSendOpt.netMode = (MSG_SMS_NETWORK_MODE_T)MsgSettingGetInt(SMS_SEND_NETWORK_MODE);
+       MsgSettingGetBool(MSG_SETTING_NOTIFICATION, &pSetting->option.generalOpt.bNotification);
 
-       MsgSettingGetBool(SMS_SEND_REPLY_PATH, &pSetting->option.smsSendOpt.bReplyPath);
+       MsgSettingGetBool(MSG_SETTING_VIBRATION, &pSetting->option.generalOpt.bVibration);
 
-       MsgSettingGetBool(SMS_SEND_DELIVERY_REPORT, &pSetting->option.smsSendOpt.bDeliveryReport);
+       MsgSettingGetBool(MSG_SETTING_PREVIEW, &pSetting->option.generalOpt.bPreview);
 
-       pSetting->option.smsSendOpt.saveStorage = (MSG_SMS_SAVE_STORAGE_T)MsgSettingGetInt(SMS_SEND_SAVE_STORAGE);
-}
+       MsgSettingGetBool(MSG_AUTO_ERASE, &pSetting->option.generalOpt.bAutoErase);
 
+       pSetting->option.generalOpt.ringtoneType = MsgSettingGetInt(MSG_SETTING_RINGTONE_TYPE);
 
-void MsgGetSMSCList(MSG_SETTING_S *pSetting)
-{
-       char keyName[DEF_BUF_LEN] = {0, };
-       char *tmpValue = NULL;
-
-       memset(&(pSetting->option.smscList), 0x00, sizeof(MSG_SMSC_LIST_S));
-
-       pSetting->option.smscList.selected = MsgSettingGetInt(SMSC_SELECTED);
-
-       pSetting->option.smscList.totalCnt = MsgSettingGetInt(SMSC_TOTAL_COUNT);
+       tmpValue = MsgSettingGetString(MSG_SETTING_RINGTONE_PATH);
+       if (tmpValue != NULL) {
+               strncpy(pSetting->option.generalOpt.ringtonePath, tmpValue, MSG_FILEPATH_LEN_MAX);
+               free(tmpValue);
+               tmpValue = NULL;
+       }
 
-       for (int i = 0; i < pSetting->option.smscList.totalCnt; i++)
-       {
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_PID, i);
+       pSetting->option.generalOpt.alertTone = (MSG_ALERT_TONE_T)MsgSettingGetInt(MSG_ALERT_REP_TYPE);
 
-               pSetting->option.smscList.smscData[i].pid = (MSG_SMS_PID_T)MsgSettingGetInt(keyName);
+       pSetting->option.generalOpt.searchTags = MsgSettingGetInt(MSG_SEARCH_TAGS);
 
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_VAL_PERIOD, i);
+}
 
-               pSetting->option.smscList.smscData[i].valPeriod = (MSG_VAL_PERIOD_T)MsgSettingGetInt(keyName);
 
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_NAME, i);
+void MsgGetSMSSendOpt(MSG_SETTING_S *pSetting)
+{
+       memset(&(pSetting->option.smsSendOpt), 0x00, sizeof(MSG_SMS_SENDOPT_S));
 
-               memset(pSetting->option.smscList.smscData[i].name, 0x00, SMSC_NAME_MAX+1);
+       pSetting->option.smsSendOpt.dcs = (msg_encode_type_t)MsgSettingGetInt(SMS_SEND_DCS);
 
-               tmpValue = MsgSettingGetString(keyName);
-               if (tmpValue != NULL) {
-                       strncpy(pSetting->option.smscList.smscData[i].name, tmpValue, SMSC_NAME_MAX);
-                       free(tmpValue);
-                       tmpValue = NULL;
-               }
+       pSetting->option.smsSendOpt.netMode = (MSG_SMS_NETWORK_MODE_T)MsgSettingGetInt(SMS_SEND_NETWORK_MODE);
 
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_TON, i);
+       MsgSettingGetBool(SMS_SEND_REPLY_PATH, &pSetting->option.smsSendOpt.bReplyPath);
 
-               pSetting->option.smscList.smscData[i].smscAddr.ton = (MSG_SMS_TON_T)MsgSettingGetInt(keyName);
+       MsgSettingGetBool(SMS_SEND_DELIVERY_REPORT, &pSetting->option.smsSendOpt.bDeliveryReport);
 
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_NPI, i);
+       pSetting->option.smsSendOpt.saveStorage = (MSG_SMS_SAVE_STORAGE_T)MsgSettingGetInt(SMS_SEND_SAVE_STORAGE);
+}
 
-               pSetting->option.smscList.smscData[i].smscAddr.npi = (MSG_SMS_NPI_T)MsgSettingGetInt(keyName);
 
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_ADDRESS, i);
+void MsgGetSMSCList(MSG_SETTING_S *pSetting)
+{
+       MSG_BEGIN();
 
-               memset(pSetting->option.smscList.smscData[i].smscAddr.address, 0x00, sizeof(pSetting->option.smscList.smscData[i].smscAddr.address));
+       MsgGetConfigInSim(pSetting);
 
-               tmpValue = MsgSettingGetString(keyName);
-               if (tmpValue != NULL) {
-                       strncpy(pSetting->option.smscList.smscData[i].smscAddr.address, tmpValue, SMSC_ADDR_MAX);
-                       free(tmpValue);
-                       tmpValue = NULL;
-               }
-       }
+       MSG_END();
 }
 
 
@@ -963,6 +1037,10 @@ void MsgGetMMSSendOpt(MSG_SETTING_S *pSetting)
 
        MsgSettingGetBool(MMS_SEND_READ_REPLY, &pSetting->option.mmsSendOpt.bReadReply);
 
+#ifdef __NOT_USED_BY_DESIGN_CHANGE__
+       MsgSettingGetBool(MSG_KEEP_COPY, &pSetting->option.mmsSendOpt.bKeepCopy);
+#endif /* __NOT_USED_BY_DESIGN_CHANGE__ */
+
        MsgSettingGetBool(MMS_SEND_BODY_REPLYING, &pSetting->option.mmsSendOpt.bBodyReplying);
 
        MsgSettingGetBool(MMS_SEND_HIDE_RECIPIENTS, &pSetting->option.mmsSendOpt.bHideRecipients);
@@ -1043,46 +1121,43 @@ void MsgGetPushMsgOpt(MSG_SETTING_S *pSetting)
 
 void MsgGetCBMsgOpt(MSG_SETTING_S *pSetting)
 {
+       msg_error_t err = MSG_SUCCESS;
+
        char keyName[DEF_BUF_LEN] = {0, };
-       char *tmpValue = NULL;
+       MsgDbHandler *dbHandle = getDbHandle();
+       msg_sim_slot_id_t simIndex = pSetting->option.cbMsgOpt.simIndex;
 
        memset(&(pSetting->option.cbMsgOpt), 0x00, sizeof(MSG_CBMSG_OPT_S));
 
-       MsgSettingGetBool(CB_RECEIVE, &pSetting->option.cbMsgOpt.bReceive);
+       MSG_DEBUG("Sim index = [%d]", simIndex);
 
-       pSetting->option.cbMsgOpt.maxSimCnt = MsgSettingGetInt(CB_MAX_SIM_COUNT);
+       /* Keep simIndex */
+       pSetting->option.cbMsgOpt.simIndex = simIndex;
 
-       pSetting->option.cbMsgOpt.channelData.channelCnt = MsgSettingGetInt(CB_CHANNEL_COUNT);
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", CB_RECEIVE, simIndex);
+       MsgSettingGetBool(keyName, &pSetting->option.cbMsgOpt.bReceive);
 
-       for (int i = 0; i < pSetting->option.cbMsgOpt.channelData.channelCnt; i++)
-       {
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", CB_CHANNEL_ACTIVATE, i);
-
-               MsgSettingGetBool(keyName, &pSetting->option.cbMsgOpt.channelData.channelInfo[i].bActivate);
-
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", CB_CHANNEL_ID_FROM, i);
-               pSetting->option.cbMsgOpt.channelData.channelInfo[i].from = MsgSettingGetInt(keyName);
-               MSG_DEBUG("channel[%d]: from: %d", i, pSetting->option.cbMsgOpt.channelData.channelInfo[i].from);
-
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", CB_CHANNEL_ID_TO, i);
-               pSetting->option.cbMsgOpt.channelData.channelInfo[i].to = MsgSettingGetInt(keyName);
-               MSG_DEBUG("channel[%d]: to: %d", i, pSetting->option.cbMsgOpt.channelData.channelInfo[i].to);
+       if (simIndex == 0) {
+               MSG_DEBUG("SIM Index = 0, bReceive is gotten");
+               return;
+       }
 
-               memset(keyName, 0x00, sizeof(keyName));
-               snprintf(keyName, DEF_BUF_LEN, "%s/%d", CB_CHANNEL_NAME, i);
+#ifndef FEATURE_SMS_CDMA
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", CB_MAX_SIM_COUNT, simIndex);
+       pSetting->option.cbMsgOpt.maxSimCnt = MsgSettingGetInt(keyName);
+#endif
 
-               tmpValue = MsgSettingGetString(keyName);
-               if (tmpValue != NULL) {
-                       strncpy(pSetting->option.cbMsgOpt.channelData.channelInfo[i].name, tmpValue, CB_CHANNEL_NAME_MAX);
-                       MSG_DEBUG("channel[%d]: channel_name: %s", i, pSetting->option.cbMsgOpt.channelData.channelInfo[i].name);
-                       free(tmpValue);
-                       tmpValue = NULL;
-               }
-       }
+#ifdef FEATURE_SMS_CDMA
+       err = MsgStoGetCBChannelInfo(dbHandle, &pSetting->option.cbMsgOpt.channelData);
+#else
+       err = MsgStoGetCBChannelInfo(dbHandle, &pSetting->option.cbMsgOpt.channelData, simIndex);
+#endif
+       if (err != MSG_SUCCESS)
+               MSG_ERR("MsgStoGetCBChannelInfo : err=[%d]", err);
 
+#ifndef FEATURE_SMS_CDMA
        for (int i = MSG_CBLANG_TYPE_ALL; i < MSG_CBLANG_TYPE_MAX; i++)
        {
                memset(keyName, 0x00, sizeof(keyName));
@@ -1090,229 +1165,94 @@ void MsgGetCBMsgOpt(MSG_SETTING_S *pSetting)
 
                MsgSettingGetBool(keyName, &pSetting->option.cbMsgOpt.bLanguage[i]);
        }
+#endif
 }
 
+
 void MsgGetVoiceMailOpt(MSG_SETTING_S *pSetting)
 {
-        char *tmpValue = NULL;
-
-        memset(&(pSetting->option.voiceMailOpt), 0x00, sizeof(MSG_VOICEMAIL_OPT_S));
-
-        tmpValue = MsgSettingGetString(VOICEMAIL_NUMBER);
-        if (tmpValue != NULL) {
-                strncpy(pSetting->option.voiceMailOpt.mailNumber, tmpValue, MAX_PHONE_NUMBER_LEN);
-                free(tmpValue);
-                tmpValue = NULL;
-        }
+       char *tmpValue = NULL;
+       char keyName[DEF_BUF_LEN];
+       msg_sim_slot_id_t simIndex;
+
+       simIndex = pSetting->option.voiceMailOpt.simIndex;
+       MSG_DEBUG("sim index = [%d]", simIndex);
+
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_NUMBER, simIndex);
+       tmpValue = MsgSettingGetString(keyName);
+       memset(pSetting->option.voiceMailOpt.mailNumber, 0x00, sizeof(pSetting->option.voiceMailOpt.mailNumber));
+       if (tmpValue != NULL) {
+               strncpy(pSetting->option.voiceMailOpt.mailNumber, tmpValue, MAX_PHONE_NUMBER_LEN);
+               MSG_SEC_DEBUG("Voicemail number = [%s]", pSetting->option.voiceMailOpt.mailNumber);
+               free(tmpValue);
+               tmpValue = NULL;
+       }
+
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_ALPHA_ID, simIndex);
+       tmpValue = MsgSettingGetString(keyName);
+       memset(pSetting->option.voiceMailOpt.alpahId, 0x00, sizeof(pSetting->option.voiceMailOpt.alpahId));
+       if (tmpValue != NULL) {
+               strncpy(pSetting->option.voiceMailOpt.alpahId, tmpValue, MAX_SIM_XDN_ALPHA_ID_LEN);
+               MSG_SEC_DEBUG("Voicemail alpha ID = [%s]", pSetting->option.voiceMailOpt.alpahId);
+               free(tmpValue);
+               tmpValue = NULL;
+       }
+
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_COUNT, simIndex);
+       pSetting->option.voiceMailOpt.voiceCnt = MsgSettingGetInt(keyName);
 }
 
 
 void MsgGetMsgSizeOpt(MSG_SETTING_S *pSetting)
 {
-        memset(&(pSetting->option.msgSizeOpt), 0x00, sizeof(MSG_MSGSIZE_OPT_S));
+       memset(&(pSetting->option.msgSizeOpt), 0x00, sizeof(MSG_MSGSIZE_OPT_S));
 
-        pSetting->option.msgSizeOpt.nMsgSize = MsgSettingGetInt(MSGSIZE_OPTION);
+       pSetting->option.msgSizeOpt.nMsgSize = MsgSettingGetInt(MSGSIZE_OPTION);
 }
 
 
 msg_error_t MsgSetConfigInSim(const MSG_SETTING_S *pSetting)
 {
-        msg_error_t err = MSG_SUCCESS;
-
-        MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
-
-        // Get Setting Data from SIM
-        if (plg != NULL)
-                err = plg->setConfigData(pSetting);
-        else
-                err = MSG_ERR_NULL_POINTER;
+       msg_error_t err = MSG_SUCCESS;
 
-        if (err != MSG_SUCCESS)
-        {
-                MSG_DEBUG("Error. Error code is %d.", err);
-                return err;
-        }
+       MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
 
-        return err;
-}
-
-static char* msg_clean_country_code(char *src)
-{
-       int ret = 1;
+       // Get Setting Data from SIM
+       if (plg != NULL)
+               err = plg->setConfigData(pSetting);
+       else
+               err = MSG_ERR_NULL_POINTER;
 
-       switch (src[ret++]-'0')
+       if (err != MSG_SUCCESS)
        {
-               case 1:
-               case 7:
-                       break;
-               case 2:
-                       switch (src[ret++]-'0')
-                       {
-                               case 0:
-                               case 7:
-                                       break;
-                               case 1:
-                               case 2:
-                               case 3:
-                               case 4:
-                               case 5:
-                               case 6:
-                               case 8:
-                               case 9:
-                                       ret += 1;
-                                       break;
-                               default:
-                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
-                                       break;
-                       }
-                       break;
-               case 3:
-                       switch (src[ret++]-'0')
-                       {
-                               case 0:
-                               case 1:
-                               case 2:
-                               case 3:
-                               case 4:
-                               case 6:
-                               case 9:
-                                       break;
-                               case 5:
-                               case 7:
-                               case 8:
-                                       ret += 1;
-                                       break;
-                               default:
-                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
-                                       break;
-                       }
-                       break;
-               case 4:
-                       switch (src[ret++]-'0')
-                       {
-                               case 0:
-                               case 1:
-                               case 3:
-                               case 4:
-                               case 5:
-                               case 6:
-                               case 7:
-                               case 8:
-                               case 9:
-                                       break;
-                               case 2:
-                                       ret += 1;
-                                       break;
-                               default:
-                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
-                                       break;
-                       }
-                       break;
-               case 5:
-                       switch (src[ret++]-'0')
-                       {
-                               case 1:
-                               case 2:
-                               case 3:
-                               case 4:
-                               case 5:
-                               case 6:
-                               case 7:
-                               case 8:
-                                       break;
-                               case 0:
-                               case 9:
-                                       ret += 1;
-                                       break;
-                               default:
-                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
-                                       break;
-                       }
-                       break;
-               case 6:
-                       switch (src[ret++]-'0')
-                       {
-                               case 0:
-                               case 1:
-                               case 2:
-                               case 3:
-                               case 4:
-                               case 5:
-                               case 6:
-                                       break;
-                               case 7:
-                               case 8:
-                               case 9:
-                                       ret += 1;
-                                       break;
-                               default:
-                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
-                                       break;
-                       }
-                       break;
-               case 8:
-                       switch (src[ret++]-'0')
-                       {
-                               case 1:
-                               case 2:
-                               case 4:
-                               case 6:
-                                       break;
-                               case 0:
-                               case 3:
-                               case 5:
-                               case 7:
-                               case 8:
-                               case 9:
-                                       ret += 1;
-                                       break;
-                               default:
-                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
-                                       break;
-                       }
-                       break;
-               case 9:
-                       switch (src[ret++]-'0')
-                       {
-                               case 0:
-                               case 1:
-                               case 2:
-                               case 3:
-                               case 4:
-                               case 5:
-                               case 8:
-                                       break;
-                               case 6:
-                               case 7:
-                               case 9:
-                                       ret += 1;
-                                       break;
-                               default:
-                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
-                                       break;
-                       }
-                       break;
-               case 0:
-               default:
-                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
-                       return src;
+               MSG_DEBUG("Error. Error code is %d.", err);
+               return err;
        }
 
-       return &src[ret];
+       return err;
 }
 
-static char* msg_normalize_number(char *src)
+
+msg_error_t MsgGetConfigInSim(MSG_SETTING_S *pSetting)
 {
-       char *normalized_number;
+       msg_error_t err = MSG_SUCCESS;
+
+       MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
 
-       if ('+' == src[0])
-               normalized_number = msg_clean_country_code(src);
-       else if ('0' == src[0])
-               normalized_number = src+1;
+       // Get Setting Data from SIM
+       if (plg != NULL)
+               err = plg->getConfigData(pSetting);
        else
-               normalized_number = src;
+               err = MSG_ERR_NULL_POINTER;
 
-       MSG_DEBUG("src = %s, normalized = %s", src, normalized_number);
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("Error. Error code is %d.", err);
+               return err;
+       }
 
-       return normalized_number;
+       return err;
 }
index ac18aa6..15641d9 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
@@ -22,7 +22,6 @@
 /*==================================================================================================
                                      VARIABLES
 ==================================================================================================*/
-extern MsgDbHandler dbHandle;
 
 
 /*==================================================================================================
@@ -31,27 +30,41 @@ extern MsgDbHandler dbHandle;
 msg_error_t MsgStoCheckDuplicatedFilter(const MSG_FILTER_S *pFilter)
 {
        MSG_BEGIN();
-
+       MsgDbHandler *dbHandle = getDbHandle();
        msg_error_t err = MSG_SUCCESS;
-       int rowCnt = 0;
 
+       char *filterStr = NULL;
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       MsgConvertStrWithEscape(pFilter->filterValue, &filterStr);
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILTER_ID FROM %s WHERE FILTER_TYPE = %d AND FILTER_VALUE = '%s';",
-                       MSGFW_FILTER_TABLE_NAME, pFilter->filterType, pFilter->filterValue);
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILTER_ID FROM %s WHERE FILTER_TYPE = %d AND FILTER_VALUE = ?;",
+                       MSGFW_FILTER_TABLE_NAME, pFilter->filterType);
 
        MSG_DEBUG("sql : %s", sqlQuery);
 
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+       {
+               if (filterStr)
+                       free(filterStr);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       dbHandle->bindText(filterStr, 1);
+
+       err = dbHandle->stepQuery();
 
-       if (err == MSG_SUCCESS)
+       if (err == MSG_ERR_DB_ROW) {
                err = MSG_ERR_FILTER_DUPLICATED;
-       else if (err == MSG_ERR_DB_NORECORD)
+       } else if (err == MSG_ERR_DB_DONE) {
                err = MSG_SUCCESS;
+       }
+
+       dbHandle->finalizeQuery();
 
-       dbHandle.freeTable();
+       if (filterStr)
+               free(filterStr);
 
        MSG_END();
 
@@ -62,7 +75,7 @@ msg_error_t MsgStoCheckDuplicatedFilter(const MSG_FILTER_S *pFilter)
 msg_error_t MsgStoAddFilter(const MSG_FILTER_S *pFilter)
 {
        MSG_BEGIN();
-
+       MsgDbHandler *dbHandle = getDbHandle();
        msg_error_t err = MSG_SUCCESS;
 
        //check duplication
@@ -77,7 +90,7 @@ msg_error_t MsgStoAddFilter(const MSG_FILTER_S *pFilter)
 
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       err = dbHandle.getRowId(MSGFW_FILTER_TABLE_NAME, &rowId);
+       err = dbHandle->getRowId(MSGFW_FILTER_TABLE_NAME, &rowId);
 
        if (err != MSG_SUCCESS)
                return err;
@@ -85,22 +98,22 @@ msg_error_t MsgStoAddFilter(const MSG_FILTER_S *pFilter)
        // Add Filter
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, ?);",
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, ?, 1);",
                        MSGFW_FILTER_TABLE_NAME, rowId, pFilter->filterType);
 
        MSG_DEBUG("sql : %s", sqlQuery);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_EXEC;
 
-       dbHandle.bindText(pFilter->filterValue, 1);
+       dbHandle->bindText(pFilter->filterValue, 1);
 
-       if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
-               dbHandle.finalizeQuery();
+       if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_EXEC;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        MSG_END();
 
@@ -111,7 +124,7 @@ msg_error_t MsgStoAddFilter(const MSG_FILTER_S *pFilter)
 msg_error_t MsgStoUpdateFilter(const MSG_FILTER_S *pFilter)
 {
        MSG_BEGIN();
-
+       MsgDbHandler *dbHandle = getDbHandle();
        msg_error_t err = MSG_SUCCESS;
 
        //check duplication
@@ -130,17 +143,17 @@ msg_error_t MsgStoUpdateFilter(const MSG_FILTER_S *pFilter)
        snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET FILTER_TYPE = %d, FILTER_VALUE = ? WHERE FILTER_ID = %d;",
                        MSGFW_FILTER_TABLE_NAME, pFilter->filterType, pFilter->filterId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       dbHandle.bindText(pFilter->filterValue, 1);
+       dbHandle->bindText(pFilter->filterValue, 1);
 
-       if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
-               dbHandle.finalizeQuery();
+       if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_EXEC;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        MSG_END();
 
@@ -153,20 +166,20 @@ msg_error_t MsgStoDeleteFilter(msg_filter_id_t filterId)
        MSG_BEGIN();
 
        char sqlQuery[MAX_QUERY_LEN+1];
-
-       dbHandle.beginTrans();
+       MsgDbHandler *dbHandle = getDbHandle();
+       dbHandle->beginTrans();
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
        snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE FILTER_ID = %d;", MSGFW_FILTER_TABLE_NAME, filterId);
 
        // Delete Filter
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
-       dbHandle.endTrans(true);
+       dbHandle->endTrans(true);
 
        MSG_END();
 
@@ -182,29 +195,29 @@ msg_error_t MsgStoGetFilterList(msg_struct_list_s *pFilterList)
                MSG_DEBUG("pFilterList is NULL");
                return MSG_ERR_NULL_POINTER;
        }
-
-       int rowCnt = 0, index = 3;
+       MsgDbHandler *dbHandle = getDbHandle();
+       int rowCnt = 0, index = 0;
 
        char sqlQuery[MAX_QUERY_LEN+1];
 
        // Get filters from DB
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILTER_ID, FILTER_TYPE, FILTER_VALUE FROM %s;", MSGFW_FILTER_TABLE_NAME);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILTER_ID, FILTER_TYPE, FILTER_VALUE, FILTER_ACTIVE FROM %s;", MSGFW_FILTER_TABLE_NAME);
 
        msg_error_t err = MSG_SUCCESS;
 
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
+       err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
 
        if (err == MSG_ERR_DB_NORECORD) {
                pFilterList->nCount = 0;
                pFilterList->msg_struct_info = NULL;
 
-               dbHandle.freeTable();
+               dbHandle->freeTable();
 
                return MSG_SUCCESS;
        } else if (err != MSG_SUCCESS) {
-               dbHandle.freeTable();
+               dbHandle->freeTable();
                return err;
        }
 
@@ -212,27 +225,53 @@ msg_error_t MsgStoGetFilterList(msg_struct_list_s *pFilterList)
 
        MSG_DEBUG("pMsgCommInfoList->nCount [%d]", pFilterList->nCount);
 
-       pFilterList->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_FILTER_S *)*rowCnt];
+       pFilterList->msg_struct_info = (msg_struct_t *)calloc(rowCnt, sizeof(MSG_FILTER_S *));
+
+       if (pFilterList->msg_struct_info != NULL) {
+               msg_struct_s* pTmp = NULL;
+
+               for (int i = 0; i < rowCnt; i++)
+               {
+                       pFilterList->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
+
+                       pTmp = (msg_struct_s *)pFilterList->msg_struct_info[i];
+                       pTmp->type = MSG_STRUCT_FILTER;
+                       pTmp->data = new MSG_FILTER_S;
+                       MSG_FILTER_S *pFilter = (MSG_FILTER_S *)pTmp->data;
+                       memset(pFilter, 0x00, sizeof(MSG_FILTER_S));
+                       pFilter->filterId = dbHandle->getColumnToInt(index++);
+                       pFilter->filterType = dbHandle->getColumnToInt(index++);
+                       memset(pFilter->filterValue, 0x00, sizeof(pFilter->filterValue));
+                       dbHandle->getColumnToString(index++, MAX_FILTER_VALUE_LEN, pFilter->filterValue);
+                       pFilter->bActive = dbHandle->getColumnToInt(index++);
+               }
+       }
 
-       msg_struct_s* pTmp = NULL;
+       dbHandle->freeTable();
 
-       for (int i = 0; i < rowCnt; i++)
-       {
-               pFilterList->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];
-
-               pTmp = (msg_struct_s *)pFilterList->msg_struct_info[i];
-               pTmp->type = MSG_STRUCT_FILTER;
-               pTmp->data = new char [sizeof(MSG_FILTER_S)];
-               MSG_FILTER_S *pFilter = (MSG_FILTER_S *)pTmp->data;
-               memset(pFilter, 0x00, sizeof(MSG_FILTER_S));
-               pFilter->filterId = dbHandle.getColumnToInt(index++);
-               pFilter->filterType = dbHandle.getColumnToInt(index++);
-               memset(pFilter->filterValue, 0x00, sizeof(pFilter->filterValue));
-               dbHandle.getColumnToString(index++, MAX_FILTER_VALUE_LEN, pFilter->filterValue);
-       }
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
 
 
-       dbHandle.freeTable();
+msg_error_t MsgStoSetFilterActivation(msg_filter_id_t filterId, bool bActive)
+{
+       MSG_BEGIN();
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       // Set Filter Activation
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET FILTER_ACTIVE = %d WHERE FILTER_ID = %d;",
+                       MSGFW_FILTER_TABLE_NAME, bActive, filterId);
+
+       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               return MSG_ERR_DB_EXEC;
+       }
 
        MSG_END();
 
index 841859e..d9261dd 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
@@ -23,8 +23,6 @@
 /*==================================================================================================
                                      VARIABLES
 ==================================================================================================*/
-extern MsgDbHandler dbHandle;
-
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
@@ -32,12 +30,12 @@ extern MsgDbHandler dbHandle;
 msg_error_t MsgStoAddFolder(const MSG_FOLDER_INFO_S *pFolderInfo)
 {
        msg_error_t err = MSG_SUCCESS;
-
+       MsgDbHandler *dbHandle = getDbHandle();
        unsigned int rowId = 0;
 
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       err = dbHandle.getRowId(MSGFW_FOLDER_TABLE_NAME, &rowId);
+       err = dbHandle->getRowId(MSGFW_FOLDER_TABLE_NAME, &rowId);
 
        if (err != MSG_SUCCESS)
                return err;
@@ -47,7 +45,7 @@ msg_error_t MsgStoAddFolder(const MSG_FOLDER_INFO_S *pFolderInfo)
        snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, '%s', %d);",
                        MSGFW_FOLDER_TABLE_NAME, rowId, pFolderInfo->folderName, pFolderInfo->folderType);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_EXEC;
 
        return MSG_SUCCESS;
@@ -57,13 +55,13 @@ msg_error_t MsgStoAddFolder(const MSG_FOLDER_INFO_S *pFolderInfo)
 msg_error_t MsgStoUpdateFolder(const MSG_FOLDER_INFO_S *pFolderInfo)
 {
        char sqlQuery[MAX_QUERY_LEN+1];
-
+       MsgDbHandler *dbHandle = getDbHandle();
        // Update Folder
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
        snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET FOLDER_NAME = '%s', FOLDER_TYPE = %d WHERE FOLDER_ID = %d;",
                        MSGFW_FOLDER_TABLE_NAME, pFolderInfo->folderName, pFolderInfo->folderType, pFolderInfo->folderId);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_EXEC;
 
        return MSG_SUCCESS;
@@ -73,16 +71,16 @@ msg_error_t MsgStoUpdateFolder(const MSG_FOLDER_INFO_S *pFolderInfo)
 msg_error_t MsgStoDeleteFolder(const msg_folder_id_t folderId)
 {
        char sqlQuery[MAX_QUERY_LEN+1];
-
-       dbHandle.beginTrans();
+       MsgDbHandler *dbHandle = getDbHandle();
+       dbHandle->beginTrans();
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
        snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE FOLDER_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, folderId);
 
        // Delete Message in the folder from msg table
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
@@ -91,18 +89,18 @@ msg_error_t MsgStoDeleteFolder(const msg_folder_id_t folderId)
                        MSGFW_FOLDER_TABLE_NAME, folderId);
 
        // Delete Message in the folder from msg table
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
        // Clear Conversation table
-       if (MsgStoClearConversationTable(&dbHandle) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (MsgStoClearConversationTable(dbHandle) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
-       dbHandle.endTrans(true);
+       dbHandle->endTrans(true);
 
        return MSG_SUCCESS;
 }
@@ -114,9 +112,9 @@ msg_error_t MsgStoGetFolderList(msg_struct_list_s *pFolderList)
                MSG_DEBUG("pFolderList is NULL");
                return MSG_ERR_NULL_POINTER;
        }
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       int rowCnt = 0;
-       int index = 3;
+       int rowCnt = 0, index = 0;
 
        char sqlQuery[MAX_QUERY_LEN+1];
 
@@ -124,8 +122,8 @@ msg_error_t MsgStoGetFolderList(msg_struct_list_s *pFolderList)
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FOLDER_ID, FOLDER_TYPE, FOLDER_NAME FROM %s;",
                        MSGFW_FOLDER_TABLE_NAME);
 
-       if (dbHandle.getTable(sqlQuery, &rowCnt) != MSG_SUCCESS) {
-               dbHandle.freeTable();
+       if (dbHandle->getTable(sqlQuery, &rowCnt, &index) != MSG_SUCCESS) {
+               dbHandle->freeTable();
                return MSG_ERR_DB_GETTABLE;
        }
 
@@ -133,29 +131,29 @@ msg_error_t MsgStoGetFolderList(msg_struct_list_s *pFolderList)
 
        MSG_DEBUG("pFolderList->nCount [%d]", pFolderList->nCount);
 
-       pFolderList->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_FOLDER_INFO_S *)*rowCnt];
+       pFolderList->msg_struct_info = (msg_struct_t *)calloc(rowCnt, sizeof(MSG_FOLDER_INFO_S *));
 
        msg_struct_s* pTmp = NULL;
 
        for (int i = 0; i < rowCnt; i++)
        {
-               pFolderList->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];
+               pFolderList->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
                pTmp = (msg_struct_s *)pFolderList->msg_struct_info[i];
                pTmp->type = MSG_STRUCT_FOLDER_INFO;
-               pTmp->data = new char[sizeof(MSG_FOLDER_INFO_S)];
+               pTmp->data = new MSG_FOLDER_INFO_S;
                MSG_FOLDER_INFO_S * pFolder = (MSG_FOLDER_INFO_S *)pTmp->data;
                memset(pFolder, 0x00, sizeof(MSG_FOLDER_INFO_S));
 
-               pFolder->folderId = dbHandle.getColumnToInt(index++);
+               pFolder->folderId = dbHandle->getColumnToInt(index++);
 
-               pFolder->folderType = dbHandle.getColumnToInt(index++);
+               pFolder->folderType = dbHandle->getColumnToInt(index++);
 
                memset(pFolder->folderName, 0x00, sizeof(pFolder->folderName));
-               dbHandle.getColumnToString(index++, MAX_FOLDER_NAME_SIZE, pFolder->folderName);
+               dbHandle->getColumnToString(index++, MAX_FOLDER_NAME_SIZE, pFolder->folderName);
 
        }
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        return MSG_SUCCESS;
 }
index 944f234..6366cc7 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <errno.h>
+#include <sys/mman.h>
+#include <fcntl.h>
+
+#include <VMessage.h>
+#include <VCard.h>
+#include "MsgVMessage.h"
 
 #include "MsgDebug.h"
 #include "MsgUtilFile.h"
 #include "MsgStorageHandler.h"
 
 
+#define MSG_DB_VERSION 1
+
 /*==================================================================================================
                                      VARIABLES
 ==================================================================================================*/
-MsgDbHandler dbHandle;
-
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
@@ -46,7 +52,8 @@ msg_error_t MsgStoConnectDB()
 
 msg_error_t MsgStoDisconnectDB()
 {
-       if (dbHandle.disconnect() != MSG_SUCCESS) {
+       MsgDbHandler *dbHandle = getDbHandle();
+       if (dbHandle->disconnect() != MSG_SUCCESS) {
                MSG_DEBUG("DB Disconnect Fail");
                return MSG_ERR_DB_DISCONNECT;
        }
@@ -57,447 +64,184 @@ msg_error_t MsgStoDisconnectDB()
 }
 
 
-msg_error_t MsgStoInitDB(bool bSimChanged)
+void MsgUpdateDBtoVer1()
 {
-       MSG_BEGIN();
-
+       MsgDbHandler *dbHandle = getDbHandle();
        msg_error_t err = MSG_SUCCESS;
-
-#ifdef MSG_DB_CREATE
-       if (MsgCreateConversationTable() != MSG_SUCCESS)
-               return MSG_ERR_DB_STORAGE_INIT;
-       if (MsgCreateAddressTable() != MSG_SUCCESS)
-               return MSG_ERR_DB_STORAGE_INIT;
-       if (MsgCreateFolderTable() != MSG_SUCCESS)
-               return MSG_ERR_DB_STORAGE_INIT;
-       if (MsgCreateMsgTable() != MSG_SUCCESS)
-               return MSG_ERR_DB_STORAGE_INIT;
-       if (MsgCreateSimMessageTable() != MSG_SUCCESS)
-               return MSG_ERR_DB_STORAGE_INIT;
-       if (MsgCreateWAPMessageTable() != MSG_SUCCESS)
-               return MSG_ERR_DB_STORAGE_INIT;
-       if (MsgCreateCBMessageTable() != MSG_SUCCESS)
-               return MSG_ERR_DB_STORAGE_INIT;
-       if (MsgCreateSyncMLMessageTable() != MSG_SUCCESS)
-               return MSG_ERR_DB_STORAGE_INIT;
-       if (MsgCreateSmsSendOptTable() != MSG_SUCCESS)
-               return MSG_ERR_DB_STORAGE_INIT;
-       if (MsgCreateFilterTable() != MSG_SUCCESS)
-               return MSG_ERR_DB_STORAGE_INIT;
-       if (MsgCreateMmsTable() != MSG_SUCCESS)
-               return MSG_ERR_DB_STORAGE_INIT;
-
-       // Add Default Folders
-       if (MsgAddDefaultFolders() != MSG_SUCCESS) {
-               MSG_DEBUG("Add Default Folders Fail");
-               return MSG_ERR_DB_STORAGE_INIT;
-       }
-
-       // Add Default Address
-       if (MsgAddDefaultAddress() != MSG_SUCCESS) {
-               MSG_DEBUG("Add Default Address Fail");
-               return MSG_ERR_DB_STORAGE_INIT;
-       }
-#endif
-
-       // Delete Msgs in Hidden Folder
-       MsgStoDeleteAllMessageInFolder(0, true, NULL);
-
-       // Reset network status
-       MsgStoResetNetworkStatus();
-
-       //clear abnormal mms message
-       MsgStoCleanAbnormalMmsData();
-
-       // Clear all old Sim data
-       MsgStoClearSimMessageInDB();
-
-       int smsCnt = 0, mmsCnt = 0;
-
-       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
-       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
-
-       // Set Indicator
-       MsgSettingSetIndicator(smsCnt, mmsCnt);
-
-       MSG_END();
-
-       return err;
-}
-
-
-msg_error_t MsgCreateConversationTable()
-{
-       msg_error_t err = MSG_SUCCESS;
-
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       if (!dbHandle.checkTableExist(MSGFW_ADDRESS_TABLE_NAME)) {
+       if (!dbHandle->checkTableExist(MSGFW_MMS_MULTIPART_TABLE_NAME)) {
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
                snprintf(sqlQuery, sizeof(sqlQuery),
-                               "CREATE TABLE %s ( \
-                               CONV_ID INTEGER NOT NULL , \
-                               UNREAD_CNT INTEGER DEFAULT 0 , \
-                               SMS_CNT INTEGER DEFAULT 0 , \
-                               MMS_CNT INTEGER DEFAULT 0 , \
-                               MAIN_TYPE INTEGER NOT NULL , \
-                               SUB_TYPE INTEGER NOT NULL , \
-                               MSG_DIRECTION INTEGER NOT NULL , \
-                               DISPLAY_TIME INTEGER , \
-                               DISPLAY_NAME TEXT , \
-                               MSG_TEXT TEXT );",
-                               MSGFW_CONVERSATION_TABLE_NAME);
-
-               err = dbHandle.execQuery(sqlQuery);
+                               "CREATE TABLE %s ( "
+                               "_ID INTEGER PRIMARY KEY AUTOINCREMENT, "
+                               "MSG_ID INTEGER NOT NULL , "
+                               "SEQ INTEGER DEFAULT 0, "
+                               "CONTENT_TYPE TEXT, "
+                               "NAME TEXT, "
+                               "CHARSET INTEGER, "
+                               "CONTENT_ID TEXT, "
+                               "CONTENT_LOCATION TEXT, "
+                               "FILE_PATH TEXT, "
+                               "TEXT TEXT, "
+                               "TCS_LEVEL INTEGER DEFAULT -1, "
+                               "MALWARE_ALLOW INTEGER DEFAULT 0, "
+                               "THUMB_FILE_PATH TEXT, "
+                               "FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID));",
+                               MSGFW_MMS_MULTIPART_TABLE_NAME);
+
+               err = dbHandle->execQuery(sqlQuery);
 
                if (err == MSG_SUCCESS)
-                       MSG_DEBUG("SUCCESS : create %s.", MSGFW_CONVERSATION_TABLE_NAME);
+                       MSG_SEC_DEBUG("SUCCESS : create %s.", MSGFW_MMS_MULTIPART_TABLE_NAME);
                else
-                       MSG_DEBUG("FAIL : create %s [%d].", MSGFW_CONVERSATION_TABLE_NAME, err);
+                       MSG_SEC_DEBUG("FAIL : create %s [%d].", MSGFW_MMS_MULTIPART_TABLE_NAME, err);
        }
-
-       return err;
 }
 
 
-msg_error_t MsgCreateAddressTable()
+void MsgStoUpdateDBVersion()
 {
-       msg_error_t err = MSG_SUCCESS;
-
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       if (!dbHandle.checkTableExist(MSGFW_ADDRESS_TABLE_NAME)) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "CREATE TABLE %s ( \
-                               ADDRESS_ID INTEGER PRIMARY KEY , \
-                               CONV_ID INTEGER  NOT NULL , \
-                               ADDRESS_TYPE INTEGER , \
-                               RECIPIENT_TYPE INTEGER , \
-                               ADDRESS_VAL TEXT , \
-                               CONTACT_ID INTEGER , \
-                               DISPLAY_NAME TEXT , \
-                               FIRST_NAME TEXT , \
-                               LAST_NAME TEXT , \
-                               IMAGE_PATH TEXT , \
-                               SYNC_TIME DATETIME , \
-                               FOREIGN KEY(CONV_ID) REFERENCES %s (CONV_ID) );",
-                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_CONVERSATION_TABLE_NAME);
-
-               err = dbHandle.execQuery(sqlQuery);
+       snprintf(sqlQuery, sizeof(sqlQuery), "PRAGMA user_version=%d;", MSG_DB_VERSION);
 
-               if (err == MSG_SUCCESS)
-                       MSG_DEBUG("SUCCESS : create %s.", MSGFW_ADDRESS_TABLE_NAME);
-               else
-                       MSG_DEBUG("FAIL : create %s [%d].", MSGFW_ADDRESS_TABLE_NAME, err);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to prepareQuery.");
+               return;
        }
 
-       return err;
-}
-
-
-msg_error_t MsgCreateFolderTable()
-{
-       msg_error_t err = MSG_SUCCESS;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       if (!dbHandle.checkTableExist(MSGFW_FOLDER_TABLE_NAME)) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "CREATE TABLE %s ( \
-                               FOLDER_ID INTEGER PRIMARY KEY, \
-                               FOLDER_NAME TEXT NOT NULL, \
-                               FOLDER_TYPE INTEGER DEFAULT 0 );",
-                               MSGFW_FOLDER_TABLE_NAME);
-
-               err = dbHandle.execQuery(sqlQuery);
-
-               if (err == MSG_SUCCESS)
-                       MSG_DEBUG("SUCCESS : create %s.", MSGFW_FOLDER_TABLE_NAME);
-               else
-                       MSG_DEBUG("FAIL : create %s [%d].", MSGFW_FOLDER_TABLE_NAME, err);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_STEP) {
+               MSG_DEBUG("Fail to stepQuery.");
+               dbHandle->finalizeQuery();
+               return;
        }
 
-       return err;
+       dbHandle->finalizeQuery();
 }
 
-
-msg_error_t MsgCreateMsgTable()
+msg_error_t MsgStoDBVerCheck()
 {
-       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
+       int dbVersion = 0;
 
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       if (!dbHandle.checkTableExist(MSGFW_MESSAGE_TABLE_NAME)) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "PRAGMA user_version;");
 
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "CREATE TABLE %s ( \
-                               MSG_ID INTEGER PRIMARY KEY , \
-                               CONV_ID INTEGER NOT NULL , \
-                               FOLDER_ID INTEGER NOT NULL , \
-                               STORAGE_ID INTEGER NOT NULL , \
-                               MAIN_TYPE INTEGER NOT NULL , \
-                               SUB_TYPE INTEGER NOT NULL , \
-                               DISPLAY_TIME DATETIME , \
-                               DATA_SIZE INTEGER DEFAULT 0 , \
-                               NETWORK_STATUS INTEGER DEFAULT 0 , \
-                               READ_STATUS INTEGER DEFAULT 0 , \
-                               PROTECTED INTEGER DEFAULT 0 , \
-                               PRIORITY INTEGER DEFAULT 0 , \
-                               MSG_DIRECTION INTEGER NOT NULL , \
-                               SCHEDULED_TIME DATETIME , \
-                               BACKUP INTEGER DEFAULT 0 , \
-                               SUBJECT TEXT , \
-                               MSG_DATA TEXT , \
-                               THUMB_PATH TEXT , \
-                               MSG_TEXT TEXT , \
-                               DELIVERY_REPORT_STATUS INTEGER DEFAULT 0 , \
-                               DELIVERY_REPORT_TIME DATETIME , \
-                               READ_REPORT_STATUS INTEGER DEFAULT 0 , \
-                               READ_REPORT_TIME DATETIME , \
-                               ATTACHMENT_COUNT INTEGER DEFAULT 0 , \
-                               FOREIGN KEY(CONV_ID) REFERENCES %s (CONV_ID) , \
-                               FOREIGN KEY(FOLDER_ID) REFERENCES %s (FOLDER_ID) );",
-                               MSGFW_MESSAGE_TABLE_NAME, MSGFW_CONVERSATION_TABLE_NAME, MSGFW_FOLDER_TABLE_NAME);
-
-               err = dbHandle.execQuery(sqlQuery);
-
-               if (err == MSG_SUCCESS)
-                       MSG_DEBUG("SUCCESS : create %s.", MSGFW_MESSAGE_TABLE_NAME);
-               else
-                       MSG_DEBUG("FAIL : create %s [%d].", MSGFW_MESSAGE_TABLE_NAME, err);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to prepareQuery.");
+               return MSG_ERR_DB_EXEC;
        }
 
-       return err;
-}
-
-
-msg_error_t MsgCreateSimMessageTable()
-{
-       msg_error_t err = MSG_SUCCESS;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       if (!dbHandle.checkTableExist(MSGFW_SIM_MSG_TABLE_NAME)) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "CREATE TABLE %s ( \
-                               MSG_ID INTEGER , \
-                               SIM_ID INTEGER NOT NULL , \
-                               FOREIGN KEY(MSG_ID) REFERENCES %s (MSG_ID) );",
-                               MSGFW_SIM_MSG_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME);
-
-               err = dbHandle.execQuery(sqlQuery);
-
-               if (err == MSG_SUCCESS)
-                       MSG_DEBUG("SUCCESS : create %s.", MSGFW_SIM_MSG_TABLE_NAME);
-               else
-                       MSG_DEBUG("FAIL : create %s [%d].", MSGFW_SIM_MSG_TABLE_NAME, err);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_STEP) {
+               MSG_DEBUG("Fail to stepQuery.");
+               dbHandle->finalizeQuery();
+               return MSG_ERR_DB_EXEC;
        }
 
-       return err;
-}
+       dbVersion = dbHandle->columnInt(0);
 
+       dbHandle->finalizeQuery();
 
-msg_error_t MsgCreateWAPMessageTable()
-{
-       msg_error_t err = MSG_SUCCESS;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
+       MSG_DEBUG("dbVersion [%d]", dbVersion);
 
-       if (!dbHandle.checkTableExist(MSGFW_PUSH_MSG_TABLE_NAME)) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "CREATE TABLE %s ( \
-                               MSG_ID INTEGER , \
-                               ACTION INTEGER , \
-                               CREATED INTEGER , \
-                               EXPIRES INTEGER , \
-                               ID TEXT , \
-                               HREF TEXT , \
-                               CONTENT TEXT , \
-                               FOREIGN KEY(MSG_ID) REFERENCES %s(MSG_ID) );",
-                               MSGFW_PUSH_MSG_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME);
-
-               err = dbHandle.execQuery(sqlQuery);
-
-               if (err == MSG_SUCCESS)
-                       MSG_DEBUG("SUCCESS : create %s.", MSGFW_PUSH_MSG_TABLE_NAME);
-               else
-                       MSG_DEBUG("FAIL : create %s [%d].", MSGFW_PUSH_MSG_TABLE_NAME, err);
+       switch (dbVersion)
+       {
+       case 0 :
+               MsgUpdateDBtoVer1();
+               /* no break */
+       default :
+               MsgStoUpdateDBVersion();
+               /* no break */
        }
 
-       return err;
+       return MSG_SUCCESS;
 }
 
-
-msg_error_t MsgCreateCBMessageTable()
+void MsgInitMmapMutex(const char *shm_file_name)
 {
-       msg_error_t err = MSG_SUCCESS;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       if (!dbHandle.checkTableExist(MSGFW_CB_MSG_TABLE_NAME)) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "CREATE TABLE %s ( \
-                               MSG_ID INTEGER , \
-                               CB_MSG_ID INTEGER NOT NULL , \
-                               FOREIGN KEY(MSG_ID) REFERENCES %s (MSG_ID) );",
-                               MSGFW_CB_MSG_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME);
-
-               err = dbHandle.execQuery(sqlQuery);
+       MSG_BEGIN();
 
-               if (err == MSG_SUCCESS)
-                       MSG_DEBUG("SUCCESS : create %s.", MSGFW_CB_MSG_TABLE_NAME);
-               else
-                       MSG_DEBUG("FAIL : create %s [%d].", MSGFW_CB_MSG_TABLE_NAME, err);
+       if(!shm_file_name) {
+               MSG_FATAL("EMAIL_ERROR_INVALID_PARAM");
+               return;
        }
 
-       return err;
-}
-
-
-msg_error_t MsgCreateSyncMLMessageTable()
-{
-       msg_error_t err = MSG_SUCCESS;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       if (!dbHandle.checkTableExist(MSGFW_SYNCML_MSG_TABLE_NAME)) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "CREATE TABLE %s ( \
-                               MSG_ID INTEGER , \
-                               EXT_ID INTEGER NOT NULL , \
-                               PINCODE INTEGER NOT NULL , \
-                               FOREIGN KEY(MSG_ID) REFERENCES %s(MSG_ID) );",
-                               MSGFW_SYNCML_MSG_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME);
-
-               err = dbHandle.execQuery(sqlQuery);
+       int fd = shm_open (shm_file_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); /*  note: permission is not working */
 
-               if (err == MSG_SUCCESS)
-                       MSG_DEBUG("SUCCESS : create %s.", MSGFW_SYNCML_MSG_TABLE_NAME);
-               else
-                       MSG_DEBUG("FAIL : create %s [%d].", MSGFW_SYNCML_MSG_TABLE_NAME, err);
+       if (fd < 0) {
+               MSG_FATAL("shm_open errno [%d]", errno);
+               return;
        }
 
-       return err;
-}
-
-msg_error_t MsgCreateSmsSendOptTable()
-{
-       msg_error_t err = MSG_SUCCESS;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
+       fchmod(fd, 0666);
+       MSG_DEBUG("** Create SHM FILE **");
+       if (ftruncate(fd, sizeof(pthread_mutex_t)) != 0) {
+               MSG_FATAL("ftruncate errno [%d]", errno);
+               return;
+       }
 
-       if (!dbHandle.checkTableExist(MSGFW_SMS_SENDOPT_TABLE_NAME)) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       pthread_mutex_t *mx = (pthread_mutex_t *)mmap(NULL, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+       if (mx == MAP_FAILED) {
+               MSG_FATAL("mmap errno [%d]", errno);
+               return ;
+       }
 
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "CREATE TABLE %s ( \
-                               MSG_ID INTEGER , \
-                               DELREP_REQ INTEGER NOT NULL , \
-                               KEEP_COPY INTEGER NOT NULL , \
-                               REPLY_PATH INTEGER NOT NULL , \
-                               FOREIGN KEY(MSG_ID) REFERENCES %s (MSG_ID) );",
-                               MSGFW_SMS_SENDOPT_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME);
+       // initialize the data on mmap
+       pthread_mutexattr_t mattr;
+       pthread_mutexattr_init(&mattr);
+       pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
+       pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST_NP);
+       pthread_mutex_init(mx, &mattr);
+       pthread_mutexattr_destroy(&mattr);
 
-               err = dbHandle.execQuery(sqlQuery);
+       close (fd);
+       MSG_END();
+}
 
-               if (err == MSG_SUCCESS)
-                               MSG_DEBUG("SUCCESS : create %s.", MSGFW_SMS_SENDOPT_TABLE_NAME);
-               else
-                               MSG_DEBUG("FAIL : create %s [%d].", MSGFW_SMS_SENDOPT_TABLE_NAME, err);
-       }
 
-       return err;
+void MsgfreeMmapMutex()
+{
+       MsgDbHandler *dbHandle = getDbHandle();
+       dbHandle->freeMmapMutex();
 }
 
 
-msg_error_t MsgCreateFilterTable()
+msg_error_t MsgStoInitDB(bool bSimChanged)
 {
+       MSG_BEGIN();
+//     MsgDbHandler *dbHandle = getDbHandle();
        msg_error_t err = MSG_SUCCESS;
 
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       if (!dbHandle.checkTableExist(MSGFW_FILTER_TABLE_NAME)) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       // Init mmap mutex for DB access
+       MsgInitMmapMutex(SHM_FILE_FOR_DB_LOCK);
 
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "CREATE TABLE %s ( \
-                               FILTER_ID INTEGER PRIMARY KEY , \
-                               FILTER_TYPE INTEGER NOT NULL , \
-                               FILTER_VALUE TEXT NOT NULL );",
-                               MSGFW_FILTER_TABLE_NAME);
-
-               err = dbHandle.execQuery(sqlQuery);
+       // Check DB version.
+       MsgStoDBVerCheck();
 
-               if (err == MSG_SUCCESS)
-                               MSG_DEBUG("SUCCESS : create %s.", MSGFW_FILTER_TABLE_NAME);
-               else
-                               MSG_DEBUG("FAIL : create %s [%d].", MSGFW_FILTER_TABLE_NAME, err);
-       }
-
-       return err;
-}
+       // Delete Msgs in Hidden Folder
+       MsgStoDeleteAllMessageInFolder(0, true, NULL);
 
+       // Reset network status
+       MsgStoResetNetworkStatus();
 
-msg_error_t MsgCreateMmsTable()
-{
-       msg_error_t err = MSG_SUCCESS;
+#if 0
+       // Reset Cb Message
+       MsgStoResetCBMessage();
+#endif
 
-       char sqlQuery[MAX_QUERY_LEN+1];
+       //clear abnormal mms message
+       MsgStoCleanAbnormalMmsData();
 
-       if (!dbHandle.checkTableExist(MMS_PLUGIN_MESSAGE_TABLE_NAME)) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       // Clear all old Sim data
+       MsgStoClearSimMessageInDB();
 
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "CREATE TABLE %s ( \
-                               MSG_ID INTEGER , \
-                               TRANSACTION_ID TEXT , \
-                               MESSAGE_ID TEXT , \
-                               FWD_MESSAGE_ID TEXT , \
-                               CONTENTS_LOCATION TEXT , \
-                               FILE_PATH TEXT , \
-                               VERSION INTEGER NOT NULL , \
-                               DATA_TYPE INTEGER DEFAULT -1 , \
-                               DATE DATETIME , \
-                               HIDE_ADDRESS INTEGER DEFAULT 0 , \
-                               ASK_DELIVERY_REPORT INTEGER DEFAULT 0 , \
-                               REPORT_ALLOWED INTEGER DEFAULT 0 , \
-                               READ_REPORT_ALLOWED_TYPE INTEGER DEFAULT 0 , \
-                               ASK_READ_REPLY INTEGER DEFAULT 0 , \
-                               READ INTEGER DEFAULT 0 , \
-                               READ_REPORT_SEND_STATUS INTEGER DEFAULT 0 , \
-                               READ_REPORT_SENT INTEGER DEFAULT 0 , \
-                               PRIORITY INTEGER DEFAULT 0 , \
-                               KEEP_COPY INTEGER DEFAULT 0 , \
-                               MSG_SIZE INTEGER NOT NULL , \
-                               MSG_CLASS INTEGER DEFAULT -1 , \
-                               EXPIRY_TIME DATETIME , \
-                               CUSTOM_DELIVERY_TIME INTEGER DEFAULT 0 , \
-                               DELIVERY_TIME DATETIME , \
-                               MSG_STATUS INTEGER DEFAULT -1 , \
-                               FOREIGN KEY(MSG_ID) REFERENCES %s (MSG_ID) );",
-                               MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME);
-
-               err = dbHandle.execQuery(sqlQuery);
+       //update sim index to 0 for all messages
+       MsgStoUpdateIMSI(0);
 
-               if (err == MSG_SUCCESS)
-                       MSG_DEBUG("SUCCESS : create %s.", MMS_PLUGIN_MESSAGE_TABLE_NAME);
-               else
-                       MSG_DEBUG("FAIL : create %s [%d].", MMS_PLUGIN_MESSAGE_TABLE_NAME, err);
-       }
+       MSG_END();
 
        return err;
 }
@@ -509,27 +253,27 @@ msg_error_t MsgAddDefaultFolders()
        int nResult = 0;
 
        char sqlQuery[MAX_QUERY_LEN+1];
-
+       MsgDbHandler *dbHandle = getDbHandle();
        // INBOX
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) FROM %s WHERE FOLDER_ID = %d;",
                        MSGFW_FOLDER_TABLE_NAME, MSG_INBOX_ID);
 
-       if (dbHandle.getTable(sqlQuery, &nRowCnt) != MSG_SUCCESS) {
-               dbHandle.freeTable();
+       if (dbHandle->getTable(sqlQuery, &nRowCnt, NULL) != MSG_SUCCESS) {
+               dbHandle->freeTable();
                return MSG_ERR_DB_GETTABLE;
        }
 
-       nResult = dbHandle.getColumnToInt(1);
+       nResult = dbHandle->getColumnToInt(1);
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        if (nResult == 0) {
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
                snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, 'INBOX', %d);",
                                MSGFW_FOLDER_TABLE_NAME, MSG_INBOX_ID, MSG_FOLDER_TYPE_INBOX);
 
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                        return MSG_ERR_DB_EXEC;
        }
 
@@ -538,21 +282,21 @@ msg_error_t MsgAddDefaultFolders()
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) FROM %s WHERE FOLDER_ID = %d;",
                        MSGFW_FOLDER_TABLE_NAME, MSG_OUTBOX_ID);
 
-       if (dbHandle.getTable(sqlQuery, &nRowCnt) != MSG_SUCCESS) {
-               dbHandle.freeTable();
+       if (dbHandle->getTable(sqlQuery, &nRowCnt, NULL) != MSG_SUCCESS) {
+               dbHandle->freeTable();
                return MSG_ERR_DB_GETTABLE;
        }
 
-       nResult = dbHandle.getColumnToInt(1);
+       nResult = dbHandle->getColumnToInt(1);
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        if (nResult == 0) {
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
                snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, 'OUTBOX', %d);",
                                MSGFW_FOLDER_TABLE_NAME, MSG_OUTBOX_ID, MSG_FOLDER_TYPE_OUTBOX);
 
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                        return MSG_ERR_DB_EXEC;
        }
 
@@ -561,21 +305,21 @@ msg_error_t MsgAddDefaultFolders()
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) FROM %s WHERE FOLDER_ID = %d;",
                        MSGFW_FOLDER_TABLE_NAME, MSG_SENTBOX_ID);
 
-       if (dbHandle.getTable(sqlQuery, &nRowCnt) != MSG_SUCCESS) {
-               dbHandle.freeTable();
+       if (dbHandle->getTable(sqlQuery, &nRowCnt, NULL) != MSG_SUCCESS) {
+               dbHandle->freeTable();
                return MSG_ERR_DB_GETTABLE;
        }
 
-       nResult = dbHandle.getColumnToInt(1);
+       nResult = dbHandle->getColumnToInt(1);
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        if (nResult == 0) {
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
                snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, 'SENTBOX', %d);",
                                MSGFW_FOLDER_TABLE_NAME, MSG_SENTBOX_ID, MSG_FOLDER_TYPE_OUTBOX);
 
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                        return MSG_ERR_DB_EXEC;
        }
 
@@ -584,21 +328,21 @@ msg_error_t MsgAddDefaultFolders()
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) FROM %s WHERE FOLDER_ID = %d;",
                        MSGFW_FOLDER_TABLE_NAME, MSG_DRAFT_ID);
 
-       if (dbHandle.getTable(sqlQuery, &nRowCnt) != MSG_SUCCESS) {
-               dbHandle.freeTable();
+       if (dbHandle->getTable(sqlQuery, &nRowCnt, NULL) != MSG_SUCCESS) {
+               dbHandle->freeTable();
                return MSG_ERR_DB_GETTABLE;
        }
 
-       nResult = dbHandle.getColumnToInt(1);
+       nResult = dbHandle->getColumnToInt(1);
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        if (nResult == 0) {
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
                snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, 'DRAFT', %d);",
                                MSGFW_FOLDER_TABLE_NAME, MSG_DRAFT_ID, MSG_FOLDER_TYPE_DRAFT);
 
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                        return MSG_ERR_DB_EXEC;
        }
 
@@ -607,21 +351,21 @@ msg_error_t MsgAddDefaultFolders()
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) FROM %s WHERE FOLDER_ID = %d;",
                        MSGFW_FOLDER_TABLE_NAME, MSG_CBMSGBOX_ID);
 
-       if (dbHandle.getTable(sqlQuery, &nRowCnt) != MSG_SUCCESS) {
-               dbHandle.freeTable();
+       if (dbHandle->getTable(sqlQuery, &nRowCnt, NULL) != MSG_SUCCESS) {
+               dbHandle->freeTable();
                return MSG_ERR_DB_GETTABLE;
        }
 
-       nResult = dbHandle.getColumnToInt(1);
+       nResult = dbHandle->getColumnToInt(1);
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        if (nResult == 0) {
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
                snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, 'CBMSGBOX', %d);",
                                MSGFW_FOLDER_TABLE_NAME, MSG_CBMSGBOX_ID, MSG_FOLDER_TYPE_INBOX);
 
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                        return MSG_ERR_DB_EXEC;
        }
 
@@ -630,67 +374,21 @@ msg_error_t MsgAddDefaultFolders()
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) FROM %s WHERE FOLDER_ID = %d;",
                        MSGFW_FOLDER_TABLE_NAME, MSG_SPAMBOX_ID);
 
-       if (dbHandle.getTable(sqlQuery, &nRowCnt) != MSG_SUCCESS) {
-               dbHandle.freeTable();
+       if (dbHandle->getTable(sqlQuery, &nRowCnt, NULL) != MSG_SUCCESS) {
+               dbHandle->freeTable();
                return MSG_ERR_DB_GETTABLE;
        }
 
-       nResult = dbHandle.getColumnToInt(1);
+       nResult = dbHandle->getColumnToInt(1);
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        if (nResult == 0) {
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
                snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, 'SPAMBOX', %d);",
                                MSGFW_FOLDER_TABLE_NAME, MSG_SPAMBOX_ID, MSG_FOLDER_TYPE_SPAMBOX);
 
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
-                       return MSG_ERR_DB_EXEC;
-       }
-
-       // SMS TEMPLATE
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) FROM %s WHERE FOLDER_ID = %d;",
-                       MSGFW_FOLDER_TABLE_NAME, MSG_SMS_TEMPLATE_ID);
-
-       if (dbHandle.getTable(sqlQuery, &nRowCnt) != MSG_SUCCESS) {
-               dbHandle.freeTable();
-               return MSG_ERR_DB_GETTABLE;
-       }
-
-       nResult = dbHandle.getColumnToInt(1);
-
-       dbHandle.freeTable();
-
-       if (nResult == 0) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, 'SMS TEMPLATE', %d);",
-                               MSGFW_FOLDER_TABLE_NAME, MSG_SMS_TEMPLATE_ID, MSG_FOLDER_TYPE_TEMPLATE);
-
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
-                       return MSG_ERR_DB_EXEC;
-       }
-
-       // MMS TEMPLATE
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) FROM %s WHERE FOLDER_ID = %d;",
-                       MSGFW_FOLDER_TABLE_NAME, MSG_MMS_TEMPLATE_ID);
-
-       if (dbHandle.getTable(sqlQuery, &nRowCnt) != MSG_SUCCESS) {
-               dbHandle.freeTable();
-               return MSG_ERR_DB_GETTABLE;
-       }
-
-       nResult = dbHandle.getColumnToInt(1);
-
-       dbHandle.freeTable();
-
-       if (nResult == 0) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, 'MMS TEMPLATE', %d);",
-                               MSGFW_FOLDER_TABLE_NAME, MSG_MMS_TEMPLATE_ID, MSG_FOLDER_TYPE_TEMPLATE);
-
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                        return MSG_ERR_DB_EXEC;
        }
 
@@ -701,7 +399,7 @@ msg_error_t MsgAddDefaultFolders()
 msg_error_t MsgAddDefaultAddress()
 {
        MSG_BEGIN();
-
+       MsgDbHandler *dbHandle = getDbHandle();
        int nRowCnt = 0, nResult = 0;
 
        char sqlQuery[MAX_QUERY_LEN+1];
@@ -710,23 +408,23 @@ msg_error_t MsgAddDefaultAddress()
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) FROM %s WHERE ADDRESS_ID = 0;",
                        MSGFW_ADDRESS_TABLE_NAME);
 
-       if (dbHandle.getTable(sqlQuery, &nRowCnt) != MSG_SUCCESS) {
-               dbHandle.freeTable();
+       if (dbHandle->getTable(sqlQuery, &nRowCnt, NULL) != MSG_SUCCESS) {
+               dbHandle->freeTable();
                return MSG_ERR_DB_GETTABLE;
        }
 
-       nResult = dbHandle.getColumnToInt(1);
+       nResult = dbHandle->getColumnToInt(1);
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        if (nResult == 0) {
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (0, 0, 0, '', 0, '', '', '', '', 0, 0, 0, 0, 0, 0, 0, 0, '');",
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (0, 0, 0, 0, '', 0, 0, '', '', '', '', '', '', 0);",
                                MSGFW_ADDRESS_TABLE_NAME);
 
                MSG_DEBUG("%s", sqlQuery);
 
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                        return MSG_ERR_DB_EXEC;
        }
 
@@ -738,6 +436,7 @@ msg_error_t MsgAddDefaultAddress()
 
 msg_error_t MsgStoResetDatabase()
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        msg_error_t err = MSG_SUCCESS;
 
        char sqlQuery[MAX_QUERY_LEN+1];
@@ -749,7 +448,7 @@ msg_error_t MsgStoResetDatabase()
 
        int listCnt = sizeof(tableList)/sizeof(char*);
 
-       dbHandle.beginTrans();
+       dbHandle->beginTrans();
 
        // Delete Database
        for (int i = 0; i < listCnt; i++)
@@ -757,8 +456,8 @@ msg_error_t MsgStoResetDatabase()
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
                snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s;", tableList[i]);
 
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_EXEC;
                }
        }
@@ -768,34 +467,34 @@ msg_error_t MsgStoResetDatabase()
        snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE STORAGE_ID <> %d;",
                        MSGFW_MESSAGE_TABLE_NAME, MSG_STORAGE_SIM);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
        // Delete Conversation Table
-       err = MsgStoClearConversationTable(&dbHandle);
+       err = MsgStoClearConversationTable(dbHandle);
 
        if (err != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+               dbHandle->endTrans(false);
                return err;
        }
 
        // Add Default Folders
        if (MsgAddDefaultFolders() != MSG_SUCCESS) {
                MSG_DEBUG("Add Default Folders Fail");
-               dbHandle.endTrans(false);
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_STORAGE_INIT;
        }
 
        // Add Default Address
        if (MsgAddDefaultAddress() != MSG_SUCCESS) {
                MSG_DEBUG("Add Default Address Fail");
-               dbHandle.endTrans(false);
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_STORAGE_INIT;
        }
 
-       dbHandle.endTrans(true);
+       dbHandle->endTrans(true);
 
        // Delete MMS Files
        MsgRmRf((char*)MSG_DATA_PATH);
@@ -817,48 +516,649 @@ msg_error_t MsgStoResetDatabase()
 }
 
 
-msg_error_t MsgStoBackupMessage()
+msg_error_t MsgStoBackupMessage(msg_message_backup_type_t type, const char *filepath)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
+       msg_error_t     err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       int rowCnt = 0;
+       MSG_MESSAGE_INFO_S msgInfo = {0, };
+       char* encoded_data = NULL;
+
+       char fileName[MSG_FILENAME_LEN_MAX+1];
+       memset(fileName, 0x00, sizeof(fileName));
+       strncpy(fileName, filepath, MSG_FILENAME_LEN_MAX);
+       if (remove(fileName) != 0) {
+               MSG_SEC_DEBUG("Fail to delete [%s].", fileName);
+       }
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       MSG_SEC_DEBUG("backup type = %d, path = %s", type, filepath);
+
+       if (type == MSG_BACKUP_TYPE_SMS) {
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT MSG_ID FROM %s "
+                               "WHERE STORAGE_ID = %d AND MAIN_TYPE = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_STORAGE_PHONE, MSG_SMS_TYPE);
+       } else if (type == MSG_BACKUP_TYPE_MMS) {
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT MSG_ID FROM %s "
+                               "WHERE STORAGE_ID = %d AND MAIN_TYPE = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_STORAGE_PHONE, MSG_MMS_TYPE);
+       } else if (type == MSG_BACKUP_TYPE_ALL) {
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT MSG_ID FROM %s "
+                               "WHERE STORAGE_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_STORAGE_PHONE);
+
+       }
+
+       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+       if (err != MSG_SUCCESS) {
+               dbHandle->freeTable();
+               return err;
+       }
+
+       MSG_DEBUG("backup number = %d", rowCnt);
+
+       int msg_id[rowCnt];
+       for (int i = 0; i < rowCnt; i++) {
+               msg_id[i] = dbHandle->getColumnToInt(i+1);
+       }
+       dbHandle->freeTable();
+
+       for (int i = 0; i < rowCnt; i++) {
+               msgInfo.addressList = NULL;
+               unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+               err = MsgStoGetMessage(msg_id[i], &msgInfo, NULL);
+               if(err != MSG_SUCCESS) {
+                       return err;
+               }
+
+               encoded_data = MsgVMessageAddRecord(dbHandle, &msgInfo);
+
+               if (msgInfo.bTextSms == false)
+               {
+                       MsgDeleteFile(msgInfo.msgData); //ipc
+               }
+               if (encoded_data != NULL) {
+                       if (MsgAppendFile(fileName, encoded_data, strlen(encoded_data)) == false) {
+                               free(encoded_data);
+                               return MSG_ERR_STORAGE_ERROR;
+                       }
+
+                       free(encoded_data);
+               }
+
+               memset(&msgInfo, 0, sizeof(MSG_MESSAGE_INFO_S));
+       }
+
+       MSG_END();
        return MSG_SUCCESS;
+
 }
 
 msg_error_t MsgStoUpdateMms(MSG_MESSAGE_INFO_S *pMsg)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
+       msg_error_t err = MSG_SUCCESS;
        char sqlQuery[MAX_QUERY_LEN+1];
+       unsigned int fileSize = 0;
+       char *pFileData = NULL;
 
        if (pMsg->msgType.subType == MSG_SENDCONF_MMS) {
+
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-               dbHandle.beginTrans();
+               dbHandle->beginTrans();
                snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET THUMB_PATH = ?, MSG_TEXT = ? WHERE MSG_ID = %d;",
                                MSGFW_MESSAGE_TABLE_NAME, pMsg->msgId);
 
-               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_EXEC;
                }
 
+               dbHandle->bindText(pMsg->thumbPath, 1);
+
+               if (pMsg->msgText[0] != '\0' && g_file_get_contents(pMsg->msgText, &pFileData, &fileSize, NULL) == true) {
+                       dbHandle->bindText(pFileData, 2);
+               }
+
+               MSG_SEC_DEBUG("thumbPath = %s , msgText = %s" , pMsg->thumbPath, pFileData);
 
-               dbHandle.bindText(pMsg->thumbPath, 1);
-               dbHandle.bindText(pMsg->msgText, 2);
-               MSG_DEBUG("thumbPath = %s , msgText = %s" , pMsg->thumbPath, pMsg->msgText);
                MSG_DEBUG("%s", sqlQuery);
 
-               if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
-                       dbHandle.finalizeQuery();
-                       dbHandle.endTrans(false);
+               if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                       dbHandle->finalizeQuery();
+                       dbHandle->endTrans(false);
+                       if (pFileData) {
+                               free(pFileData);
+                               pFileData = NULL;
+                       }
+
                        return MSG_ERR_DB_EXEC;
                }
 
-               dbHandle.finalizeQuery();
-               dbHandle.endTrans(true);
+               dbHandle->finalizeQuery();
+               dbHandle->endTrans(true);
+
+               if (pFileData) {
+                       free(pFileData);
+                       pFileData = NULL;
+               }
        } else {
-               MsgStoUpdateMMSMessage(pMsg);
+
+               err = MsgStoUpdateMMSMessage(pMsg);
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgStoUpdateMMSMessage() error : %d", err);
+               }
+
+       }
+
+       return err;
+}
+
+msg_error_t MsgStoRestoreMessage(const char *filepath, msg_id_list_s **result_id_list)
+{
+       if (result_id_list == NULL) {
+               MSG_DEBUG("result_id_list is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       msg_error_t err = MSG_SUCCESS;
+       MSG_MESSAGE_INFO_S msgInfo = {0,};
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       VTree* vMsg = NULL;
+       VObject* pObject = NULL;
+
+       msg_id_list_s *msgIdList = NULL;
+       msgIdList = (msg_id_list_s *)calloc(1, sizeof(msg_id_list_s));
+
+       int dataSize = 0;
+
+       char fileName[MSG_FILENAME_LEN_MAX+1];
+       char *pData = NULL;
+       char *pCurrent = NULL;
+       char *pTemp = NULL;
+
+       *result_id_list = NULL;
+
+#ifdef MSG_FOR_DEBUG
+       char sample[10000] = "BEGIN:VMSG\r\nX-MESSAGE-TYPE:SMS\r\nX-IRMC-BOX:INBOX\r\nX-SS-DT:20100709T155811Z\r\nBEGIN:VBODY\r\nX-BODY-SUBJECT:hekseh\r\nX-BODY-CONTENTS;ENCODING=BASE64:aGVsbG93b3JsZA==\r\nEND:VBODY\r\nBEGIN:VCARD\r\nVERSION:2.1\r\nTEL:01736510664\r\nEND:VCARD\r\nEND:VMSG\r\n";
+       vMsg = vmsg_decode(sample);
+#else
+       memset(fileName, 0x00, sizeof(fileName));
+       strncpy(fileName, filepath, MSG_FILENAME_LEN_MAX);
+       pData = MsgOpenAndReadMmsFile(fileName, 0, -1, &dataSize);
+       if (pData == NULL) {
+               if (msgIdList) {
+                       if (msgIdList->msgIdList)
+                               free(msgIdList->msgIdList);
+                       free(msgIdList);
+               }
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       pCurrent = pData;
+
+       while ((pTemp = strstr(pCurrent, "END:VMSG")) != NULL)
+       {
+               MSG_DEBUG("Start Position: %s", pCurrent);
+
+               while (*pCurrent == '\r' || *pCurrent == '\n')
+                       pCurrent++;
+
+               MSG_DEBUG("Start Position2: %s", pCurrent);
+
+               vMsg = vmsg_decode(pCurrent);
+               if (vMsg == NULL) {
+                       err = MSG_ERR_STORAGE_ERROR;
+                       goto __RETURN;
+               }
+#endif
+
+               pObject = vMsg->pTop;
+
+               memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+               while (1)
+               {
+                       while (1)
+                       {
+                               MSG_DEBUG("pObject type [%d], pObject Value [%s]", pObject->property, pObject->pszValue[0]);
+
+                               switch (pObject->property)
+                               {
+                                       case VMSG_TYPE_MSGTYPE :
+                                       {
+                                               if (!strncmp(pObject->pszValue[0], "SMS", strlen("SMS"))) {
+                                                       msgInfo.msgType.mainType = MSG_SMS_TYPE;
+                                                       msgInfo.msgType.subType = MSG_NORMAL_SMS;
+                                               } else if (!strncmp(pObject->pszValue[0], "MMS RETRIEVED", strlen("MMS RETRIEVED"))) {
+                                                       msgInfo.msgType.mainType = MSG_MMS_TYPE;
+                                                       msgInfo.msgType.subType = MSG_RETRIEVE_AUTOCONF_MMS;
+                                               } else if (!strncmp(pObject->pszValue[0], "MMS SEND", strlen("MMS SEND"))) {
+                                                       msgInfo.msgType.mainType = MSG_MMS_TYPE;
+                                                       msgInfo.msgType.subType = MSG_SENDCONF_MMS;
+                                               } else if (!strncmp(pObject->pszValue[0], "MMS NOTIFICATION", strlen("MMS NOTIFICATION"))) {
+                                                       msgInfo.msgType.mainType = MSG_MMS_TYPE;
+                                                       msgInfo.msgType.subType = MSG_NOTIFICATIONIND_MMS;
+                                               } else {
+                                                       vmsg_free_vtree_memory(vMsg);
+                                                       err = MSG_ERR_STORAGE_ERROR;
+                                                       goto __RETURN;
+                                               }
+                                       }
+                                       break;
+
+                                       case VMSG_TYPE_MSGBOX :
+                                       {
+                                               if(!strncmp(pObject->pszValue[0], "INBOX", strlen("INBOX"))) {
+                                                       msgInfo.folderId= MSG_INBOX_ID;
+                                                       msgInfo.direction=MSG_DIRECTION_TYPE_MT;
+
+                                                       if (msgInfo.msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS)
+                                                               msgInfo.networkStatus=MSG_NETWORK_RETRIEVE_SUCCESS;
+                                                       else if (msgInfo.msgType.subType == MSG_SENDCONF_MMS)
+                                                               msgInfo.networkStatus=MSG_NETWORK_SEND_SUCCESS;
+                                                       else
+                                                               msgInfo.networkStatus=MSG_NETWORK_RECEIVED;
+
+                                               } else if(!strncmp(pObject->pszValue[0], "OUTBOX", strlen("OUTBOX"))) {
+                                                       msgInfo.folderId= MSG_OUTBOX_ID;
+                                                       msgInfo.direction=MSG_DIRECTION_TYPE_MO;
+
+                                                       msgInfo.networkStatus=MSG_NETWORK_SEND_FAIL;
+                                               } else if(!strncmp(pObject->pszValue[0], "SENTBOX", strlen("SENTBOX"))) {
+                                                       msgInfo.folderId= MSG_SENTBOX_ID;
+                                                       msgInfo.direction=MSG_DIRECTION_TYPE_MO;
+
+                                                       msgInfo.networkStatus=MSG_NETWORK_SEND_SUCCESS;
+                                               } else if(!strncmp(pObject->pszValue[0], "DRAFTBOX", strlen("DRAFTBOX"))) {
+                                                       msgInfo.folderId=MSG_DRAFT_ID;
+                                                       msgInfo.direction=MSG_DIRECTION_TYPE_MO;
+
+                                                       msgInfo.networkStatus=MSG_NETWORK_NOT_SEND;
+                                               } else {
+                                                       vmsg_free_vtree_memory(vMsg);
+                                                       err = MSG_ERR_STORAGE_ERROR;
+                                                       goto __RETURN;
+                                               }
+                                       }
+                                       break;
+
+                                       case VMSG_TYPE_STATUS :
+                                       {
+                                               if(!strncmp(pObject->pszValue[0], "READ", strlen("READ"))) {
+                                                       msgInfo.bRead = true;
+                                               } else if(!strncmp(pObject->pszValue[0], "UNREAD", strlen("UNREAD"))) {
+                                                       msgInfo.bRead = false;
+                                               } else {
+                                                       vmsg_free_vtree_memory(vMsg);
+                                                       err = MSG_ERR_STORAGE_ERROR;
+                                                       goto __RETURN;
+                                               }
+                                       }
+                                       break;
+
+                                       case VMSG_TYPE_DATE :
+                                       {
+                                               struct tm       displayTime;
+
+                                               if (!_convert_vdata_str_to_tm(pObject->pszValue[0], &displayTime)) {
+                                                       vmsg_free_vtree_memory( vMsg );
+                                                       err = MSG_ERR_STORAGE_ERROR;
+                                                       goto __RETURN;
+                                               }
+
+                                               msgInfo.displayTime = mktime(&displayTime);
+                                       }
+                                       break;
+
+                                       case VMSG_TYPE_SUBJECT :
+                                       {
+                                               MSG_DEBUG("subject length is [%d].", strlen(pObject->pszValue[0]));
+
+                                               if(strlen(pObject->pszValue[0]) > 0) {
+                                                       strncpy(msgInfo.subject, pObject->pszValue[0], MAX_SUBJECT_LEN);
+                                                       if ( msgInfo.subject[strlen(pObject->pszValue[0])-1] == '\r' )
+                                                               msgInfo.subject[strlen(pObject->pszValue[0])-1]= '\0';
+                                               }
+                                       }
+                                       break;
+
+                                       case VMSG_TYPE_BODY :
+                                       {
+                                               if (msgInfo.msgType.mainType == MSG_SMS_TYPE) {
+                                                       if (pObject->numOfBiData > MAX_MSG_DATA_LEN) {
+                                                               msgInfo.bTextSms = false;
+                                                               char fileName[MAX_COMMON_INFO_SIZE + 1];
+                                                               memset(fileName, 0x00, sizeof(fileName));
+
+                                                               if (MsgCreateFileName(fileName) == false) {
+                                                                       vmsg_free_vtree_memory(vMsg);
+                                                                       err = MSG_ERR_STORAGE_ERROR;
+                                                                       goto __RETURN;
+                                                               }
+
+                                                               if (MsgWriteIpcFile(fileName, pObject->pszValue[0], pObject->numOfBiData) == false) {
+                                                                       vmsg_free_vtree_memory(vMsg);
+                                                                       err = MSG_ERR_STORAGE_ERROR;
+                                                                       goto __RETURN;
+                                                               }
+
+                                                               strncpy(msgInfo.msgData, fileName, MAX_MSG_DATA_LEN);
+                                                               msgInfo.dataSize = pObject->numOfBiData;
+                                                       } else {
+                                                               msgInfo.bTextSms = true;
+
+                                                               if(pObject->numOfBiData > 0) {
+                                                                       memset(msgInfo.msgText, 0x00, sizeof(msgInfo.msgText));
+                                                                       memcpy(msgInfo.msgText, pObject->pszValue[0], pObject->numOfBiData);
+
+                                                                       msgInfo.dataSize = pObject->numOfBiData;
+                                                               }
+                                                       }
+                                               } else {
+                                                       msgInfo.bTextSms = true;
+#if 0
+                                                       if(msgInfo.msgType.subType == MSG_NOTIFICATIONIND_MMS) {
+
+                                                                       msgInfo.bTextSms = true;
+
+                                                               // Save Message Data into File
+                                                               char fileName[MAX_COMMON_INFO_SIZE+1];
+                                                               memset(fileName, 0x00, sizeof(fileName));
+
+                                                               if (MsgCreateFileName(fileName) == false) {
+                                                                       vmsg_free_vtree_memory(vMsg);
+                                                                       return MSG_ERR_STORAGE_ERROR;
+                                                               }
+
+                                                               if (MsgWriteIpcFile(fileName, pObject->pszValue[0], pObject->numOfBiData) == false) {
+                                                                       vmsg_free_vtree_memory(vMsg);
+                                                                       return MSG_ERR_STORAGE_ERROR;
+                                                               }
+                                                               strncpy(msgInfo.msgData, MSG_IPC_DATA_PATH, MAX_MSG_DATA_LEN);
+                                                               strncat(msgInfo.msgData, fileName, MAX_MSG_DATA_LEN-strlen(msgInfo.msgData));
+                                                               msgInfo.dataSize = strlen(fileName);
+                                                               MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(msgInfo.msgType.mainType);
+                                                               if (plg == NULL) {
+                                                                       vmsg_free_vtree_memory(vMsg);
+                                                                       return MSG_ERR_NULL_POINTER;
+                                                               }
+                                                               err =  plg->restoreMsg(&msgInfo, pObject->pszValue[0], pObject->numOfBiData, NULL);
+
+                                                       } else {
+//////////////// From here was avaliable
+                                                               char    retrievedFilePath[MAX_FULL_PATH_SIZE] = {0,};
+                                                               MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(msgInfo.msgType.mainType);
+                                                               if (plg == NULL) {
+                                                                       vmsg_free_vtree_memory(vMsg);
+                                                                       return MSG_ERR_NULL_POINTER;
+                                                               }
+                                                               err =  plg->restoreMsg(&msgInfo, pObject->pszValue[0], pObject->numOfBiData, retrievedFilePath);
+                                                               msgInfo.bTextSms = false;
+
+                                                               char fileName[MAX_COMMON_INFO_SIZE+1];
+                                                               memset(fileName, 0x00, sizeof(fileName));
+
+                                                               if (MsgCreateFileName(fileName) == false) {
+                                                                       vmsg_free_vtree_memory(vMsg);
+                                                                       return MSG_ERR_STORAGE_ERROR;
+                                                               }
+                                                               MSG_SEC_DEBUG("fileName: %s, retrievedFilePath: %s (%d)", fileName, retrievedFilePath, strlen(retrievedFilePath));
+
+                                                               if (MsgWriteIpcFile(fileName, retrievedFilePath, strlen(retrievedFilePath)+ 1) == false) {
+                                                                       vmsg_free_vtree_memory(vMsg);
+                                                                       return MSG_ERR_STORAGE_ERROR;
+                                                               }
+                                                               strncpy(msgInfo.msgData, fileName, MAX_MSG_DATA_LEN);
+                                                               msgInfo.dataSize = strlen(retrievedFilePath) + 1;
+
+                                                               if (err != MSG_SUCCESS)
+                                                                       return vmsg_free_vtree_memory(vMsg);
+///////////////////////////
+                                                       }
+#else
+
+                                                       msgInfo.bTextSms = false;
+
+                                                       char fileName[MAX_COMMON_INFO_SIZE+1];
+                                                       memset(fileName, 0x00, sizeof(fileName));
+
+                                                       if (MsgCreateFileName(fileName) == false) {
+                                                               vmsg_free_vtree_memory(vMsg);
+                                                               err = MSG_ERR_STORAGE_ERROR;
+                                                               goto __RETURN;
+                                                       }
+
+                                                       if (MsgWriteIpcFile(fileName, pObject->pszValue[0], pObject->numOfBiData) == false) {
+                                                               vmsg_free_vtree_memory(vMsg);
+                                                               err = MSG_ERR_STORAGE_ERROR;
+                                                               goto __RETURN;
+                                                       }
+
+                                                       //set serialized mms data ipcfilename
+                                                       strncpy(msgInfo.msgData, fileName, MAX_MSG_DATA_LEN);
+#endif
+                                               }
+                                       }
+                                       break;
+
+                                       case VCARD_TYPE_TEL :
+                                       {
+                                               MSG_ADDRESS_INFO_S * addrInfo = NULL;
+
+                                               msgInfo.nAddressCnt++;
+
+                                               if (msgInfo.addressList == NULL) {
+                                                       addrInfo = (MSG_ADDRESS_INFO_S *)calloc(1, sizeof(MSG_ADDRESS_INFO_S));
+                                               } else {
+                                                       addrInfo = (MSG_ADDRESS_INFO_S *)realloc(msgInfo.addressList, msgInfo.nAddressCnt * sizeof(MSG_ADDRESS_INFO_S));
+                                               }
+
+                                               if (addrInfo == NULL) {
+                                                       vmsg_free_vtree_memory(vMsg);
+                                                       err = MSG_ERR_STORAGE_ERROR;
+                                                       goto __RETURN;
+
+                                               }
+
+                                               msgInfo.addressList = addrInfo;
+
+                                               msgInfo.addressList[msgInfo.nAddressCnt-1].addressType = MSG_ADDRESS_TYPE_PLMN;
+                                               msgInfo.addressList[msgInfo.nAddressCnt-1].recipientType = MSG_RECIPIENTS_TYPE_TO;
+                                               strncpy(msgInfo.addressList[msgInfo.nAddressCnt-1].addressVal, pObject->pszValue[0], MAX_ADDRESS_VAL_LEN);
+
+                                       }
+                                       break;
+                               }
+
+                               if (pObject->pSibling != NULL)
+                                       pObject = pObject->pSibling;
+                               else
+                                       break;
+                       }
+
+                       if (vMsg->pNext != NULL) {
+                               vMsg = vMsg->pNext;
+                               pObject = vMsg->pTop;
+                       } else {
+                               break;
+                       }
+               }
+
+               msgInfo.bBackup = true; // Set Backup Flag
+               msgInfo.storageId = MSG_STORAGE_PHONE; // Set Storage Id
+               msgInfo.priority = MSG_MESSAGE_PRIORITY_NORMAL; // Set Priority
+
+               err = MsgStoAddMessage(&msgInfo, NULL);
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgStoAddMessage() error : %d", err);
+               }
+
+               if (msgInfo.msgType.mainType == MSG_MMS_TYPE)
+                       MsgStoUpdateMms(&msgInfo);
+
+               if (msgIdList->nCount == 0) {
+                       msgIdList->msgIdList = (msg_message_id_t*)calloc(1, sizeof(msg_message_id_t));
+               } else {
+                       msg_message_id_t * msg_id_list;
+                       msg_id_list = (msg_message_id_t*)realloc(msgIdList->msgIdList, sizeof(msg_message_id_t)*(msgIdList->nCount+1));
+
+                       if (msg_id_list)
+                               msgIdList->msgIdList = msg_id_list;
+                       else {
+                               MSG_DEBUG("realloc failed");
+                               err = MSG_ERR_UNKNOWN;
+                               goto __RETURN;
+                       }
+               }
+
+               msgIdList->msgIdList[msgIdList->nCount] = msgInfo.msgId;
+               msgIdList->nCount++;
+
+               vmsg_free_vtree_memory(vMsg);
+
+               vMsg = NULL;
+               pCurrent = pTemp + strlen("END:VMSG");
+#ifndef MSG_FOR_DEBUG
+       }
+#endif
+       *result_id_list = msgIdList;
+
+__RETURN:
+       if(pData)
+       {
+               free( pData );
+               pData = NULL;
+               pCurrent = NULL;
+       }
+
+       if (*result_id_list == NULL && msgIdList) {
+               if (msgIdList->msgIdList) {
+                       free(msgIdList->msgIdList);
+               }
+               free(msgIdList);
+       }
+
+       return err;
+}
+
+msg_error_t MsgStoAddPushEvent(MSG_PUSH_EVENT_INFO_S* pPushEvent)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
+       unsigned int rowId = 0;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       // Check whether Same record exists or not.
+#if 0
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT * FROM %s WHERE CONTENT_TYPE LIKE '%s' AND APP_ID LIKE '%s' AND (PKG_NAME LIKE '%s' OR SECURE = 1);",
+                       MSGFW_PUSH_CONFIG_TABLE_NAME, pPushEvent->contentType, pPushEvent->appId, pPushEvent->pkgName);
+#else
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT * FROM %s WHERE CONTENT_TYPE LIKE '%s' AND APP_ID LIKE '%s';",
+                       MSGFW_PUSH_CONFIG_TABLE_NAME, pPushEvent->contentType, pPushEvent->appId);
+#endif
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Query Failed [%s]", sqlQuery);
+               return MSG_ERR_DB_PREPARE;
+       }
+
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               dbHandle->finalizeQuery();
+               return MSG_ERR_DB_ROW;
+       }
+       dbHandle->finalizeQuery();
+
+       dbHandle->beginTrans();
+
+       if (dbHandle->getRowId(MSGFW_PUSH_CONFIG_TABLE_NAME, &rowId) != MSG_SUCCESS) {
+               MSG_DEBUG("getRowId is failed!!!");
        }
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, ?, ?, ?, %d, 0, 0);",
+                       MSGFW_PUSH_CONFIG_TABLE_NAME, rowId, pPushEvent->bLaunch);
+
+
+       MSG_DEBUG("QUERY : %s", sqlQuery);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       dbHandle->bindText(pPushEvent->contentType, 1);
+       dbHandle->bindText(pPushEvent->appId, 2);
+       dbHandle->bindText(pPushEvent->pkgName, 3);
+
+       if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle->finalizeQuery();
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       dbHandle->finalizeQuery();
+       dbHandle->endTrans(true);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoDeletePushEvent(MSG_PUSH_EVENT_INFO_S* pPushEvent)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
+       dbHandle->beginTrans();
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE CONTENT_TYPE LIKE '%s' AND APP_ID LIKE '%s' AND PKG_NAME LIKE '%s';",
+                       MSGFW_PUSH_CONFIG_TABLE_NAME, pPushEvent->contentType, pPushEvent->appId, pPushEvent->pkgName);
+
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+       dbHandle->endTrans(true);
        return MSG_SUCCESS;
 }
 
-msg_error_t MsgStoRestoreMessage()
+msg_error_t MsgStoUpdatePushEvent(MSG_PUSH_EVENT_INFO_S* pSrc, MSG_PUSH_EVENT_INFO_S* pDst)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
+       dbHandle->beginTrans();
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET CONTENT_TYPE = ?, APP_ID = ?, PKG_NAME = ?, LAUNCH = %d WHERE CONTENT_TYPE LIKE '%s' AND APP_ID LIKE '%s' AND PKG_NAME LIKE '%s';",
+                       MSGFW_PUSH_CONFIG_TABLE_NAME, pDst->bLaunch, pSrc->contentType, pSrc->appId, pSrc->pkgName);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       dbHandle->bindText(pDst->contentType, 1);
+       dbHandle->bindText(pDst->appId, 2);
+       dbHandle->bindText(pDst->pkgName, 3);
+
+       if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle->finalizeQuery();
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       dbHandle->finalizeQuery();
+       dbHandle->endTrans(true);
+
        return MSG_SUCCESS;
 }
index 6630f54..06f9250 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
@@ -35,6 +35,8 @@
 #include "MsgStorageHandler.h"
 #include "MsgNotificationWrapper.h"
 #include "MsgMmsMessage.h"
+#include "MsgDevicedWrapper.h"
+
 
 using namespace std;
 
@@ -42,7 +44,6 @@ using namespace std;
 /*==================================================================================================
                                      VARIABLES
 ==================================================================================================*/
-extern MsgDbHandler dbHandle;
 
 Mutex delNotiMx;
 CndVar delNoticv;
@@ -56,115 +57,11 @@ bool delLogRunning = false;
 /*==================================================================================================
                                      FUNCTION FOR THREAD
 ==================================================================================================*/
-static gboolean startToDeleteNoti(void *pVoid)
-{
-       MSG_BEGIN();
-
-       msg_id_list_s *pMsgIdList = (msg_id_list_s *)pVoid;
-
-       MSG_DEBUG("pMsgIdList->nCount [%d]", pMsgIdList->nCount);
-
-       delNotiMx.lock();
-
-       while (delNotiRunning) {
-               delNoticv.wait(delNotiMx.pMutex());
-       }
-
-       delNotiRunning = true;
-
-       for (int i = 0; i < pMsgIdList->nCount; i++) {
-               MsgDeleteNotiByMsgId(pMsgIdList->msgIdList[i]);
-
-               /** sleep for moment */
-               if ((i%100 == 0) && (i != 0))
-                       usleep(70000);
-       }
-
-       delNotiRunning = false;
-
-       delNoticv.signal();
-       delNotiMx.unlock();
-
-       // memory free
-       if (pMsgIdList != NULL) {
-               //free peer info list
-               if (pMsgIdList->msgIdList != NULL)
-                       delete [] pMsgIdList->msgIdList;
-
-               delete [] pMsgIdList;
-       }
-
-       MSG_END();
-
-       return FALSE;
-}
-
-
-static gboolean startToDeletePhoneLog(void *pVoid)
-{
-       MSG_BEGIN();
-
-       msg_id_list_s *pMsgIdList = (msg_id_list_s *)pVoid;
-
-       MSG_DEBUG("pMsgIdList->nCount [%d]", pMsgIdList->nCount);
-
-       delLogMx.lock();
-
-       while (delLogRunning){
-               delLogcv.wait(delLogMx.pMutex());
-       }
-
-       delLogRunning = true;
-
-       int transBegin = MsgContactSVCBeginTrans();
-
-       for (int i = 0; i < pMsgIdList->nCount; i++) {
-               if (transBegin == 0)
-                       MsgDeletePhoneLog(pMsgIdList->msgIdList[i]);
-
-               /** sleep for moment */
-               if ((i%100 == 0) && (i!=0)) {
-                       if (transBegin == 0) {
-                               MsgContactSVCEndTrans(true);
-                               usleep(70000);
-                       }
-                       transBegin = MsgContactSVCBeginTrans();
-               }
-       }
-
-       if (transBegin == 0)
-               MsgContactSVCEndTrans(true);
-
-       delLogRunning = false;
-
-       delLogcv.signal();
-       delLogMx.unlock();
-
-       // memory free
-       if (pMsgIdList != NULL) {
-               //free peer info list
-               if (pMsgIdList->msgIdList != NULL)
-                       delete [] pMsgIdList->msgIdList;
-
-               delete [] pMsgIdList;
-       }
-
-       MSG_END();
-
-       return FALSE;
-}
-
-static gboolean updateUnreadMsgCount(void *pVoid)
+static gboolean resetNotification(void *pVoid)
 {
        MSG_BEGIN();
 
-       int smsCnt = 0;
-       int mmsCnt = 0;
-
-       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
-       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
-
-       MsgSettingSetIndicator(smsCnt, mmsCnt);
+       MsgRefreshAllNotification(true, false, false);
 
        MSG_END();
 
@@ -175,6 +72,7 @@ static gboolean updateUnreadMsgCount(void *pVoid)
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
+
 msg_error_t MsgStoAddMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo)
 {
        MSG_BEGIN();
@@ -186,139 +84,225 @@ msg_error_t MsgStoAddMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pS
 
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       dbHandle.beginTrans();
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       dbHandle->beginTrans();
 
        if (pMsg->nAddressCnt > 0) {
-               err = MsgStoAddAddress(&dbHandle, pMsg, &convId);
+               err = MsgStoAddAddress(dbHandle, pMsg, &convId);
 
                if (err != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+                       dbHandle->endTrans(false);
                        return err;
                }
 
                pMsg->threadId = convId;
        }
 
-
-       ///////// temporary code for draft message in conversation view.
-       if(convId > 0 && pMsg->folderId == MSG_DRAFT_ID) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "DELETE FROM %s WHERE CONV_ID = %d AND FOLDER_ID = %d;",
-                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_DRAFT_ID);
-
-               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
-
-               err = dbHandle.execQuery(sqlQuery);
-
+       if (pMsg->msgId > 0) {
+               rowId = pMsg->msgId;
+       } else {
+               // get rowId
+               err = dbHandle->getRowId(MSGFW_MESSAGE_TABLE_NAME, &rowId);
                if (err != MSG_SUCCESS) {
-                       MSG_DEBUG("fail to delete draft messages.");
+                       dbHandle->endTrans(false);
+                       return err;
                }
+               pMsg->msgId = (msg_message_id_t)rowId;
        }
-       ////////
-
-       err = dbHandle.getRowId(MSGFW_MESSAGE_TABLE_NAME, &rowId);
-
-       if (err != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return err;
-       }
-
-       pMsg->msgId = (msg_message_id_t)rowId;
 
        int fileSize = 0;
+       gchar *contents = NULL;
 
        char *pFileData = NULL;
-       AutoPtr<char> buf(&pFileData);
+       unique_ptr<char*, void(*)(char**)> buf(&pFileData, unique_ptr_deleter);
 
-       // Get File Data
-       if (pMsg->bTextSms == false) {
-               if (MsgOpenAndReadFile(pMsg->msgData, &pFileData, &fileSize) == false) {
-                       dbHandle.endTrans(false);
-                       return MSG_ERR_STORAGE_ERROR;
-               }
-               MSG_DEBUG("file size [%d]", fileSize);
-       }
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_IMSI, pMsg->sim_idx);
+
+       char *imsi = MsgSettingGetString(keyName);
 
        // Add Message
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, %d, %d, %ld, %d, %d, %d, %d, %d, %d, %ld, %d, ?, ?, ?, ?, %d, 0, %d, 0, 0);",
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, %d, %d, %u, %d, %d, %d, %d, %d, %d, %d, %d, ?, '', '', ?, 0, %d, '%s');",
                        MSGFW_MESSAGE_TABLE_NAME, rowId, convId, pMsg->folderId, pMsg->storageId, pMsg->msgType.mainType, pMsg->msgType.subType,
-                       pMsg->displayTime, pMsg->dataSize, pMsg->networkStatus, pMsg->bRead, pMsg->bProtected, pMsg->priority, pMsg->direction,
-                       0, pMsg->bBackup, MSG_DELIVERY_REPORT_NONE, MSG_READ_REPORT_NONE);
+                       (unsigned int)pMsg->displayTime, pMsg->dataSize, pMsg->networkStatus, pMsg->bRead, pMsg->bProtected, pMsg->priority, pMsg->direction,
+                       0, pMsg->bBackup, pMsg->sim_idx, imsi);
 
        MSG_DEBUG("QUERY : %s", sqlQuery);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       g_free(imsi);
+       imsi = NULL;
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
-       dbHandle.bindText(pMsg->subject, 1);
+       dbHandle->bindText(pMsg->subject, 1);
 
-       dbHandle.bindText(pMsg->msgData, 2);
+       if (pMsg->msgType.subType == MSG_NOTIFICATIONIND_MMS) {
+               dbHandle->bindText("", 2);
+       } else {
+               if (pMsg->bTextSms == false) {
+                       //CID 47860: pMsg->msgData is an array, hence null check is not required
+                       char fn[MSG_FILEPATH_LEN_MAX];
+                       memset(fn,0x00,MSG_FILEPATH_LEN_MAX);
+                       snprintf(fn, MSG_FILEPATH_LEN_MAX, "%s%s", MSG_IPC_DATA_PATH, pMsg->msgData);
+
+                       if (g_file_get_contents(fn, &contents, NULL, NULL)) {
+                               MSG_DEBUG("g_file_get_contents() Success!!");
+                               dbHandle->bindText(contents, 2);
+                       } else {
+                               MSG_DEBUG("g_file_get_contents() Failed!!");
+                               dbHandle->bindText("", 2);
+                       }
 
-       dbHandle.bindText(pMsg->thumbPath, 3);
+               } else
+                       dbHandle->bindText(pMsg->msgText, 2);
+       }
 
-       if (pMsg->bTextSms == false)
-               dbHandle.bindText(pFileData, 4);
-       else
-               dbHandle.bindText(pMsg->msgText, 4);
+       if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle->finalizeQuery();
+               dbHandle->endTrans(false);
+               //free contents
+               if (contents) {
+                       g_free(contents);
+                       contents = NULL;
+               }
 
-       if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
-               dbHandle.finalizeQuery();
-               dbHandle.endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
+
+       //free contents
+       if (contents) {
+               g_free(contents);
+               contents = NULL;
+       }
 
        if (pMsg->msgType.subType != MSG_SENDREQ_MMS) {
-               err = MsgStoUpdateConversation(&dbHandle, convId);
+               err = MsgStoUpdateConversation(dbHandle, convId);
 
                if (err != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+                       dbHandle->endTrans(false);
                        return err;
                }
        }
 
-       dbHandle.endTrans(true);
-
+#if 0
        /* In the case of MMS Message, load the MMS plugin to save MMS PDU */
        if (pMsg->msgType.mainType == MSG_MMS_TYPE) {
-               MMS_MESSAGE_DATA_S mmsMsg;
-               memset(&mmsMsg, 0x00, sizeof(MMS_MESSAGE_DATA_S));
-
-               if (pMsg->dataSize == 0) {
-                       MSG_DEBUG("pMsg->dataSize == 0, So Making emtpy MMS body.");
-                       char * tempMmsBody = _MsgMmsSerializeMessageData(&mmsMsg, &(pMsg->dataSize));
-                       memcpy(&pMsg->msgText, tempMmsBody, pMsg->dataSize);
-                       free(tempMmsBody);
-               }
 
                if (pMsg->msgType.subType != MSG_DELIVERYIND_MMS && pMsg->msgType.subType != MSG_READORGIND_MMS) {
+
                        MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_MMS_TYPE);
+                       if (plg == NULL) {
+                               dbHandle->endTrans(false);
+                               return MSG_ERR_NULL_POINTER;
+                       }
+
+                       if (pFileData == NULL) {
+                               if (MsgOpenAndReadFile(pMsg->msgData, &pFileData, &fileSize) == false) {
+                                       dbHandle->endTrans(false);
+                                       return MSG_ERR_STORAGE_ERROR;
+                               }
 
-                       //pMsg->msgId = pMsg->refernceId;
+                               MSG_DEBUG("file size [%d]", fileSize);
+                       }
 
                        err = plg->addMessage(pMsg, pSendOptInfo, pFileData);
 
-                       if (err != MSG_SUCCESS)
+                       if (err != MSG_SUCCESS) {
+                               dbHandle->endTrans(false);
                                return MSG_ERR_STORAGE_ERROR;
+                       }
+
+                       if (pMsg->msgType.subType == MSG_SENDREQ_MMS
+                                       || pMsg->msgType.subType == MSG_RETRIEVE_MMS
+                                       || pMsg->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS
+                                       || pMsg->msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS) {
 
-                       if (pMsg->msgType.subType == MSG_SENDREQ_MMS) {
                                MSG_DEBUG("pMsg->msgText: %s, pMsg->thumbPath: %s ", pMsg->msgText, pMsg->thumbPath);
 
                                err = MsgStoUpdateMMSMessage(pMsg);
 
-                               if (err != MSG_SUCCESS)
+                               if (err != MSG_SUCCESS) {
+                                       dbHandle->endTrans(false);
+                                       return MSG_ERR_STORAGE_ERROR;
+                               }
+
+                       }
+               }
+       } else if (pMsg->msgType.mainType == MSG_SMS_TYPE && pSendOptInfo != NULL) {
+               MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
+               if (plg == NULL) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_NULL_POINTER;
+               }
+               err = plg->addMessage(pMsg, pSendOptInfo, NULL);
+               if (err != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_STORAGE_ERROR;
+               }
+       }
+#else
+       if (pMsg->msgType.mainType == MSG_MMS_TYPE) {
+               char *pMmsSerializedData = NULL;
+               unique_ptr<char*, void(*)(char**)> buf_mms(&pMmsSerializedData, unique_ptr_deleter);
+
+               if (pMsg->msgType.subType != MSG_DELIVERYIND_MMS && pMsg->msgType.subType != MSG_READORGIND_MMS) {
+
+                       MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_MMS_TYPE);
+
+                       if (pMmsSerializedData == NULL) {
+                               if (MsgOpenAndReadFile(pMsg->msgData, &pMmsSerializedData, &fileSize) == false) {
+                                       dbHandle->endTrans(false);
                                        return MSG_ERR_STORAGE_ERROR;
+                               }
+
+                               MSG_DEBUG("file size [%d]", fileSize);
+                       }
+
+                       err = plg->addMessage(pMsg, pSendOptInfo, pMmsSerializedData);
 
+                       if (err != MSG_SUCCESS) {
+                               dbHandle->endTrans(false);
+                               return MSG_ERR_STORAGE_ERROR;
+                       }
+
+//                     if (pMsg->msgText[0] != '\0') {
+//                             g_file_get_contents(pMsg->msgText, &pFileData, (gsize *)&fileSize, NULL);
+//                             MSG_DEBUG("file size [%d]", fileSize);
+//                     }
+
+                       if (pMsg->msgType.subType == MSG_SENDREQ_MMS
+                               || pMsg->msgType.subType == MSG_RETRIEVE_MMS
+                               || pMsg->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS
+                               || pMsg->msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS)
+                       {
+                               MSG_DEBUG("pMsg->msgText: %s, pMsg->thumbPath: %s ", pMsg->msgText, pMsg->thumbPath);
+
+                               err = MsgStoUpdateMMSMessage(pMsg);
                        }
+
+               }
+       } else {
+
+               // Get File Data
+               if (pMsg->bTextSms == false) {
+                       if (MsgOpenAndReadFile(pMsg->msgData, &pFileData, &fileSize) == false) {
+                               dbHandle->endTrans(false);
+                               return MSG_ERR_STORAGE_ERROR;
+                       }
+                       MSG_DEBUG("file size [%d]", fileSize);
                }
        }
+#endif
+       dbHandle->endTrans(true);
 
        MSG_END();
 
@@ -333,14 +317,56 @@ msg_error_t MsgStoUpdateMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S
        char sqlQuery[MAX_QUERY_LEN+1];
 
        msg_thread_id_t convId = 0;
+       MsgDbHandler *dbHandle = getDbHandle();
+       dbHandle->beginTrans();
+
+       MSG_MAIN_TYPE_T prevType;
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MAIN_TYPE FROM %s WHERE MSG_ID = %d;",
+                       MSGFW_MESSAGE_TABLE_NAME, pMsg->msgId);
+
+       MSG_DEBUG("QUERY : %s", sqlQuery);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_PREPARE;
+       }
+
+       if (dbHandle->stepQuery() != MSG_ERR_DB_ROW) {
+               dbHandle->finalizeQuery();
+               dbHandle->endTrans(false);
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       prevType = dbHandle->columnInt(0);
+       dbHandle->finalizeQuery();
+
+       //check msg type with previous type
+       if (prevType != pMsg->msgType.mainType) {
+               MSG_DEBUG("different msg type to update [prev : %d], [current : %d]", prevType, pMsg->msgType.mainType);
+
+               err = MsgStoDeleteMessage(pMsg->msgId, false);
+               if (err != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return err;
+               }
+
+               err = MsgStoAddMessage(pMsg, pSendOptInfo);
+               if (err != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return err;
+               }
 
-       dbHandle.beginTrans();
+               dbHandle->endTrans(false);
+               return err;
+       }
 
        if (pMsg->nAddressCnt > 0) {
-               err = MsgStoAddAddress(&dbHandle, pMsg, &convId);
+               pMsg->threadId = 0;
+               err = MsgStoAddAddress(dbHandle, pMsg, &convId);
 
                if (err != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+                       dbHandle->endTrans(false);
                        return err;
                }
        }
@@ -348,12 +374,12 @@ msg_error_t MsgStoUpdateMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S
        int fileSize = 0;
 
        char *pFileData = NULL;
-       AutoPtr<char> buf(&pFileData);
+       unique_ptr<char*, void(*)(char**)> buf(&pFileData, unique_ptr_deleter);
 
        // Get File Data
        if (pMsg->bTextSms == false) {
                if (MsgOpenAndReadFile(pMsg->msgData, &pFileData, &fileSize) == false) {
-                       dbHandle.endTrans(false);
+                       dbHandle->endTrans(false);
                        return MSG_ERR_STORAGE_ERROR;
                }
        }
@@ -391,77 +417,95 @@ msg_error_t MsgStoUpdateMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S
 
        snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET CONV_ID = %d, FOLDER_ID = %d, STORAGE_ID = %d, MAIN_TYPE = %d, SUB_TYPE = %d, \
                        DISPLAY_TIME = %lu, DATA_SIZE = %d, NETWORK_STATUS = %d, READ_STATUS = %d, PROTECTED = %d, PRIORITY = %d, MSG_DIRECTION = %d, \
-                       BACKUP = %d, SUBJECT = ?, MSG_DATA = ?, THUMB_PATH = ?, MSG_TEXT = ? \
+                       BACKUP = %d, SUBJECT = ?, MSG_TEXT = ? \
                        WHERE MSG_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, convId, pMsg->folderId, pMsg->storageId, pMsg->msgType.mainType, pMsg->msgType.subType, pMsg->displayTime, pMsg->dataSize,
                        pMsg->networkStatus, pMsg->bRead, pMsg->bProtected, pMsg->priority, pMsg->direction, pMsg->bBackup, pMsg->msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
-       dbHandle.bindText(pMsg->subject, 1);
-
-       dbHandle.bindText(pMsg->msgData, 2);
-
-       dbHandle.bindText(pMsg->thumbPath, 3);
+       dbHandle->bindText(pMsg->subject, 1);
 
        if (pMsg->msgType.mainType == MSG_SMS_TYPE && pMsg->bTextSms == false)
-               dbHandle.bindText(pFileData, 4);
+               dbHandle->bindText(pFileData, 2);
        else
-               dbHandle.bindText(pMsg->msgText, 4);
+               dbHandle->bindText(pMsg->msgText, 2);
 
        MSG_DEBUG("%s", sqlQuery);
 
-       if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
-               dbHandle.finalizeQuery();
-               dbHandle.endTrans(false);
+       if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle->finalizeQuery();
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        if (pMsg->msgType.mainType == MSG_SMS_TYPE && pSendOptInfo != NULL) {
                if (pSendOptInfo->bSetting == true) {
                        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET \
-                                       DELREP_REQ = %d, KEEP_COPY = %d, REPLY_PATH = %d \
-                                       WHERE MSG_ID = %d;",
-                                       MSGFW_SMS_SENDOPT_TABLE_NAME, pSendOptInfo->bDeliverReq,
-                                       pSendOptInfo->bKeepCopy, pSendOptInfo->option.smsSendOptInfo.bReplyPath, pMsg->msgId);
-
-                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.endTrans(false);
+                       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET "
+                                       "DELREP_REQ = %d, "
+                                       "KEEP_COPY = %d, "
+                                       "REPLY_PATH = %d, "
+                                       "ENCODE_TYPE = %d "
+                                       "WHERE MSG_ID = %d;",
+                                       MSGFW_SMS_SENDOPT_TABLE_NAME,
+                                       pSendOptInfo->bDeliverReq,
+                                       pSendOptInfo->bKeepCopy,
+                                       pSendOptInfo->option.smsSendOptInfo.bReplyPath,
+                                       pMsg->encodeType,
+                                       pMsg->msgId);
+
+                       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->endTrans(false);
                                return MSG_ERR_DB_EXEC;
                        }
                }
        } else if (pMsg->msgType.mainType == MSG_MMS_TYPE) {
                MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_MMS_TYPE);
+               if (plg == NULL) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_NULL_POINTER;
+               }
 
                err = plg->updateMessage(pMsg, pSendOptInfo, pFileData);
 
                if (err != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+                       dbHandle->endTrans(false);
                        return MSG_ERR_STORAGE_ERROR;
                }
+
+               if (pMsg->msgType.subType == MSG_SENDREQ_MMS) {
+                       MSG_SEC_DEBUG("pMsg->msgText: %s, pMsg->thumbPath: %s ", pMsg->msgText, pMsg->thumbPath);
+
+                       err = MsgStoUpdateMMSMessage(pMsg);
+
+                       if (err != MSG_SUCCESS) {
+                               dbHandle->endTrans(false);
+                               return MSG_ERR_STORAGE_ERROR;
+                       }
+               }
        }
 
-       err = MsgStoUpdateConversation(&dbHandle, convId);
+       err = MsgStoUpdateConversation(dbHandle, convId);
 
        if (err != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+               dbHandle->endTrans(false);
                return MSG_ERR_STORAGE_ERROR;
        }
 
-       err = MsgStoClearConversationTable(&dbHandle);
+       err = MsgStoClearConversationTable(dbHandle);
 
        if (err != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+               dbHandle->endTrans(false);
                return MSG_ERR_STORAGE_ERROR;
        }
 
-       dbHandle.endTrans(true);
+       dbHandle->endTrans(true);
 
        return MSG_SUCCESS;
 }
@@ -473,30 +517,34 @@ msg_error_t MsgStoUpdateReadStatus(msg_message_id_t msgId, bool bRead)
 
        msg_storage_id_t storageId;
 
-       if (MsgStoSetReadStatus(&dbHandle, msgId, bRead) != MSG_SUCCESS) {
+       MsgDbHandler *dbHandle = getDbHandle();
+       if (MsgStoSetReadStatus(dbHandle, msgId, bRead) != MSG_SUCCESS) {
                MSG_DEBUG("MsgStoSetReadStatus() Error");
                return MSG_ERR_STORAGE_ERROR;
        }
 
+       MsgRefreshAllNotification(true, false, false);
+
        // Get STORAGE_ID
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT STORAGE_ID FROM %s WHERE MSG_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               storageId = dbHandle.columnInt(0);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               storageId = dbHandle->columnInt(0);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        MSG_DEBUG("StorageId:[%d]", storageId);
 
+#ifndef FEATURE_SMS_CDMA
        // Update Read Status for SIM Msg
        if (storageId == MSG_STORAGE_SIM) {
                MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
@@ -508,122 +556,99 @@ msg_error_t MsgStoUpdateReadStatus(msg_message_id_t msgId, bool bRead)
 
                // Get SIM Msg ID
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT SIM_ID FROM %s WHERE MSG_ID = %d;",
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT SIM_SLOT_ID, SIM_ID FROM %s WHERE MSG_ID = %d;",
                                MSGFW_SIM_MSG_TABLE_NAME, msgId);
 
-               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                        return MSG_ERR_DB_PREPARE;
 
                msg_sim_id_t simId;
+               msg_sim_slot_id_t sim_idx;
 
-               while (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-                       simId = dbHandle.columnInt(0);
+               while (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+                       sim_idx = dbHandle->columnInt(0);
+                       simId = dbHandle->columnInt(1);
 
-                       if (plg->setReadStatus(simId) != MSG_SUCCESS) {
+                       if (plg->setReadStatus(sim_idx, simId) != MSG_SUCCESS) {
                                MSG_DEBUG("Fail to Set Read Status for SIM SMS");
                                continue;
                        }
                }
-
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
        }
-
+#endif
        return MSG_SUCCESS;
 }
 
 
-msg_error_t MsgStoUpdateThreadReadStatus(msg_thread_id_t threadId)
+msg_error_t MsgStoUpdateThreadReadStatus(msg_thread_id_t threadId, msg_id_list_s *pMsgIdList)
 {
        MSG_BEGIN();
 
        msg_error_t err = MSG_SUCCESS;
 
-       int rowCnt = 0;
-       int index = 1;
-       msg_id_list_s *pUnreadMsgIdList = NULL;
-
-       pUnreadMsgIdList = (msg_id_list_s *)new char[sizeof(msg_id_list_s)];
-       memset(pUnreadMsgIdList, 0x00, sizeof(msg_id_list_s));
-
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       // Get MSG_ID List
+       /*** Get msg id list **/
+       int rowCnt = 0, index = 0;
+       pMsgIdList->nCount = 0;
+       MsgDbHandler *dbHandle = getDbHandle();
+
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s A WHERE CONV_ID = %d AND READ_STATUS = 0;",
-                       MSGFW_MESSAGE_TABLE_NAME, threadId);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s "
+                       "WHERE CONV_ID = %d AND READ_STATUS = 0 AND STORAGE_ID = %d AND FOLDER_ID < %d;",
+                       MSGFW_MESSAGE_TABLE_NAME,
+                       threadId, MSG_STORAGE_PHONE, MSG_SPAMBOX_ID);
 
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
+       err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
 
        if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
                return err;
        }
 
-       pUnreadMsgIdList->nCount = rowCnt;
+       if (rowCnt <= 0) {
+               dbHandle->freeTable();
+               return MSG_SUCCESS;
+       }
 
-       MSG_DEBUG("unreadMsgIdList.nCount [%d]", pUnreadMsgIdList->nCount);
+       pMsgIdList->nCount = rowCnt;
+       MSG_DEBUG("pMsgIdList->nCount [%d]", pMsgIdList->nCount);
 
-       pUnreadMsgIdList->msgIdList = (msg_message_id_t *)new char[sizeof(msg_message_id_t) * rowCnt];
+       pMsgIdList->msgIdList = (msg_message_id_t *)new char[sizeof(msg_message_id_t) * rowCnt];
 
        for (int i = 0; i < rowCnt; i++)
-               pUnreadMsgIdList->msgIdList[i] = dbHandle.getColumnToInt(index++);
-
-       dbHandle.freeTable();
-
-
-       // Get sim MSG_ID
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s A \
-                       WHERE CONV_ID = %d AND READ_STATUS = 0 AND STORAGE_ID = %d;",
-                       MSGFW_MESSAGE_TABLE_NAME, threadId, MSG_STORAGE_SIM);
+               pMsgIdList->msgIdList[i] = dbHandle->getColumnToInt(index++);
 
-       rowCnt = 0;
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
-
-       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
-               return err;
-       }
-
-       for (int i = 1; i <= rowCnt; i++) {
-               MsgStoUpdateReadStatus(dbHandle.getColumnToInt(i), true);
-       }
-
-       dbHandle.freeTable();
+       dbHandle->freeTable();
+       /*** **/
 
        // set read status
+       dbHandle->beginTrans();
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET READ_STATUS = %d \
-                       WHERE CONV_ID = %d AND READ_STATUS = 0;",
-                       MSGFW_MESSAGE_TABLE_NAME, 1, threadId);
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET READ_STATUS = %d "
+                       "WHERE CONV_ID = %d AND READ_STATUS = 0 AND STORAGE_ID = %d AND FOLDER_ID < %d;",
+                       MSGFW_MESSAGE_TABLE_NAME, 1,
+                       threadId, MSG_STORAGE_PHONE, MSG_SPAMBOX_ID);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
+       }
 
 
-       if (MsgStoUpdateConversation(&dbHandle, threadId) != MSG_SUCCESS) {
+       if (MsgStoUpdateConversation(dbHandle, threadId) != MSG_SUCCESS) {
                MSG_DEBUG("MsgStoUpdateConversation() Error");
+               dbHandle->endTrans(false);
                return MSG_ERR_STORAGE_ERROR;
        }
 
-       if (g_idle_add(updateUnreadMsgCount, NULL) == 0) {
-               MSG_DEBUG("updateUnreadMsgCount() Error");
+       dbHandle->endTrans(true);
+       if (g_idle_add(resetNotification, NULL) == 0) {
+               MSG_DEBUG("resetNotification() Error");
        }
 
-       if (pUnreadMsgIdList->nCount > 0) {
-               if (g_idle_add(startToDeleteNoti, (void *)pUnreadMsgIdList) == 0) {
-                       MSG_DEBUG("startToDeleteNoti not invoked: %s", strerror(errno));
-                       // memory free
-                       if (pUnreadMsgIdList != NULL) {
-                               //free peer info list
-                               if (pUnreadMsgIdList->msgIdList != NULL)
-                                       delete [] pUnreadMsgIdList->msgIdList;
-
-                               delete [] pUnreadMsgIdList;
-                       }
-                       err = MSG_ERR_UNKNOWN;
-               }
-       }
        MSG_END();
 
        return MSG_SUCCESS;
@@ -633,12 +658,13 @@ msg_error_t MsgStoUpdateThreadReadStatus(msg_thread_id_t threadId)
 msg_error_t MsgStoUpdateProtectedStatus(msg_message_id_t msgId, bool bProtected)
 {
        char sqlQuery[MAX_QUERY_LEN+1];
+       MsgDbHandler *dbHandle = getDbHandle();
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
        snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET PROTECTED = %d WHERE MSG_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, (int)bProtected, msgId);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_EXEC;
 
        return MSG_SUCCESS;
@@ -654,14 +680,37 @@ msg_error_t MsgStoDeleteMessage(msg_message_id_t msgId, bool bCheckIndication)
        msg_error_t err = MSG_SUCCESS;
 
        char sqlQuery[MAX_QUERY_LEN+1];
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       // delete report notification
+       char tempAddr[MAX_ADDRESS_VAL_LEN+1];
+       memset(tempAddr, 0x00, sizeof(tempAddr));
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT B.ADDRESS_VAL FROM %s A, %s B WHERE A.CONV_ID = B.CONV_ID AND A.MSG_ID = %d;"
+                       , MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, msgId);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle->stepQuery() != MSG_ERR_DB_ROW) {
+               dbHandle->finalizeQuery();
+               return MSG_ERR_DB_DONE;
+       }
+
+       snprintf(tempAddr, sizeof(tempAddr), "%s", dbHandle->columnText(0));
+
+       MSG_SEC_DEBUG("Updated address = %s", tempAddr);
+
+       MsgDeleteReportNotification(tempAddr);
+
+       dbHandle->finalizeQuery();
 
        // Get SUB_TYPE, STORAGE_ID
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.MAIN_TYPE, A.SUB_TYPE, A.FOLDER_ID, A.STORAGE_ID, A.READ_STATUS, B.CONV_ID \
-                       FROM %s A, %s B WHERE A.MSG_ID = %d AND A.CONV_ID = B.CONV_ID;",
-                       MSGFW_MESSAGE_TABLE_NAME, MSGFW_CONVERSATION_TABLE_NAME, msgId);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MAIN_TYPE, SUB_TYPE, FOLDER_ID, STORAGE_ID, READ_STATUS, CONV_ID, SIM_INDEX \
+                       FROM %s WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
                MSG_DEBUG("Query Failed [%s]", sqlQuery);
                return MSG_ERR_DB_PREPARE;
        }
@@ -670,80 +719,90 @@ msg_error_t MsgStoDeleteMessage(msg_message_id_t msgId, bool bCheckIndication)
        msg_folder_id_t folderId;
        msg_storage_id_t storageId;
        msg_thread_id_t convId;
+       msg_sim_slot_id_t simIndex;
        bool bRead;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               msgType.mainType = dbHandle.columnInt(0);
-               msgType.subType = dbHandle.columnInt(1);
-               folderId = dbHandle.columnInt(2);
-               storageId = dbHandle.columnInt(3);
-               bRead = dbHandle.columnInt(4);
-               convId = dbHandle.columnInt(5);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               msgType.mainType = dbHandle->columnInt(0);
+               msgType.subType = dbHandle->columnInt(1);
+               folderId = dbHandle->columnInt(2);
+               storageId = dbHandle->columnInt(3);
+               bRead = dbHandle->columnInt(4);
+               convId = dbHandle->columnInt(5);
+               simIndex = dbHandle->columnInt(6);
 
-               MSG_DEBUG("Main Type:[%d] SubType:[%d] FolderId:[%d] StorageId:[%d] ConversationId:[%d]", msgType.mainType, msgType.subType, folderId, storageId, convId);
+               MSG_DEBUG("Main Type:[%d] SubType:[%d] FolderId:[%d] StorageId:[%d] ReadStatus:[%d] ConversationId:[%d], simIndex=[%d]", msgType.mainType, msgType.subType, folderId, storageId, bRead, convId, simIndex);
        } else {
                MSG_DEBUG("MsgStepQuery() Error [%s]", sqlQuery);
 
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
 
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
 
        if (plg == NULL) {
                MSG_DEBUG("SMS Plug-in is NULL");
-
                return MSG_ERR_NULL_POINTER;
        }
 
-       dbHandle.beginTrans();
+       dbHandle->beginTrans();
 
+#ifndef FEATURE_SMS_CDMA
        // Check sim message
        if (storageId == MSG_STORAGE_SIM) {
-               // get sim message id
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT SIM_ID FROM %s WHERE MSG_ID = %d;",
-                               MSGFW_SIM_MSG_TABLE_NAME, msgId);
+               msg_sim_id_t simMsgId;
+               msg_sim_slot_id_t sim_idx;
 
-               MSG_DEBUG("sqlQuery is [%s]", sqlQuery);
+               while (true) {
+                       // get sim message id
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT SIM_SLOT_ID, SIM_ID FROM %s WHERE MSG_ID = %d;",
+                                       MSGFW_SIM_MSG_TABLE_NAME, msgId);
 
-               msg_sim_id_t simMsgId;
+                       MSG_DEBUG("sqlQuery is [%s]", sqlQuery);
 
-               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
-                       return MSG_ERR_DB_PREPARE;
-               }
+                       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->endTrans(false);
+                               return MSG_ERR_DB_PREPARE;
+                       }
+
+                       if (dbHandle->stepQuery() != MSG_ERR_DB_ROW) {
+                               break;
+                       }
 
-               while (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-                       simMsgId = dbHandle.columnInt(0);
+                       sim_idx = dbHandle->columnInt(0);
+                       simMsgId = dbHandle->columnInt(1);
 
                        MSG_DEBUG("SIM Msg Id : [%d]", simMsgId);
 
-                       err = plg->deleteSimMessage(simMsgId);
+                       err = plg->deleteSimMessage(sim_idx, simMsgId);
 
                        if (err != MSG_SUCCESS) {
-                               dbHandle.finalizeQuery();
-                               dbHandle.endTrans(false);
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(false);
                                return err;
                        }
 
+                       dbHandle->finalizeQuery();
+
                        //Sim message delete in db table
                        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE SIM_ID = %d;", MSGFW_SIM_MSG_TABLE_NAME, simMsgId);
+                       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE SIM_ID = %d AND SIM_SLOT_ID =%d;", MSGFW_SIM_MSG_TABLE_NAME, simMsgId, sim_idx);
 
-                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.finalizeQuery();
-                               dbHandle.endTrans(false);
+                       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(false);
                                return MSG_ERR_DB_EXEC;
                        }
                }
 
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
        }
-
+#endif
        /* each type has to be handled in plug in ? */
        if (msgType.mainType == MSG_SMS_TYPE) {
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -751,8 +810,18 @@ msg_error_t MsgStoDeleteMessage(msg_message_id_t msgId, bool bCheckIndication)
                                MSGFW_SMS_SENDOPT_TABLE_NAME, msgId);
 
                // Delete SMS Send Option
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;",
+                               MSGFW_SMS_REPORT_TABLE_NAME, msgId);
+
+               // Delete Data from SMS_REPORT table
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_EXEC;
                }
 
@@ -762,8 +831,8 @@ msg_error_t MsgStoDeleteMessage(msg_message_id_t msgId, bool bCheckIndication)
                                        MSGFW_CB_MSG_TABLE_NAME, msgId);
 
                        // Delete Push Message from push table
-                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.endTrans(false);
+                       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->endTrans(false);
                                return MSG_ERR_DB_EXEC;
                        }
                } else if (msgType.subType >= MSG_WAP_SI_SMS && msgType.subType <= MSG_WAP_CO_SMS) {
@@ -772,8 +841,8 @@ msg_error_t MsgStoDeleteMessage(msg_message_id_t msgId, bool bCheckIndication)
                                        MSGFW_PUSH_MSG_TABLE_NAME, msgId);
 
                        // Delete Push Message from push table
-                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.endTrans(false);
+                       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->endTrans(false);
                                return MSG_ERR_DB_EXEC;
                        }
                } else if (msgType.subType == MSG_SYNCML_CP) {
@@ -782,66 +851,129 @@ msg_error_t MsgStoDeleteMessage(msg_message_id_t msgId, bool bCheckIndication)
                                        MSGFW_SYNCML_MSG_TABLE_NAME, msgId);
 
                        // Delete SyncML Message from syncML table
-                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.endTrans(false);
+                       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->endTrans(false);
                                return MSG_ERR_DB_EXEC;
                        }
                }
        } else if (msgType.mainType == MSG_MMS_TYPE) {
 
-               char filePath[MSG_FILEPATH_LEN_MAX] = {0,};
-               char thumbnailpath[MSG_FILEPATH_LEN_MAX] = {0,};
-               char dirPath[MSG_FILEPATH_LEN_MAX]= {0,};
+               char filePath[MSG_FILEPATH_LEN_MAX + 1] = {0,};
+               char dirPath[MSG_FILEPATH_LEN_MAX + 1]= {0,};
+
+               {//remove multipart
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILE_PATH FROM %s WHERE MSG_ID = %d;",
+                                       MSGFW_MMS_MULTIPART_TABLE_NAME, msgId);
+
+                       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->endTrans(false);
+                               return MSG_ERR_DB_PREPARE;
+                       }
+
+                       while (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+                               memset(filePath, 0x00, sizeof(filePath));
+                               strncpy(filePath, (char *)dbHandle->columnText(0), MSG_FILEPATH_LEN_MAX);
+                               if (remove(filePath) == -1)
+                                       MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+                               else
+                                       MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
+                       }
+                       dbHandle->finalizeQuery();
+
+                       // Delete Data from Multipart table
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;",
+                                       MSGFW_MMS_MULTIPART_TABLE_NAME, msgId);
+
+                       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->endTrans(false);
+                               return MSG_ERR_DB_EXEC;
+                       }
+               }
+
 
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
                snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILE_PATH FROM %s WHERE MSG_ID = %d;",
                                MMS_PLUGIN_MESSAGE_TABLE_NAME, msgId);
 
-               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_PREPARE;
                }
 
-               if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-                       strncpy(filePath, (char *)dbHandle.columnText(0), MSG_FILEPATH_LEN_MAX);
+               if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+                       strncpy(filePath, (char *)dbHandle->columnText(0), MSG_FILEPATH_LEN_MAX);
 
                        snprintf(dirPath, MSG_FILEPATH_LEN_MAX, "%s.dir", filePath);
 
                        if (remove(filePath) == -1)
-                               MSG_DEBUG("Fail to delete file [%s]", filePath);
+                               MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
                        else
-                               MSG_DEBUG("Success to delete file [%s]", filePath);
+                               MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
 
                        MsgRmRf(dirPath);
 
                        rmdir(dirPath);
 
-                       // remove thumbnail file
-                       char *fileName = NULL;
-                       fileName = strrchr(filePath, '/');
-
-                       snprintf(thumbnailpath, MSG_FILEPATH_LEN_MAX, MSG_THUMBNAIL_PATH"%s.jpg", fileName+1);
-                       if(remove(thumbnailpath) == -1)
-                               MSG_DEBUG("Fail to delete thumbnail [%s]", thumbnailpath);
-                       else
-                               MSG_DEBUG("Success to delete thumbnail [%s]", thumbnailpath);
-
                } else {
                        MSG_DEBUG("MsgStepQuery() Error [%s]", sqlQuery);
-                       dbHandle.finalizeQuery();
-                       dbHandle.endTrans(false);
+                       dbHandle->finalizeQuery();
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_STEP;
                }
 
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
+
+               // remove thumbnail file
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT VALUE FROM %s "
+                               "WHERE MSG_ID = %d AND (TYPE=%d OR TYPE=%d);",
+                               MSGFW_MMS_PREVIEW_TABLE_NAME, msgId, MSG_MMS_ITEM_TYPE_IMG, MSG_MMS_ITEM_TYPE_VIDEO);
+
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_PREPARE;
+               }
+
+               while (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+                       memset(filePath, 0x00, sizeof(filePath));
+                       strncpy(filePath, (char *)dbHandle->columnText(0), MSG_FILEPATH_LEN_MAX);
+                       if (remove(filePath) == -1)
+                               MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+                       else
+                               MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
+               }
+
+               dbHandle->finalizeQuery();
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;",
+                               MSGFW_MMS_PREVIEW_TABLE_NAME, msgId);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
 
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
                snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;",
                                MMS_PLUGIN_MESSAGE_TABLE_NAME, msgId);
 
                // Delete Data from MMS table
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;",
+                               MSGFW_REPORT_TABLE_NAME, msgId);
+
+               // Delete Data from MMS STATUS table
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_EXEC;
                }
        }
@@ -850,53 +982,57 @@ msg_error_t MsgStoDeleteMessage(msg_message_id_t msgId, bool bCheckIndication)
        snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, msgId);
 
        // Delete Message from msg table
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
-       // Clear Conversation table
-       if (MsgStoClearConversationTable(&dbHandle) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+#ifdef FEATURE_SMS_CDMA
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_UNIQUENESS_INFO_TABLE_NAME, msgId);
+
+       // Delete Message from uniqueness table
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
+#endif
 
-       // Update conversation table.
-       if (MsgStoUpdateConversation(&dbHandle, convId) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return MSG_ERR_STORAGE_ERROR;
-       }
+       if (convId > 0) {
+               // Clear Conversation table
+               if (MsgStoClearConversationTable(dbHandle) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
 
-       dbHandle.endTrans(true);
+               // Update conversation table.
+               if (MsgStoUpdateConversation(dbHandle, convId) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_STORAGE_ERROR;
+               }
+       }
+       dbHandle->endTrans(true);
 
        if (msgType.mainType == MSG_SMS_TYPE && folderId == MSG_INBOX_ID) {
                msgType.classType = MSG_CLASS_NONE;
 
                // Set memory status in SIM
-               if (MsgStoCheckMsgCntFull(&dbHandle, &msgType, folderId) == MSG_SUCCESS) {
+               if (MsgStoCheckMsgCntFull(dbHandle, &msgType, folderId) == MSG_SUCCESS) {
                        MSG_DEBUG("Set Memory Status");
 
+#ifndef FEATURE_SMS_CDMA
+                       plg->setMemoryStatus(simIndex, MSG_SUCCESS);
+#else
                        plg->setMemoryStatus(MSG_SUCCESS);
+#endif
                }
        }
 
        if (bCheckIndication == true) {
                MSG_DEBUG("bCheckIndication is true.");
-
-               int smsCnt = 0;
-               int mmsCnt = 0;
-
-               smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
-               mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
-
-               MsgSettingSetIndicator(smsCnt, mmsCnt);
-
-               MsgDeleteNotiByMsgId(msgId);
+               MsgRefreshAllNotification(true, false, false);
        }
 
-       //Delete phone log
-       MsgDeletePhoneLog(msgId);
-
        return MSG_SUCCESS;
 }
 
@@ -909,12 +1045,22 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
 
        queue<msg_thread_id_t> threadList;
 
+#ifdef FEATURE_SMS_CDMA
        const char *tableList[] = {MSGFW_PUSH_MSG_TABLE_NAME, MSGFW_CB_MSG_TABLE_NAME,
-                                               MSGFW_SYNCML_MSG_TABLE_NAME, MSGFW_SMS_SENDOPT_TABLE_NAME, 
-                                               MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME};
+                                               MSGFW_SYNCML_MSG_TABLE_NAME, MSGFW_SMS_SENDOPT_TABLE_NAME,
+                                               MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_MMS_PREVIEW_TABLE_NAME,
+                                               MSGFW_REPORT_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                                               MSGFW_UNIQUENESS_INFO_TABLE_NAME};
+#else
+       const char *tableList[] = {MSGFW_PUSH_MSG_TABLE_NAME, MSGFW_CB_MSG_TABLE_NAME,
+                                               MSGFW_SYNCML_MSG_TABLE_NAME, MSGFW_SMS_SENDOPT_TABLE_NAME,
+                                               MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_MMS_PREVIEW_TABLE_NAME,
+                                               MSGFW_REPORT_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME};
+#endif
 
        int listCnt = sizeof(tableList)/sizeof(char *);
        int rowCnt = 0;
+       MsgDbHandler *dbHandle = getDbHandle();
 
        // Get conversation ID from Folder
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -922,31 +1068,33 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT(CONV_ID) FROM %s WHERE FOLDER_ID = %d",
                        MSGFW_MESSAGE_TABLE_NAME, folderId);
 
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
+       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
        if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-               MSG_DEBUG("sql query is %s.", sqlQuery);
-
-               dbHandle.freeTable();
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
                return err;
        }
 
        if (rowCnt <= 0) {
-               dbHandle.freeTable();
-
+               dbHandle->freeTable();
                return MSG_SUCCESS;
        }
 
        for (int i = 1; i <= rowCnt; i++) {
-               MSG_DEBUG("thread ID : %d", dbHandle.getColumnToInt(i));
-               threadList.push((msg_thread_id_t)dbHandle.getColumnToInt(i));
+               MSG_DEBUG("thread ID : %d", dbHandle->getColumnToInt(i));
+               threadList.push((msg_thread_id_t)dbHandle->getColumnToInt(i));
        }
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        /*** Get msg id list **/
        msg_id_list_s *pToDeleteMsgIdList = NULL;
        pToDeleteMsgIdList = (msg_id_list_s *)new char[sizeof(msg_id_list_s)];
+       if (pToDeleteMsgIdList == NULL) {
+               MSG_DEBUG("pToDeleteMsgIdList is NULL.");
+               return MSG_ERR_NULL_POINTER;
+       }
        memset(pToDeleteMsgIdList, 0x00, sizeof(msg_id_list_s));
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -954,20 +1102,18 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
                        MSGFW_MESSAGE_TABLE_NAME, folderId);
 
        rowCnt = 0;
-       int index = 1;
+       int index = 0;
 
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
+       err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
 
        if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
-
-               dbHandle.freeTable();
-
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
                goto FREE_MEMORY;
        }
 
        if (rowCnt <= 0) {
-               dbHandle.freeTable();
+               dbHandle->freeTable();
                err = MSG_SUCCESS;
 
                goto FREE_MEMORY;
@@ -980,9 +1126,9 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
        pToDeleteMsgIdList->msgIdList = (msg_message_id_t *)new char[sizeof(msg_message_id_t) * rowCnt];
 
        for (int i = 0; i < rowCnt; i++)
-               pToDeleteMsgIdList->msgIdList[i] = dbHandle.getColumnToInt(index++);
+               pToDeleteMsgIdList->msgIdList[i] = dbHandle->getColumnToInt(index++);
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
        /*** **/
 
        /*** Delete Sim Message In Folder **/
@@ -992,37 +1138,33 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
                snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE FOLDER_ID = %d AND STORAGE_ID = %d",
                                MSGFW_MESSAGE_TABLE_NAME, folderId, MSG_STORAGE_SIM);
 
-               MSG_DEBUG("sql query is %s.", sqlQuery);
-
                rowCnt = 0;
 
-               err = dbHandle.getTable(sqlQuery, &rowCnt);
-
+               err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
                if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-                       dbHandle.freeTable();
-
+                       dbHandle->freeTable();
                        goto FREE_MEMORY;
                }
 
                for (int i = 1; i <= rowCnt; i++) {
-                       err = MsgStoDeleteMessage(dbHandle.getColumnToInt(i), false);
+                       err = MsgStoDeleteMessage(dbHandle->getColumnToInt(i), false);
 
                        if (err != MSG_SUCCESS) {
                                MSG_DEBUG("MsgStoDeleteMessage() Error!!!");
 
-                               dbHandle.freeTable();
+                               dbHandle->freeTable();
 
                                goto FREE_MEMORY;
                        }
 
                        //Delete phone log
-                       MsgDeletePhoneLog(dbHandle.getColumnToInt(i));
+//                     MsgDeletePhoneLog(dbHandle->getColumnToInt(i));
                }
 
-               dbHandle.freeTable();
+               dbHandle->freeTable();
        }
 
-       dbHandle.beginTrans();
+       dbHandle->beginTrans();
 
        for (int i = 0; i < listCnt; i++) {
                if (!strcmp(tableList[i], MMS_PLUGIN_MESSAGE_TABLE_NAME)) {
@@ -1031,7 +1173,38 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
 
                        char filePath[MSG_FILEPATH_LEN_MAX] = {0,};
                        char dirPath[MSG_FILEPATH_LEN_MAX] = {0,};
-                       char thumbnailPath[MSG_FILEPATH_LEN_MAX] = {0,};
+
+                       {//remove multipart
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILE_PATH FROM %s;",
+                                               MSGFW_MMS_MULTIPART_TABLE_NAME);
+
+                               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                                       dbHandle->endTrans(false);
+                                       return MSG_ERR_DB_PREPARE;
+                               }
+
+                               while (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+                                       memset(filePath, 0x00, sizeof(filePath));
+                                       strncpy(filePath, (char *)dbHandle->columnText(0), MSG_FILEPATH_LEN_MAX);
+                                       if (remove(filePath) == -1)
+                                               MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+                                       else
+                                               MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
+                               }
+                               dbHandle->finalizeQuery();
+
+                               // Delete Data from Multipart table
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s;",
+                                               MSGFW_MMS_MULTIPART_TABLE_NAME);
+
+                               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                                       err = MSG_ERR_DB_EXEC;
+                                       dbHandle->endTrans(false);
+                                       goto FREE_MEMORY;
+                               }
+                       }
 
                        //get mms msg id list
                        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -1039,16 +1212,14 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
                                        WHERE A.FOLDER_ID = %d AND A.MAIN_TYPE = %d AND A.MSG_ID = B.MSG_ID",
                                        MSGFW_MESSAGE_TABLE_NAME, MMS_PLUGIN_MESSAGE_TABLE_NAME, folderId, MSG_MMS_TYPE);
 
-                       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
-
-                       err = dbHandle.getTable(sqlQuery, &rowCnt);
+                       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
                        MSG_DEBUG("rowCnt %d", rowCnt);
 
                        if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-                               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+                               MSG_DEBUG("Fail to getTable().");
 
-                               dbHandle.freeTable();
-                               dbHandle.endTrans(false);
+                               dbHandle->freeTable();
+                               dbHandle->endTrans(false);
 
                                goto FREE_MEMORY;
                        }
@@ -1056,38 +1227,52 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
                        for (int i = 1; i <= rowCnt; i++) {
 
                                memset(filePath, 0x00, sizeof(filePath));
-                               dbHandle.getColumnToString(i, MSG_FILEPATH_LEN_MAX, filePath);
+                               dbHandle->getColumnToString(i, MSG_FILEPATH_LEN_MAX, filePath);
 
-                               MSG_DEBUG("filePath [%s]", filePath);
+                               MSG_SEC_DEBUG("filePath [%s]", filePath);
 
                                //delete raw file
                                snprintf(dirPath, sizeof(dirPath), "%s.dir", filePath);
 
                                if (remove(filePath) == -1)
-                                       MSG_DEBUG("Fail to delete file [%s]", filePath);
+                                       MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
                                else
-                                       MSG_DEBUG("Success to delete file [%s]", filePath);
+                                       MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
 
                                MsgRmRf(dirPath);
 
                                rmdir(dirPath);
-                               // delete thumbnail
 
-                               char *fileName = NULL;
-                               fileName = strrchr(filePath, '/');
+                       }
 
-                               snprintf(thumbnailPath, sizeof(thumbnailPath), MSG_THUMBNAIL_PATH"%s.jpg", fileName+1);
+                       dbHandle->freeTable();
+               }
 
-                               if (remove(thumbnailPath) == -1)
-                                       MSG_DEBUG("Fail to delete thumbnail [%s]", thumbnailPath);
-                               else
-                                       MSG_DEBUG("Success to delete thumbnail [%s]", thumbnailPath);
+               // delete thumbnail
+               char filePath[MSG_FILEPATH_LEN_MAX] = {0,};
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT VALUE FROM %s "
+                               "WHERE (TYPE=%d OR TYPE=%d) "
+                               "AND (MSG_ID IN (SELECT MSG_ID FROM %s WHERE FOLDER_ID = %d));",
+                               MSGFW_MMS_PREVIEW_TABLE_NAME, MSG_MMS_ITEM_TYPE_IMG, MSG_MMS_ITEM_TYPE_VIDEO, MSGFW_MESSAGE_TABLE_NAME, folderId);
 
-                       }
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_PREPARE;
+               }
 
-                       dbHandle.freeTable();
+               while (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+                       memset(filePath, 0x00, sizeof(filePath));
+                       strncpy(filePath, (char *)dbHandle->columnText(0), MSG_FILEPATH_LEN_MAX);
+                       if (remove(filePath) == -1)
+                               MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+                       else
+                               MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
                }
 
+               dbHandle->finalizeQuery();
+
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
                snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID IN \
@@ -1095,9 +1280,9 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
                                tableList[i], MSGFW_MESSAGE_TABLE_NAME, folderId);
 
                // Delete Message in specific folder from table
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
                        MSG_DEBUG("sqlQuery [%s]", sqlQuery);
-                       dbHandle.endTrans(false);
+                       dbHandle->endTrans(false);
                        err = MSG_ERR_DB_EXEC;
 
                        goto FREE_MEMORY;
@@ -1105,8 +1290,8 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
        }
 
        // Clear Conversation table
-       if (MsgStoClearConversationTable(&dbHandle) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (MsgStoClearConversationTable(dbHandle) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                err = MSG_ERR_DB_EXEC;
 
                goto FREE_MEMORY;
@@ -1114,28 +1299,18 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
 
        // Update Address
        while (!threadList.empty()) {
-               err = MsgStoUpdateConversation(&dbHandle, threadList.front());
+               err = MsgStoUpdateConversation(dbHandle, threadList.front());
 
                threadList.pop();
 
                if (err != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+                       dbHandle->endTrans(false);
 
                        goto FREE_MEMORY;
                }
        }
 
-       dbHandle.endTrans(true);
-
-       if (folderId == MSG_INBOX_ID) {
-               int smsCnt = 0;
-               int mmsCnt = 0;
-
-               smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
-               mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
-
-               MsgSettingSetIndicator(smsCnt, mmsCnt);
-       }
+       dbHandle->endTrans(true);
 
 /*** Set pMsgIdList **/
        if (pMsgIdList != NULL && pToDeleteMsgIdList->nCount > 0) {
@@ -1149,18 +1324,8 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
 /*** Create thread  for noti and phone log delete. **/
        if (!bOnlyDB) {
                if (pToDeleteMsgIdList->nCount > 0) {
-
-                       msg_id_list_s *pToDeleteMsgIdListCpy = NULL;
-                       pToDeleteMsgIdListCpy = (msg_id_list_s *)new char[sizeof(msg_id_list_s)];
-                       memset(pToDeleteMsgIdListCpy, 0x00, sizeof(msg_id_list_s));
-
-                       pToDeleteMsgIdListCpy->nCount = pToDeleteMsgIdList->nCount;
-
-                       pToDeleteMsgIdListCpy->msgIdList = (msg_message_id_t *)new char[sizeof(msg_message_id_t)*pToDeleteMsgIdList->nCount];
-                       memcpy(pToDeleteMsgIdListCpy->msgIdList, pToDeleteMsgIdList->msgIdList, sizeof(msg_message_id_t)*pToDeleteMsgIdList->nCount);
-
-                       if (g_idle_add(startToDeleteNoti, (void *)pToDeleteMsgIdList) == 0) {
-                               MSG_DEBUG("startToDeleteNoti not invoked: %s", strerror(errno));
+//                     if (g_idle_add(startToDeletePhoneLog, (void *)pToDeleteMsgIdList) == 0) {
+//                             MSG_DEBUG("startToDeletePhoneLog not invoked: %s", strerror(errno));
                                // memory free
                                if (pToDeleteMsgIdList != NULL) {
                                        //free peer info list
@@ -1169,21 +1334,10 @@ msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyD
 
                                        delete [] pToDeleteMsgIdList;
                                }
-                               err = MSG_ERR_UNKNOWN;
-                       }
-
-                       if (g_idle_add(startToDeletePhoneLog, (void *)pToDeleteMsgIdListCpy) == 0) {
-                               MSG_DEBUG("startToDeletePhoneLog not invoked: %s", strerror(errno));
-                               // memory free
-                               if (pToDeleteMsgIdListCpy != NULL) {
-                                       //free peer info list
-                                       if (pToDeleteMsgIdListCpy->msgIdList != NULL)
-                                               delete [] pToDeleteMsgIdListCpy->msgIdList;
+//                             err = MSG_ERR_UNKNOWN;
+//                     }
 
-                                       delete [] pToDeleteMsgIdListCpy;
-                               }
-                               err = MSG_ERR_UNKNOWN;
-                       }
+                       MsgRefreshAllNotification(true, false, false);
                }
        }
 /*** **/
@@ -1212,242 +1366,584 @@ FREE_MEMORY:
 }
 
 
-msg_error_t MsgStoMoveMessageToFolder(msg_message_id_t msgId, msg_folder_id_t destFolderId)
+msg_error_t MsgStoDeleteMessageByList(msg_id_list_s *pMsgIdList)
 {
-       MSG_MESSAGE_TYPE_S msgType;
-       msg_thread_id_t convId;
+       std::string q;
 
-       MsgStoGetMsgType(msgId, &msgType);
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+       if (pMsgIdList->nCount < 1) {
+               MSG_DEBUG("pMsgIdList->nCount < 1");
+               return err;
+       }
 
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       queue<msg_thread_id_t> threadList1, threadList2;
+
+#ifdef FEATURE_SMS_CDMA
+       const char *tableList[] = {MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_MMS_PREVIEW_TABLE_NAME,
+                                               MSGFW_PUSH_MSG_TABLE_NAME, MSGFW_CB_MSG_TABLE_NAME,
+                                               MSGFW_SYNCML_MSG_TABLE_NAME, MSGFW_SMS_SENDOPT_TABLE_NAME,
+                                               MSGFW_REPORT_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                                               MSGFW_SMS_REPORT_TABLE_NAME, MSGFW_MMS_MULTIPART_TABLE_NAME,
+                                               MSGFW_UNIQUENESS_INFO_TABLE_NAME};
+#else
+       const char *tableList[] = {MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_MMS_PREVIEW_TABLE_NAME,
+                                               MSGFW_PUSH_MSG_TABLE_NAME, MSGFW_CB_MSG_TABLE_NAME,
+                                               MSGFW_SYNCML_MSG_TABLE_NAME, MSGFW_SMS_SENDOPT_TABLE_NAME,
+                                               MSGFW_REPORT_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                                               MSGFW_SMS_REPORT_TABLE_NAME, MSGFW_MMS_MULTIPART_TABLE_NAME};
+#endif
 
-       if (msgType.mainType == MSG_SMS_TYPE)
-               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET FOLDER_ID = %d WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, destFolderId, msgId);
-       else
-               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET FOLDER_ID = %d WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, destFolderId, msgId);
+       int listCnt = sizeof(tableList)/sizeof(char *);
+       int rowCnt = 0;
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       dbHandle->beginTrans();
+       // reset msgid temp table
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s;", MSGFW_TMP_MSGID_TABLE_NAME);
+       MSG_DEBUG("[%s]", sqlQuery);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
+       }
 
-       /* get conversation id */
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle->finalizeQuery();
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CONV_ID FROM %s WHERE MSG_ID = %d;",
-                                                       MSGFW_MESSAGE_TABLE_NAME, msgId);
+       dbHandle->finalizeQuery();
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (?)", MSGFW_TMP_MSGID_TABLE_NAME);
+       MSG_DEBUG("[%s]", sqlQuery);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_PREPARE;
+       }
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW)
-               convId = dbHandle.columnInt(0);
+       for (int i = 0; i < pMsgIdList->nCount; i++) {
+               dbHandle->resetQuery();
+               dbHandle->bindInt(pMsgIdList->msgIdList[i], 1);
+               if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                       dbHandle->finalizeQuery();
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
+       }
 
-       MSG_DEBUG("convId : %d",  convId);
+       dbHandle->finalizeQuery();
+       dbHandle->endTrans(true);
 
-       dbHandle.finalizeQuery();
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT(CONV_ID) FROM %s WHERE MSG_ID IN %s;", MSGFW_MESSAGE_TABLE_NAME, MSGFW_TMP_MSGID_TABLE_NAME);
 
-       /* update conversation table */
-       MsgStoUpdateConversation(&dbHandle, convId);
+       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
-       return MSG_SUCCESS;
-}
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
+               return err;
+       }
 
+       MSG_DEBUG("rowCnt [%d]", rowCnt);
 
-msg_error_t MsgStoMoveMessageToStorage(msg_message_id_t msgId, msg_storage_id_t destStorageId)
-{
-       MSG_BEGIN();
+       if (rowCnt < 1) {
+               dbHandle->freeTable();
+               return MSG_SUCCESS;
+       }
 
-       msg_error_t err = MSG_SUCCESS;
+       for (int i = 1; i <= rowCnt; i++) {
+               MSG_DEBUG("thread ID : %d", dbHandle->getColumnToInt(i));
+               threadList1.push((msg_thread_id_t)dbHandle->getColumnToInt(i));
+               threadList2.push((msg_thread_id_t)dbHandle->getColumnToInt(i));
+       }
+       dbHandle->freeTable();
 
-       char sqlQuery[MAX_QUERY_LEN+1];
+       // delete report notification
+       char tempAddr[MAX_ADDRESS_VAL_LEN+1];
+       while (!threadList1.empty()) {
+               memset(tempAddr, 0x00, sizeof(tempAddr));
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT B.ADDRESS_VAL FROM %s A, %s B WHERE A.CONV_ID = B.CONV_ID AND A.CONV_ID = %d;"
+                               , MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, threadList1.front());
 
-       MSG_DEBUG("msgId : %d, destStorageId : %d", msgId, destStorageId);
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_PREPARE;
 
-       switch (destStorageId) {
-       case MSG_STORAGE_SIM : // Move message to sim card
-               {
-                       MSG_MESSAGE_INFO_S msgInfo;
-                       SMS_SIM_ID_LIST_S simIdList;
+               if (dbHandle->stepQuery() != MSG_ERR_DB_ROW) {
+                       dbHandle->finalizeQuery();
+                       return MSG_ERR_DB_DONE;
+               }
 
-                       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
-                       memset(&simIdList, 0x00, sizeof(SMS_SIM_ID_LIST_S));
+               snprintf(tempAddr, sizeof(tempAddr), "%s", dbHandle->columnText(0));
 
-                       if ((err = MsgStoGetMessage(msgId, &msgInfo, NULL)) != MSG_SUCCESS)
-                               return err;
+               MSG_SEC_DEBUG("Updated address = %s", tempAddr);
 
-                       MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
+               MsgDeleteReportNotification(tempAddr);
 
-                       if ((err = plg->saveSimMessage(&msgInfo, &simIdList)) != MSG_SUCCESS)
-                               return err;
+               dbHandle->finalizeQuery();
 
-                       dbHandle.beginTrans();
+               threadList1.pop();
+       }
 
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET STORAGE_ID = %d WHERE MSG_ID = %d;",
-                                       MSGFW_MESSAGE_TABLE_NAME, destStorageId, msgId);
 
-                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.endTrans(false);
-                               return MSG_ERR_DB_EXEC;
-                       }
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE STORAGE_ID = %d AND MSG_ID IN %s;",
+                       MSGFW_MESSAGE_TABLE_NAME, MSG_STORAGE_SIM, MSGFW_TMP_MSGID_TABLE_NAME);
 
-                       for (unsigned int i = 0; i < simIdList.count; i++) {
-                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d);",
-                                               MSGFW_SIM_MSG_TABLE_NAME, msgId, simIdList.simId[i]);
+       rowCnt = 0;
+       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
-                               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                                       dbHandle.endTrans(false);
-                                       return MSG_ERR_DB_EXEC;
-                               }
-                       }
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
+               rowCnt = 0;
+       }
 
-                       dbHandle.endTrans(true);
+       for (int i = 1; i <= rowCnt; i++) {
+               err = MsgStoDeleteMessage(dbHandle->getColumnToInt(i), false);
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgStoDeleteMessage() Error!!!");
                }
-       break;
+       }
+       dbHandle->freeTable();
+       /*** **/
 
-       default: //Moving message to memory (when destination storage id is MSG_STORAGE_PHONE)
-               {
-                       bool bSimMsg = false;
-                       int rowCnt = 0;
+       dbHandle->beginTrans();
+       for (int i = 0; i < listCnt; i++) {
+               if ( !i ) {
+
+                       char filePath[MSG_FILEPATH_LEN_MAX];
+                       char dirPath[MSG_FILEPATH_LEN_MAX];
+
+                       rowCnt = 0;
 
                        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT STORAGE_ID FROM %s WHERE MSG_ID = %d;",
-                                       MSGFW_MESSAGE_TABLE_NAME, msgId);
+                       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILE_PATH FROM %s WHERE MSG_ID IN %s;", MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_TMP_MSGID_TABLE_NAME);
 
-                       err = dbHandle.getTable(sqlQuery, &rowCnt);
+                       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
-                       if (err != MSG_SUCCESS) {
-                               dbHandle.freeTable();
-                               return err;
+                       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+                               MSG_DEBUG("Fail to getTable().");
+                               rowCnt = 0;
                        }
 
-                       if (dbHandle.getColumnToInt(1) == MSG_STORAGE_SIM) {
-                               MSG_DEBUG("It is SIM Message");
-                               bSimMsg = true;
+                       MSG_DEBUG("rowCnt %d", rowCnt);
+
+                       for (int i = 1; i <= rowCnt; i++) {
+                               dbHandle->getColumnToString(i, MSG_FILEPATH_LEN_MAX, filePath);
+
+                               MSG_SEC_DEBUG("filePath [%s]", filePath);
+
+                               // Delete raw file.
+                               snprintf(dirPath, sizeof(dirPath), "%s.dir", filePath);
+
+                               if (remove(filePath) == -1)
+                                       MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+                               else
+                                       MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
+
+                               MsgRmRf(dirPath);
+
+                               rmdir(dirPath);
                        }
+                       dbHandle->freeTable();
 
-                       dbHandle.freeTable();
+               } else if (i == 1) {
 
-                       if (bSimMsg == true) {
-                               msg_sim_id_t simMsgId;
+                       char filePath[MSG_FILEPATH_LEN_MAX] = {0,};
 
-                               // get sim message id
-                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       rowCnt = 0;
 
-                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT SIM_ID FROM %s WHERE MSG_ID = %d;",
-                                               MSGFW_SIM_MSG_TABLE_NAME, msgId);
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT VALUE FROM %s WHERE (TYPE = %d OR TYPE = %d) AND MSG_ID IN %s;",
+                                       MSGFW_MMS_PREVIEW_TABLE_NAME, MSG_MMS_ITEM_TYPE_IMG, MSG_MMS_ITEM_TYPE_VIDEO, MSGFW_TMP_MSGID_TABLE_NAME);
 
-                               MSG_DEBUG("sqlQuery is %s.", sqlQuery);
+                       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
-                               err = dbHandle.getTable(sqlQuery, &rowCnt);
+                       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+                               MSG_DEBUG("Fail to getTable().");
+                               rowCnt = 0;
+                       }
 
-                               if (err != MSG_SUCCESS) {
-                                       dbHandle.freeTable();
-                                       return err;
-                               }
+                       MSG_DEBUG("rowCnt %d", rowCnt);
 
-                               //Delete messages in sim card
-                               MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
+                       for (int i = 1; i <= rowCnt; i++) {
+                               memset(filePath, 0x00, sizeof(filePath));
+                               dbHandle->getColumnToString(i, MSG_FILEPATH_LEN_MAX, filePath);
+                               if (remove(filePath) == -1)
+                                       MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+                               else
+                                       MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
+                       }
+                       dbHandle->freeTable();
+               } else if (!strcmp(tableList[i], MSGFW_MMS_MULTIPART_TABLE_NAME)) {
+                               // MMS file path to delete.
+                               char filePath[MSG_FILEPATH_LEN_MAX] = {0,};
 
-                               for (int i = 0; i < rowCnt; i++) {
-                                       simMsgId = dbHandle.getColumnToInt(i+1);
+                               rowCnt = 0;
 
-                                       MSG_DEBUG("simMsgId is %d.", simMsgId);
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILE_PATH FROM %s WHERE MSG_ID IN %s;", MSGFW_MMS_MULTIPART_TABLE_NAME, MSGFW_TMP_MSGID_TABLE_NAME);
 
-                                       if ((err = plg->deleteSimMessage(simMsgId)) != MSG_SUCCESS) {
-                                               dbHandle.freeTable();
-                                               return err;
-                                       }
+                               err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+                               if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+                                       MSG_DEBUG("Fail to getTable().");
+                                       rowCnt = 0;
                                }
 
-                               dbHandle.freeTable();
+                               MSG_DEBUG("rowCnt %d", rowCnt);
 
-                               dbHandle.beginTrans();
+                               for (int i = 1; i <= rowCnt; i++) {
+                                       memset(filePath, 0x00, sizeof(filePath));
+                                       dbHandle->getColumnToString(i, MSG_FILEPATH_LEN_MAX, filePath);
+                                       if (filePath[0] != '\0') {
+                                               if (remove(filePath) == -1)
+                                                       MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+                                               else
+                                                       MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
+                                       }
+                               }
+                               dbHandle->freeTable();
 
-                               //Delete Messages in SIM Msg table
+                               // MMS thumbnail path to delete
                                memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;",
-                                               MSGFW_SIM_MSG_TABLE_NAME, msgId);
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT THUMB_FILE_PATH FROM %s WHERE MSG_ID IN %s;", MSGFW_MMS_MULTIPART_TABLE_NAME, MSGFW_TMP_MSGID_TABLE_NAME);
 
-                               MSG_DEBUG("sqlQuery is %s.", sqlQuery);
+                               err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
-                               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                                       dbHandle.endTrans(false);
-                                       return MSG_ERR_DB_EXEC;
+                               if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+                                       MSG_DEBUG("Fail to getTable().");
+                                       rowCnt = 0;
                                }
 
-                               //Move storage id
-                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET STORAGE_ID = %d WHERE MSG_ID = %d;",
-                                               MSGFW_MESSAGE_TABLE_NAME, destStorageId, msgId);
+                               MSG_DEBUG("rowCnt %d", rowCnt);
 
-                               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                                       dbHandle.endTrans(false);
-                                       return MSG_ERR_DB_EXEC;
+                               for (int i = 1; i <= rowCnt; i++) {
+                                       memset(filePath, 0x00, sizeof(filePath));
+                                       dbHandle->getColumnToString(i, MSG_FILEPATH_LEN_MAX, filePath);
+                                       if (filePath[0] != '\0') {
+                                               if (remove(filePath) == -1)
+                                                       MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+                                               else
+                                                       MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
+                                       }
                                }
 
-                               dbHandle.endTrans(true);
-                       }
+                               dbHandle->freeTable();
                }
-       }
 
-       return MSG_SUCCESS;
-}
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID IN %s;", tableList[i], MSGFW_TMP_MSGID_TABLE_NAME);
 
+               // Delete Message in specific folder from table
+               err = dbHandle->execQuery(sqlQuery);
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("Fail to execQuery().");
+               }
+       }
 
-msg_error_t MsgStoCountMessage(msg_folder_id_t folderId, MSG_COUNT_INFO_S *pCountInfo)
-{
-       if (pCountInfo == NULL) {
+       // Clear Conversation table
+       err = MsgStoClearConversationTable(dbHandle);
+       if (err != MSG_SUCCESS) MSG_DEBUG("Fail to MsgStoClearConversationTable().");
+
+       // Update Address
+       while (!threadList2.empty()) {
+               err = MsgStoUpdateConversation(dbHandle, threadList2.front());
+               if (err != MSG_SUCCESS) MSG_DEBUG("Fail to MsgStoUpdateConversation().");
+               threadList2.pop();
+       }
+       err = dbHandle->endTrans(true);
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to endTrans(true).");
+               dbHandle->endTrans(false);
+               return err;
+       }
+
+       if (g_idle_add(resetNotification, NULL) == 0) {
+               MSG_DEBUG("resetNotification() Error");
+       }
+
+       MSG_END();
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoMoveMessageToFolder(msg_message_id_t msgId, msg_folder_id_t destFolderId)
+{
+       msg_error_t err = MSG_SUCCESS;
+       MSG_MESSAGE_TYPE_S msgType;
+       msg_thread_id_t convId = 0;
+
+       MsgStoGetMsgType(msgId, &msgType);
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       if (msgType.mainType == MSG_SMS_TYPE)
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET FOLDER_ID = %d WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, destFolderId, msgId);
+       else
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET FOLDER_ID = %d WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, destFolderId, msgId);
+
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+       /* get conversation id */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CONV_ID FROM %s WHERE MSG_ID = %d;",
+                                                       MSGFW_MESSAGE_TABLE_NAME, msgId);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW)
+               convId = dbHandle->columnInt(0);
+
+       MSG_DEBUG("convId : %d",  convId);
+
+       dbHandle->finalizeQuery();
+
+       /* update conversation table */
+       err = MsgStoUpdateConversation(dbHandle, convId);
+
+       /* update notification */
+       MsgRefreshAllNotification(true, false, false);
+
+       return err;
+}
+
+
+msg_error_t MsgStoMoveMessageToStorage(msg_message_id_t msgId, msg_storage_id_t destStorageId)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       MSG_DEBUG("msgId : %d, destStorageId : %d", msgId, destStorageId);
+
+       switch (destStorageId) {
+       case MSG_STORAGE_SIM : // Move message to sim card
+       case MSG_STORAGE_SIM2 :
+               {
+                       MSG_MESSAGE_INFO_S msgInfo;
+                       SMS_SIM_ID_LIST_S simIdList;
+
+                       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+                       memset(&simIdList, 0x00, sizeof(SMS_SIM_ID_LIST_S));
+
+                       if ((err = MsgStoGetMessage(msgId, &msgInfo, NULL)) != MSG_SUCCESS)
+                               return err;
+
+                       MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
+                       if (plg == NULL) {
+                               MSG_DEBUG("SMS Plug-in is NULL");
+                               return MSG_ERR_NULL_POINTER;
+                       }
+
+                       if (destStorageId == MSG_STORAGE_SIM)
+                               msgInfo.sim_idx = 1;
+                       else if (destStorageId == MSG_STORAGE_SIM2)
+                               msgInfo.sim_idx = 2;
+
+                       if ((err = plg->saveSimMessage(&msgInfo, &simIdList)) != MSG_SUCCESS)
+                               return err;
+
+                       dbHandle->beginTrans();
+
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET STORAGE_ID = %d, SIM_INDEX = %d WHERE MSG_ID = %d;",
+                                       MSGFW_MESSAGE_TABLE_NAME, MSG_STORAGE_SIM, msgInfo.sim_idx, msgId);
+                       MSG_DEBUG("SQL query=[%s]", sqlQuery);
+
+                       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->endTrans(false);
+                               return MSG_ERR_DB_EXEC;
+                       }
+
+                       for (unsigned int i = 0; i < simIdList.count; i++) {
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d);",
+                                               MSGFW_SIM_MSG_TABLE_NAME, msgInfo.sim_idx, simIdList.simId[i], msgId);
+                               MSG_DEBUG("SQL query=[%s]", sqlQuery);
+
+                               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                                       dbHandle->endTrans(false);
+                                       return MSG_ERR_DB_EXEC;
+                               }
+                       }
+
+                       dbHandle->endTrans(true);
+               }
+       break;
+
+       default: //Moving message to memory (when destination storage id is MSG_STORAGE_PHONE)
+               {
+                       bool bSimMsg = false;
+                       int rowCnt = 0;
+
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT STORAGE_ID FROM %s WHERE MSG_ID = %d;",
+                                       MSGFW_MESSAGE_TABLE_NAME, msgId);
+
+                       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+                       if (err != MSG_SUCCESS) {
+                               MSG_DEBUG("Fail to getTable().");
+                               dbHandle->freeTable();
+                               return err;
+                       }
+
+                       if (dbHandle->getColumnToInt(1) == MSG_STORAGE_SIM) {
+                               MSG_DEBUG("It is SIM Message");
+                               bSimMsg = true;
+                       }
+
+                       dbHandle->freeTable();
+
+#ifndef FEATURE_SMS_CDMA
+                       if (bSimMsg == true) {
+                               msg_sim_id_t simMsgId;
+                               msg_sim_slot_id_t sim_idx;
+
+                               // get sim message id
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+                               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT SIM_SLOT_ID, SIM_ID FROM %s WHERE MSG_ID = %d;",
+                                               MSGFW_SIM_MSG_TABLE_NAME, msgId);
+
+                               int index = 0;
+
+                               err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+                               if (err != MSG_SUCCESS) {
+                                       MSG_DEBUG("Fail to getTable().");
+                                       dbHandle->freeTable();
+                                       return err;
+                               }
+
+                               //Delete messages in sim card
+                               MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
+                               if (plg == NULL) {
+                                       MSG_DEBUG("SMS Plug-in is NULL");
+                                       dbHandle->freeTable();
+                                       return MSG_ERR_NULL_POINTER;
+                               }
+
+                               for (int i = 0; i < rowCnt; i++) {
+                                       sim_idx =  dbHandle->getColumnToInt(index++);
+                                       simMsgId = dbHandle->getColumnToInt(index++);
+
+                                       MSG_DEBUG("simMsgId is %d.", simMsgId);
+
+                                       if ((err = plg->deleteSimMessage(sim_idx, simMsgId)) != MSG_SUCCESS) {
+                                               dbHandle->freeTable();
+                                               return err;
+                                       }
+                               }
+
+                               dbHandle->freeTable();
+
+                               dbHandle->beginTrans();
+
+                               //Delete Messages in SIM Msg table
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;",
+                                               MSGFW_SIM_MSG_TABLE_NAME, msgId);
+                               MSG_DEBUG("SQL query=[%s]", sqlQuery);
+
+                               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                                       dbHandle->endTrans(false);
+                                       return MSG_ERR_DB_EXEC;
+                               }
+
+                               //Move storage id
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET STORAGE_ID = %d WHERE MSG_ID = %d;",
+                                               MSGFW_MESSAGE_TABLE_NAME, destStorageId, msgId);
+                               MSG_DEBUG("SQL query=[%s]", sqlQuery);
+
+                               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                                       dbHandle->endTrans(false);
+                                       return MSG_ERR_DB_EXEC;
+                               }
+
+                               dbHandle->endTrans(true);
+                       }
+#endif
+               }
+               break;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoCountMessage(msg_folder_id_t folderId, MSG_COUNT_INFO_S *pCountInfo)
+{
+       if (pCountInfo == NULL) {
                MSG_DEBUG("pCountInfo is NULL");
                return MSG_ERR_NULL_POINTER;
        }
 
        char sqlQuery[MAX_QUERY_LEN+1];
+       MsgDbHandler *dbHandle = getDbHandle();
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE FOLDER_ID = %d AND READ_STATUS = 1 \
-                       UNION ALL SELECT COUNT(MSG_ID) FROM %s WHERE FOLDER_ID = %d AND READ_STATUS = 0 \
-                       UNION ALL SELECT COUNT(MSG_ID) FROM %s WHERE FOLDER_ID = %d AND MAIN_TYPE = %d \
-                       UNION ALL SELECT COUNT(MSG_ID) FROM %s WHERE FOLDER_ID = %d AND MAIN_TYPE = %d;",
-                       MSGFW_MESSAGE_TABLE_NAME, folderId,
-                       MSGFW_MESSAGE_TABLE_NAME, folderId,
-                       MSGFW_MESSAGE_TABLE_NAME, folderId, MSG_SMS_TYPE,
-                       MSGFW_MESSAGE_TABLE_NAME, folderId, MSG_MMS_TYPE);
-
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE FOLDER_ID = %d AND READ_STATUS = 1 AND STORAGE_ID = %d "
+                       "UNION ALL SELECT COUNT(MSG_ID) FROM %s WHERE FOLDER_ID = %d AND READ_STATUS = 0 AND STORAGE_ID = %d "
+                       "UNION ALL SELECT COUNT(MSG_ID) FROM %s WHERE FOLDER_ID = %d AND MAIN_TYPE = %d AND STORAGE_ID = %d "
+                       "UNION ALL SELECT COUNT(MSG_ID) FROM %s WHERE FOLDER_ID = %d AND MAIN_TYPE = %d AND STORAGE_ID = %d;",
+                       MSGFW_MESSAGE_TABLE_NAME, folderId, MSG_STORAGE_PHONE,
+                       MSGFW_MESSAGE_TABLE_NAME, folderId, MSG_STORAGE_PHONE,
+                       MSGFW_MESSAGE_TABLE_NAME, folderId, MSG_SMS_TYPE, MSG_STORAGE_PHONE,
+                       MSGFW_MESSAGE_TABLE_NAME, folderId, MSG_MMS_TYPE, MSG_STORAGE_PHONE);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               pCountInfo->nReadCnt = dbHandle.columnInt(0);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               pCountInfo->nReadCnt = dbHandle->columnInt(0);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               pCountInfo->nUnreadCnt = dbHandle.columnInt(0);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               pCountInfo->nUnreadCnt = dbHandle->columnInt(0);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               pCountInfo->nSms = dbHandle.columnInt(0);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               pCountInfo->nSms = dbHandle->columnInt(0);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               pCountInfo->nMms = dbHandle.columnInt(0);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               pCountInfo->nMms = dbHandle->columnInt(0);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        return MSG_SUCCESS;
 }
@@ -1465,6 +1961,7 @@ msg_error_t MsgStoCountMsgByType(const MSG_MESSAGE_TYPE_S *pMsgType, int *pMsgCo
        char sqlQuery[MAX_QUERY_LEN+1];
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
+       MsgDbHandler *dbHandle = getDbHandle();
        // SMS
        if ((pMsgType->mainType == MSG_SMS_TYPE) &&
                        (pMsgType->subType == MSG_NORMAL_SMS || pMsgType->subType == MSG_STATUS_REPORT_SMS || pMsgType->subType == MSG_CONCAT_SIM_SMS)) {
@@ -1484,17 +1981,17 @@ msg_error_t MsgStoCountMsgByType(const MSG_MESSAGE_TYPE_S *pMsgType, int *pMsgCo
                return MSG_ERR_INVALID_PARAMETER;
        }
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               *pMsgCount = dbHandle.columnInt(0);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               *pMsgCount = dbHandle->columnInt(0);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        return MSG_SUCCESS;
 }
@@ -1503,36 +2000,35 @@ msg_error_t MsgStoCountMsgByType(const MSG_MESSAGE_TYPE_S *pMsgType, int *pMsgCo
 msg_error_t MsgStoGetMessage(msg_message_id_t msgId, MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo)
 {
        char sqlQuery[MAX_QUERY_LEN+1];
-
-       int order = MsgGetContactNameOrder();
-
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID, CONV_ID, FOLDER_ID, STORAGE_ID, MAIN_TYPE, \
                        SUB_TYPE, DISPLAY_TIME, DATA_SIZE, NETWORK_STATUS, READ_STATUS, PROTECTED, \
-                       BACKUP, PRIORITY, MSG_DIRECTION, SCHEDULED_TIME, SUBJECT, MSG_TEXT, THUMB_PATH \
+                       BACKUP, PRIORITY, MSG_DIRECTION, SCHEDULED_TIME, SUBJECT, MSG_TEXT, THUMB_PATH, SIM_INDEX \
                        FROM %s WHERE MSG_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               pMsg->msgId = dbHandle.columnInt(0);
-               pMsg->threadId = dbHandle.columnInt(1);
-               pMsg->folderId = dbHandle.columnInt(2);
-               pMsg->storageId = dbHandle.columnInt(3);
-               pMsg->msgType.mainType = dbHandle.columnInt(4);
-               pMsg->msgType.subType = dbHandle.columnInt(5);
-               pMsg->displayTime = (time_t)dbHandle.columnInt(6);
-               pMsg->dataSize = dbHandle.columnInt(7);
-               pMsg->networkStatus = dbHandle.columnInt(8);
-               pMsg->bRead = dbHandle.columnInt(9);
-               pMsg->bProtected = dbHandle.columnInt(10);
-               pMsg->bBackup = dbHandle.columnInt(11);
-               pMsg->priority = dbHandle.columnInt(12);
-               pMsg->direction= dbHandle.columnInt(13);
-
-               strncpy(pMsg->subject, (char *)dbHandle.columnText(15), MAX_SUBJECT_LEN);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               pMsg->msgId = dbHandle->columnInt(0);
+               pMsg->threadId = dbHandle->columnInt(1);
+               pMsg->folderId = dbHandle->columnInt(2);
+               pMsg->storageId = dbHandle->columnInt(3);
+               pMsg->msgType.mainType = dbHandle->columnInt(4);
+               pMsg->msgType.subType = dbHandle->columnInt(5);
+               pMsg->displayTime = (time_t)dbHandle->columnInt(6);
+               pMsg->dataSize = dbHandle->columnInt(7);
+               pMsg->networkStatus = dbHandle->columnInt(8);
+               pMsg->bRead = dbHandle->columnInt(9);
+               pMsg->bProtected = dbHandle->columnInt(10);
+               pMsg->bBackup = dbHandle->columnInt(11);
+               pMsg->priority = dbHandle->columnInt(12);
+               pMsg->direction= dbHandle->columnInt(13);
+
+               strncpy(pMsg->subject, (char *)dbHandle->columnText(15), MAX_SUBJECT_LEN);
 
                /* Temp_File_Handling */
                if (pMsg->msgType.mainType == MSG_SMS_TYPE || pMsg->msgType.subType == MSG_NOTIFICATIONIND_MMS) {
@@ -1540,21 +2036,21 @@ msg_error_t MsgStoGetMessage(msg_message_id_t msgId, MSG_MESSAGE_INFO_S *pMsg, M
                                char msgData[pMsg->dataSize+1];
                                memset(msgData, 0x00, sizeof(msgData));
 
-                               strncpy(msgData, (char *)dbHandle.columnText(16), pMsg->dataSize);
+                               strncpy(msgData, (char *)dbHandle->columnText(16), pMsg->dataSize);
 
                                // Save Message Data into File
-                               char fileName[MAX_COMMON_INFO_SIZE+1];
+                               char fileName[MSG_FILENAME_LEN_MAX+1];
                                memset(fileName, 0x00, sizeof(fileName));
 
                                if (MsgCreateFileName(fileName) == false) {
-                                       dbHandle.finalizeQuery();
+                                       dbHandle->finalizeQuery();
                                        return MSG_ERR_STORAGE_ERROR;
                                }
 
-                               MSG_DEBUG("Save Message Data into file : size[%d] name[%s]\n", pMsg->dataSize, fileName);
+                               MSG_SEC_DEBUG("Save Message Data into file : size[%d] name[%s]\n", pMsg->dataSize, fileName);
 
                                if (MsgWriteIpcFile(fileName, msgData, pMsg->dataSize) == false) {
-                                       dbHandle.finalizeQuery();
+                                       dbHandle->finalizeQuery();
                                        return MSG_ERR_STORAGE_ERROR;
                                }
 
@@ -1563,53 +2059,57 @@ msg_error_t MsgStoGetMessage(msg_message_id_t msgId, MSG_MESSAGE_INFO_S *pMsg, M
                                pMsg->bTextSms = false;
                        } else {
                                memset(pMsg->msgText, 0x00, sizeof(pMsg->msgText));
-                               strncpy(pMsg->msgText, (char *)dbHandle.columnText(16), pMsg->dataSize);
+                               strncpy(pMsg->msgText, (char *)dbHandle->columnText(16), pMsg->dataSize);
 
                                // For WAP PUSH SI Message
                                if (pMsg->msgType.subType == MSG_WAP_SI_SMS) {
                                        strncat(pMsg->msgText, "\n", MAX_MSG_TEXT_LEN-strlen(pMsg->msgText));
                                        strncat(pMsg->msgText, pMsg->subject, MAX_MSG_TEXT_LEN-strlen(pMsg->msgText));
-                                       MSG_DEBUG("pMsg->msgText : [%s]", pMsg->msgText);
+                                       MSG_SEC_DEBUG("pMsg->msgText : [%s]", pMsg->msgText);
                                        pMsg->dataSize = sizeof(pMsg->msgText);
                                }
 
                                pMsg->bTextSms = true;
                        }
                } else {
-                       if (dbHandle.columnText(16) != NULL)
-                               strncpy(pMsg->msgText, (char *)dbHandle.columnText(16), MAX_MSG_TEXT_LEN);
+                       if (dbHandle->columnText(16) != NULL)
+                               strncpy(pMsg->msgText, (char *)dbHandle->columnText(16), MAX_MSG_TEXT_LEN);
                }
 
                // thumbnail path
-               if (dbHandle.columnText(17)!=NULL && ((char *)dbHandle.columnText(17))[0] != '\0') {
-                       strncpy(pMsg->thumbPath, (char *)dbHandle.columnText(17), MSG_FILEPATH_LEN_MAX);
+               if (dbHandle->columnText(17)!= NULL && ((char *)dbHandle->columnText(17))[0] != '\0') {
+                       strncpy(pMsg->thumbPath, (char *)dbHandle->columnText(17), MSG_FILEPATH_LEN_MAX);
                        MSG_DEBUG("pMsg->thumbPath : [%s]", pMsg->thumbPath);
                }
+               pMsg->sim_idx = dbHandle->columnInt(18);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                MSG_DEBUG("%s", sqlQuery);
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
 
        // get address information.
-       MsgStoGetAddressByMsgId(&dbHandle, pMsg->msgId, order, &pMsg->nAddressCnt, pMsg->addressList);
+       MsgStoGetAddressByMsgId(dbHandle, pMsg->msgId, MsgGetContactNameOrder(), &pMsg->nAddressCnt, &pMsg->addressList);
 
        // Get MMS body if it is MMS.
        if ((pMsg->networkStatus == MSG_NETWORK_RETRIEVE_SUCCESS &&
-                       (pMsg->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || pMsg->msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS)) ||
-                       pMsg->msgType.subType == MSG_SENDREQ_MMS || pMsg->msgType.subType == MSG_SENDCONF_MMS) {
+                       (pMsg->msgType.subType == MSG_RETRIEVE_MMS || pMsg->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || pMsg->msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS)) ||
+                       pMsg->msgType.subType == MSG_SENDREQ_MMS || pMsg->msgType.subType == MSG_SENDCONF_MMS || pMsg->msgType.subType == MSG_NOTIFICATIONIND_MMS) {
                msg_error_t err = MSG_SUCCESS;
-               MMS_MESSAGE_DATA_S      mmsMsg;
                char *pDestMsg = NULL;
+               int temp_size = pMsg->dataSize;//save raw file size;
 
                // call mms plugin to get mms specific message data
                MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(pMsg->msgType.mainType);
-               memset(&mmsMsg, 0, sizeof(MMS_MESSAGE_DATA_S));
-               err =  plg->getMmsMessage(pMsg, pSendOptInfo, &mmsMsg, &pDestMsg);
+               if (plg == NULL) {
+                       MSG_DEBUG("SMS Plug-in is NULL");
+                       return MSG_ERR_NULL_POINTER;
+               }
 
+               err =  plg->getMmsMessage(pMsg, pSendOptInfo, &pDestMsg);
                if (err != MSG_SUCCESS) {
                        if (pDestMsg) {
                                free(pDestMsg);
@@ -1623,7 +2123,7 @@ msg_error_t MsgStoGetMessage(msg_message_id_t msgId, MSG_MESSAGE_INFO_S *pMsg, M
                // Encode MMS specific data to MMS_MESSAGE_DATA_S
                if (pMsg->dataSize > MAX_MSG_DATA_LEN) {
                        // Save Message Data into File
-                       char tempFileName[MAX_COMMON_INFO_SIZE+1];
+                       char tempFileName[MSG_FILENAME_LEN_MAX+1];
                        memset(tempFileName, 0x00, sizeof(tempFileName));
 
                        if (MsgCreateFileName(tempFileName) == false) {
@@ -1633,7 +2133,7 @@ msg_error_t MsgStoGetMessage(msg_message_id_t msgId, MSG_MESSAGE_INFO_S *pMsg, M
                                }
                                return MSG_ERR_STORAGE_ERROR;
                        }
-                       MSG_DEBUG("Save Message Data into file : size[%d] name[%s]\n", pMsg->dataSize, tempFileName);
+                       MSG_SEC_DEBUG("Save Message Data into file : size[%d] name[%s]\n", pMsg->dataSize, tempFileName);
 
                        if (MsgWriteIpcFile(tempFileName, pDestMsg, pMsg->dataSize) == false) {
                                if(pDestMsg) {
@@ -1643,13 +2143,14 @@ msg_error_t MsgStoGetMessage(msg_message_id_t msgId, MSG_MESSAGE_INFO_S *pMsg, M
                                return MSG_ERR_STORAGE_ERROR;
                        }
                        strncpy(pMsg->msgData, tempFileName, MAX_MSG_DATA_LEN);
-                       //pMsg->dataSize = strlen(fileName);
                        pMsg->bTextSms = false;
                } else {
                        strncpy(pMsg->msgData, pDestMsg, pMsg->dataSize);
                        pMsg->bTextSms = true;
                }
 
+               pMsg->dataSize = temp_size;//raw file size;
+
                if (pDestMsg) {
                        free(pDestMsg);
                        pDestMsg = NULL;
@@ -1658,134 +2159,43 @@ msg_error_t MsgStoGetMessage(msg_message_id_t msgId, MSG_MESSAGE_INFO_S *pMsg, M
 
        // Get SMS Sending Options
        if (pMsg->msgType.mainType == MSG_SMS_TYPE && pSendOptInfo != NULL)
-               MsgStoGetSmsSendOpt(pMsg->msgId, pSendOptInfo);
+               MsgStoGetSmsSendOpt(pMsg, pSendOptInfo);
 
        return MSG_SUCCESS;
 }
 
-
-msg_error_t MsgStoGetFolderViewList(msg_folder_id_t folderId, const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pMsgFolderViewList)
+msg_error_t MsgStoGetFailedMessage(int **failed_msg_list, int *count)
 {
-       if (pMsgFolderViewList == NULL) {
-               MSG_DEBUG("pMsgFolderViewList is NULL");
-               return MSG_ERR_NULL_POINTER;
-       }
-
-       int rowCnt = 0;
-       int index = 19; // numbers of index
-
+       MSG_BEGIN();
 
+       msg_error_t err = MSG_SUCCESS;
        char sqlQuery[MAX_QUERY_LEN+1];
-       char sqlSort[64];
+       int rowCnt = 0, index = 0;
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       // Get Name Order
-       int order = MsgGetContactNameOrder();
-
-       // Get Message In Folder
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       if (folderId == MSG_ALLBOX_ID) {
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID, CONV_ID, FOLDER_ID, STORAGE_ID, MAIN_TYPE, SUB_TYPE, \
-                               DISPLAY_TIME, DATA_SIZE, NETWORK_STATUS, READ_STATUS, PROTECTED, BACKUP, PRIORITY, \
-                               MSG_DIRECTION, SCHEDULED_TIME, SUBJECT, MSG_TEXT, ATTACHMENT_COUNT, THUMB_PATH \
-                               FROM %s WHERE FOLDER_ID < %d ",
-                               MSGFW_MESSAGE_TABLE_NAME, MSG_SPAMBOX_ID);
-       } else {
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID, CONV_ID, FOLDER_ID, STORAGE_ID, MAIN_TYPE, SUB_TYPE, \
-                               DISPLAY_TIME, DATA_SIZE, NETWORK_STATUS, READ_STATUS, PROTECTED, BACKUP, PRIORITY, \
-                               MSG_DIRECTION, SCHEDULED_TIME, SUBJECT, MSG_TEXT, ATTACHMENT_COUNT, THUMB_PATH \
-                               FROM %s WHERE FOLDER_ID = %d ",
-                               MSGFW_MESSAGE_TABLE_NAME, folderId);
-       }
-
-       memset(sqlSort, 0x00, sizeof(sqlSort));
-       MsgMakeSortRule(pSortRule, sqlSort);
-       strncat(sqlQuery, sqlSort, strlen(sqlSort));
-
-       msg_error_t  err = dbHandle.getTable(sqlQuery, &rowCnt);
-
-       if (err == MSG_ERR_DB_NORECORD) {
-               pMsgFolderViewList->nCount = 0;
-               pMsgFolderViewList->msg_struct_info = NULL;
-
-               dbHandle.freeTable();
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE NETWORK_STATUS = %d AND FOLDER_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_NETWORK_SEND_PENDING, MSG_OUTBOX_ID);
+       err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
 
+       if(err == MSG_ERR_DB_NORECORD){
+               dbHandle->freeTable();
                return MSG_SUCCESS;
-       } else if (err != MSG_SUCCESS) {
-               MSG_DEBUG("sqlQuery is - %s", sqlQuery);
-               dbHandle.freeTable();
-               return err;
        }
+       *count = rowCnt;
+       int *list = new int[rowCnt];
 
-       pMsgFolderViewList->nCount = rowCnt;
-
-       MSG_DEBUG("pMsgCommInfoList->nCount [%d]", pMsgFolderViewList->nCount);
-
-       pMsgFolderViewList->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t) * rowCnt];
-
-       msg_struct_s *msg = NULL;
-       MSG_MESSAGE_HIDDEN_S *pTmp = NULL;
-
-       for (int i = 0; i < rowCnt; i++) {
-               pMsgFolderViewList->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];;
-
-               msg = (msg_struct_s *)pMsgFolderViewList->msg_struct_info[i];
-
-               msg->type = MSG_STRUCT_MESSAGE_INFO;
-               msg->data = new char[sizeof(MSG_MESSAGE_HIDDEN_S)];
-
-               pTmp = (MSG_MESSAGE_HIDDEN_S *)msg->data;
-
-               pTmp->pData = NULL;
-               pTmp->pMmsData = NULL;
-
-               pTmp->msgId = dbHandle.getColumnToInt(index++);
-               pTmp->threadId = dbHandle.getColumnToInt(index++);
-               pTmp->folderId = dbHandle.getColumnToInt(index++);
-               pTmp->storageId = dbHandle.getColumnToInt(index++);
-               pTmp->mainType = dbHandle.getColumnToInt(index++);
-               pTmp->subType = dbHandle.getColumnToInt(index++);
-               pTmp->displayTime = (time_t)dbHandle.getColumnToInt(index++);
-               pTmp->dataSize = dbHandle.getColumnToInt(index++);
-               pTmp->networkStatus = dbHandle.getColumnToInt(index++);
-               pTmp->bRead = dbHandle.getColumnToInt(index++);
-               pTmp->bProtected = dbHandle.getColumnToInt(index++);
-               pTmp->bBackup = dbHandle.getColumnToInt(index++);
-               pTmp->priority = dbHandle.getColumnToInt(index++);
-               pTmp->direction= dbHandle.getColumnToInt(index++);
-               index++; // This field is reserved.
-
-               dbHandle.getColumnToString(index++, MAX_SUBJECT_LEN, pTmp->subject);
-
-               if (pTmp->mainType == MSG_MMS_TYPE &&
-                       (pTmp->networkStatus == MSG_NETWORK_RETRIEVING || pTmp->networkStatus == MSG_NETWORK_RETRIEVE_FAIL || pTmp->subType == MSG_NOTIFICATIONIND_MMS)) {
-                       pTmp->pData = NULL;
-                       index++;
-               } else {
-                       pTmp->pData = (void *)new char[pTmp->dataSize + 2];
-                       memset(pTmp->pData, 0x00, sizeof(pTmp->pData));
-
-                       dbHandle.getColumnToString(index++, pTmp->dataSize+1, (char *)pTmp->pData);
-               }
-
-               // get address information from db.
-               msg_struct_list_s *addr_list = (msg_struct_list_s *)new msg_struct_list_s;
-
-               MsgStoGetAddressByMsgId(&dbHandle, pTmp->msgId, order, addr_list);
-
-               pTmp->addr_list = addr_list;
-
-               pTmp->attachCount = dbHandle.getColumnToInt(index++);
-
-               dbHandle.getColumnToString(index++, MSG_FILEPATH_LEN_MAX, pTmp->thumbPath);
+       for(int i=0; i<rowCnt; ++i){
+               list[i] = dbHandle->getColumnToInt(index++);
        }
+       *failed_msg_list = list;
+       dbHandle->freeTable();
 
-       dbHandle.freeTable();
-
-       return MSG_SUCCESS;
+       MSG_END();
+       return err;
 }
 
-
 msg_error_t MsgStoAddSyncMLMessage(MSG_MESSAGE_INFO_S *pMsgInfo, int extId, int pinCode)
 {
        MSG_BEGIN();
@@ -1796,24 +2206,25 @@ msg_error_t MsgStoAddSyncMLMessage(MSG_MESSAGE_INFO_S *pMsgInfo, int extId, int
 
        unsigned int rowId = 0;
        msg_thread_id_t convId = 0;
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       dbHandle.beginTrans();
+       dbHandle->beginTrans();
 
        if (pMsgInfo->nAddressCnt > 0) {
-               err = MsgStoAddAddress(&dbHandle, pMsgInfo, &convId);
+               err = MsgStoAddAddress(dbHandle, pMsgInfo, &convId);
 
                if (err != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+                       dbHandle->endTrans(false);
                        return err;
                }
        }
 
        // Add Message Table
        pMsgInfo->threadId = convId;
-       rowId = MsgStoAddMessageTable(&dbHandle, pMsgInfo);
+       rowId = MsgStoAddMessageTable(dbHandle, pMsgInfo);
 
        if (rowId <= 0) {
-               dbHandle.endTrans(false);
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_ROW;
        }
 
@@ -1821,31 +2232,22 @@ msg_error_t MsgStoAddSyncMLMessage(MSG_MESSAGE_INFO_S *pMsgInfo, int extId, int
        snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d);",
                        MSGFW_SYNCML_MSG_TABLE_NAME, rowId, extId, pinCode);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
-       if (MsgStoUpdateConversation(&dbHandle, convId) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (MsgStoUpdateConversation(dbHandle, convId) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_STORAGE_ERROR;
        }
 
-       dbHandle.endTrans(true);
+       dbHandle->endTrans(true);
 
        pMsgInfo->msgId = (msg_message_id_t)rowId;
 
-       MsgSoundPlayStart();
-
-       int smsCnt = 0;
-       int mmsCnt = 0;
-
-       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
-       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
-
-       MsgSettingHandleNewMsg(smsCnt, mmsCnt);
-
-       MsgInsertNoti(&dbHandle, pMsgInfo);
+       MsgInsertNotification(pMsgInfo);
+       MsgChangePmState();
 
        MSG_END();
 
@@ -1855,6 +2257,7 @@ msg_error_t MsgStoAddSyncMLMessage(MSG_MESSAGE_INFO_S *pMsgInfo, int extId, int
 
 msg_error_t MsgStoGetMsgType(msg_message_id_t msgId, MSG_MESSAGE_TYPE_S *pMsgType)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -1862,15 +2265,15 @@ msg_error_t MsgStoGetMsgType(msg_message_id_t msgId, MSG_MESSAGE_TYPE_S *pMsgTyp
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MAIN_TYPE, SUB_TYPE FROM %s WHERE MSG_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               pMsgType->mainType = dbHandle.columnInt(0);
-               pMsgType->subType = dbHandle.columnInt(1);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               pMsgType->mainType = dbHandle->columnInt(0);
+               pMsgType->subType = dbHandle->columnInt(1);
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        return MSG_SUCCESS;
 }
@@ -1880,6 +2283,7 @@ msg_error_t MsgStoGetQuickPanelData(msg_quickpanel_type_t QPtype, MSG_MESSAGE_IN
 {
        msg_error_t     err = MSG_SUCCESS;
 
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -1907,17 +2311,17 @@ msg_error_t MsgStoGetQuickPanelData(msg_quickpanel_type_t QPtype, MSG_MESSAGE_IN
        // Get Message ID
        msg_message_id_t msgId;
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               msgId = dbHandle.columnInt(0);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               msgId = dbHandle->columnInt(0);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        // Get Message Info
        err = MsgStoGetMessage(msgId, pMsg, NULL);
@@ -1926,1038 +2330,266 @@ msg_error_t MsgStoGetQuickPanelData(msg_quickpanel_type_t QPtype, MSG_MESSAGE_IN
 }
 
 
-msg_error_t MsgStoGetThreadViewList(const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pThreadViewList)
+msg_error_t MsgStoDeleteThreadMessageList(msg_thread_id_t threadId, bool bIncludeProtect, msg_id_list_s *pMsgIdList)
 {
-       pThreadViewList->nCount = 0;
-       pThreadViewList->msg_struct_info = NULL;
-
-       int rowCnt = 0;
-       int index = 10; // numbers of index
+       msg_error_t err = MSG_SUCCESS;
 
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CONV_ID, UNREAD_CNT, SMS_CNT, MMS_CNT, \
-                       MAIN_TYPE, SUB_TYPE, MSG_DIRECTION, DISPLAY_TIME, DISPLAY_NAME, MSG_TEXT \
-                       FROM %s WHERE SMS_CNT > 0 OR MMS_CNT > 0 ORDER BY DISPLAY_TIME DESC;",
-                       MSGFW_CONVERSATION_TABLE_NAME);
+       /*** Get msg id list **/
+       int rowCnt = 0, index = 0;
 
-       msg_error_t  err = dbHandle.getTable(sqlQuery, &rowCnt);
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       if (err == MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
-               return MSG_SUCCESS;
-       } else if (err != MSG_SUCCESS) {
-               MSG_DEBUG("%s", sqlQuery);
-               dbHandle.freeTable();
-               return err;
+#ifdef MSG_NOTI_INTEGRATION
+       if (bIncludeProtect) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE \
+                               CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, threadId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE);
+       } else {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE \
+                               CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND PROTECTED = 0;",
+                               MSGFW_MESSAGE_TABLE_NAME, threadId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE);
+       }
+#else
+       if (bIncludeProtect) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE \
+                               CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, threadId, MSG_ALLBOX_ID, MSG_CBMSGBOX_ID, MSG_STORAGE_PHONE);
+       } else {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE \
+                               CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND PROTECTED = 0;",
+                               MSGFW_MESSAGE_TABLE_NAME, threadId, MSG_ALLBOX_ID, MSG_CBMSGBOX_ID, MSG_STORAGE_PHONE);
        }
+#endif
 
-       if (rowCnt < 1) {
-               MSG_DEBUG("rowCnt is %d", rowCnt);
-               dbHandle.freeTable();
+       err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
                return err;
        }
 
-       pThreadViewList->nCount = rowCnt;
-
-       MSG_DEBUG("pThreadViewList->nCount [%d]", pThreadViewList->nCount);
-
-       pThreadViewList->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t)*rowCnt];
-
-       MSG_THREAD_VIEW_S *pTmp = NULL;
-       msg_struct_s *thread_t = NULL;
-
-       for (int i = 0; i < rowCnt; i++) {
-               thread_t = (msg_struct_s *)new msg_struct_s;
-               pThreadViewList->msg_struct_info[i] = (msg_struct_t)thread_t;
-
-               thread_t->type = MSG_STRUCT_THREAD_INFO;
-               thread_t->data = new MSG_THREAD_VIEW_S;
-
-               pTmp = (MSG_THREAD_VIEW_S *)thread_t->data;
-               memset(pTmp, 0x00, sizeof(MSG_THREAD_VIEW_S));
-
-               pTmp->threadId = dbHandle.getColumnToInt(index++);
+       if (rowCnt <= 0) {
+//             dbHandle->freeTable();
+               err = MSG_SUCCESS;
+       }
 
-               pTmp->unreadCnt = dbHandle.getColumnToInt(index++);
-               pTmp->smsCnt = dbHandle.getColumnToInt(index++);
-               pTmp->mmsCnt = dbHandle.getColumnToInt(index++);
+       pMsgIdList->nCount = rowCnt;
 
-               pTmp->mainType = dbHandle.getColumnToInt(index++);
-               pTmp->subType = dbHandle.getColumnToInt(index++);
+       MSG_DEBUG("pMsgIdList->nCount [%d]", pMsgIdList->nCount);
 
-               pTmp->direction = dbHandle.getColumnToInt(index++);
-               pTmp->threadTime = (time_t)dbHandle.getColumnToInt(index++);
+       pMsgIdList->msgIdList = (msg_message_id_t *)new char[sizeof(msg_message_id_t) * rowCnt];
 
-               memset(pTmp->threadName, 0x00, sizeof(pTmp->threadName));
-               dbHandle.getColumnToString(index++, MAX_THREAD_NAME_LEN, pTmp->threadName);
+       for (int i = 0; i < rowCnt; i++)
+               pMsgIdList->msgIdList[i] = dbHandle->getColumnToInt(index++);
 
-               memset(pTmp->threadData, 0x00, sizeof(pTmp->threadData));
-               dbHandle.getColumnToString(index++, MAX_THREAD_DATA_LEN, pTmp->threadData);
-       }
+       dbHandle->freeTable();
+       /*** **/
 
-       dbHandle.freeTable();
+       err = MsgStoDeleteMessageByList(pMsgIdList);
 
-       return MSG_SUCCESS;
+       return err;
 }
 
 
-msg_error_t MsgStoGetConversationViewList(msg_thread_id_t threadId, msg_struct_list_s *pConvViewList)
+msg_error_t MsgStoCountMsgByContact(const MSG_THREAD_LIST_INDEX_S *pAddrInfo, MSG_THREAD_COUNT_INFO_S *pThreadCountInfo)
 {
-       MSG_BEGIN();
-
-       pConvViewList->nCount = 0;
-       pConvViewList->msg_struct_info = NULL;
-
-       int rowCnt = 0;
-       int index = 19; /** numbers of index */
-       int order = 0;
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       // get address information.
-       order = MsgGetContactNameOrder();
-
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID, CONV_ID, FOLDER_ID, STORAGE_ID, MAIN_TYPE, SUB_TYPE, \
-                       DISPLAY_TIME, DATA_SIZE, NETWORK_STATUS, READ_STATUS, PROTECTED, BACKUP, PRIORITY, \
-                       MSG_DIRECTION, SCHEDULED_TIME, SUBJECT, MSG_TEXT, ATTACHMENT_COUNT, THUMB_PATH \
-                       FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d ORDER BY DISPLAY_TIME, MSG_ID ASC;",
-                       MSGFW_MESSAGE_TABLE_NAME, threadId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID);
-
-       msg_error_t err = dbHandle.getTable(sqlQuery, &rowCnt);
-
-       if (err == MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
-               return MSG_SUCCESS;
-       } else if (err != MSG_SUCCESS) {
-               MSG_DEBUG("%s", sqlQuery);
-               dbHandle.freeTable();
-               return err;
-       }
-
-       pConvViewList->nCount = rowCnt;
-
-       MSG_DEBUG("pConvViewList->nCount [%d]", pConvViewList->nCount);
-
-       pConvViewList->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t) * rowCnt];
-
-       msg_struct_s *msg = NULL;
-       MSG_MESSAGE_HIDDEN_S *pTmp = NULL;
-
-       for (int i = 0; i < rowCnt; i++) {
-               pConvViewList->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];;
-
-               msg = (msg_struct_s *)pConvViewList->msg_struct_info[i];
-
-               msg->type = MSG_STRUCT_MESSAGE_INFO;
-               msg->data = new char[sizeof(MSG_MESSAGE_HIDDEN_S)];
-
-               pTmp = (MSG_MESSAGE_HIDDEN_S *)msg->data;
-
-               pTmp->pData = NULL;
-               pTmp->pMmsData = NULL;
-
-               pTmp->msgId = dbHandle.getColumnToInt(index++);
-               pTmp->threadId = dbHandle.getColumnToInt(index++);
-               pTmp->folderId = dbHandle.getColumnToInt(index++);
-               pTmp->storageId = dbHandle.getColumnToInt(index++);
-               pTmp->mainType = dbHandle.getColumnToInt(index++);
-               pTmp->subType = dbHandle.getColumnToInt(index++);
-               pTmp->displayTime = (time_t)dbHandle.getColumnToInt(index++);
-               pTmp->dataSize = dbHandle.getColumnToInt(index++);
-               pTmp->networkStatus = dbHandle.getColumnToInt(index++);
-               pTmp->bRead = dbHandle.getColumnToInt(index++);
-               pTmp->bProtected = dbHandle.getColumnToInt(index++);
-               pTmp->bBackup = dbHandle.getColumnToInt(index++);
-               pTmp->priority = dbHandle.getColumnToInt(index++);
-               pTmp->direction = dbHandle.getColumnToInt(index++);
-               index++; // This field is reserved.
-
-               dbHandle.getColumnToString(index++, MAX_SUBJECT_LEN, pTmp->subject);
-
-               if (pTmp->mainType == MSG_MMS_TYPE &&
-                       (pTmp->networkStatus == MSG_NETWORK_RETRIEVING || pTmp->networkStatus == MSG_NETWORK_RETRIEVE_FAIL || pTmp->subType == MSG_NOTIFICATIONIND_MMS)) {
-                       pTmp->pData = NULL;
-                       index++;
-               } else {
-                       pTmp->pData = (void *)new char[pTmp->dataSize+2];
-                       memset(pTmp->pData, 0x00, pTmp->dataSize+2);
-
-                       dbHandle.getColumnToString(index++, pTmp->dataSize+1, (char *)pTmp->pData);
-               }
-
-               pTmp->attachCount = dbHandle.getColumnToInt(index++);
-
-               dbHandle.getColumnToString(index++, MSG_FILEPATH_LEN_MAX, pTmp->thumbPath);
-
-               // set address list handle.
-               msg_struct_list_s *addrlist = (msg_struct_list_s *)new msg_struct_list_s;
-               memset(addrlist, 0x00, sizeof(msg_struct_list_s));
-               MsgDbHandler dbHandleForInner;
-               MsgStoGetAddressByConvId(&dbHandleForInner, threadId, order, addrlist);
-
-               pTmp->addr_list = addrlist;
-
-       }
-
-       dbHandle.freeTable();
-
-       MSG_END();
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t MsgStoDeleteThreadMessageList(msg_thread_id_t threadId, msg_id_list_s *pMsgIdList)
-{
-       msg_error_t err = MSG_SUCCESS;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-       /*** Get msg id list **/
-       msg_id_list_s *pToDeleteMsgIdList = NULL;
-
-       int rowCnt = 0;
-       int index = 1;
-       // Set Indicator
-       int smsCnt = 0;
-       int mmsCnt = 0;
-
-       const char *tableList[] = {MSGFW_PUSH_MSG_TABLE_NAME, MSGFW_CB_MSG_TABLE_NAME,
-                       MSGFW_SYNCML_MSG_TABLE_NAME, MSGFW_SMS_SENDOPT_TABLE_NAME, 
-                       MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME};
-
-       int listCnt = sizeof(tableList)/sizeof(char *);
-
-       pToDeleteMsgIdList = (msg_id_list_s *)new char[sizeof(msg_id_list_s)];
-       memset(pToDeleteMsgIdList, 0x00, sizeof(msg_id_list_s));
-
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE CONV_ID = %d", MSGFW_MESSAGE_TABLE_NAME, threadId);
-
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
-
-       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
-
-               dbHandle.freeTable();
-
-               goto FREE_MEMORY;
-       }
-
-       if (rowCnt <= 0) {
-               dbHandle.freeTable();
-               err = MSG_SUCCESS;
-
-               goto FREE_MEMORY;
-       }
-
-       pToDeleteMsgIdList->nCount = rowCnt;
-
-       MSG_DEBUG("pToDeleteMsgIdList->nCount [%d]", pToDeleteMsgIdList->nCount);
-
-       pToDeleteMsgIdList->msgIdList = (msg_message_id_t *)new char[sizeof(msg_message_id_t) * rowCnt];
-
-       for (int i = 0; i < rowCnt; i++)
-               pToDeleteMsgIdList->msgIdList[i] = dbHandle.getColumnToInt(index++);
-
-       dbHandle.freeTable();
-       /*** **/
-
-       /*** Delete Sim Message **/
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE CONV_ID = %d AND STORAGE_ID = %d",
-                       MSGFW_MESSAGE_TABLE_NAME, threadId, MSG_STORAGE_SIM);
-
-       rowCnt = 0;
-
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
-
-       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
-
-               dbHandle.freeTable();
-
-               goto FREE_MEMORY;
-       }
-
-       for (int i = 1; i <= rowCnt; i++) {
-               err = MsgStoDeleteMessage(dbHandle.getColumnToInt(i), false);
-
-               if (err != MSG_SUCCESS) {
-                       MSG_DEBUG("MsgStoDeleteMessage() Error!!!");
-
-                       dbHandle.freeTable();
-
-                       goto FREE_MEMORY;
-               }
-       }
-
-       dbHandle.freeTable();
-       /*** **/
-
-       dbHandle.beginTrans();
-
-       for (int i = 0; i < listCnt; i++) {
-               if (!strcmp(tableList[i], MMS_PLUGIN_MESSAGE_TABLE_NAME)) {
-
-                       int rowCnt = 0;
-
-                       //get mms msg id list
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILE_PATH FROM %s A, %s B\
-                                       WHERE A.CONV_ID = %d AND A.MAIN_TYPE = %d AND A.MSG_ID = B.MSG_ID;",
-                                       MSGFW_MESSAGE_TABLE_NAME, MMS_PLUGIN_MESSAGE_TABLE_NAME, threadId, MSG_MMS_TYPE);
-
-                       err = dbHandle.getTable(sqlQuery, &rowCnt);
-                       MSG_DEBUG("rowCnt %d", rowCnt);
-
-                       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-                               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
-
-                               dbHandle.freeTable();
-                               dbHandle.endTrans(false);
-
-                               goto FREE_MEMORY;
-                       }
-
-                       for (int i = 1; i <= rowCnt; i++) {
-
-                               char filePath[MSG_FILEPATH_LEN_MAX] = {0,};
-                               char dirPath[MSG_FILEPATH_LEN_MAX] = {0,};
-                               char thumbnailPath[MSG_FILEPATH_LEN_MAX] = {0,};
-
-                               dbHandle.getColumnToString(i, MSG_FILEPATH_LEN_MAX, filePath);
-
-                               MSG_DEBUG("filePath [%s]", filePath);
-
-                               //delete raw file
-                               snprintf(dirPath, sizeof(dirPath), "%s.dir", filePath);
-
-                               if (remove(filePath) == -1)
-                                       MSG_DEBUG("Fail to delete file [%s]", filePath);
-                               else
-                                       MSG_DEBUG("Success to delete file [%s]", filePath);
-
-                               MsgRmRf(dirPath);
-
-                               // remove directory also
-                               rmdir(dirPath);
-
-                               // delete thumbnail
-                               char *fileName = NULL;
-                               fileName = strrchr(filePath, '/');
-
-                               snprintf(thumbnailPath, sizeof(thumbnailPath), MSG_THUMBNAIL_PATH"%s.jpg", fileName+1);
-
-                               if (remove(thumbnailPath) == -1)
-                                       MSG_DEBUG("Fail to delete thumbnail [%s]", thumbnailPath);
-                               else
-                                       MSG_DEBUG("Success to delete thumbnail [%s]", thumbnailPath);
-                       }
-
-                       dbHandle.freeTable();
-               }
-
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID IN \
-                               (SELECT MSG_ID FROM %s WHERE CONV_ID = %d);",
-                               tableList[i], MSGFW_MESSAGE_TABLE_NAME, threadId);
-
-               // Delete Message in specific folder from table
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
-                       dbHandle.endTrans(false);
-                       err = MSG_ERR_DB_EXEC;
-
-                       goto FREE_MEMORY;
-               }
-       }
-
-       // Clear Conversation table
-       if (MsgStoClearConversationTable(&dbHandle) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               err = MSG_ERR_DB_EXEC;
-
-               goto FREE_MEMORY;
-       }
-
-       dbHandle.endTrans(true);
-
-       MSG_MESSAGE_TYPE_S msgType;
-
-       msgType.mainType = MSG_SMS_TYPE;
-       msgType.subType = MSG_NORMAL_SMS;
-       msgType.classType = MSG_CLASS_NONE;
-
-       // Set memory status in SIM
-       if (MsgStoCheckMsgCntFull(&dbHandle, &msgType, MSG_INBOX_ID) == MSG_SUCCESS) {
-               MSG_DEBUG("Set Memory Status");
-
-               MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
-
-               if (plg == NULL) {
-                       MSG_DEBUG("SMS Plug-in is NULL");
-                       err = MSG_ERR_NULL_POINTER;
-
-                       goto FREE_MEMORY;
-               }
-
-               plg->setMemoryStatus(MSG_SUCCESS);
-       }
-
-       // Set Indicator
-       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
-       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
-
-       MsgSettingSetIndicator(smsCnt, mmsCnt);
-
-/*** Set pMsgIdList **/
-       if (pMsgIdList != NULL && pToDeleteMsgIdList->nCount > 0) {
-               pMsgIdList->nCount = pToDeleteMsgIdList->nCount;
-
-               pMsgIdList->msgIdList = (msg_message_id_t *)new char[sizeof(msg_message_id_t)*pToDeleteMsgIdList->nCount];
-               memcpy(pMsgIdList->msgIdList, pToDeleteMsgIdList->msgIdList, sizeof(msg_message_id_t)*pToDeleteMsgIdList->nCount);
-       }
-/*** **/
-
-       /*** Create thread  for noti and phone log delete. **/
-       if (pToDeleteMsgIdList->nCount > 0) {
-               msg_id_list_s *pToDeleteMsgIdListCpy = NULL;
-               pToDeleteMsgIdListCpy = (msg_id_list_s *)new char[sizeof(msg_id_list_s)];
-               memset(pToDeleteMsgIdListCpy, 0x00, sizeof(msg_id_list_s));
-
-               pToDeleteMsgIdListCpy->nCount = pToDeleteMsgIdList->nCount;
-
-               pToDeleteMsgIdListCpy->msgIdList = (msg_message_id_t *)new char[sizeof(msg_message_id_t)*pToDeleteMsgIdList->nCount];
-               memcpy(pToDeleteMsgIdListCpy->msgIdList, pToDeleteMsgIdList->msgIdList, sizeof(msg_message_id_t)*pToDeleteMsgIdList->nCount);
-
-               if (g_idle_add(startToDeleteNoti, (void *)pToDeleteMsgIdList) == 0) {
-                       MSG_DEBUG("startToDeleteNoti not invoked: %s", strerror(errno));
-                       // memory free
-                       if (pToDeleteMsgIdList != NULL) {
-                               //free peer info list
-                               if (pToDeleteMsgIdList->msgIdList != NULL)
-                                       delete [] pToDeleteMsgIdList->msgIdList;
-
-                               delete [] pToDeleteMsgIdList;
-                       }
-                       err = MSG_ERR_UNKNOWN;
-               }
-
-               if (g_idle_add(startToDeletePhoneLog, (void *)pToDeleteMsgIdListCpy) == 0) {
-                       MSG_DEBUG("startToDeletePhoneLog not invoked: %s", strerror(errno));
-                       // memory free
-                       if (pToDeleteMsgIdListCpy != NULL) {
-                               //free peer info list
-                               if (pToDeleteMsgIdListCpy->msgIdList != NULL)
-                                       delete [] pToDeleteMsgIdListCpy->msgIdList;
-
-                               delete [] pToDeleteMsgIdListCpy;
-                       }
-                       err = MSG_ERR_UNKNOWN;
-               }
-       }
-       /*** **/
-
-       return MSG_SUCCESS;
-
-FREE_MEMORY:
-       MSG_DEBUG("Error case Free Memory");
-       // memory free
-       if (pToDeleteMsgIdList != NULL) {
-               //free peer info list
-               if (pToDeleteMsgIdList->msgIdList != NULL) {
-                       delete [] pToDeleteMsgIdList->msgIdList;
-                       pToDeleteMsgIdList->msgIdList = NULL;
-               }
-
-               delete [] pToDeleteMsgIdList;
-               pToDeleteMsgIdList = NULL;
-       }
-
-       return err;
-}
-
-
-msg_error_t MsgStoCountMsgByContact(const MSG_THREAD_LIST_INDEX_S *pAddrInfo, MSG_THREAD_COUNT_INFO_S *pThreadCountInfo)
-{
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       if (pAddrInfo->contactId > 0) {
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) AS TOTAL, \
-                               SUM(CASE WHEN READ_STATUS=0 AND FOLDER_ID=%d THEN 1 ELSE 0 END), \
-                               SUM(CASE WHEN MAIN_TYPE=%d THEN 1 ELSE 0 END), \
-                               SUM(CASE WHEN MAIN_TYPE=%d THEN 1 ELSE 0 END) \
-                               FROM (SELECT * FROM %s A  JOIN %s B ON A.ADDRESS_ID = B.ADDRESS_ID WHERE B.CONTACT_ID = %d)",
-                               MSG_INBOX_ID, MSG_SMS_TYPE, MSG_MMS_TYPE, MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, pAddrInfo->contactId);
-       } else {
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) AS TOTAL, \
-                               SUM(CASE WHEN READ_STATUS=0 AND FOLDER_ID=%d THEN 1 ELSE 0 END), \
-                               SUM(CASE WHEN MAIN_TYPE=%d THEN 1 ELSE 0 END), \
-                               SUM(CASE WHEN MAIN_TYPE=%d THEN 1 ELSE 0 END) \
-                               FROM (SELECT * FROM %s A  JOIN %s B ON A.ADDRESS_ID = B.ADDRESS_ID WHERE B.ADDRESS_VAL = '%s')",
-                               MSG_INBOX_ID, MSG_SMS_TYPE, MSG_MMS_TYPE, MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, pAddrInfo->msgAddrInfo.addressVal);
-       }
-
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
-
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               pThreadCountInfo->totalCount = dbHandle.columnInt(0);
-               pThreadCountInfo->unReadCount = dbHandle.columnInt(1);
-               pThreadCountInfo->smsMsgCount = dbHandle.columnInt(2);
-               pThreadCountInfo->mmsMsgCount = dbHandle.columnInt(3);
-       } else {
-               dbHandle.finalizeQuery();
-               return MSG_ERR_DB_STEP;
-       }
-
-       dbHandle.finalizeQuery();
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t MsgStoSearchMessage(const char *pSearchString, msg_struct_list_s *pThreadViewList)
-{
-       if (!pSearchString)
-               return MSG_ERR_NULL_POINTER;
-
-       // Clear Out Parameter
-       pThreadViewList->nCount = 0;
-       pThreadViewList->msg_struct_info = NULL;
-
-       tr1::unordered_set<msg_thread_id_t> IdList;
-       queue<MSG_THREAD_VIEW_S> searchList;
-
-       MSG_THREAD_VIEW_S threadView;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       // Replace string for '%' and '_' character
-       char *ext1_str = NULL;
-       char *ext2_str = NULL;
-
-       ext1_str = MsgStoReplaceString(pSearchString, "_", "\\_");
-       ext2_str = MsgStoReplaceString(ext1_str, "%", "\\%");
-
-       // Search - Address, Name
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT C.CONV_ID, C.UNREAD_CNT, C.SMS_CNT, C.MMS_CNT, C.DISPLAY_NAME, \
-                       B.MAIN_TYPE, B.SUB_TYPE, B.MSG_DIRECTION, B.DISPLAY_TIME, B.MSG_TEXT \
-                       FROM %s A, %s B, %s C \
-                       WHERE A.CONV_ID = B.CONV_ID AND B.FOLDER_ID > 0 AND B.FOLDER_ID < %d \
-                       AND ( B.MSG_TEXT LIKE '%%%s%%' ESCAPE '\\' \
-                       OR B.SUBJECT LIKE '%%%s%%' ESCAPE '\\' \
-                       OR A.ADDRESS_VAL LIKE '%%%s%%' ESCAPE '\\' \
-                       OR A.DISPLAY_NAME LIKE '%%%s%%' ESCAPE '\\' \
-                       OR A.FIRST_NAME LIKE '%%%s%%' ESCAPE '\\' \
-                       OR A.LAST_NAME LIKE '%%%s%%' ESCAPE '\\' ) \
-                       AND A.CONV_ID = C.CONV_ID \
-                       ORDER BY B.DISPLAY_TIME DESC;",
-                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, MSGFW_CONVERSATION_TABLE_NAME,
-                       MSG_SPAMBOX_ID, ext2_str, ext2_str, ext2_str, ext2_str, ext2_str, ext2_str);
-
-
-       if (ext1_str) {
-               free(ext1_str);
-               ext1_str = NULL;
-       }
-
-       if (ext2_str) {
-               free(ext2_str);
-               ext2_str = NULL;
-       }
-
-       MSG_DEBUG("[%s]", sqlQuery);
-
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-               MSG_DEBUG("Prepare query fail. [%s]", sqlQuery);
-               return MSG_ERR_DB_PREPARE;
-       }
-
-       while (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               memset(&threadView, 0x00, sizeof(threadView));
-
-               threadView.threadId = dbHandle.columnInt(0);
-               threadView.unreadCnt = dbHandle.columnInt(1);
-               threadView.smsCnt = dbHandle.columnInt(2);
-               threadView.mmsCnt = dbHandle.columnInt(3);
-
-               strncpy(threadView.threadName, (char *)dbHandle.columnText(4), MAX_THREAD_NAME_LEN);
-
-               threadView.mainType = dbHandle.columnInt(5);
-               threadView.subType = dbHandle.columnInt(6);
-
-               threadView.direction = dbHandle.columnInt(7);
-               threadView.threadTime = (time_t)dbHandle.columnInt(8);
-
-               strncpy(threadView.threadData, (char *)dbHandle.columnText(9), MAX_THREAD_DATA_LEN);
-
-               tr1::unordered_set<msg_thread_id_t>::iterator it;
-
-               it = IdList.find(threadView.threadId);
-
-               if (it == IdList.end()) {
-                       IdList.insert(threadView.threadId);
-                       searchList.push(threadView);
-               }
-
-       }
-
-       dbHandle.finalizeQuery();
-
-       // Add data to Out Parameter
-       pThreadViewList->nCount = searchList.size();
-       pThreadViewList->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t) * searchList.size()];
-
-       MSG_THREAD_VIEW_S *pTmp = NULL;
-       msg_struct_s *thread_t = NULL;
-
-       int index = 0;
-
-       while (!searchList.empty()) {
-               thread_t = (msg_struct_s *)new msg_struct_s;
-               pThreadViewList->msg_struct_info[index] = (msg_struct_t)thread_t;
-
-               thread_t->type = MSG_STRUCT_THREAD_INFO;
-               thread_t->data = new MSG_THREAD_VIEW_S;
-
-               pTmp = (MSG_THREAD_VIEW_S *)thread_t->data;
-               memset(pTmp, 0x00, sizeof(MSG_THREAD_VIEW_S));
-
-               memcpy(pTmp, &(searchList.front()), sizeof(MSG_THREAD_VIEW_S));
-
-               searchList.pop();
-
-               index++;
-       }
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t MsgStoSearchMessage(const MSG_SEARCH_CONDITION_S *pSearchCon, int offset, int limit, msg_struct_list_s *pMsgList)
-{
-       // Clear Out Parameter
-       pMsgList->nCount = 0;
-       pMsgList->msg_struct_info = NULL;
-
-       int rowCnt = 0;
-       int index = 26; // numbers of index
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-       char sqlQuerySubset[(MAX_QUERY_LEN/5)+1];
-
-       char firstName[MAX_DISPLAY_NAME_LEN+1], lastName[MAX_DISPLAY_NAME_LEN+1];
-       char displayName[MAX_DISPLAY_NAME_LEN+1];
-
-       char *ext1_str = NULL;
-       char *ext2_str = NULL;
-
-       // Get Name Order
-       int order = MsgGetContactNameOrder();
-
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.MSG_ID, A.CONV_ID, A.FOLDER_ID, A.STORAGE_ID, A.MAIN_TYPE, A.SUB_TYPE, \
-                       A.DISPLAY_TIME, A.DATA_SIZE, A.NETWORK_STATUS, A.READ_STATUS, A.PROTECTED, A.BACKUP, A.PRIORITY, \
-                       A.MSG_DIRECTION, A.SCHEDULED_TIME, A.SUBJECT, A.MSG_TEXT, B.ADDRESS_TYPE, B.RECIPIENT_TYPE, \
-                       B.CONTACT_ID, B.ADDRESS_VAL, B.DISPLAY_NAME, B.FIRST_NAME, B.LAST_NAME, A.ATTACHMENT_COUNT, A.THUMB_PATH \
-                       FROM %s A, %s B \
-                       WHERE A.CONV_ID = B.CONV_ID AND B.ADDRESS_ID <> 0 ",
-                       MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME);
-
-       //// folder
-       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
-
-       if (pSearchCon->folderId == MSG_ALLBOX_ID)
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.FOLDER_ID > 0 AND A.FOLDER_ID < %d ", MSG_CBMSGBOX_ID);
-       else if (pSearchCon->folderId == MSG_IOSBOX_ID)
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.FOLDER_ID > 0 AND A.FOLDER_ID < %d ", MSG_DRAFT_ID);
-       else
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.FOLDER_ID = %d ", pSearchCon->folderId);
-
-       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
-
-
-       //// msg type
-       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
-
-       switch (pSearchCon->msgType) {
-               case MSG_TYPE_SMS:
-                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.MAIN_TYPE = %d AND A.SUB_TYPE = %d ", MSG_SMS_TYPE, MSG_NORMAL_SMS);
-                       break;
-
-               case MSG_TYPE_MMS:
-                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.MAIN_TYPE = %d ", MSG_MMS_TYPE);
-                       break;
-
-               case MSG_TYPE_MMS_JAVA:
-                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.MAIN_TYPE = %d AND A.SUB_TYPE = %d ", MSG_MMS_TYPE, MSG_SENDREQ_JAVA_MMS);
-                       break;
-
-               case MSG_TYPE_SMS_SYNCML:
-                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.MAIN_TYPE = %d AND A.SUB_TYPE = %d ", MSG_SMS_TYPE, MSG_SYNCML_CP);
-                       break;
-
-               case MSG_TYPE_SMS_REJECT:
-                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.MAIN_TYPE = %d AND A.SUB_TYPE = %d ", MSG_SMS_TYPE, MSG_REJECT_SMS);
-                       break;
-
-               default:
-                       MSG_DEBUG("msg type is not set.");
-                       break;
-       }
-
-       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
-
-       /// string
-       if (pSearchCon->pSearchVal != NULL) {
-
-               // Replace string for '%' and '_' character
-               ext1_str = MsgStoReplaceString(pSearchCon->pSearchVal, "_", "\\_");
-               ext2_str = MsgStoReplaceString(ext1_str, "%", "\\%");
-
-               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND ( A.MSG_TEXT LIKE '%%%s%%' ESCAPE '\\' \
-                               OR A.SUBJECT LIKE '%%%s%%' ESCAPE '\\' \
-                               OR B.ADDRESS_VAL LIKE '%%%s%%' ESCAPE '\\' \
-                               OR B.DISPLAY_NAME LIKE '%%%s%%' ESCAPE '\\' \
-                               OR B.FIRST_NAME LIKE '%%%s%%' ESCAPE '\\' \
-                               OR B.LAST_NAME LIKE '%%%s%%' ESCAPE '\\') ",
-                               ext2_str, ext2_str, ext2_str, ext2_str, ext2_str, ext2_str);
-               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
-
-               if (ext1_str) {
-                       free(ext1_str);
-                       ext1_str = NULL;
-               }
-
-               if (ext2_str) {
-                       free(ext2_str);
-                       ext2_str = NULL;
-               }
-       }
-
-       /// address
-       if (pSearchCon->pAddressVal != NULL) {
-
-               // Replace string for '%' and '_' character
-               ext1_str = MsgStoReplaceString(pSearchCon->pAddressVal, "_", "\\_");
-               ext2_str = MsgStoReplaceString(ext1_str, "%", "\\%");
-
-               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND B.ADDRESS_VAL LIKE '%%%s%%' ESCAPE '\\' ", ext2_str);
-               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
-
-               if (ext1_str) {
-                       free(ext1_str);
-                       ext1_str = NULL;
-               }
-
-               if (ext2_str) {
-                       free(ext2_str);
-                       ext2_str = NULL;
-               }
-       }
-
-       /// limit, offset
-       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
-
-       if (offset >= 0 && limit > 0)
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "ORDER BY A.DISPLAY_TIME DESC LIMIT %d OFFSET %d;", limit, offset);
-       else
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "ORDER BY A.DISPLAY_TIME DESC;");
-
-       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
-
-       msg_error_t err = dbHandle.getTable(sqlQuery, &rowCnt);
-
-       if (err == MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
-
-               return MSG_SUCCESS;
-       } else if (err != MSG_SUCCESS) {
-               MSG_DEBUG("Get table fail. [%s]", sqlQuery);
-
-               dbHandle.freeTable();
-
-               return err;
-       }
-
-       pMsgList->nCount = rowCnt;
-
-       MSG_DEBUG("pMsgList->nCount [%d]", pMsgList->nCount);
-
-       pMsgList->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t) * rowCnt];
-
-       MSG_MESSAGE_HIDDEN_S *pTmp = NULL;
-       msg_struct_s *msg = NULL;
-
-       for (int i = 0; i < rowCnt; i++) {
-               pMsgList->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
-
-               msg = (msg_struct_s *)pMsgList->msg_struct_info[i];
-
-               msg->type = MSG_STRUCT_MESSAGE_INFO;
-               msg->data = (int *)new char[sizeof(MSG_MESSAGE_HIDDEN_S)];
-
-               pTmp = (MSG_MESSAGE_HIDDEN_S *)msg->data;
-
-               memset(pTmp, 0x00, sizeof(MSG_MESSAGE_HIDDEN_S));
-
-               pTmp->pData = NULL;
-               pTmp->pMmsData = NULL;
-
-               pTmp->msgId = dbHandle.getColumnToInt(index++);
-               pTmp->threadId = dbHandle.getColumnToInt(index++);
-               pTmp->folderId = dbHandle.getColumnToInt(index++);
-               pTmp->storageId = dbHandle.getColumnToInt(index++);
-               pTmp->mainType = dbHandle.getColumnToInt(index++);
-               pTmp->subType = dbHandle.getColumnToInt(index++);
-               pTmp->displayTime = (time_t)dbHandle.getColumnToInt(index++);
-               pTmp->dataSize = dbHandle.getColumnToInt(index++);
-               pTmp->networkStatus = dbHandle.getColumnToInt(index++);
-               pTmp->bRead = dbHandle.getColumnToInt(index++);
-               pTmp->bProtected = dbHandle.getColumnToInt(index++);
-               pTmp->bBackup = dbHandle.getColumnToInt(index++);
-               pTmp->priority = dbHandle.getColumnToInt(index++);
-               pTmp->direction= dbHandle.getColumnToInt(index++);
-               index++; // This field is reserved.
-
-               dbHandle.getColumnToString(index++, MAX_SUBJECT_LEN, pTmp->subject);
-
-               if (pTmp->mainType == MSG_MMS_TYPE &&
-                       (pTmp->networkStatus == MSG_NETWORK_RETRIEVING || pTmp->networkStatus == MSG_NETWORK_RETRIEVE_FAIL || pTmp->subType == MSG_NOTIFICATIONIND_MMS)) {
-                       pTmp->pData = NULL;
-                       index++;
-               } else {
-                       MSG_DEBUG("pTmp->dataSize [%d]", pTmp->dataSize);
-                       pTmp->pData = (void *)new char[pTmp->dataSize + 2];
-                       memset(pTmp->pData, 0x00, sizeof(pTmp->pData));
-
-                       dbHandle.getColumnToString(index++, pTmp->dataSize+1, (char *)pTmp->pData);
-               }
-
-               msg_struct_list_s *addr_list = (msg_struct_list_s *)new msg_struct_list_s;
-               msg_struct_s *addr_info = NULL;
-               MSG_ADDRESS_INFO_S *address = NULL;
-
-               addr_list->nCount = 1;
-               addr_list->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t *)*MAX_TO_ADDRESS_CNT];
-
-               msg_struct_s *pTmpAddr = NULL;
-
-               for (int i = 0; i < MAX_TO_ADDRESS_CNT; i++) {
-                       addr_list->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];
-                       pTmpAddr = (msg_struct_s *)addr_list->msg_struct_info[i];
-                       pTmpAddr->type = MSG_STRUCT_ADDRESS_INFO;
-                       pTmpAddr->data = new MSG_ADDRESS_INFO_S;
-                       memset(pTmpAddr->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
-
-                       addr_list->msg_struct_info[i] = (msg_struct_t)pTmpAddr;
-               }
-
-               addr_info = (msg_struct_s *)addr_list->msg_struct_info[0];
-               address = (MSG_ADDRESS_INFO_S *)addr_info->data;
-               address->addressType = dbHandle.getColumnToInt(index++);
-               address->recipientType = dbHandle.getColumnToInt(index++);
-               address->contactId = dbHandle.getColumnToInt(index++);
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
 
-               dbHandle.getColumnToString(index++, MAX_ADDRESS_VAL_LEN, address->addressVal);
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-               memset(displayName, 0x00, sizeof(displayName));
-               dbHandle.getColumnToString(index++, MAX_DISPLAY_NAME_LEN, displayName);
+       if (pAddrInfo->contactId > 0) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) AS TOTAL, \
+                               SUM(CASE WHEN READ_STATUS=0 AND FOLDER_ID=%d THEN 1 ELSE 0 END), \
+                               SUM(CASE WHEN MAIN_TYPE=%d THEN 1 ELSE 0 END), \
+                               SUM(CASE WHEN MAIN_TYPE=%d THEN 1 ELSE 0 END) \
+                               FROM (SELECT * FROM %s A  JOIN %s B ON A.CONV_ID = B.CONV_ID WHERE B.CONTACT_ID = %d)",
+                               MSG_INBOX_ID, MSG_SMS_TYPE, MSG_MMS_TYPE, MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, pAddrInfo->contactId);
+       } else {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) AS TOTAL, \
+                               SUM(CASE WHEN READ_STATUS=0 AND FOLDER_ID=%d THEN 1 ELSE 0 END), \
+                               SUM(CASE WHEN MAIN_TYPE=%d THEN 1 ELSE 0 END), \
+                               SUM(CASE WHEN MAIN_TYPE=%d THEN 1 ELSE 0 END) \
+                               FROM (SELECT * FROM %s A  JOIN %s B ON A.CONV_ID = B.CONV_ID WHERE B.ADDRESS_VAL = '%s')",
+                               MSG_INBOX_ID, MSG_SMS_TYPE, MSG_MMS_TYPE, MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, pAddrInfo->msgAddrInfo.addressVal);
+       }
 
-               memset(firstName, 0x00, sizeof(firstName));
-               dbHandle.getColumnToString(index++, MAX_DISPLAY_NAME_LEN, firstName);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
 
-               memset(lastName, 0x00, sizeof(lastName));
-               dbHandle.getColumnToString(index++, MAX_DISPLAY_NAME_LEN, lastName);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               pThreadCountInfo->totalCount = dbHandle->columnInt(0);
+               pThreadCountInfo->unReadCount = dbHandle->columnInt(1);
+               pThreadCountInfo->smsMsgCount = dbHandle->columnInt(2);
+               pThreadCountInfo->mmsMsgCount = dbHandle->columnInt(3);
+       } else {
+               dbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
 
-               if (strlen(displayName) <= 0) {
-                       if (order == 0) {
-                               if (firstName[0] != '\0') {
-                                       strncpy(displayName, firstName, MAX_DISPLAY_NAME_LEN);
-                               }
+       dbHandle->finalizeQuery();
 
-                               if (lastName[0] != '\0') {
-                                       strncat(displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                                       strncat(displayName, lastName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-                       } else if (order == 1) {
-                               if (lastName[0] != '\0') {
-                                       strncpy(displayName, lastName, MAX_DISPLAY_NAME_LEN);
-                                       strncat(displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
+       return MSG_SUCCESS;
+}
 
-                               if (firstName[0] != '\0') {
-                                       strncat(displayName, firstName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-                       }
-               }
 
-               strncpy(address->displayName, displayName, MAX_DISPLAY_NAME_LEN);
+msg_error_t MsgStoGetSyncMLExtId(msg_message_id_t msgId, int *extId)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
 
-               pTmp->addr_list = addr_list;
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-               pTmp->attachCount = dbHandle.getColumnToInt(index++);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT EXT_ID FROM %s WHERE MSG_ID = %d;",
+                       MSGFW_SYNCML_MSG_TABLE_NAME, msgId);
 
-               dbHandle.getColumnToString(index++, MSG_FILEPATH_LEN_MAX, pTmp->thumbPath);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
 
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               *extId = dbHandle->columnInt(0);
+       } else {
+               dbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
        }
-       dbHandle.freeTable();
-
-       return MSG_SUCCESS;
-}
-
-
-void MsgConvertNumber(const char *pSrcNum, char *pDestNum)
-{
-       int overLen = 0;
-       int i = 0;
-
-       overLen = strlen(pSrcNum) - MAX_PRECONFIG_NUM;
 
-       for (i = 0; i < MAX_PRECONFIG_NUM; i++)
-               pDestNum[i] = pSrcNum[i+overLen];
+       dbHandle->finalizeQuery();
 
-       pDestNum[i] = '\0';
+       return MSG_SUCCESS;
 }
 
 
-msg_error_t MsgStoGetRejectMsgList(const char *pNumber, msg_struct_list_s *pRejectMsgList)
+msg_error_t MsgStoGetSmsReportStatus(msg_message_id_t msgId, int *count, MSG_REPORT_STATUS_INFO_S **pReportStatus)
 {
-       // Clear Out Parameter
-       pRejectMsgList->nCount = 0;
-       pRejectMsgList->msg_struct_info = NULL;
-
-       int rowCnt = 0;
-       int index = 3; // numbers of index
-
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
+       msg_error_t err = MSG_SUCCESS;
 
-       // Search Reject Msg
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "SELECT ADDRESS_VAL, STATUS_TYPE, STATUS, TIME "
+                       "FROM %s "
+                       "WHERE MSG_ID = %d "
+                       "order by TIME ASC;"
+                       , MSGFW_SMS_REPORT_TABLE_NAME, msgId);
 
-       if (pNumber != NULL) {
-               char phoneNumber[MAX_PRECONFIG_NUM+1];
-               memset(phoneNumber, 0x00, sizeof(phoneNumber));
-
-               if (strlen(pNumber) > MAX_PRECONFIG_NUM)
-                       MsgConvertNumber(pNumber, phoneNumber);
-               else
-                       strncpy(phoneNumber, pNumber, MAX_PRECONFIG_NUM);
-
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT B.MSG_ID, B.MSG_TEXT, B.DISPLAY_TIME \
-                               FROM %s A, %s B \
-                               WHERE A.CONV_ID = B.CONV_ID AND B.MAIN_TYPE = %d \
-                               AND B.SUB_TYPE = %d AND A.ADDRESS_VAL LIKE '%%%s' \
-                               ORDER BY B.DISPLAY_TIME DESC;",
-                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
-                               MSG_SMS_TYPE, MSG_REJECT_SMS, phoneNumber);
-       } else {
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT B.MSG_ID, B.MSG_TEXT, B.DISPLAY_TIME \
-                               FROM %s A, %s B \
-                               WHERE A.CONV_ID = B.CONV_ID AND B.MAIN_TYPE = %d AND B.SUB_TYPE = %d \
-                               ORDER BY B.DISPLAY_TIME DESC;",
-                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
-                               MSG_SMS_TYPE, MSG_REJECT_SMS);
-       }
-
-       msg_error_t  err = dbHandle.getTable(sqlQuery, &rowCnt);
+       int rowCnt = 0, index = 0;
+       err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
 
        if (err != MSG_SUCCESS) {
-               MSG_DEBUG("%s", sqlQuery);
-
-               dbHandle.freeTable();
-
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
                return err;
        }
 
-       pRejectMsgList->nCount = rowCnt;
-
-       MSG_DEBUG("pRejectMsgList->nCount [%d]", pRejectMsgList->nCount);
-
-       pRejectMsgList->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_REJECT_MSG_INFO_S *)*rowCnt];
-
-       msg_struct_s* pTmp = NULL;
+       *count =  rowCnt;
+       MSG_REPORT_STATUS_INFO_S *report_status = (MSG_REPORT_STATUS_INFO_S*)new char[sizeof(MSG_REPORT_STATUS_INFO_S)*rowCnt];
+       memset(report_status, 0x00, sizeof(MSG_REPORT_STATUS_INFO_S)*rowCnt);
 
        for (int i = 0; i < rowCnt; i++) {
-               pRejectMsgList->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];
+               dbHandle->getColumnToString(index++, MAX_ADDRESS_VAL_LEN, report_status[i].addressVal);
+               report_status[i].type = dbHandle->getColumnToInt(index++);
+               report_status[i].status = dbHandle->getColumnToInt(index++);
+               report_status[i].statusTime = (time_t)dbHandle->getColumnToInt(index++);
 
-               pTmp = (msg_struct_s *)pRejectMsgList->msg_struct_info[i];
-               pTmp->type = MSG_STRUCT_REJECT_MSG_INFO;
-               pTmp->data = new char[sizeof(MSG_FOLDER_INFO_S)];
-               MSG_REJECT_MSG_INFO_S * pMsg = (MSG_REJECT_MSG_INFO_S *)pTmp->data;
-               memset(pMsg, 0x00, sizeof(MSG_REJECT_MSG_INFO_S));
-
-               pMsg->msgId = dbHandle.getColumnToInt(index++);
-               memset(pMsg->msgText, 0x00, sizeof(pMsg->msgText));
-               dbHandle.getColumnToString(index++, MAX_MSG_TEXT_LEN, pMsg->msgText);
-
-               pMsg->displayTime = (time_t)dbHandle.getColumnToInt(index++);
+               MSG_SEC_DEBUG("(%d/%d) address = %s, report_type = %d, report_status = %d, report_time = %d", i+1, rowCnt, report_status[i].addressVal, report_status[i].type, report_status[i].status, report_status[i].statusTime);
        }
 
-       dbHandle.freeTable();
+       *pReportStatus = report_status;
+
+       dbHandle->freeTable();
 
        return MSG_SUCCESS;
 }
 
-
-msg_error_t MsgStoGetSyncMLExtId(msg_message_id_t msgId, int *extId)
+msg_error_t MsgStoGetMmsReportStatus(msg_message_id_t msgId, int *count, MSG_REPORT_STATUS_INFO_S **pReportStatus)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       msg_direction_type_t    direction = MSG_DIRECTION_TYPE_MO;
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT EXT_ID FROM %s WHERE MSG_ID = %d;",
-                       MSGFW_SYNCML_MSG_TABLE_NAME, msgId);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_DIRECTION FROM %s WHERE MSG_ID = %d;",
+                       MSGFW_MESSAGE_TABLE_NAME, msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               *extId = dbHandle.columnInt(0);
-       } else {
-               dbHandle.finalizeQuery();
-               return MSG_ERR_DB_STEP;
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               direction = dbHandle->columnInt(0);
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
-       return MSG_SUCCESS;
-}
+       if (direction == MSG_DIRECTION_TYPE_MO) {//get received report list of MO message
 
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               //MSG_ID INTEGER , ADDRESS_VAL TEXT , STATUS_TYPE INTEGER , STATUS INTEGER DEFAULT 0 , TIME DATETIME)
+               //select * from MSG_REPORT_TABLE where MSG_ID=38 order by ADDRESS_VAL DESC, STATUS_TYPE ASC;
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT ADDRESS_VAL, STATUS_TYPE, STATUS, TIME "
+                               "FROM %s "
+                               "WHERE MSG_ID = %d "
+                               "order by ADDRESS_VAL DESC, STATUS_TYPE ASC;"
+                               , MSGFW_REPORT_TABLE_NAME, msgId);
+
+               int rowCnt = 0, index = 0;
+               msg_error_t  err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("Fail to getTable().");
+                       dbHandle->freeTable();
+                       return err;
+               }
 
-msg_error_t MsgStoGetReportStatus(msg_message_id_t msgId, MSG_REPORT_STATUS_INFO_S *pReportStatus)
-{
-       char sqlQuery[MAX_QUERY_LEN+1];
+               *count = rowCnt;
+               MSG_REPORT_STATUS_INFO_S *report_status = (MSG_REPORT_STATUS_INFO_S*)new char[sizeof(MSG_REPORT_STATUS_INFO_S)*rowCnt];
+               memset(report_status, 0x00, sizeof(MSG_REPORT_STATUS_INFO_S)*rowCnt);
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               for (int i = 0; i < rowCnt; i++) {
+                       dbHandle->getColumnToString(index++, MAX_ADDRESS_VAL_LEN, report_status[i].addressVal);
+                       report_status[i].type = dbHandle->getColumnToInt(index++);
+                       report_status[i].status = dbHandle->getColumnToInt(index++);
+                       report_status[i].statusTime = (time_t)dbHandle->getColumnToInt(index++);
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DELIVERY_REPORT_STATUS, \
-                       DELIVERY_REPORT_TIME, READ_REPORT_STATUS, READ_REPORT_TIME \
-                       FROM %s WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, msgId);
+                       MSG_DEBUG("(%d/%d) addr = %s, report_type = %d, report_status = %d, report_time = %d", i+1, rowCnt, report_status[i].addressVal, report_status[i].type, report_status[i].status, report_status[i].statusTime );
+               }
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
+               *pReportStatus = report_status;
+
+               dbHandle->freeTable();
+
+       } else if (direction == MSG_DIRECTION_TYPE_MT) {//read report sent status of MT message
+
+               int readReportSentStatus;
+
+               if (MsgStoCheckReadReportRequested(dbHandle, msgId) == false) {
+                       *count = 0;
+                       *pReportStatus = NULL;
+                       return MSG_ERR_READREPORT_NOT_REQUESTED;
+               }
+
+               MsgStoGetReadReportSendStatus(msgId, &readReportSentStatus);
+
+               *count =  1;
+
+               MSG_REPORT_STATUS_INFO_S *report_status = (MSG_REPORT_STATUS_INFO_S*)new char[sizeof(MSG_REPORT_STATUS_INFO_S)];
+               memset(report_status, 0x00, sizeof(MSG_REPORT_STATUS_INFO_S));
+
+               report_status->addressVal[0] = '\0';
+               report_status->type = MSG_REPORT_TYPE_READ_REPORT_SENT;
+               report_status->status = readReportSentStatus;
+               report_status->statusTime = 0;
+
+               MSG_DEBUG("report_type = %d, report_status = %d", report_status->type, report_status->status);
+
+               *pReportStatus = report_status;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               pReportStatus->deliveryStatus = (msg_delivery_report_status_t)dbHandle.columnInt(0);
-               pReportStatus->deliveryStatusTime = (time_t)dbHandle.columnInt(1);
-               pReportStatus->readStatus = (msg_read_report_status_t)dbHandle.columnInt(2);
-               pReportStatus->readStatusTime = (time_t)dbHandle.columnInt(3);
-       }
 
-       dbHandle.finalizeQuery();
+       }
 
        return MSG_SUCCESS;
 }
@@ -2965,16 +2597,23 @@ msg_error_t MsgStoGetReportStatus(msg_message_id_t msgId, MSG_REPORT_STATUS_INFO
 
 msg_error_t MsgStoGetThreadIdByAddress(const MSG_MESSAGE_INFO_S *pMsg, msg_thread_id_t *pThreadId)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        if(pMsg->nAddressCnt > 0) {
-               if (MsgExistAddress(&dbHandle, pMsg, pThreadId) == true) {
+               if (MsgExistAddress(dbHandle, pMsg, pThreadId) == true) {
                        MSG_DEBUG("Conversation ID : [%d]", *pThreadId);
-               } else {
-                       *pThreadId = 0;
-                       return MSG_ERR_STORAGE_ERROR;
+
+                       // check thread count
+                       MSG_THREAD_VIEW_S threadInfo;
+                       memset(&threadInfo, 0x00, sizeof(MSG_THREAD_VIEW_S));
+                       MsgStoGetThreadInfo(*pThreadId, &threadInfo);
+                       MSG_DEBUG("threadInfo.smsCnt [%d], threadInfo.mmsCnt [%d]", threadInfo.smsCnt, threadInfo.mmsCnt);
+                       if ((threadInfo.smsCnt + threadInfo.mmsCnt) > 0) {
+                               return MSG_SUCCESS;
+                       }
                }
-       } else {
-               *pThreadId = 0;
        }
+
+       *pThreadId = 0;
        return MSG_SUCCESS;
 }
 
@@ -2983,26 +2622,25 @@ msg_error_t MsgStoGetThreadUnreadCnt(msg_thread_id_t threadId, int *cnt)
 {
        MSG_BEGIN();
 
+       MsgDbHandler *dbHandle = getDbHandle();
        int msgCnt = 0;
        *cnt = 0;
 
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
        // Get MSG_ID
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s A \
                        WHERE CONV_ID = %d AND READ_STATUS = 0;", MSGFW_MESSAGE_TABLE_NAME, threadId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               msgCnt = dbHandle.columnInt(0);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               msgCnt = dbHandle->columnInt(0);
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        *cnt = msgCnt;
 
@@ -3012,69 +2650,85 @@ msg_error_t MsgStoGetThreadUnreadCnt(msg_thread_id_t threadId, int *cnt)
 }
 
 
-msg_error_t MsgStoGetAddressList(const msg_thread_id_t threadId, msg_struct_list_s *pAddrList)
-{
-       msg_error_t err = MSG_SUCCESS;
-
-       int order = MsgGetContactNameOrder();
-
-       err = MsgStoGetAddressByConvId(&dbHandle, threadId, order, pAddrList);
-
-       return err;
-}
-
-
 msg_error_t MsgStoGetThreadInfo(msg_thread_id_t threadId, MSG_THREAD_VIEW_S *pThreadInfo)
 {
        MSG_BEGIN();
 
-       int rowCnt;
-       int index = 10; // numbers of index
+       MsgDbHandler *dbHandle = getDbHandle();
+       int rowCnt = 0, index = 0;
 
        char sqlQuery[MAX_QUERY_LEN+1];
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CONV_ID, UNREAD_CNT, SMS_CNT, MMS_CNT, \
-                       MAIN_TYPE, SUB_TYPE, MSG_DIRECTION, DISPLAY_TIME, DISPLAY_NAME, MSG_TEXT \
-                       FROM %s WHERE CONV_ID = %d;",
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.CONV_ID, A.UNREAD_CNT, A.SMS_CNT, A.MMS_CNT, "
+                       "A.MAIN_TYPE, A.SUB_TYPE, A.MSG_DIRECTION, A.DISPLAY_TIME, A.DISPLAY_NAME, A.MSG_TEXT, "
+                       "(SELECT COUNT(*) FROM %s B WHERE B.CONV_ID = A.CONV_ID AND B.PROTECTED = 1) AS PROTECTED, "
+                       "(SELECT COUNT(*) FROM %s B WHERE B.CONV_ID = A.CONV_ID AND B.FOLDER_ID = %d) AS DRAFT, "
+                       "(SELECT COUNT(*) FROM %s B WHERE B.CONV_ID = A.CONV_ID AND B.NETWORK_STATUS = %d) AS FAILED, "
+                       "(SELECT COUNT(*) FROM %s B WHERE B.CONV_ID = A.CONV_ID AND B.NETWORK_STATUS = %d) AS SENDING, "
+                       "(SELECT SIM_INDEX FROM %s B WHERE B.CONV_ID = A.CONV_ID) "
+                       "FROM %s A WHERE A.CONV_ID = %d AND A.SMS_CNT + A.MMS_CNT > 0;",
+                       MSGFW_MESSAGE_TABLE_NAME,
+                       MSGFW_MESSAGE_TABLE_NAME, MSG_DRAFT_ID,
+                       MSGFW_MESSAGE_TABLE_NAME, MSG_NETWORK_SEND_FAIL,
+                       MSGFW_MESSAGE_TABLE_NAME, MSG_NETWORK_SENDING,
+                       MSGFW_MESSAGE_TABLE_NAME,
                        MSGFW_CONVERSATION_TABLE_NAME, threadId);
 
-       msg_error_t  err = dbHandle.getTable(sqlQuery, &rowCnt);
+       msg_error_t err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
 
        if (err == MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
+               dbHandle->freeTable();
                return MSG_SUCCESS;
        } else if (err != MSG_SUCCESS) {
-               MSG_DEBUG("%s", sqlQuery);
-               dbHandle.freeTable();
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
                return err;
        }
 
        if (rowCnt < 1) {
                MSG_DEBUG("rowCnt is %d", rowCnt);
-               dbHandle.freeTable();
+               dbHandle->freeTable();
                return err;
        } else {
-               pThreadInfo->threadId = dbHandle.getColumnToInt(index++);
+               pThreadInfo->threadId = dbHandle->getColumnToInt(index++);
 
-               pThreadInfo->unreadCnt = dbHandle.getColumnToInt(index++);
-               pThreadInfo->smsCnt = dbHandle.getColumnToInt(index++);
-               pThreadInfo->mmsCnt = dbHandle.getColumnToInt(index++);
+               pThreadInfo->unreadCnt = dbHandle->getColumnToInt(index++);
+               pThreadInfo->smsCnt = dbHandle->getColumnToInt(index++);
+               pThreadInfo->mmsCnt = dbHandle->getColumnToInt(index++);
 
-               pThreadInfo->mainType = dbHandle.getColumnToInt(index++);
-               pThreadInfo->subType = dbHandle.getColumnToInt(index++);
+               pThreadInfo->mainType = dbHandle->getColumnToInt(index++);
+               pThreadInfo->subType = dbHandle->getColumnToInt(index++);
 
-               pThreadInfo->direction = dbHandle.getColumnToInt(index++);
-               pThreadInfo->threadTime = (time_t)dbHandle.getColumnToInt(index++);
+               pThreadInfo->direction = dbHandle->getColumnToInt(index++);
+               pThreadInfo->threadTime = (time_t)dbHandle->getColumnToInt(index++);
 
                memset(pThreadInfo->threadName, 0x00, sizeof(pThreadInfo->threadName));
-               dbHandle.getColumnToString(index++, MAX_THREAD_NAME_LEN, pThreadInfo->threadName);
+               dbHandle->getColumnToString(index++, MAX_THREAD_NAME_LEN, pThreadInfo->threadName);
 
                memset(pThreadInfo->threadData, 0x00, sizeof(pThreadInfo->threadData));
-               dbHandle.getColumnToString(index++, MAX_THREAD_DATA_LEN, pThreadInfo->threadData);
+               dbHandle->getColumnToString(index++, MAX_THREAD_DATA_LEN, pThreadInfo->threadData);
+
+               int protectedCnt = dbHandle->getColumnToInt(index++);
+               if (protectedCnt > 0)
+                       pThreadInfo->bProtected = true;
+
+               int draftCnt = dbHandle->getColumnToInt(index++);
+               if (draftCnt > 0)
+                       pThreadInfo->bDraft = true;
+
+               int failedCnt = dbHandle->getColumnToInt(index++);
+               if (failedCnt > 0)
+                       pThreadInfo->bSendFailed = true;
+
+               int sendingCnt = dbHandle->getColumnToInt(index++);
+               if (sendingCnt > 0)
+                       pThreadInfo->bSending = true;
+
+               pThreadInfo->simIndex = dbHandle->getColumnToInt(index++);
        }
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        MSG_END();
 
@@ -3082,176 +2736,366 @@ msg_error_t MsgStoGetThreadInfo(msg_thread_id_t threadId, MSG_THREAD_VIEW_S *pTh
 }
 
 
-msg_error_t MsgStoGetMessageList(msg_folder_id_t folderId, msg_thread_id_t threadId, msg_message_type_t msgType, msg_storage_id_t storageId, msg_struct_list_s *pMsgList)
+msg_error_t MsgStoRestoreMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo)
 {
-       // Clear Out Parameter
-       pMsgList->nCount = 0;
-       pMsgList->msg_struct_info = NULL;
-
-       int rowCnt = 0;
-       int index = 19; // numbers of index
+       MSG_BEGIN();
 
+       MsgDbHandler *dbHandle = getDbHandle();
+       msg_error_t err = MSG_SUCCESS;
        char sqlQuery[MAX_QUERY_LEN+1];
-       char sqlQuerySubset[(MAX_QUERY_LEN/5)+1];
 
-       // Get Name Order
-       int order = MsgGetContactNameOrder();
+       if(MsgExistConversation(dbHandle, pMsg->threadId))
+       {
+               // add message to address table  which having same thread_id and datetime;
+               for (int i=0; i<pMsg->nAddressCnt; i++) {
+                       if(MsgExistAddress(dbHandle, pMsg, pMsg->threadId, i) == false)
+                       {
+                               unsigned int addrId;
+                               MSG_CONTACT_INFO_S contactInfo;
+                               memset(&contactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+                               // Get Contact Info
+//                             if (MsgGetContactInfo(&(pMsg->addressList[i]), &contactInfo) != MSG_SUCCESS) {
+//                                     MSG_DEBUG("MsgGetContactInfo() fail.");
+//                             }
+                               err = dbHandle->getRowId(MSGFW_ADDRESS_TABLE_NAME, &addrId);
+                               if (err != MSG_SUCCESS) {
+                                       MSG_DEBUG("pDbHandle->getRowId fail. [%d]", err);
+                                       return err;
+                               }
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                               // Add Address
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, '%s', %d, %d, ?, ?, ?, ?, ?, '%s', 0);",
+                                                       MSGFW_ADDRESS_TABLE_NAME, addrId, pMsg->threadId, pMsg->addressList[i].addressType, pMsg->addressList[i].recipientType, pMsg->addressList[i].addressVal,
+                                                       contactInfo.contactId, contactInfo.addrbookId, contactInfo.imagePath);
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID, CONV_ID, FOLDER_ID, STORAGE_ID, MAIN_TYPE, SUB_TYPE, \
-                       DISPLAY_TIME, DATA_SIZE, NETWORK_STATUS, READ_STATUS, PROTECTED, BACKUP, PRIORITY, \
-                       MSG_DIRECTION, SCHEDULED_TIME, SUBJECT, MSG_TEXT, ATTACHMENT_COUNT, THUMB_PATH \
-                       FROM %s WHERE ", MSGFW_MESSAGE_TABLE_NAME);
+                               MSG_SEC_DEBUG("Add Address Info. [%s]", sqlQuery);
 
+                               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+                                       return MSG_ERR_DB_PREPARE;
 
-       //// folder
-       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                               dbHandle->bindText(contactInfo.firstName, 1);
+                               dbHandle->bindText(contactInfo.lastName, 2);
+                               dbHandle->bindText(contactInfo.middleName, 3);
+                               dbHandle->bindText(contactInfo.prefix, 4);
+                               dbHandle->bindText(contactInfo.suffix, 5);
 
-       if (folderId == MSG_ALLBOX_ID)
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "FOLDER_ID > 0 AND FOLDER_ID < %d ", MSG_CBMSGBOX_ID);
-       else if (folderId == MSG_IOSBOX_ID)
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "FOLDER_ID > 0 AND FOLDER_ID < %d ", MSG_DRAFT_ID);
-       else
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "FOLDER_ID = %d ", folderId);
+                               if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                                       dbHandle->finalizeQuery();
+                                       return MSG_ERR_DB_STEP;
+                               }
+
+                               dbHandle->finalizeQuery();
 
-       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+                               // set conversation display name by conv id
+                               MsgStoSetConversationDisplayName(dbHandle, pMsg->threadId);
+                       }
+               }
 
 
-       //// thread
-       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               if(!MsgExistMessage(dbHandle, pMsg))
+               {
+                       unsigned int rowId = 0;
 
-       if (threadId > 0)
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND CONV_ID = %d ", threadId);
+                       if(pMsg->threadId > 0 && pMsg->folderId == MSG_DRAFT_ID) {
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+                               snprintf(sqlQuery, sizeof(sqlQuery),
+                                               "DELETE FROM %s WHERE CONV_ID = %d AND FOLDER_ID = %d;",
+                                               MSGFW_MESSAGE_TABLE_NAME, pMsg->threadId, MSG_DRAFT_ID);
 
+                               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
 
-       //// msg type
-       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                               err = dbHandle->execQuery(sqlQuery);
 
-       switch (msgType) {
-               case MSG_TYPE_SMS:
-                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND MAIN_TYPE = %d AND SUB_TYPE = %d ", MSG_SMS_TYPE, MSG_NORMAL_SMS);
-                       break;
+                               if (err != MSG_SUCCESS) {
+                                       MSG_DEBUG("fail to delete draft messages.");
+                               }
+                       }
 
-               case MSG_TYPE_MMS:
-                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND MAIN_TYPE = %d ", MSG_MMS_TYPE);
-                       break;
+                       err = dbHandle->getRowId(MSGFW_MESSAGE_TABLE_NAME, &rowId);
 
-               case MSG_TYPE_MMS_JAVA:
-                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND MAIN_TYPE = %d AND SUB_TYPE = %d ", MSG_MMS_TYPE, MSG_SENDREQ_JAVA_MMS);
-                       break;
+                       pMsg->msgId = (msg_message_id_t)rowId;
 
-               case MSG_TYPE_SMS_SYNCML:
-                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND MAIN_TYPE = %d AND SUB_TYPE = %d ", MSG_SMS_TYPE, MSG_SYNCML_CP);
-                       break;
+                       int fileSize = 0;
 
-               case MSG_TYPE_SMS_REJECT:
-                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND MAIN_TYPE = %d AND SUB_TYPE = %d ", MSG_SMS_TYPE, MSG_REJECT_SMS);
-                       break;
+                       char *pFileData = NULL;
+                       unique_ptr<char*, void(*)(char**)> buf(&pFileData, unique_ptr_deleter);
 
-               default:
-                       MSG_DEBUG("msg type is not set.");
-       }
+                       // Get File Data
+                       if (pMsg->bTextSms == false) {
+                               if (MsgOpenAndReadFile(pMsg->msgData, &pFileData, &fileSize) == false) {
+                                       return MSG_ERR_STORAGE_ERROR;
+                               }
+                               MSG_DEBUG("file size [%d]", fileSize);
+                       }
 
-       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+                       char keyName[MAX_VCONFKEY_NAME_LEN];
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_IMSI, pMsg->sim_idx);
 
-       //// storage
-       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                       char *imsi = MsgSettingGetString(keyName);
 
-       if (storageId > MSG_STORAGE_UNKNOWN)
-               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND STORAGE_ID = %d ", storageId);
+                       // Add Message
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, %d, %d, %ld, %d, %d, %d, %d, %d, %d, 0, %d, ?, '', '', ?, 0, %d, '%s');",
+                                       MSGFW_MESSAGE_TABLE_NAME, rowId, pMsg->threadId, pMsg->folderId, pMsg->storageId, pMsg->msgType.mainType, pMsg->msgType.subType,
+                                       pMsg->displayTime, pMsg->dataSize, pMsg->networkStatus, pMsg->bRead, pMsg->bProtected, pMsg->priority, pMsg->direction,
+                                       pMsg->bBackup, pMsg->sim_idx, imsi);
 
 
-       /// order
-       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
-       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "ORDER BY DISPLAY_TIME DESC;");
+                       MSG_DEBUG("QUERY : %s", sqlQuery);
 
-       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+                       if (imsi) {
+                               free(imsi);
+                               imsi = NULL;
+                       }
 
-       msg_error_t err = dbHandle.getTable(sqlQuery, &rowCnt);
+                       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                               return MSG_ERR_DB_EXEC;
+                       }
 
-       if (err == MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
+                       dbHandle->bindText(pMsg->subject, 1);
 
-               return MSG_SUCCESS;
-       } else if (err != MSG_SUCCESS) {
-               MSG_DEBUG("Get table fail. [%s]", sqlQuery);
+                       if (pMsg->bTextSms == false)
+                               dbHandle->bindText(pFileData, 2);
+                       else
+                               dbHandle->bindText(pMsg->msgText, 2);
 
-               dbHandle.freeTable();
+                       if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                               dbHandle->finalizeQuery();
+                               return MSG_ERR_DB_EXEC;
+                       }
 
-               return err;
+                       dbHandle->finalizeQuery();
+
+                       if (pMsg->msgType.subType != MSG_SENDREQ_MMS) {
+                               err = MsgStoUpdateConversation(dbHandle, pMsg->threadId);
+
+                               if (err != MSG_SUCCESS) {
+                                       return err;
+                               }
+                       }
+
+                       /* In the case of MMS Message, load the MMS plugin to save MMS PDU */
+                       if (pMsg->msgType.mainType == MSG_MMS_TYPE) {
+                               if (pMsg->msgType.subType != MSG_DELIVERYIND_MMS && pMsg->msgType.subType != MSG_READORGIND_MMS) {
+                                       MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_MMS_TYPE);
+                                       if (plg == NULL)
+                                               return MSG_ERR_NULL_POINTER;
+
+                                       err = plg->addMessage(pMsg, pSendOptInfo, pFileData);
+
+                                       if (err != MSG_SUCCESS)
+                                               return MSG_ERR_STORAGE_ERROR;
+
+                                       if (pMsg->msgType.subType == MSG_SENDREQ_MMS) {
+                                               MSG_SEC_DEBUG("pMsg->msgText: %s, pMsg->thumbPath: %s ", pMsg->msgText, pMsg->thumbPath);
+
+                                               err = MsgStoUpdateMMSMessage(pMsg);
+
+                                               if (err != MSG_SUCCESS)
+                                                       return MSG_ERR_STORAGE_ERROR;
+
+                                       }
+                               }
+                       }
+
+               }
+       }
+       else
+       {
+               // add message to conversation, message, address table;
+               pMsg->msgId = 0;
+               err = MsgStoAddMessage(pMsg, pSendOptInfo);
        }
 
-       pMsgList->nCount = rowCnt;
+       MSG_END();
 
-       MSG_DEBUG("pMsgList->nCount [%d]", pMsgList->nCount);
+       return err;
+}
 
-       pMsgList->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t) * rowCnt];
 
-       MSG_MESSAGE_HIDDEN_S *pTmp = NULL;
-       msg_struct_s *msg = NULL;
+msg_message_id_t MsgStoAddSimMessage(MSG_MESSAGE_INFO_S *pMsg, int *simIdList, int listSize)
+{
+       MSG_BEGIN();
+       MsgDbHandler *dbHandle = getDbHandle();
+       if (pMsg == NULL || pMsg->msgType.mainType == MSG_MMS_TYPE) {
+               MSG_DEBUG("pMsg == NULL || pMsg->msgType.mainType == MSG_MMS_TYPE");
+               return 0;
+       }
 
-       for (int i = 0; i < rowCnt; i++) {
-               pMsgList->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
-
-               msg = (msg_struct_s *)pMsgList->msg_struct_info[i];
-
-               msg->type = MSG_STRUCT_MESSAGE_INFO;
-               msg->data = (int *)new char[sizeof(MSG_MESSAGE_HIDDEN_S)];
-
-               pTmp = (MSG_MESSAGE_HIDDEN_S *)msg->data;
-
-               memset(pTmp, 0x00, sizeof(MSG_MESSAGE_HIDDEN_S));
-
-               pTmp->pData = NULL;
-               pTmp->pMmsData = NULL;
-
-               pTmp->msgId = dbHandle.getColumnToInt(index++);
-               pTmp->threadId = dbHandle.getColumnToInt(index++);
-               pTmp->folderId = dbHandle.getColumnToInt(index++);
-               pTmp->storageId = dbHandle.getColumnToInt(index++);
-               pTmp->mainType = dbHandle.getColumnToInt(index++);
-               pTmp->subType = dbHandle.getColumnToInt(index++);
-               pTmp->displayTime = (time_t)dbHandle.getColumnToInt(index++);
-               pTmp->dataSize = dbHandle.getColumnToInt(index++);
-               pTmp->networkStatus = dbHandle.getColumnToInt(index++);
-               pTmp->bRead = dbHandle.getColumnToInt(index++);
-               pTmp->bProtected = dbHandle.getColumnToInt(index++);
-               pTmp->bBackup = dbHandle.getColumnToInt(index++);
-               pTmp->priority = dbHandle.getColumnToInt(index++);
-               pTmp->direction = dbHandle.getColumnToInt(index++);
-               index++; // This field is reserved.
-
-               dbHandle.getColumnToString(index++, MAX_SUBJECT_LEN, pTmp->subject);
-
-               if (pTmp->mainType == MSG_MMS_TYPE &&
-                       (pTmp->networkStatus == MSG_NETWORK_RETRIEVING || pTmp->networkStatus == MSG_NETWORK_RETRIEVE_FAIL || pTmp->subType == MSG_NOTIFICATIONIND_MMS)) {
-                       pTmp->pData = NULL;
-                       index++;
+       if ((pMsg->msgType.subType >= MSG_REPLACE_TYPE1_SMS) && (pMsg->msgType.subType <= MSG_REPLACE_TYPE7_SMS)) {
+               if (pMsg->msgId > 0) {
+                       pMsg->bRead = false;
+                       if (MsgStoUpdateMessage(pMsg, NULL) != MSG_SUCCESS) {
+                               MSG_DEBUG("MsgStoUpdateMessage is failed!!!");
+                       }
                } else {
-                       pTmp->pData = (void *)new char[pTmp->dataSize+2];
-                       memset(pTmp->pData, 0x00, pTmp->dataSize+2);
+                       if (MsgStoAddMessage(pMsg, NULL) != MSG_SUCCESS) {
+                               MSG_DEBUG("MsgStoAddMessage is failed!!!");
+                       }
+               }
+       } else {
+               pMsg->msgId = 0;
+               if (MsgStoAddMessage(pMsg, NULL) != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgStoAddMessage is failed!!!");
+               }
+       }
+
+       if(simIdList) {
+               dbHandle->beginTrans();
+
+               MSG_DEBUG("simIdList exist.");
+               int simId = 0;
+               for(int i=0; i < listSize; ++i)
+               {
+                       if(simIdList[i]) {
+                               simId = simIdList[i] - 1;
+                               char sqlQuery[MAX_QUERY_LEN+1];
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d);",
+                                               MSGFW_SIM_MSG_TABLE_NAME, pMsg->sim_idx, simId, pMsg->msgId);
 
-                       dbHandle.getColumnToString(index++, pTmp->dataSize+1, (char *)pTmp->pData);
+                               MSG_DEBUG("QUERY : %s", sqlQuery);
+
+                               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                                       dbHandle->endTrans(false);
+                                       return 0;
+                               }
+                       } else {
+                               break;
+                       }
+               }
+
+               dbHandle->endTrans(true);
+       }
+
+       MSG_END();
+
+       return pMsg->msgId;
+}
+
+#ifdef FEATURE_SMS_CDMA
+msg_error_t MsgCheckUniqueness(bool bInsert, msg_message_id_t msgId, MSG_UNIQUE_INDEX_S *p_msg)
+{
+       MSG_BEGIN();
+
+       MsgDbHandler *dbHandle = getDbHandle();
+       int nRowCnt = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       if (!bInsert) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               dbHandle->beginTrans();
+
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT * FROM %s WHERE TELE_MSG_ID = %d AND ADDRESS = '%s' AND SUB_ADDRESS = '%s' AND TIME_STAMP = '%s' AND TELESVC_ID = %d;",
+                                       MSGFW_UNIQUENESS_INFO_TABLE_NAME, p_msg->tele_msgId, p_msg->address, p_msg->sub_address, p_msg->time_stamp, p_msg->telesvc_id);
+
+               dbHandle->getTable(sqlQuery, &nRowCnt, NULL);
+               MSG_DEBUG("nRowCnt = [%d]", nRowCnt);
+
+               dbHandle->freeTable();
+               dbHandle->endTrans(true);
+
+               if (nRowCnt == 0) {
+                       MSG_DEBUG("<<<<This incoming message is a new message>>>>");
+                       return MSG_SUCCESS;
+               }
+               else {
+                       MSG_DEBUG("<<<<This incoming message is a repeated message>>>>");
+                       return MSG_ERR_UNKNOWN;
+               }
+       }
+       else {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               dbHandle->beginTrans();
+
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, '%s', '%s', '%s', %d);",
+                                       MSGFW_UNIQUENESS_INFO_TABLE_NAME, msgId, p_msg->tele_msgId, p_msg->address, p_msg->sub_address, p_msg->time_stamp, p_msg->telesvc_id);
+
+               dbHandle->execQuery(sqlQuery);
+               dbHandle->endTrans(true);
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+#endif
+
+msg_error_t MsgStoUpdateIMSI(int sim_idx)
+{
+       MSG_BEGIN();
+       MSG_DEBUG("sim_idx = %d", sim_idx);
+
+//     msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+
+       dbHandle->beginTrans();
+
+       if(sim_idx == 0){
+               MSG_DEBUG("sim index is 0");
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET SIM_INDEX = 0;",
+                               MSGFW_MESSAGE_TABLE_NAME);
+
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
+
+               if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                       dbHandle->finalizeQuery();
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
                }
+       }
+       else
+       {
+               MSG_DEBUG("sim index is %d", sim_idx);
 
-               pTmp->attachCount = dbHandle.getColumnToInt(index++);
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_IMSI, sim_idx);
+
+               char *imsi = MsgSettingGetString(keyName);
+
+               MSG_DEBUG("imsi value exist -> %s", imsi);
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-               dbHandle.getColumnToString(index++, MSG_FILEPATH_LEN_MAX, pTmp->thumbPath);
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET SIM_INDEX = %d \
+                               WHERE SIM_IMSI LIKE '%s';",
+                               MSGFW_MESSAGE_TABLE_NAME, sim_idx, imsi);
 
-               // add address information.
-               order = MsgGetContactNameOrder();
+               if (imsi) {
+                       free(imsi);
+                       imsi = NULL;
+               }
 
-               msg_struct_list_s *addr_list = (msg_struct_list_s *)new msg_struct_list_s;
-               MsgStoGetAddressByMsgId(&dbHandle, pTmp->msgId, order, addr_list);
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
 
-               pTmp->addr_list = addr_list;
+               if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                       dbHandle->finalizeQuery();
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
        }
-       dbHandle.freeTable();
+
+       dbHandle->finalizeQuery();
+       dbHandle->endTrans(true);
+
+       MSG_END();
 
        return MSG_SUCCESS;
 }
index dd2f5c0..91b5534 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
@@ -26,7 +26,6 @@
 /*==================================================================================================
                                      VARIABLES
 ==================================================================================================*/
-extern MsgDbHandler dbHandle;
 
 
 /*==================================================================================================
@@ -34,6 +33,7 @@ extern MsgDbHandler dbHandle;
 ==================================================================================================*/
 msg_error_t MsgStoGetText(msg_message_id_t msgId, char *pSubject, char *pMsgText)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -41,24 +41,24 @@ msg_error_t MsgStoGetText(msg_message_id_t msgId, char *pSubject, char *pMsgText
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT SUBJECT, MSG_TEXT FROM %s WHERE MSG_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, msgId);
 
-       if(dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if(dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if(dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+       if(dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
 
-               char *subject = (char*)dbHandle.columnText(0);
-               char *text = (char*)dbHandle.columnText(1);
+               char *subject = (char*)dbHandle->columnText(0);
+               char *text = (char*)dbHandle->columnText(1);
 
                if(subject)
                        strncpy(pSubject, subject, MAX_SUBJECT_LEN);
                if(text)
                        strncpy(pMsgText, text, MAX_MSG_TEXT_LEN);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        return MSG_SUCCESS;
 
@@ -70,105 +70,262 @@ msg_error_t MsgStoUpdateMMSMessage(MSG_MESSAGE_INFO_S *pMsg)
 {
        MSG_BEGIN();
 
+       MSG_SEC_DEBUG("pMsg->msgText [%s]", pMsg->msgText);
+       MsgDbHandler *dbHandle = getDbHandle();
+       msg_error_t err = MSG_SUCCESS;
+
+       unsigned int fileSize = 0;
+       char *pFileData = NULL;
+
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       dbHandle.beginTrans();
-
        if(pMsg->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || pMsg->msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS) {
                if( pMsg->networkStatus == MSG_NETWORK_RETRIEVE_SUCCESS ) {
                        snprintf(sqlQuery, sizeof(sqlQuery),
-                                       "UPDATE %s SET MAIN_TYPE = %d, SUB_TYPE = %d, DISPLAY_TIME = %lu, SUBJECT = ?, NETWORK_STATUS = %d, MSG_TEXT = ?, THUMB_PATH = '%s', DATA_SIZE = %d WHERE MSG_ID = %d;",
-                                       MSGFW_MESSAGE_TABLE_NAME, pMsg->msgType.mainType, pMsg->msgType.subType, pMsg->displayTime, pMsg->networkStatus, pMsg->thumbPath,  pMsg->dataSize, pMsg->msgId);
+                                       "UPDATE %s SET MAIN_TYPE = %d, SUB_TYPE = %d, FOLDER_ID = %d, DISPLAY_TIME = %lu, SUBJECT = ?, NETWORK_STATUS = %d, MSG_TEXT = ?, THUMB_PATH = '%s', DATA_SIZE = %d WHERE MSG_ID = %d;",
+                                       MSGFW_MESSAGE_TABLE_NAME, pMsg->msgType.mainType, pMsg->msgType.subType, pMsg->folderId, pMsg->displayTime, pMsg->networkStatus, pMsg->thumbPath,  pMsg->dataSize, pMsg->msgId);
 
-                       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.endTrans(false);
+                       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
                                return MSG_ERR_DB_PREPARE;
                        }
 
-                       dbHandle.bindText(pMsg->subject, 1);
-                       dbHandle.bindText(pMsg->msgText, 2);
-               } else if( pMsg->networkStatus == MSG_NETWORK_RETRIEVE_FAIL) {
+                       dbHandle->bindText(pMsg->subject, 1);
+
+                       if (pMsg->msgText[0] != '\0' && g_file_get_contents(pMsg->msgText, &pFileData, &fileSize, NULL) == true) {
+                               dbHandle->bindText(pFileData, 2);
+                       } else {
+                               dbHandle->bindText("", 2);
+                       }
+
+               } else if (pMsg->networkStatus == MSG_NETWORK_RETRIEVE_FAIL) {
                        snprintf(sqlQuery, sizeof(sqlQuery),
                                        "UPDATE %s SET MAIN_TYPE = %d, SUB_TYPE = %d, SUBJECT = ?, NETWORK_STATUS = %d, MSG_TEXT = ?, THUMB_PATH = '%s' WHERE MSG_ID = %d;",
                                        MSGFW_MESSAGE_TABLE_NAME, pMsg->msgType.mainType, pMsg->msgType.subType, pMsg->networkStatus, pMsg->thumbPath,  pMsg->msgId);
 
-                       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.endTrans(false);
+                       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
                                return MSG_ERR_DB_PREPARE;
                        }
 
-                       dbHandle.bindText(pMsg->subject, 1);
-                       dbHandle.bindText(pMsg->msgText, 2);
+//                     if (MsgOpenAndReadFile(pMsg->msgText, &pFileData, &fileSize) == false) {
+                       if (g_file_get_contents(pMsg->msgText, &pFileData, &fileSize, NULL) == false) {
+                               return MSG_ERR_STORAGE_ERROR;
+                       }
+
+                       dbHandle->bindText(pMsg->subject, 1);
+
+                       if (pMsg->msgText[0] != '\0' && g_file_get_contents(pMsg->msgText, &pFileData, &fileSize, NULL) == true) {
+                               dbHandle->bindText(pFileData, 2);
+                       } else {
+                               dbHandle->bindText("", 2);
+                       }
                }
-       } else if (pMsg->msgType.subType == MSG_SENDREQ_MMS) {
+       } else if (pMsg->msgType.subType == MSG_SENDREQ_MMS || pMsg->msgType.subType == MSG_RETRIEVE_MMS) {
                snprintf(sqlQuery, sizeof(sqlQuery),
-                               "UPDATE %s SET MSG_DATA = '%s', MSG_TEXT = ?, THUMB_PATH = '%s' WHERE MSG_ID = %d;",
-                               MSGFW_MESSAGE_TABLE_NAME, pMsg->msgData, pMsg->thumbPath, pMsg->msgId);
+                               "UPDATE %s SET MSG_TEXT = ?, THUMB_PATH = '%s', DATA_SIZE = %d WHERE MSG_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsg->thumbPath, pMsg->dataSize, pMsg->msgId);
 
-               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
                        return MSG_ERR_DB_PREPARE;
                }
 
-               dbHandle.bindText(pMsg->msgText, 1);
+               if (pMsg->msgText[0] != '\0' && g_file_get_contents(pMsg->msgText, &pFileData, &fileSize, NULL) == true) {
+                       dbHandle->bindText(pFileData, 1);
+               } else {
+                       dbHandle->bindText("", 1);
+               }
        } else {
-               snprintf(sqlQuery, sizeof(sqlQuery),
-                               "UPDATE %s SET MAIN_TYPE = %d, SUB_TYPE = %d, FOLDER_ID = %d, NETWORK_STATUS = %d WHERE MSG_ID = %d;",
-                               MSGFW_MESSAGE_TABLE_NAME, pMsg->msgType.mainType, pMsg->msgType.subType, pMsg->folderId, pMsg->networkStatus, pMsg->msgId);
+               if (pMsg->msgType.subType == MSG_SENDCONF_MMS && pMsg->networkStatus == MSG_NETWORK_SEND_FAIL) {
+                       snprintf(sqlQuery, sizeof(sqlQuery),
+                                       "UPDATE %s SET MAIN_TYPE = %d, SUB_TYPE = %d, FOLDER_ID = %d, NETWORK_STATUS = %d, DISPLAY_TIME = %lu, READ_STATUS = 0 WHERE MSG_ID = %d;",
+                                       MSGFW_MESSAGE_TABLE_NAME, pMsg->msgType.mainType, pMsg->msgType.subType, pMsg->folderId, pMsg->networkStatus, pMsg->displayTime, pMsg->msgId);
 
-               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+               } else {
+                       snprintf(sqlQuery, sizeof(sqlQuery),
+                                       "UPDATE %s SET MAIN_TYPE = %d, SUB_TYPE = %d, FOLDER_ID = %d, NETWORK_STATUS = %d, DISPLAY_TIME = %lu WHERE MSG_ID = %d;",
+                                       MSGFW_MESSAGE_TABLE_NAME, pMsg->msgType.mainType, pMsg->msgType.subType, pMsg->folderId, pMsg->networkStatus, pMsg->displayTime, pMsg->msgId);
+               }
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
                        return MSG_ERR_DB_PREPARE;
                }
        }
 
-       if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
-               dbHandle.finalizeQuery();
-               dbHandle.endTrans(false);
-               MSG_DEBUG("Update MMS Message. Fail [%s]", sqlQuery);
+       MSG_DEBUG("[%s]", sqlQuery);
+
+       err = dbHandle->stepQuery();
+
+       if (pFileData != NULL) {
+               g_free(pFileData);
+       }
+
+       if (err != MSG_ERR_DB_DONE) {
+               dbHandle->finalizeQuery();
+               MSG_DEBUG("Update MMS Message. Fail.");
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
+
+       /* PLM P141008-05143  :  Notification.Ind address is 1, but MMS retreived Conf address is correct.
+        * So adding code for comparing exist address and new address and replace with new address(MMSconf) address */
+
+       if(pMsg->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || pMsg->msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS) {
+               if (pMsg->nAddressCnt == 1 && pMsg->addressList) {
+                       char tmpAddressVal[MAX_ADDRESS_VAL_LEN+1] = {0,};
+                       msg_address_type_t tmpAddressType;
+                       msg_recipient_type_t tmpRecipientType;
+                       int tmpConvId;
+
+                       //compare stored address and currnt address
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+                       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                                       "A.CONV_ID, "
+                                       "A.ADDRESS_TYPE, "
+                                       "A.RECIPIENT_TYPE, "
+                                       "A.ADDRESS_VAL "
+                                       "FROM %s A, %s B "
+                                       "WHERE A.CONV_ID = B.CONV_ID "
+                                       "AND B.MSG_ID = %d;",
+                                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                                       pMsg->msgId);
+
+                       MSG_DEBUG("[%s]", sqlQuery);
+
+                       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                               return MSG_ERR_DB_PREPARE;
+                       }
+
+                       err = dbHandle->stepQuery();
+
+                       if (err == MSG_ERR_DB_ROW) {
+                               tmpConvId = dbHandle->columnInt(0);
+                               tmpAddressType = dbHandle->columnInt(1);
+                               tmpRecipientType = dbHandle->columnInt(2);
+                               strncpy(tmpAddressVal, (char*)dbHandle->columnText(3), MAX_ADDRESS_VAL_LEN);
+
+                               dbHandle->finalizeQuery();
+
+                               //compare stored addressList and current addressList
+                               if (tmpAddressType != pMsg->addressList->addressType ||
+                                       tmpRecipientType != pMsg->addressList->recipientType ||
+                                       (strncmp(tmpAddressVal, pMsg->addressList->addressVal, MAX_ADDRESS_VAL_LEN) != 0)) {
+
+                                       MSG_WARN("AddressList of NotiInd and MMSConf are different!!, Replace AddressList to MMSConf data");
+                                       MSG_WARN("AddType [NotiInd : %d], [MMSConf : %d]", tmpAddressType, pMsg->addressList->addressType);
+                                       MSG_WARN("RcptType [NotiInd : %d], [MMSConf : %d]", tmpRecipientType, pMsg->addressList->recipientType);
+                                       MSG_SEC_INFO("AddressVal [NotiInd : %s], [MMSConf : %s]", tmpAddressVal, pMsg->addressList->addressVal);
+
+                                       // If MMSConf AddressList is already exist, Replace exist ConvId with matching msgId
+                                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+                                       snprintf(sqlQuery, sizeof(sqlQuery),
+                                               "SELECT CONV_ID FROM %s WHERE ADDRESS_VAL = '%s'",
+                                               MSGFW_ADDRESS_TABLE_NAME, pMsg->addressList->addressVal);
+
+                                       MSG_DEBUG("[%s]", sqlQuery);
+
+                                       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                                               return MSG_ERR_DB_PREPARE;
+                                       }
+
+                                       err = dbHandle->stepQuery();
+
+                                       if (err == MSG_ERR_DB_ROW) {
+                                               tmpConvId = dbHandle->columnInt(0);
+
+                                               dbHandle->finalizeQuery();
+
+                                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+                                               snprintf(sqlQuery, sizeof(sqlQuery),
+                                                       "UPDATE %s SET CONV_ID = %d WHERE MSG_ID = %d;",
+                                                       MSGFW_MESSAGE_TABLE_NAME, tmpConvId, pMsg->msgId);
+
+                                               MSG_DEBUG("[%s]", sqlQuery);
+
+                                               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                                                       return MSG_ERR_DB_PREPARE;
+                                               }
+
+                                               err = dbHandle->stepQuery();
+
+                                               if (err != MSG_ERR_DB_DONE) {
+                                                       dbHandle->finalizeQuery();
+                                                       MSG_ERR("Replacing CONV_ID with exist one. Fail.");
+                                                       return MSG_ERR_DB_STEP;
+                                               }
+
+                                               dbHandle->finalizeQuery();
+                                       } else {
+                                               dbHandle->finalizeQuery();
+
+                                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+                                               snprintf(sqlQuery, sizeof(sqlQuery),
+                                                       "UPDATE %s SET ADDRESS_TYPE = %d, RECIPIENT_TYPE = %d, ADDRESS_VAL = '%s' WHERE CONV_ID = %d;",
+                                                       MSGFW_ADDRESS_TABLE_NAME, pMsg->addressList->addressType, pMsg->addressList->recipientType, pMsg->addressList->addressVal, tmpConvId);
+
+                                               MSG_DEBUG("[%s]", sqlQuery);
+
+                                               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                                                       return MSG_ERR_DB_PREPARE;
+                                               }
+
+                                               err = dbHandle->stepQuery();
+
+                                               if (err != MSG_ERR_DB_DONE) {
+                                                       dbHandle->finalizeQuery();
+                                                       MSG_ERR("Replacing Address with MMSConf Address. Fail.");
+                                                       return MSG_ERR_DB_STEP;
+                                               }
+
+                                               dbHandle->finalizeQuery();
+                                       }
+                               }
+                       } else {
+                               dbHandle->finalizeQuery();
+                               return MSG_ERR_DB_STEP;
+                       }
+               }
+       }
 
        msg_thread_id_t convId = 0;
-       int row = 0;
+       int rowCnt = 0;
 
        // Get SUB_TYPE, STORAGE_ID
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CONV_ID FROM %s WHERE MSG_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, pMsg->msgId);
 
-       if (dbHandle.getTable(sqlQuery, &row) != MSG_SUCCESS) {
-               dbHandle.freeTable();
-               dbHandle.endTrans(false);
+       if (dbHandle->getTable(sqlQuery, &rowCnt, NULL) != MSG_SUCCESS) {
+               dbHandle->freeTable();
                return MSG_ERR_DB_PREPARE;
        }
 
-       if (row > 0) {
-               convId = dbHandle.getColumnToInt(1);
+       if (rowCnt > 0) {
+               convId = dbHandle->getColumnToInt(1);
 
                MSG_DEBUG("Conversation id:[%d]", convId);
 
-               if (MsgStoUpdateConversation(&dbHandle, convId) != MSG_SUCCESS) {
+               if (MsgStoUpdateConversation(dbHandle, convId) != MSG_SUCCESS) {
                        MSG_DEBUG("MsgStoUpdateConversation() Error");
-                       dbHandle.freeTable();
-                       dbHandle.endTrans(false);
+                       dbHandle->freeTable();
 
                        return MSG_ERR_STORAGE_ERROR;
                }
 
+               if (MsgStoClearConversationTable(dbHandle) != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgStoClearConversationTable() Error");
+               }
+
        } else {
-               MSG_DEBUG("MsgStepQuery() Error [%s]", sqlQuery);
-               dbHandle.freeTable();
-               dbHandle.endTrans(false);
+               dbHandle->freeTable();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.freeTable();
-       dbHandle.endTrans(true);
+       dbHandle->freeTable();
 
        MSG_END();
 
@@ -178,6 +335,7 @@ msg_error_t MsgStoUpdateMMSMessage(MSG_MESSAGE_INFO_S *pMsg)
 
 msg_error_t MsgStoGetContentLocation(MSG_MESSAGE_INFO_S* pMsgInfo)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -185,23 +343,23 @@ msg_error_t MsgStoGetContentLocation(MSG_MESSAGE_INFO_S* pMsgInfo)
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CONTENTS_LOCATION FROM %s WHERE MSG_ID = %d;",
                        MMS_PLUGIN_MESSAGE_TABLE_NAME, pMsgInfo->msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               if (dbHandle.columnText(0) != NULL) {
-                       strncpy(pMsgInfo->msgData, (char*)dbHandle.columnText(0), MAX_MSG_DATA_LEN);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               if (dbHandle->columnText(0) != NULL) {
+                       strncpy(pMsgInfo->msgData, (char*)dbHandle->columnText(0), MAX_MSG_DATA_LEN);
                        pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
                } else {
-                       dbHandle.finalizeQuery();
+                       dbHandle->finalizeQuery();
                        return MSG_ERR_DB_NORECORD;
                }
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        return MSG_SUCCESS;
 }
@@ -209,6 +367,7 @@ msg_error_t MsgStoGetContentLocation(MSG_MESSAGE_INFO_S* pMsgInfo)
 
 msg_error_t MsgStoSetReadReportSendStatus(msg_message_id_t msgId, int readReportSendStatus)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        bool bReadReportSent = false;
 
        if((MmsRecvReadReportSendStatus)readReportSendStatus == MMS_RECEIVE_READ_REPORT_SENT)
@@ -223,7 +382,7 @@ msg_error_t MsgStoSetReadReportSendStatus(msg_message_id_t msgId, int readReport
        snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET READ_REPORT_SEND_STATUS = %d, READ_REPORT_SENT = %d WHERE MSG_ID = %d;",
                        MMS_PLUGIN_MESSAGE_TABLE_NAME, (MmsRecvReadReportSendStatus)readReportSendStatus, (int)bReadReportSent, msgId);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_EXEC;
 
        return MSG_SUCCESS;
@@ -232,33 +391,38 @@ msg_error_t MsgStoSetReadReportSendStatus(msg_message_id_t msgId, int readReport
 
 msg_error_t MsgStoGetOrgAddressList(MSG_MESSAGE_INFO_S *pMsg)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        msg_error_t err = MSG_SUCCESS;
        char sqlQuery[MAX_QUERY_LEN+1];
-       int rowCnt = 0;
-       int index = 3;
+       int rowCnt = 0, index = 0;
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.ADDRESS_TYPE, A.RECIPIENT_TYPE, A.ADDRESS_VAL FROM %s A, %s B \
-                       WHERE A.CONV_ID = B.CONV_ID AND B.MSG_ID = %d;",
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                       "A.ADDRESS_TYPE, "
+                       "A.RECIPIENT_TYPE, "
+                       "A.ADDRESS_VAL "
+                       "FROM %s A, %s B "
+                       "WHERE A.CONV_ID = B.CONV_ID "
+                       "AND B.MSG_ID = %d;",
                        MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, pMsg->msgId);
 
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
+       err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
 
        if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
+               dbHandle->freeTable();
                return err;
        }
 
        for(int i = 0; i < rowCnt; i++)
        {
-               pMsg->addressList[i].addressType = dbHandle.getColumnToInt(index++);
-               pMsg->addressList[i].recipientType = dbHandle.getColumnToInt(index++);
-               dbHandle.getColumnToString(index++, MAX_ADDRESS_VAL_LEN, pMsg->addressList[i].addressVal);
+               pMsg->addressList[i].addressType = dbHandle->getColumnToInt(index++);
+               pMsg->addressList[i].recipientType = dbHandle->getColumnToInt(index++);
+               dbHandle->getColumnToString(index++, MAX_ADDRESS_VAL_LEN, pMsg->addressList[i].addressVal);
        }
 
        pMsg->nAddressCnt = rowCnt;
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        return MSG_SUCCESS;
 }
@@ -266,6 +430,7 @@ msg_error_t MsgStoGetOrgAddressList(MSG_MESSAGE_INFO_S *pMsg)
 
 msg_error_t MsgStoGetSubject(msg_message_id_t msgId, char *pSubject)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -273,63 +438,44 @@ msg_error_t MsgStoGetSubject(msg_message_id_t msgId, char *pSubject)
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT SUBJECT FROM %s WHERE MSG_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               strncpy(pSubject, (char*)dbHandle.columnText(0), MAX_SUBJECT_LEN);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               strncpy(pSubject, (char*)dbHandle->columnText(0), MAX_SUBJECT_LEN);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        return MSG_SUCCESS;
 }
 
-
-msg_error_t MsgStoUpdateNetworkStatus(MSG_MESSAGE_INFO_S *pMsgInfo, msg_network_status_t status)
-{
-       MSG_BEGIN();
-
-       msg_error_t err = MSG_SUCCESS;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET NETWORK_STATUS = %d WHERE MSG_ID = %d;",
-                       MSGFW_MESSAGE_TABLE_NAME, status, pMsgInfo->msgId);
-
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_EXEC;
-
-       MSG_END();
-       return err;
-}
-
-
 msg_error_t MsgStoGetRecipientList(msg_message_id_t msgId, MSG_RECIPIENTS_LIST_S *pRecipientList)
 {
        if (pRecipientList == NULL) {
                MSG_DEBUG("pRecipientList is NULL");
                return MSG_ERR_NULL_POINTER;
        }
-
-       int rowCnt = 0, index = 7;
-
+       MsgDbHandler *dbHandle = getDbHandle();
+       int rowCnt = 0, index = 0;
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT B.ADDRESS_TYPE, B.RECIPIENT_TYPE, \
-                       B.ADDRESS_VAL, B.CONTACT_ID, B.DISPLAY_NAME, B.FIRST_NAME, B.LAST_NAME \
-                       FROM %s A, %s B WHERE A.MSG_ID = %d AND A.CONV_ID = B.CONV_ID;",
-                       MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, msgId);
-
-       if (dbHandle.getTable(sqlQuery, &rowCnt) != MSG_SUCCESS) {
-               dbHandle.freeTable();
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                       "B.ADDRESS_TYPE, "
+                       "B.RECIPIENT_TYPE, "
+                       "B.ADDRESS_VAL "
+                       "FROM %s A, %s B "
+                       "WHERE A.MSG_ID = %d "
+                       "AND A.CONV_ID = B.CONV_ID;",
+                       MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME,
+                       msgId);
+
+       if (dbHandle->getTable(sqlQuery, &rowCnt, &index) != MSG_SUCCESS) {
+               dbHandle->freeTable();
                return MSG_ERR_DB_GETTABLE;
        }
 
@@ -341,57 +487,20 @@ msg_error_t MsgStoGetRecipientList(msg_message_id_t msgId, MSG_RECIPIENTS_LIST_S
 
        MSG_ADDRESS_INFO_S* pTmp = pRecipientList->recipientAddr;
 
-       char firstName[MAX_THREAD_NAME_LEN+1], lastName[MAX_THREAD_NAME_LEN+1];
-       char displayName[MAX_DISPLAY_NAME_LEN+1];
-
-       int order = MsgGetContactNameOrder();
-
        for (int i = 0; i < rowCnt; i++)
        {
-               pTmp->addressType = dbHandle.getColumnToInt(index++);
-               pTmp->recipientType= dbHandle.getColumnToInt(index++);
+               pTmp->addressType = dbHandle->getColumnToInt(index++);
+               pTmp->recipientType= dbHandle->getColumnToInt(index++);
 
                memset(pTmp->addressVal, 0x00, sizeof(pTmp->addressVal));
-               dbHandle.getColumnToString(index++, MAX_ADDRESS_VAL_LEN, pTmp->addressVal);
+               dbHandle->getColumnToString(index++, MAX_ADDRESS_VAL_LEN, pTmp->addressVal);
 
-               pTmp->contactId= dbHandle.getColumnToInt(index++);
-
-               memset(displayName, 0x00, sizeof(displayName));
-               dbHandle.getColumnToString(index++, MAX_THREAD_NAME_LEN, displayName);
-
-               memset(firstName, 0x00, sizeof(firstName));
-               dbHandle.getColumnToString(index++, MAX_THREAD_NAME_LEN, firstName);
-
-               memset(lastName, 0x00, sizeof(lastName));
-               dbHandle.getColumnToString(index++, MAX_THREAD_NAME_LEN, lastName);
-
-               if (strlen(displayName) <= 0) {
-                       if (order == 0) {
-                               if (firstName[0] != '\0')
-                                       strncpy(displayName, firstName, MAX_DISPLAY_NAME_LEN);
-
-                               if (lastName[0] != '\0') {
-                                       strncat(displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                                       strncat(displayName, lastName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-                       } else if (order == 1) {
-                               if (lastName[0] != '\0') {
-                                       strncpy(displayName, lastName, MAX_DISPLAY_NAME_LEN);
-                                       strncat(displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-
-                               if (firstName[0] != '\0')
-                                       strncat(displayName, firstName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                       }
-               }
-
-               memset(pTmp->displayName, 0x00, sizeof(pTmp->displayName));
-               strncpy(pTmp->displayName, displayName, MAX_DISPLAY_NAME_LEN);
+               strncpy(pTmp->displayName, pTmp->addressVal, MAX_DISPLAY_NAME_LEN);
 
                pTmp++;
        }
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        return MSG_SUCCESS;
 }
@@ -399,6 +508,7 @@ msg_error_t MsgStoGetRecipientList(msg_message_id_t msgId, MSG_RECIPIENTS_LIST_S
 
 msg_error_t MsgStoGetReadStatus(msg_message_id_t msgId, bool *pReadStatus)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -406,17 +516,17 @@ msg_error_t MsgStoGetReadStatus(msg_message_id_t msgId, bool *pReadStatus)
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT READ_STATUS FROM %s WHERE MSG_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               *pReadStatus = (bool)dbHandle.columnInt(0);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               *pReadStatus = (bool)dbHandle->columnInt(0);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        return MSG_SUCCESS;
 }
@@ -424,30 +534,69 @@ msg_error_t MsgStoGetReadStatus(msg_message_id_t msgId, bool *pReadStatus)
 
 msg_error_t MsgStoGetAddrInfo(msg_message_id_t msgId, MSG_ADDRESS_INFO_S *pAddrInfo)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
        // Add Address
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.ADDRESS_TYPE, A.RECIPIENT_TYPE, A.CONTACT_ID, A.ADDRESS_VAL \
-                       FROM %s A, %s B WHERE A.CONV_ID = B.CONV_ID AND B.MSG_ID = %d;",
-                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, msgId);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                       "A.ADDRESS_TYPE, "
+                       "A.RECIPIENT_TYPE, "
+                       "A.CONTACT_ID, "
+                       "A.ADDRESS_VAL "
+                       "FROM %s A, %s B "
+                       "WHERE A.CONV_ID = B.CONV_ID "
+                       "AND B.MSG_ID = %d;",
+                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                       msgId);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               pAddrInfo->addressType = dbHandle->columnInt(0);
+               pAddrInfo->recipientType = dbHandle->columnInt(1);
+               pAddrInfo->contactId = dbHandle->columnInt(2);
+
+               strncpy(pAddrInfo->addressVal, (char*)dbHandle->columnText(3), MAX_ADDRESS_VAL_LEN);
+       } else {
+               dbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle->finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t MsgStoGetReadReportSendStatus(msg_message_id_t msgId, int *pReadReportSendStatus)
+{
+       MmsRecvReadReportSendStatus readReportSendStatus = MMS_RECEIVE_READ_REPORT_NO_SEND;
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                       "READ_REPORT_SEND_STATUS "
+                       "FROM %s WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               pAddrInfo->addressType = dbHandle.columnInt(0);
-               pAddrInfo->recipientType = dbHandle.columnInt(1);
-               pAddrInfo->contactId = dbHandle.columnInt(2);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               readReportSendStatus = (MmsRecvReadReportSendStatus)dbHandle->columnInt(0);
+
+               *pReadReportSendStatus = readReportSendStatus;
 
-               strncpy(pAddrInfo->addressVal, (char*)dbHandle.columnText(3), MAX_ADDRESS_VAL_LEN);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        return MSG_SUCCESS;
 }
index 7e1895e..72c934a 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <queue>
@@ -31,48 +31,14 @@ using namespace std;
 /*==================================================================================================
                                      VARIABLES
 ==================================================================================================*/
-extern MsgDbHandler dbHandle;
 
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
-msg_error_t MsgInitSimMessage(MSG_SIM_STATUS_T SimStatus)
-{
-       MSG_DEBUG("Start SIM Message Initialization");
-
-       msg_error_t err = MSG_SUCCESS;
-
-       // Set SIM count of vconf to 0
-       if (MsgSettingSetInt(SIM_USED_COUNT, 0) != MSG_SUCCESS) {
-               MSG_DEBUG("Error to set config data [%s]", SIM_USED_COUNT);
-       }
-
-       if (MsgSettingSetInt(SIM_TOTAL_COUNT, 0) != MSG_SUCCESS) {
-               MSG_DEBUG("Error to set config data [%s]", SIM_TOTAL_COUNT);
-       }
-
-       if (SimStatus != MSG_SIM_STATUS_NOT_FOUND) {
-               MSG_MAIN_TYPE_T mainType = MSG_SMS_TYPE;
-               MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(mainType);
-
-               if (plg == NULL) {
-                       MSG_DEBUG("No plugin for %d type", mainType);
-                       return MSG_ERR_INVALID_PLUGIN_HANDLE;
-               }
-
-               // Check SIM Status
-               MSG_DEBUG(" ** SIM is available - status : [%d] ** ", SimStatus);
-
-               err = plg->initSimMessage();
-       }
-
-       return err;
-}
-
-
 msg_error_t MsgStoClearSimMessageInDB()
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        msg_error_t err = MSG_SUCCESS;
 
        char sqlQuery[MAX_QUERY_LEN+1];
@@ -87,33 +53,32 @@ msg_error_t MsgStoClearSimMessageInDB()
 
        int rowCnt = 0;
 
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
+       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
        if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-               MSG_DEBUG("sql query is %s.", sqlQuery);
-
-               dbHandle.freeTable();
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
                return err;
        }
 
        if (rowCnt <= 0) {
-               dbHandle.freeTable();
+               dbHandle->freeTable();
                return MSG_SUCCESS;
        }
 
        for (int i = 1; i <= rowCnt; i++)
        {
-               MSG_DEBUG("thread ID : %d", dbHandle.getColumnToInt(i));
-               threadList.push((msg_thread_id_t)dbHandle.getColumnToInt(i));
+               MSG_DEBUG("thread ID : %d", dbHandle->getColumnToInt(i));
+               threadList.push((msg_thread_id_t)dbHandle->getColumnToInt(i));
        }
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        const char* tableList[] = {MSGFW_SMS_SENDOPT_TABLE_NAME, MSGFW_SIM_MSG_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME};
 
        int listCnt = sizeof(tableList)/sizeof(char*);
 
-       dbHandle.beginTrans();
+       dbHandle->beginTrans();
 
        for (int i = 0; i < listCnt; i++)
        {
@@ -124,32 +89,32 @@ msg_error_t MsgStoClearSimMessageInDB()
                                tableList[i], MSGFW_MESSAGE_TABLE_NAME, MSG_STORAGE_SIM);
 
                // Delete SIM Message in tables
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_EXEC;
                }
        }
 
        // Clear Conversation table
-       if (MsgStoClearConversationTable(&dbHandle) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (MsgStoClearConversationTable(dbHandle) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
        // Update Address
        while (!threadList.empty())
        {
-               err = MsgStoUpdateConversation(&dbHandle, threadList.front());
+               err = MsgStoUpdateConversation(dbHandle, threadList.front());
 
                threadList.pop();
 
                if (err != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+                       dbHandle->endTrans(false);
                        return err;
                }
        }
 
-       dbHandle.endTrans(true);
+       dbHandle->endTrans(true);
 
        return MSG_SUCCESS;
 }
index 52fa76f..e6925aa 100755 (executable)
@@ -1,22 +1,23 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
+#include <queue>
 
 #include "MsgDebug.h"
 #include "MsgCppTypes.h"
 #include "MsgUtilStorage.h"
 #include "MsgStorageHandler.h"
 
+using namespace std;
 
 /*==================================================================================================
                                      VARIABLES
 ==================================================================================================*/
-extern MsgDbHandler dbHandle;
 
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
-msg_error_t MsgMakeSortRule(const MSG_SORT_RULE_S *pSortRule, char *pSqlSort)
-{
-       char sql[128];
-       char order[6];
-
-       memset(sql, 0x00, sizeof(sql));
-       memset(order, 0x00, sizeof(order));
-
-       if (pSortRule->bAscending == true)
-               strncpy(order, "ASC", 5);
-       else
-               strncpy(order, "DESC", 5);
-
-       int nameOrder = MsgGetContactNameOrder();
-
-       switch (pSortRule->sortType)
-       {
-               case MSG_SORT_BY_DISPLAY_FROM :
-                       if (nameOrder == 0)
-                               snprintf(sql, sizeof(sql), "ORDER BY B.FIRST_NAME %s, B.LAST_NAME %s, B.ADDRESS_VAL, A.DISPLAY_TIME DESC;", order, order);
-                       else
-                               snprintf(sql, sizeof(sql), "ORDER BY B.LAST_NAME %s, B.FIRST_NAME %s, B.ADDRESS_VAL, A.DISPLAY_TIME DESC;", order, order);
-                       break;
-               case MSG_SORT_BY_DISPLAY_TO :
-                       if (nameOrder == 0)
-                               snprintf(sql, sizeof(sql), "ORDER BY B.FIRST_NAME %s, B.LAST_NAME %s, B.ADDRESS_VAL, A.DISPLAY_TIME DESC;", order, order);
-                       else
-                               snprintf(sql, sizeof(sql), "ORDER BY B.LAST_NAME %s, B.FIRST_NAME %s, B.ADDRESS_VAL, A.DISPLAY_TIME DESC;", order, order);
-                       break;
-               case MSG_SORT_BY_DISPLAY_TIME :
-                       snprintf(sql, sizeof(sql), "ORDER BY DISPLAY_TIME %s;", order);
-                       break;
-               case MSG_SORT_BY_MSG_TYPE :
-                       snprintf(sql, sizeof(sql), "ORDER BY MAIN_TYPE %s, DISPLAY_TIME DESC;", order);
-                       break;
-               case MSG_SORT_BY_READ_STATUS :
-                       snprintf(sql, sizeof(sql), "ORDER BY READ_STATUS %s, DISPLAY_TIME DESC;", order);
-                       break;
-               case MSG_SORT_BY_STORAGE_TYPE :
-                       snprintf(sql, sizeof(sql), "ORDER BY A.STORAGE_ID %s, A.DISPLAY_TIME DESC;", order);
-                       break;
-               case MSG_SORT_BY_THREAD_NAME :
-                       if (nameOrder == 0)
-                               snprintf(sql, sizeof(sql), "ORDER BY FIRST_NAME %s, LAST_NAME %s;", order, order);
-                       else
-                               snprintf(sql, sizeof(sql), "ORDER BY LAST_NAME %s, FIRST_NAME %s;", order, order);
-                       break;
-               case MSG_SORT_BY_THREAD_DATE :
-                       snprintf(sql, sizeof(sql), "ORDER BY MSG_TIME %s;", order);
-                       break;
-               case MSG_SORT_BY_THREAD_COUNT :
-                       snprintf(sql, sizeof(sql), "ORDER BY UNREAD_CNT %s;", order);
-                       break;
-               default :
-                       snprintf(sql, sizeof(sql), "ORDER BY A.DISPLAY_TIME %s;", order);
-                       break;
-       }
-
-       memcpy(pSqlSort, sql, strlen(sql));
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t MsgStoGetSmsSendOpt(msg_message_id_t msgId, MSG_SENDINGOPT_INFO_S* pSendOpt)
+msg_error_t MsgStoGetSmsSendOpt(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S* pSendOpt)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DELREP_REQ, KEEP_COPY, REPLY_PATH FROM %s WHERE MSG_ID = %d;",
-                       MSGFW_SMS_SENDOPT_TABLE_NAME, msgId);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DELREP_REQ, KEEP_COPY, REPLY_PATH, ENCODE_TYPE FROM %s WHERE MSG_ID = %d;",
+                       MSGFW_SMS_SENDOPT_TABLE_NAME, pMsg->msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
                pSendOpt->bSetting = true;
-               pSendOpt->bDeliverReq = (bool)dbHandle.columnInt(0);
-               pSendOpt->bKeepCopy = (bool)dbHandle.columnInt(1);
-               pSendOpt->option.smsSendOptInfo.bReplyPath = (bool)dbHandle.columnInt(2);
+               pSendOpt->bDeliverReq = (bool)dbHandle->columnInt(0);
+               pSendOpt->bKeepCopy = (bool)dbHandle->columnInt(1);
+               pSendOpt->option.smsSendOptInfo.bReplyPath = (bool)dbHandle->columnInt(2);
+               pMsg->encodeType = dbHandle->columnInt(3);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        return MSG_SUCCESS;
 }
@@ -133,6 +72,7 @@ msg_error_t MsgStoGetSmsSendOpt(msg_message_id_t msgId, MSG_SENDINGOPT_INFO_S* p
 
 msg_error_t MsgStoGetMmsSendOpt(msg_message_id_t msgId, MSG_SENDINGOPT_INFO_S* pSendOpt)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -140,32 +80,32 @@ msg_error_t MsgStoGetMmsSendOpt(msg_message_id_t msgId, MSG_SENDINGOPT_INFO_S* p
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT ASK_DELIVERY_REPORT, KEEP_COPY, ASK_READ_REPLY, EXPIRY_TIME, PRIORITY FROM %s WHERE MSG_ID = %d;",
                        MMS_PLUGIN_MESSAGE_TABLE_NAME, msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
                pSendOpt->bSetting = true;
-               pSendOpt->bDeliverReq = (bool)dbHandle.columnInt(0);
-               pSendOpt->bKeepCopy = (bool)dbHandle.columnInt(1);
-               pSendOpt->option.mmsSendOptInfo.bReadReq = (bool)dbHandle.columnInt(2);
-               pSendOpt->option.mmsSendOptInfo.expiryTime.time = (unsigned int)dbHandle.columnInt(3);
-               pSendOpt->option.mmsSendOptInfo.priority = (msg_priority_type_t)dbHandle.columnInt(4);
+               pSendOpt->bDeliverReq = (bool)dbHandle->columnInt(0);
+               pSendOpt->bKeepCopy = (bool)dbHandle->columnInt(1);
+               pSendOpt->option.mmsSendOptInfo.bReadReq = (bool)dbHandle->columnInt(2);
+               pSendOpt->option.mmsSendOptInfo.expiryTime.time = (unsigned int)dbHandle->columnInt(3);
+               pSendOpt->option.mmsSendOptInfo.priority = (msg_priority_type_t)dbHandle->columnInt(4);
        } else {
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
        return MSG_SUCCESS;
 }
 
+
 bool MsgStoCheckSyncMLMsgInThread(msg_thread_id_t threadId)
 {
-       msg_error_t err = MSG_SUCCESS;
        int rowCnt = 0;
        bool isSyncMLMsg = false;
-
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -173,15 +113,15 @@ bool MsgStoCheckSyncMLMsgInThread(msg_thread_id_t threadId)
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE SUB_TYPE = %d AND CONV_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, MSG_SYNCML_CP, threadId);
 
-       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
-
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
+       if (dbHandle->getTable(sqlQuery, &rowCnt, NULL) != MSG_SUCCESS) {
+               MSG_DEBUG("getTable is failed!!!");
+       }
 
        if (rowCnt > 0) isSyncMLMsg = true;
 
        MSG_DEBUG("rowCnt [%d]", rowCnt);
 
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        return isSyncMLMsg;
 }
@@ -190,17 +130,27 @@ bool MsgStoCheckSyncMLMsgInThread(msg_thread_id_t threadId)
 msg_error_t MsgStoResetNetworkStatus()
 {
        MSG_BEGIN();
-
+       MsgDbHandler *dbHandle = getDbHandle();
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
        snprintf(sqlQuery, sizeof(sqlQuery),
-                       "UPDATE %s SET NETWORK_STATUS = %d WHERE NETWORK_STATUS = %d; UPDATE %s SET NETWORK_STATUS = %d WHERE NETWORK_STATUS = %d;",
-                       MSGFW_MESSAGE_TABLE_NAME, MSG_NETWORK_SEND_FAIL, MSG_NETWORK_SENDING,
+                       "UPDATE %s SET NETWORK_STATUS = %d WHERE NETWORK_STATUS = %d;",
+                       MSGFW_MESSAGE_TABLE_NAME, MSG_NETWORK_SEND_FAIL, MSG_NETWORK_SENDING);
+
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               //continue reset process for MSG_NETWORK_RETRIEVE_FAIL case
+               MSG_INFO("execQuery is failed");
+       }
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "UPDATE %s SET NETWORK_STATUS = %d WHERE NETWORK_STATUS = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, MSG_NETWORK_RETRIEVE_FAIL, MSG_NETWORK_RETRIEVING);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_EXEC;
 
        MSG_END();
@@ -208,13 +158,34 @@ msg_error_t MsgStoResetNetworkStatus()
        return MSG_SUCCESS;
 }
 
+#if 0
+msg_error_t MsgStoResetCBMessage()
+{
+       MSG_BEGIN();
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s",
+                       MSGFW_RECEIVED_CB_MSG_TABLE_NAME);
+
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Delete Received CB Msg Fail!!");
+               return MSG_ERR_DB_EXEC;
+       }
+
+       MSG_END();
+       return MSG_SUCCESS;
+}
+#endif
+
 
 msg_error_t MsgStoCleanAbnormalMmsData()
 {
        MSG_BEGIN();
 
-       int rowCnt = 0, index = 2; // numbers of index
-
+       int rowCnt = 0, index = 0; // numbers of index
+       MsgDbHandler *dbHandle = getDbHandle();
        msg_message_id_t msgId;
 
        char sqlQuery[MAX_QUERY_LEN+1];
@@ -225,14 +196,14 @@ msg_error_t MsgStoCleanAbnormalMmsData()
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.MSG_ID, A.FILE_PATH FROM %s A, %s B WHERE A.MSG_ID = B.MSG_ID AND (B.SUB_TYPE = %d OR B.SUB_TYPE = %d OR B.SUB_TYPE = %d);",
                        MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, MSG_SENDCONF_MMS, MSG_RETRIEVE_AUTOCONF_MMS, MSG_RETRIEVE_MANUALCONF_MMS);
 
-       msg_error_t  err = dbHandle.getTable(sqlQuery, &rowCnt);
+       msg_error_t  err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
 
        if (err == MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
+               dbHandle->freeTable();
                return MSG_SUCCESS;
        } else if (err != MSG_SUCCESS) {
-               MSG_DEBUG("%s", sqlQuery);
-               dbHandle.freeTable();
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
                return err;
        }
 
@@ -241,13 +212,13 @@ msg_error_t MsgStoCleanAbnormalMmsData()
        {
                memset(filePath, 0x00, sizeof(filePath));
 
-               msgId = dbHandle.getColumnToInt(index++);
+               msgId = dbHandle->getColumnToInt(index++);
 
-               dbHandle.getColumnToString(index++, MSG_FILEPATH_LEN_MAX, filePath);
+               dbHandle->getColumnToString(index++, MSG_FILEPATH_LEN_MAX, filePath);
 
                if(strlen(filePath) > 1) {
                        MSG_DEBUG("strlen(filePath) [%d]", strlen(filePath));
-                       MSG_DEBUG("filePath [%s]", filePath);
+                       MSG_SEC_DEBUG("filePath [%s]", filePath);
 
                        if(MsgGetFileSize(filePath) < 0) {
                                // abnormal mms message
@@ -259,25 +230,26 @@ msg_error_t MsgStoCleanAbnormalMmsData()
                }
 
        }
-       dbHandle.freeTable();
+       dbHandle->freeTable();
 
        MSG_END();
 
        return MSG_SUCCESS;
 }
 
+
 msg_error_t MsgStoCheckReadReportStatus(msg_message_id_t msgId)
 {
        MSG_BEGIN();
 
        bool    bReadReportRequested;
        bool    bReadReportIsSent;
-
-       bReadReportRequested = MsgStoCheckReadReportRequested(&dbHandle, msgId);
+       MsgDbHandler *dbHandle = getDbHandle();
+       bReadReportRequested = MsgStoCheckReadReportRequested(dbHandle, msgId);
        if(bReadReportRequested == false)
                return MSG_ERR_READREPORT_NOT_REQUESTED;
 
-       bReadReportIsSent = MsgStoCheckReadReportIsSent(&dbHandle, msgId);
+       bReadReportIsSent = MsgStoCheckReadReportIsSent(dbHandle, msgId);
        if(bReadReportIsSent == true)
                return MSG_ERR_READREPORT_ALEADY_SENT;
 
@@ -286,3 +258,612 @@ msg_error_t MsgStoCheckReadReportStatus(msg_message_id_t msgId)
        return MSG_SUCCESS;
 }
 
+
+msg_error_t MsgStoAutoDeleteConversation(msg_thread_id_t threadId, msg_id_list_s *msgIdList)
+{
+       MSG_BEGIN();
+       MsgDbHandler *dbHandle = getDbHandle();
+       msg_error_t err = MSG_SUCCESS;
+
+       bool bAutoErase = false;
+       MsgSettingGetBool(MSG_AUTO_ERASE, &bAutoErase);
+
+       if (bAutoErase) {
+
+               MSG_DEBUG("threadId [%d]", threadId);
+
+               //msg_id_list_s msgIdList;
+               int currentSmsCnt = 0;
+               int currentMmsCnt = 0;
+               int limitSmsCnt = 0;
+               int limitMmsCnt = 0;
+
+               char sqlQuery[MAX_QUERY_LEN+1];
+
+               int rowCnt = 0, index = 0;
+
+               //memset(msgIdList, 0x00, sizeof(msg_id_list_s));
+
+               // Get current count of messages
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+#ifdef MSG_NOTI_INTEGRATION
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT COUNT(MSG_ID) FROM %s "
+                               "WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND MAIN_TYPE = %d "
+                               "UNION ALL "
+                               "SELECT COUNT(MSG_ID) FROM %s "
+                               "WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND MAIN_TYPE = %d AND SUB_TYPE NOT IN (%d, %d, %d);",
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               threadId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE, MSG_SMS_TYPE,
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               threadId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE, MSG_MMS_TYPE, MSG_DELIVERYIND_MMS, MSG_READRECIND_MMS, MSG_READORGIND_MMS);
+#else
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT COUNT(MSG_ID) FROM %s "
+                               "WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND MAIN_TYPE = %d "
+                               "UNION ALL "
+                               "SELECT COUNT(MSG_ID) FROM %s "
+                               "WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND MAIN_TYPE = %d AND SUB_TYPE NOT IN (%d, %d, %d);",
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               threadId, MSG_ALLBOX_ID, MSG_CBMSGBOX_ID, MSG_STORAGE_PHONE, MSG_SMS_TYPE,
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               threadId, MSG_ALLBOX_ID, MSG_CBMSGBOX_ID, MSG_STORAGE_PHONE, MSG_MMS_TYPE, MSG_DELIVERYIND_MMS, MSG_READRECIND_MMS, MSG_READORGIND_MMS);
+#endif
+
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+                       return MSG_ERR_DB_PREPARE;
+               }
+
+               if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+                       currentSmsCnt = dbHandle->columnInt(0);
+               } else {
+                       dbHandle->finalizeQuery();
+                       return MSG_ERR_DB_STEP;
+               }
+
+               if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+                       currentMmsCnt = dbHandle->columnInt(0);
+               } else {
+                       dbHandle->finalizeQuery();
+                       return MSG_ERR_DB_STEP;
+               }
+
+               dbHandle->finalizeQuery();
+
+               MSG_DEBUG("currentSmsCnt [%d], currentMmsCnt [%d]", currentSmsCnt, currentMmsCnt);
+
+               if (currentSmsCnt > 0 || currentMmsCnt > 0) {
+                       limitSmsCnt = MsgSettingGetInt(MSG_SMS_LIMIT);
+                       limitMmsCnt = MsgSettingGetInt(MSG_MMS_LIMIT);
+
+                       if (limitSmsCnt < 0 || limitMmsCnt < 0) {
+                               MSG_DEBUG("limitSmsCnt [%d], limitMmsCnt [%d]", limitSmsCnt, limitMmsCnt);
+                               return MSG_SUCCESS;
+                       }
+               } else { // !(currentSmsCnt > 0 || currentMmsCnt > 0)
+                       return MSG_SUCCESS;
+               }
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+#ifdef MSG_NOTI_INTEGRATION
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT DISTINCT(MSG_ID) FROM %s "
+                               "WHERE MSG_ID IN "
+                               "(SELECT MSG_ID FROM %s "
+                               "WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND PROTECTED = 0 "
+                               "AND MAIN_TYPE = %d ORDER BY MSG_ID ASC LIMIT %d) "
+                               "OR MSG_ID IN "
+                               "(SELECT MSG_ID FROM %s "
+                               "WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND PROTECTED = 0 "
+                               "AND MAIN_TYPE = %d AND SUB_TYPE NOT IN (%d, %d, %d) ORDER BY MSG_ID ASC LIMIT %d);",
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               threadId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE,
+                               MSG_SMS_TYPE, ((currentSmsCnt-limitSmsCnt)>0)?(currentSmsCnt-limitSmsCnt):0,
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               threadId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE,
+                               MSG_MMS_TYPE, MSG_DELIVERYIND_MMS, MSG_READRECIND_MMS, MSG_READORGIND_MMS, ((currentMmsCnt-limitMmsCnt)>0)?(currentMmsCnt-limitMmsCnt):0);
+#else
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT DISTINCT(MSG_ID) FROM %s "
+                               "WHERE MSG_ID IN "
+                               "(SELECT MSG_ID FROM %s "
+                               "WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND PROTECTED = 0 "
+                               "AND MAIN_TYPE = %d ORDER BY MSG_ID ASC LIMIT %d) "
+                               "OR MSG_ID IN "
+                               "(SELECT MSG_ID FROM %s "
+                               "WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND PROTECTED = 0 "
+                               "AND MAIN_TYPE = %d AND SUB_TYPE NOT IN (%d, %d, %d) ORDER BY MSG_ID ASC LIMIT %d);",
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               threadId, MSG_ALLBOX_ID, MSG_CBMSGBOX_ID, MSG_STORAGE_PHONE,
+                               MSG_SMS_TYPE, ((currentSmsCnt-limitSmsCnt)>0)?(currentSmsCnt-limitSmsCnt):0,
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               threadId, MSG_ALLBOX_ID, MSG_CBMSGBOX_ID, MSG_STORAGE_PHONE,
+                               MSG_MMS_TYPE, MSG_DELIVERYIND_MMS, MSG_READRECIND_MMS, MSG_READORGIND_MMS, ((currentMmsCnt-limitMmsCnt)>0)?(currentMmsCnt-limitMmsCnt):0);
+#endif
+               err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+               if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+                       MSG_DEBUG("Fail to getTable().");
+                       dbHandle->freeTable();
+                       return err;
+               }
+
+               if (rowCnt <= 0) {
+                       MSG_DEBUG("rowCnt <= 0");
+                       dbHandle->freeTable();
+                       return MSG_SUCCESS;
+               }
+
+               msgIdList->nCount = rowCnt;
+
+               MSG_DEBUG("msgIdList.nCount [%d]", msgIdList->nCount);
+
+               msgIdList->msgIdList = (msg_message_id_t *)new char[sizeof(msg_message_id_t) * rowCnt];
+
+               for (int i = 0; i < rowCnt; i++) {
+                       msgIdList->msgIdList[i] = dbHandle->getColumnToInt(index++);
+               }
+
+               dbHandle->freeTable();
+
+               // delete message
+               err = MsgStoDeleteMessageByList(msgIdList);
+
+               //delete [] (char*)msgIdList.msgIdList;
+
+       } else {
+               MSG_DEBUG("bAutoErase [%d]", bAutoErase);
+       }
+
+       MSG_END();
+
+       return err;
+}
+
+
+msg_error_t MsgStoGetReplaceMsgId(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       msg_thread_id_t convId = 0;
+
+       /** Check if new address or not */
+       if (MsgExistAddress(dbHandle, pMsgInfo, &convId) == true) {
+               MSG_DEBUG("Address Info. exists [%d]", convId);
+
+               /**  Find Replace Type Msg : Same Replace Type, Same Origin Address, Same Storage ID */
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE SUB_TYPE = %d AND CONV_ID = %d AND STORAGE_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsgInfo->msgType.subType, convId, pMsgInfo->storageId);
+
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_PREPARE;
+
+               if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+                       pMsgInfo->msgId = dbHandle->columnInt(0);
+               } else {
+                       dbHandle->finalizeQuery();
+                       return MSG_ERR_DB_STEP;
+               }
+
+               dbHandle->finalizeQuery();
+       }
+
+       return err;
+}
+
+
+msg_error_t MsgStoAddWAPMsg(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
+       MSG_PUSH_MESSAGE_S pushMsg = {};
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       int fileSize = 0;
+
+       char* pFileData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&pFileData, unique_ptr_deleter);
+
+       if (MsgOpenAndReadFile(pMsgInfo->msgData, &pFileData, &fileSize) == false)
+               return MSG_ERR_STORAGE_ERROR;
+
+       MSG_DEBUG("fileSize : %d", fileSize);
+
+       memcpy(&pushMsg, pFileData, fileSize);
+
+       /** Delete temporary file */
+       MsgDeleteFile(pMsgInfo->msgData);
+
+       /** check pPushMsg data */
+
+       MSG_DEBUG("check pushMsg data");
+       MSG_DEBUG("pushMsg.action : [%d]", pushMsg.action);
+       MSG_DEBUG("pushMsg.received : [%d]", pushMsg.received);
+       MSG_DEBUG("pushMsg.created : [%d]", pushMsg.created);
+       MSG_DEBUG("pushMsg.expires : [%d]", pushMsg.expires);
+       MSG_SEC_DEBUG("pushMsg.id : [%s]", pushMsg.id);
+       MSG_DEBUG("pushMsg.href : [%s]", pushMsg.href);
+       MSG_DEBUG("pushMsg.contents : [%s]", pushMsg.contents);
+
+       bool bProceed = true;
+
+       /**  check validation of contents */
+       if (MsgStoCheckPushMsgValidation(&pushMsg, &bProceed) != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to check Push Message validation.");
+       }
+
+       /**  if validation check value is false */
+       /** return and drop message. */
+       if (bProceed == false)
+               return MSG_ERR_INVALID_MESSAGE;
+
+
+       /**  Update Msg Text - remove */
+       strncpy(pMsgInfo->msgText, pushMsg.href, MAX_MSG_TEXT_LEN);
+
+       if (pushMsg.contents[0] != '\0') {
+               strncat(pMsgInfo->msgText, " ", MAX_MSG_TEXT_LEN - strlen(pMsgInfo->msgText));
+               strncat(pMsgInfo->msgText, pushMsg.contents, MAX_MSG_TEXT_LEN - strlen(pMsgInfo->msgText));
+       }
+
+       pMsgInfo->dataSize = strlen(pMsgInfo->msgText);
+
+       pMsgInfo->bTextSms = true;
+       pMsgInfo->folderId = MSG_INBOX_ID;
+       pMsgInfo->storageId = MSG_STORAGE_PHONE;
+
+       msg_thread_id_t convId = 0;
+
+       dbHandle->beginTrans();
+
+       if (pMsgInfo->nAddressCnt > 0) {
+
+               err = MsgStoAddAddress(dbHandle, pMsgInfo, &convId);
+
+               if (err != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return err;
+               }
+
+               pMsgInfo->threadId = convId;
+       }
+
+       /**  get last row count for Message id */
+       unsigned int rowId = 0;
+
+       /** Add Message Table */
+       rowId = MsgStoAddMessageTable(dbHandle, pMsgInfo);
+
+       if (rowId <= 0) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_ROW;
+       }
+
+       pMsgInfo->msgId = (msg_message_id_t)rowId;
+
+       /**  add msg_push_table */
+       snprintf (sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %lu, %lu, ?, ?, ?)",
+                       MSGFW_PUSH_MSG_TABLE_NAME, pMsgInfo->msgId, pushMsg.action, pushMsg.created, pushMsg.expires);
+
+       if ((err = dbHandle->prepareQuery(sqlQuery)) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return err;
+       }
+
+       dbHandle->bindText(pushMsg.id, 1);
+
+       dbHandle->bindText(pushMsg.href, 2);
+
+       dbHandle->bindText(pushMsg.contents, 3);
+
+       if ((err = dbHandle->stepQuery()) != MSG_ERR_DB_DONE) {
+               dbHandle->finalizeQuery();
+               dbHandle->endTrans(false);
+               return err;
+       }
+
+       dbHandle->finalizeQuery();
+
+       /** Update conversation table. */
+       if (MsgStoUpdateConversation(dbHandle, convId) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       dbHandle->endTrans(true);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoAddCOWAPMsg(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
+       char href[MAX_PUSH_CACHEOP_MAX_URL_LEN+1];
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       int fileSize = 0;
+
+       char* pFileData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&pFileData, unique_ptr_deleter);
+
+       if (MsgOpenAndReadFile(pMsgInfo->msgData, &pFileData, &fileSize) == false)
+               return MSG_ERR_STORAGE_ERROR;
+
+       MSG_PUSH_CACHEOP_S *pPushMsg;
+
+       pPushMsg = (MSG_PUSH_CACHEOP_S*)pFileData;
+
+       for (int i = 0; i < pPushMsg->invalObjectCnt; i++) {
+
+               int msgid = -1;
+
+               memset(href, 0x00, sizeof(href));
+               strncpy(href, &(pPushMsg->invalObjectUrl[i][0]), MAX_PUSH_CACHEOP_MAX_URL_LEN);
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf (sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE HREF LIKE '%%%s%%';", MSGFW_PUSH_MSG_TABLE_NAME, href);
+
+               dbHandle->beginTrans();
+
+               err = dbHandle->prepareQuery(sqlQuery);
+
+               if ((dbHandle->stepQuery() == MSG_ERR_DB_ROW) && err == MSG_SUCCESS) {
+
+                       msgid = dbHandle->columnInt(0);
+
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID= %d;", MSGFW_PUSH_MSG_TABLE_NAME, msgid);
+
+                       /** Delete Message from Push table */
+                       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(false);
+                               continue;
+                       }
+
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, msgid);
+
+                       /** Delete Message from msg table */
+                       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(false);
+                               continue;
+                       }
+
+                       /** Update all Address */
+                       if (MsgStoUpdateAllAddress() != MSG_SUCCESS) {
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(false);
+                               continue;
+                       }
+
+                       /** Clear Conversation table */
+                       if (MsgStoClearConversationTable(dbHandle) != MSG_SUCCESS) {
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(false);
+                               continue;
+                       }
+               }
+
+               dbHandle->finalizeQuery();
+
+               dbHandle->endTrans(true);
+       }
+
+       for (int i = 0; i < pPushMsg->invalServiceCnt; i++) {
+
+               int msgid = -1;
+
+               memset(href, 0x00, sizeof(href));
+               strncpy(href, &(pPushMsg->invalObjectUrl[i][0]), MAX_PUSH_CACHEOP_MAX_URL_LEN);
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE HREF LIKE '%%%s%%'", MSGFW_PUSH_MSG_TABLE_NAME, href);
+
+               dbHandle->beginTrans();
+
+               err = dbHandle->prepareQuery(sqlQuery);
+
+               if ((dbHandle->stepQuery() == MSG_ERR_DB_ROW) && err == MSG_SUCCESS) {
+
+                       msgid = dbHandle->columnInt(0);
+
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID='%d'", MSGFW_PUSH_MSG_TABLE_NAME, msgid);
+
+                       /** Delete Message from Push table */
+                       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(false);
+                               continue;
+                       }
+
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, msgid);
+
+                       /** Delete Message from msg table */
+                       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(false);
+                               continue;
+                       }
+
+                       /**  Update all Address */
+                       if (MsgStoUpdateAllAddress() != MSG_SUCCESS) {
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(false);
+                               continue;
+                       }
+
+                       /** Clear Address table */
+                       if (MsgStoClearConversationTable(dbHandle) != MSG_SUCCESS) {
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(false);
+                               continue;
+                       }
+               }
+
+               dbHandle->finalizeQuery();
+
+               dbHandle->endTrans(true);
+       }
+
+       /** delete temporary file */
+       MsgDeleteFile(pMsgInfo->msgData);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoAddCBMsg(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
+       unsigned int rowId = 0;
+       msg_thread_id_t convId = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       dbHandle->beginTrans();
+
+       if (pMsgInfo->nAddressCnt > 0) {
+               err = MsgStoAddAddress(dbHandle, pMsgInfo, &convId);
+
+               if (err != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return err;
+               }
+
+               pMsgInfo->threadId = convId;
+       }
+
+       /**  Add Message Table */
+       rowId = MsgStoAddMessageTable(dbHandle, pMsgInfo);
+
+       if (rowId <= 0) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_ROW;
+       }
+
+       /**  Get CB Msg ID */
+       unsigned short cbMsgId = (unsigned short)pMsgInfo->msgId;
+
+       /** Add CB Msg in MSG_CBMSG_TABLE */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d);",
+                       MSGFW_CB_MSG_TABLE_NAME, rowId, cbMsgId);
+
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       /**  Update conversation table. */
+       if (MsgStoUpdateConversation(dbHandle, convId) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       dbHandle->endTrans(true);
+
+       /** Assign Msg ID */
+       pMsgInfo->msgId = (msg_message_id_t)rowId;
+
+       return err;
+}
+
+
+msg_error_t MsgStoCheckPushMsgValidation(MSG_PUSH_MESSAGE_S *pPushMsg, bool *pbProceed)
+{
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
+       unsigned long oldExpireTime = 0;
+       int rowCnt = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       /**  is push message is expired?? */
+       if (pPushMsg->received > pPushMsg->expires) {
+               MSG_DEBUG("Push Message is expired.");
+               pbProceed = false;
+               return err;
+       }
+
+       if (pPushMsg->action == MSG_PUSH_SL_ACTION_EXECUTE_LOW) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT EXPIRES FROM %s WHERE ID = '%s' AND ACTION = %d",
+                               MSGFW_PUSH_MSG_TABLE_NAME, pPushMsg->id, pPushMsg->action);
+       } else {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT EXPIRES FROM %s WHERE ID = '%s'",
+                               MSGFW_PUSH_MSG_TABLE_NAME, pPushMsg->id);
+       }
+
+       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+       if (rowCnt < 1) {
+               dbHandle->freeTable();
+               return MSG_SUCCESS;
+       }
+
+       oldExpireTime = dbHandle->getColumnToInt(1);
+
+       dbHandle->freeTable();
+
+       if (pPushMsg->created < oldExpireTime) {
+               MSG_DEBUG("Push Message is expired.");
+               pbProceed = false;
+               return err;
+       }
+
+       return err;
+}
+
+
+msg_error_t MsgStoUpdateAllAddress()
+{
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
+       int rowCnt = 0, index = 0;
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT ADDRESS_ID FROM %s", MSGFW_ADDRESS_TABLE_NAME);
+
+       err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               dbHandle->freeTable();
+               return MSG_SUCCESS;
+       } else if ( err != MSG_SUCCESS) {
+               dbHandle->freeTable();
+               return err;
+       }
+
+       for (int i = 0; i < rowCnt; i++) {
+
+               err = MsgStoUpdateConversation(dbHandle, index++);
+
+               if (err != MSG_SUCCESS)
+                       break;
+       }
+
+       dbHandle->freeTable();
+
+       return err;
+}
+
index 3fde433..fa0aff2 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
@@ -19,6 +19,7 @@
 
 #include "MsgDebug.h"
 #include "MsgUtilFile.h"
+#include "MsgUtilStorage.h"
 #include "MsgException.h"
 #include "MsgGconfWrapper.h"
 #include "MsgPluginManager.h"
 #include "MsgSubmitHandler.h"
 
 
+
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
 msg_error_t MsgSubmitReq(MSG_REQUEST_INFO_S *pReqInfo, bool bScheduled)
 {
        msg_error_t err = MSG_SUCCESS;
-
        static int reqId = 1;
 
        pReqInfo->reqId = reqId;
@@ -40,11 +41,12 @@ msg_error_t MsgSubmitReq(MSG_REQUEST_INFO_S *pReqInfo, bool bScheduled)
 
        MSG_DEBUG("==== Msg ID = [%d] ====", pReqInfo->msgInfo.msgId);
        MSG_DEBUG("==== Folder ID = [%d] ====", pReqInfo->msgInfo.folderId);
-       MSG_DEBUG("==== Main Type = [%d] ====", pReqInfo->msgInfo.msgType.mainType);
-       MSG_DEBUG("==== Sub Type = [%d] ====", pReqInfo->msgInfo.msgType.subType);
+       MSG_INFO("==== Main Type = [%d] ====", pReqInfo->msgInfo.msgType.mainType);
+       MSG_INFO("==== Sub Type = [%d] ====", pReqInfo->msgInfo.msgType.subType);
        MSG_DEBUG("==== Class Type = [%d] ====", pReqInfo->msgInfo.msgType.classType);
        MSG_DEBUG("==== Message Data = [%s] ====", pReqInfo->msgInfo.msgData);
-       MSG_DEBUG("==== Message Text = [%s] ====", pReqInfo->msgInfo.msgText);
+       MSG_SEC_DEBUG("==== Message Text = [%s] ====", pReqInfo->msgInfo.msgText);
+       MSG_INFO("==== SIM Index = [%d] ====", pReqInfo->msgInfo.sim_idx);
 
        MSG_DEBUG("==== bSetting = [%d] ====", pReqInfo->sendOptInfo.bSetting);
 
@@ -80,15 +82,17 @@ msg_error_t MsgSubmitReqSMS(MSG_REQUEST_INFO_S *pReqInfo)
        MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(mainType);
 
        if (plg == NULL)
-               THROW(MsgException::PLUGIN_ERROR, "No plugin for %d type", mainType);
+               return MSG_ERR_NULL_POINTER;
 
        // If MSG ID > 0 -> MSG in DRAFT
        // Move Folder to OUTBOX
        if (pReqInfo->msgInfo.msgPort.valid == false) {
                pReqInfo->msgInfo.folderId = MSG_OUTBOX_ID;
 
-               if (pReqInfo->msgInfo.msgId > 0 && (pReqInfo->msgInfo.folderId == MSG_DRAFT_ID || pReqInfo->msgInfo.folderId == MSG_OUTBOX_ID))
-                       err = MsgStoUpdateMessage(&(pReqInfo->msgInfo), &(pReqInfo->sendOptInfo));
+       if (pReqInfo->msgInfo.msgId > 0 && (pReqInfo->msgInfo.folderId == MSG_DRAFT_ID || pReqInfo->msgInfo.folderId == MSG_OUTBOX_ID))
+               err = MsgStoUpdateMessage(&(pReqInfo->msgInfo), &(pReqInfo->sendOptInfo));
+               if (err != MSG_SUCCESS)
+                       return err;
        }
 
        err = plg->submitReq(pReqInfo);
@@ -96,19 +100,36 @@ msg_error_t MsgSubmitReqSMS(MSG_REQUEST_INFO_S *pReqInfo)
        return err;
 }
 
-
 msg_error_t MsgSubmitReqMMS(MSG_REQUEST_INFO_S *pReqInfo)
 {
        msg_error_t err = MSG_SUCCESS;
-
+       MsgDbHandler *dbHandle = getDbHandle();
        MSG_RECIPIENTS_LIST_S pRecipientList;
 
+       MsgPlugin *sms_plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
+
+       if (sms_plg == NULL){
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       int defaultNetworkSimId = 0;
+
+       err = sms_plg->getDefaultNetworkSimId(&defaultNetworkSimId);
+       if (err != MSG_SUCCESS) {
+               MSG_ERR("getDefaultNetworkSimId is failed=[%d]", err);
+               return err;
+       } else if (pReqInfo->msgInfo.sim_idx != defaultNetworkSimId) {
+               MSG_ERR("It is not default network SIM ID, request SIM=[%d], activated SIM=[%d]", pReqInfo->msgInfo.sim_idx, defaultNetworkSimId);
+               return MSG_ERR_INVALID_PARAMETER;
+
+       }
+
        MSG_MAIN_TYPE_T msgMainType = pReqInfo->msgInfo.msgType.mainType;
        MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(msgMainType);
 
        if(!plg)
        {
-               MsgStoUpdateNetworkStatus(&(pReqInfo->msgInfo), MSG_NETWORK_SEND_FAIL);
+               MsgStoUpdateNetworkStatus(dbHandle, &(pReqInfo->msgInfo), MSG_NETWORK_SEND_FAIL);
                MSG_DEBUG("No Plugin for %d type", msgMainType);
 
                return MSG_ERR_INVALID_PLUGIN_HANDLE;
@@ -126,82 +147,69 @@ msg_error_t MsgSubmitReqMMS(MSG_REQUEST_INFO_S *pReqInfo)
                // copy whole of MMS PDU filepath to msgData
                strncpy(fileName, pReqInfo->msgInfo.msgData, MAX_COMMON_INFO_SIZE);
                memset(pReqInfo->msgInfo.msgData, 0x00, MAX_MSG_DATA_LEN+1);
-               snprintf(pReqInfo->msgInfo.msgData, MAX_MSG_DATA_LEN+1, MSG_IPC_DATA_PATH"%s", fileName);
+               snprintf(pReqInfo->msgInfo.msgData, MAX_MSG_DATA_LEN+1, "%s%s", MSG_IPC_DATA_PATH, fileName);
 
-               MSG_DEBUG("JAVA MMS PDU filepath:%s", pReqInfo->msgInfo.msgData);
+               MSG_SEC_DEBUG("JAVA MMS PDU filepath:%s", pReqInfo->msgInfo.msgData);
 
                // submit request
-               plg->submitReq(pReqInfo);
+               err = plg->submitReq(pReqInfo);
 
                if(err != MSG_SUCCESS)
                {
                        MSG_DEBUG("Update Network Status : [%d]", err);
-                       MsgStoUpdateNetworkStatus(&(pReqInfo->msgInfo),MSG_NETWORK_SEND_FAIL);
+                       MsgStoUpdateNetworkStatus(dbHandle, &(pReqInfo->msgInfo),MSG_NETWORK_SEND_FAIL);
                }
 
                return err;
        }
        else if((pReqInfo->msgInfo.msgType.subType == MSG_SENDREQ_MMS) || (pReqInfo->msgInfo.msgType.subType == MSG_FORWARD_MMS))
        {
-               // update address list in the ase of existing message
-               if(pReqInfo->msgInfo.msgId > 0)
-               {
-                       err = MsgStoGetOrgAddressList(&(pReqInfo->msgInfo));
-
-                       if(err != MSG_SUCCESS)
-                               MSG_DEBUG("[WARNING]MsgStoGetOrgAddressList returned not a MSG_SUCCESS");
-               }
-
                if(pReqInfo->msgInfo.msgId > 0 && (pReqInfo->msgInfo.folderId == MSG_DRAFT_ID || pReqInfo->msgInfo.folderId == MSG_OUTBOX_ID)) {
-                       MSG_ADDRESS_INFO_S addrInfo = {0,};
-                       int addrIdx = 0;
-
-                       err = MsgStoGetAddrInfo(pReqInfo->msgInfo.msgId, &addrInfo);
-
-                       if (err == MSG_SUCCESS) {
-                               for (int i = 0; i < pReqInfo->msgInfo.nAddressCnt; i++) {
-                                       //if (pReqInfo->msgInfo.addressList[i].threadId == addrInfo.threadId) {
-                                       if (!strcmp(pReqInfo->msgInfo.addressList[i].addressVal, addrInfo.addressVal)) {
-                                               addrIdx = i;
-                                               MSG_DEBUG("addrIdx = %d, address = [%s]", addrIdx, pReqInfo->msgInfo.addressList[i].addressVal);
-                                               break;
-                                       }
-                               }
-                       } else {
-                               MSG_DEBUG("[Error]MsgStoGetAddrInfo is failed");
-                       }
-
+                       MSG_DEBUG("Not New Message.");
                        pReqInfo->msgInfo.folderId = MSG_OUTBOX_ID;
                        err = MsgStoUpdateMessage(&(pReqInfo->msgInfo), &(pReqInfo->sendOptInfo));
-
-                       MsgStoUpdateNetworkStatus(&(pReqInfo->msgInfo), pReqInfo->msgInfo.networkStatus);
                } else {
-                       //new message case
-                       MSG_DEBUG("New Message");
+                       MSG_DEBUG("New Message.");
+                       pReqInfo->msgInfo.msgId = 0;
                        pReqInfo->msgInfo.folderId = MSG_OUTBOX_ID;
                        err = MsgStoAddMessage(&(pReqInfo->msgInfo), &(pReqInfo->sendOptInfo));
-                       //pReqInfo->msgInfo.msgId = 0;
                }
        }
        else if(pReqInfo->msgInfo.msgType.subType == MSG_READREPLY_MMS)
        {
+               msg_read_report_status_t readStatus;
+
                err = MsgStoCheckReadReportStatus(pReqInfo->msgInfo.msgId);
-               if(err != MSG_SUCCESS)
+               if(err != MSG_SUCCESS) {
+
+                       MSG_INFO("msg id [%d], read report could NOT send [%d]", pReqInfo->msgInfo.msgId, err);
                        return err;
+               }
+
+               memcpy(&readStatus, pReqInfo->msgInfo.msgData, sizeof(msg_read_report_status_t));
+               if (readStatus == MSG_READ_REPORT_REJECT_BY_USER) {
+
+                       MSG_INFO("msg id [%d], read report reject by user", pReqInfo->msgInfo.msgId);
+
+                       err = MsgStoSetReadReportSendStatus(pReqInfo->msgInfo.msgId, MMS_RECEIVE_READ_REPORT_NO_SENT);
+
+                       return err;
+               }
 
                err = MsgStoGetRecipientList(pReqInfo->msgInfo.msgId, &pRecipientList);
                if(err != MSG_SUCCESS)
                        return MSG_ERR_PLUGIN_STORAGE;
 
                pReqInfo->msgInfo.nAddressCnt = pRecipientList.recipientCnt;
+               pReqInfo->msgInfo.addressList = pRecipientList.recipientAddr;
 
-               for(int i = 0; i < pRecipientList.recipientCnt; i++)
-               {
-                       pReqInfo->msgInfo.addressList[i].addressType = pRecipientList.recipientAddr[i].addressType;
-                       pReqInfo->msgInfo.addressList[i].recipientType = MSG_RECIPIENTS_TYPE_TO;
-                       pReqInfo->msgInfo.addressList[i].contactId = pRecipientList.recipientAddr[i].contactId;
-                       strncpy(pReqInfo->msgInfo.addressList[i].addressVal, pRecipientList.recipientAddr[i].addressVal, MAX_ADDRESS_VAL_LEN);
-               }
+//                     for(int i = 0; i < pRecipientList.recipientCnt; i++)
+//                     {
+//                             pReqInfo->msgInfo.addressList[i].addressType = pRecipientList.recipientAddr[i].addressType;
+//                             pReqInfo->msgInfo.addressList[i].recipientType = MSG_RECIPIENTS_TYPE_TO;
+//                             pReqInfo->msgInfo.addressList[i].contactId = pRecipientList.recipientAddr[i].contactId;
+//                             strncpy(pReqInfo->msgInfo.addressList[i].addressVal, pRecipientList.recipientAddr[i].addressVal, MAX_ADDRESS_VAL_LEN);
+//                     }
 
                char subject[MAX_SUBJECT_LEN+1];
 
@@ -215,7 +223,7 @@ msg_error_t MsgSubmitReqMMS(MSG_REQUEST_INFO_S *pReqInfo)
        }
        else if(pReqInfo->msgInfo.msgType.subType == MSG_RETRIEVE_MMS)
        {
-               MsgStoUpdateNetworkStatus(&(pReqInfo->msgInfo), pReqInfo->msgInfo.networkStatus);
+               MsgStoUpdateNetworkStatus(dbHandle, &(pReqInfo->msgInfo), pReqInfo->msgInfo.networkStatus);
        }
 
        /* reject_msg_support */
@@ -232,7 +240,7 @@ msg_error_t MsgSubmitReqMMS(MSG_REQUEST_INFO_S *pReqInfo)
                case MSG_FORWARD_MMS:
                        MsgDeleteFile(pReqInfo->msgInfo.msgData);
                        memset(pReqInfo->msgInfo.msgData, 0x00, MAX_MSG_DATA_LEN+1);
-                       snprintf(pReqInfo->msgInfo.msgData, MAX_MSG_DATA_LEN+1, MSG_DATA_PATH"%d.mms", pReqInfo->msgInfo.msgId);
+                       snprintf(pReqInfo->msgInfo.msgData, MAX_MSG_DATA_LEN+1, "%s%d.mms", MSG_DATA_PATH, pReqInfo->msgInfo.msgId);
                        break;
 
                case MSG_READREPLY_MMS:
@@ -251,12 +259,15 @@ msg_error_t MsgSubmitReqMMS(MSG_REQUEST_INFO_S *pReqInfo)
        /* reject_msg_support */
 
        // Check SIM is present or not
-       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, pReqInfo->msgInfo.sim_idx);
+       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
 
        if(simStatus == MSG_SIM_STATUS_NOT_FOUND)
        {
                MSG_DEBUG("SIM is not present...");
-               MsgStoUpdateNetworkStatus(&(pReqInfo->msgInfo), MSG_NETWORK_SEND_FAIL);
+               MsgStoUpdateNetworkStatus(dbHandle, &(pReqInfo->msgInfo), MSG_NETWORK_SEND_FAIL);
 
                return MSG_ERR_NO_SIM;
        }
@@ -270,16 +281,15 @@ msg_error_t MsgSubmitReqMMS(MSG_REQUEST_INFO_S *pReqInfo)
        if (err != MSG_SUCCESS)
        {
                if(pReqInfo->msgInfo.msgType.subType == MSG_RETRIEVE_MMS )
-                       MsgStoUpdateNetworkStatus(&(pReqInfo->msgInfo), MSG_NETWORK_RETRIEVE_FAIL);
+                       MsgStoUpdateNetworkStatus(dbHandle, &(pReqInfo->msgInfo), MSG_NETWORK_RETRIEVE_FAIL);
                else
-                       MsgStoUpdateNetworkStatus(&(pReqInfo->msgInfo), MSG_NETWORK_SEND_FAIL);
+                       MsgStoUpdateNetworkStatus(dbHandle, &(pReqInfo->msgInfo), MSG_NETWORK_SEND_FAIL);
        }
 
 
        return err;
 }
 
-
 msg_error_t MsgCancelReq(msg_request_id_t reqId)
 {
        msg_error_t err = MSG_SUCCESS;
@@ -292,9 +302,9 @@ msg_error_t MsgUpdateSentMsg(msg_message_id_t MsgId, msg_network_status_t Status
 {
        msg_error_t err = MSG_SUCCESS;
 
+#ifdef MSG_MMS_KEEPCOPY
        bool bKeepCopy = true;
 
-#ifdef MSG_MMS_KEEPCOPY
        MSG_SENDINGOPT_INFO_S sendOpt = {};
 
        if (msgType.mainType == MSG_MMS_TYPE)
@@ -308,18 +318,23 @@ msg_error_t MsgUpdateSentMsg(msg_message_id_t MsgId, msg_network_status_t Status
                        ret = MsgSettingGetBool(MSG_KEEP_COPY, &bKeepCopy);
                }
        }
-#endif
-
        // Move Msg to SENTBOX
        if (Status == MSG_NETWORK_SEND_SUCCESS)
        {
-               MSG_DEBUG(" In Status == MSG_NETWORK_SEND_SUCCESS and  bKeepCopy is [%d]", bKeepCopy);
+               MSG_DEBUG("In Status == MSG_NETWORK_SEND_SUCCESS and  bKeepCopy is [%d]", bKeepCopy);
                if (bKeepCopy == true)
                        err = MsgStoMoveMessageToFolder(MsgId, MSG_SENTBOX_ID);
                else
                        err = MsgStoDeleteMessage(MsgId, false);
        }
-
+#else
+       // Move Msg to SENTBOX
+       if (Status == MSG_NETWORK_SEND_SUCCESS)
+       {
+               MSG_DEBUG("In Status == MSG_NETWORK_SEND_SUCCESS and bKeepCopy is true");
+               err = MsgStoMoveMessageToFolder(MsgId, MSG_SENTBOX_ID);
+       }
+#endif
        return err;
 }
 
@@ -328,7 +343,7 @@ void MsgCopyReqInfo(MSG_REQUEST_INFO_S *pSrc, int addrIdx, MSG_REQUEST_INFO_S *p
 {
        MSG_BEGIN();
 
-       memset(pDest, 0x00, sizeof(pDest));
+       memset(pDest, 0x00, sizeof(MSG_REQUEST_INFO_S));
 
        // Copy Request ID
        pDest->reqId = pSrc->reqId;
index 7034931..614a9fa 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
@@ -29,6 +29,11 @@ int MsgAddFilterHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        // Get Filter Structure
@@ -57,6 +62,11 @@ int MsgUpdateFilterHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        // Get Filter Structure
@@ -85,6 +95,11 @@ int MsgDeleteFilterHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        // Get Filter Structure
@@ -111,12 +126,56 @@ int MsgDeleteFilterHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 }
 
 
+int MsgSetFilterActivationHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       int eventSize = 0;
+
+       // Get Filter Structure
+       msg_filter_id_t  *pFilterId = (msg_filter_id_t *)pCmd->cmdData;
+
+       bool setFlag = false;
+
+       memcpy(&setFlag, pCmd->cmdData+sizeof(msg_filter_id_t), sizeof(bool));
+
+       MSG_DEBUG("Filter id : %d", *pFilterId);
+
+       // Delete Filter
+       err = MsgStoSetFilterActivation(*pFilterId, setFlag);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoSetFilterActivation()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoSetFilterActivation()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_SET_FILTER_ACTIVATION, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
 int MsgGetFilterListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
@@ -132,7 +191,15 @@ int MsgGetFilterListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
                // Encoding Filter List Data
                dataSize = MsgEncodeFilterList(&filterList, &encodedData);
 
-               delete [] filterList.msg_struct_info;
+               if (filterList.msg_struct_info) {
+                       msg_struct_s *msg_struct;
+                       for (int i = 0; i < filterList.nCount; i++) {
+                               msg_struct = (msg_struct_s *)filterList.msg_struct_info[i];
+                               delete (MSG_FILTER_S *)msg_struct->data;
+                               delete msg_struct;
+                       }
+                       g_free(filterList.msg_struct_info);
+               }
        }
        else
        {
@@ -150,6 +217,11 @@ int MsgSetFilterOperationHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        // Get Filter Flag
@@ -180,8 +252,13 @@ int MsgGetFilterOperationHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
index 5304c11..7a25234 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
@@ -20,6 +20,7 @@
 #include "MsgUtilFunction.h"
 #include "MsgCppTypes.h"
 
+using namespace std;
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
@@ -28,6 +29,11 @@ int MsgSetConfigHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
        int eventType = -1;
 
@@ -89,19 +95,43 @@ int MsgGetConfigHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0;
        int eventSize = 0;
        int eventType = -1;
 
        // Get Option Type
-       MSG_OPTION_TYPE_T* type = (MSG_OPTION_TYPE_T*)pCmd->cmdData;
+       MSG_OPTION_TYPE_T type = 0;
+       memcpy((void *)&type, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(MSG_OPTION_TYPE_T));
 
        // Get Config Data
        MSG_SETTING_S setting;
-       setting.type = *type;
+       setting.type = type;
+
+       msg_sim_slot_id_t simIndex = 0;
+       switch(setting.type) {
+       case MSG_CBMSG_OPT :
+               memcpy(&simIndex, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_OPTION_TYPE_T)), sizeof(msg_sim_slot_id_t));
+               setting.option.cbMsgOpt.simIndex = simIndex;
+               break;
+       case MSG_VOICEMAIL_OPT :
+               memcpy(&simIndex, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_OPTION_TYPE_T)), sizeof(msg_sim_slot_id_t));
+               setting.option.voiceMailOpt.simIndex = simIndex;
+               break;
+       case MSG_SMSC_LIST :
+               memcpy(&simIndex, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_OPTION_TYPE_T)), sizeof(msg_sim_slot_id_t));
+               setting.option.smscList.simIndex = simIndex;
+               break;
+       default :
+               break;
+       }
 
        err = MsgGetConfigData(&setting);
 
index a661a90..e28ce3d 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdlib.h>
 #include "MsgPluginManager.h"
 #include "MsgTransManager.h"
 #include "MsgCmdHandler.h"
-
+#include "MsgNotificationWrapper.h"
+#include "MsgMutex.h"
+#include <glib.h>
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
+
+Mutex mx;
+int g_job_cnt = 0;
+
+static gboolean  __refresh_noti(void *data)
+{
+       mx.lock();
+
+       g_job_cnt--;
+
+       if (g_job_cnt <= 0) {
+               MSG_DEBUG("## Refresh notification ##");
+               if (MsgRefreshNotification(MSG_NOTI_TYPE_NORMAL, false, false) != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgRefreshNoti is failed");
+               }
+               g_job_cnt = 0;
+       }
+
+       mx.unlock();
+
+       return FALSE;
+
+}
+
 int MsgAddMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
-       // Get Message Info
-       MSG_MESSAGE_INFO_S* pMsgInfo = (MSG_MESSAGE_INFO_S*)pCmd->cmdData;
+       MSG_MESSAGE_INFO_S msgInfo;
+       MSG_SENDINGOPT_INFO_S sendOptInfo;
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+       memset(&sendOptInfo, 0x00, sizeof(MSG_SENDINGOPT_INFO_S));
 
-       // Get Sending Option
-       MSG_SENDINGOPT_INFO_S* pSendOptInfo = (MSG_SENDINGOPT_INFO_S*)(pCmd->cmdData + sizeof(MSG_MESSAGE_INFO_S));
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
 
-       // Add Message
-       err = MsgStoAddMessage(pMsgInfo, pSendOptInfo);
+       MsgDecodeMsgInfo((char *)pCmd->cmdData, &msgInfo, &sendOptInfo);
 
-       if (err == MSG_SUCCESS) {
-                       MSG_DEBUG("Command Handle Success : MsgStoAddMessage()");
+       if(msgInfo.threadId) // threadId is not 0 : message restore from S-Cloud
+       {
+               err = MsgStoRestoreMessage(&msgInfo, &sendOptInfo);
+
+               if (err == MSG_SUCCESS) {
+                               MSG_DEBUG("Command Handle Success : MsgStoRestoreMessage()");
+
+                               // Encoding Message ID
+                               dataSize = MsgEncodeMsgId(&(msgInfo.msgId), &encodedData);
+               } else {
+                       MSG_DEBUG("Command Handle Fail : MsgStoRestoreMessage()");
+               }
+       }
+       else
+       {
+               // Add Message
+               msgInfo.msgId = 0;
+               err = MsgStoAddMessage(&msgInfo, &sendOptInfo);
 
+               if (err == MSG_SUCCESS) {
+                       MSG_DEBUG("Command Handle Success : MsgStoAddMessage()");
                        // Encoding Message ID
-                       dataSize = MsgEncodeMsgId(&(pMsgInfo->msgId), &encodedData);
+                       dataSize = MsgEncodeMsgId(&(msgInfo.msgId), &encodedData);
                } else {
                        MSG_DEBUG("Command Handle Fail : MsgStoAddMessage()");
                }
-
-       // Delete Temp File for Message Data
-       if (pMsgInfo->bTextSms == false)
-               MsgDeleteFile(pMsgInfo->msgData); //ipc
+       }
 
        //storage change CB
        msg_id_list_s msgIdList;
@@ -68,11 +115,23 @@ int MsgAddMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
 
        msgIdList.nCount = 1;
-       msgIds[0] = pMsgInfo->msgId;
+       msgIds[0] = msgInfo.msgId;
        msgIdList.msgIdList = msgIds;
 
        MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
 
+       // Update unread message status
+       if (msgInfo.folderId == MSG_INBOX_ID && msgInfo.bRead == false) {
+               mx.lock();
+               g_job_cnt++;
+               g_timeout_add(300, __refresh_noti, NULL);
+               mx.unlock();
+       }
+
+       // Delete Temp File for Message Data
+       if (msgInfo.bTextSms == false)
+               MsgDeleteFile(msgInfo.msgData); //ipc
+
        // Make Event Data
        eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_ADD_MSG, err, (void**)ppEvent);
 
@@ -84,16 +143,30 @@ int MsgAddSyncMLMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
-       int eventSize = 0;
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+
+       int dataSize = 0, eventSize = 0;
 
        int extId = 0, pinCode = 0;
 
-       MSG_MESSAGE_INFO_S msgInfo = {};
+       MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
 
        memcpy(&extId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(int));
        memcpy(&pinCode, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(int)), sizeof(int));
-       memcpy(&msgInfo, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(int)+sizeof(int)), sizeof(MSG_MESSAGE_INFO_S));
 
+       MsgDecodeMsgInfo((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(int)+sizeof(int), &msgInfo);
+
+       msgInfo.msgId = 0;
        // Add Message
        err = MsgStoAddSyncMLMessage(&msgInfo, extId, pinCode);
 
@@ -101,6 +174,9 @@ int MsgAddSyncMLMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        {
                MSG_DEBUG("Command Handle Success : MsgStoAddSyncMLMessage()");
 
+               // Encoding Message ID
+               dataSize = MsgEncodeMsgId(&(msgInfo.msgId), &encodedData);
+
                // broadcast to listener threads, here
                MsgTransactionManager::instance()->broadcastIncomingMsgCB(err, &msgInfo);
                //storage change CB
@@ -120,7 +196,7 @@ int MsgAddSyncMLMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        }
 
        // Make Event Data
-       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_ADD_SYNCML_MSG, err, (void**)ppEvent);
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_ADD_SYNCML_MSG, err, (void**)ppEvent);
 
        return eventSize;
 }
@@ -130,16 +206,25 @@ int MsgUpdateMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
-       // Get Message Info
-       MSG_MESSAGE_INFO_S* pMsgInfo = (MSG_MESSAGE_INFO_S*)pCmd->cmdData;
+       MSG_MESSAGE_INFO_S msgInfo;
+       MSG_SENDINGOPT_INFO_S sendOptInfo;
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+       memset(&sendOptInfo, 0x00, sizeof(MSG_SENDINGOPT_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
 
-       // Get Sending Option
-       MSG_SENDINGOPT_INFO_S* pSendOptInfo = (MSG_SENDINGOPT_INFO_S*)(pCmd->cmdData + sizeof(MSG_MESSAGE_INFO_S));
+       MsgDecodeMsgInfo((char *)pCmd->cmdData, &msgInfo, &sendOptInfo);
 
        // Update Message
-       err = MsgStoUpdateMessage(pMsgInfo, pSendOptInfo);
+       err = MsgStoUpdateMessage(&msgInfo, &sendOptInfo);
 
        if (err == MSG_SUCCESS)
                MSG_DEBUG("Command Handle Success : MsgStoUpdateMessage()");
@@ -147,8 +232,8 @@ int MsgUpdateMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
                MSG_DEBUG("Command Handle Fail : MsgStoUpdateMessage()");
 
        // Delete Temp File for Message Data
-       if (pMsgInfo->bTextSms == false)
-               MsgDeleteFile(pMsgInfo->msgData); //ipc
+       if (msgInfo.bTextSms == false)
+               MsgDeleteFile(msgInfo.msgData); //ipc
 
        //storage change CB
        msg_id_list_s msgIdList;
@@ -156,7 +241,7 @@ int MsgUpdateMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
 
        msgIdList.nCount = 1;
-       msgIds[0] = pMsgInfo->msgId;
+       msgIds[0] = msgInfo.msgId;
        msgIdList.msgIdList = msgIds;
 
        MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
@@ -172,6 +257,11 @@ int MsgUpdateReadStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        msg_message_id_t msgId;
@@ -183,6 +273,8 @@ int MsgUpdateReadStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        // Update Read Status
        err = MsgStoUpdateReadStatus(msgId, readStatus);
 
+       MSG_DEBUG("message id = [%d], readStatus = [%d]", msgId, readStatus);
+
        if (err == MSG_SUCCESS)
        {
                MSG_DEBUG("Command Handle Success : MsgStoUpdateReadStatus()");
@@ -192,6 +284,17 @@ int MsgUpdateReadStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
                MSG_DEBUG("Command Handle Fail : MsgStoUpdateReadStatus()");
        }
 
+       //storage change CB
+       msg_id_list_s msgIdList;
+       msg_message_id_t msgIds[1];
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+       msgIdList.nCount = 1;
+       msgIds[0] = msgId;
+       msgIdList.msgIdList = msgIds;
+
+       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+
        // Make Event Data
        eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_UPDATE_READ, err, (void**)ppEvent);
 
@@ -203,6 +306,11 @@ int MsgUpdateThreadReadStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        msg_thread_id_t threadId;
@@ -216,12 +324,47 @@ int MsgUpdateThreadReadStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 
        if (unReadCnt > 0) {
 
-               err = MsgStoUpdateThreadReadStatus(threadId);
+               msg_id_list_s msgIdList;
+               memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+               err = MsgStoUpdateThreadReadStatus(threadId, &msgIdList);
 
-               if (err == MSG_SUCCESS)
+               if (err == MSG_SUCCESS) {
                        MSG_DEBUG("Command Handle Success : MsgStoUpdateThreadReadStatus()");
-               else
+                       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+               } else {
                        MSG_DEBUG("Command Handle Fail : MsgStoUpdateThreadReadStatus()");
+               }
+
+               if(msgIdList.msgIdList != NULL)
+                       delete [] (char*)msgIdList.msgIdList;
+       }
+
+       // delete report notification
+       if (err == MSG_SUCCESS) {
+               MsgDbHandler *dbHandle = getDbHandle();
+               char tempAddr[MAX_ADDRESS_VAL_LEN+1];
+               char sqlQuery[MAX_QUERY_LEN+1];
+
+               memset(tempAddr, 0x00, sizeof(tempAddr));
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT B.ADDRESS_VAL FROM %s A, %s B WHERE A.CONV_ID = B.CONV_ID AND A.CONV_ID = %d;"
+                               , MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, threadId);
+
+               err = dbHandle->prepareQuery(sqlQuery);
+
+               if (err == MSG_SUCCESS) {
+                       err = dbHandle->stepQuery();
+
+                       if (err == MSG_ERR_DB_ROW) {
+                               snprintf(tempAddr, sizeof(tempAddr), "%s", dbHandle->columnText(0));
+                               MSG_SEC_DEBUG("Updated address = %s", tempAddr);
+                               MsgDeleteReportNotification(tempAddr);
+                               err = MSG_SUCCESS;
+                       }
+               }
+
+               dbHandle->finalizeQuery();
        }
 
        // Make Event Data
@@ -236,6 +379,11 @@ int MsgUpdateProtectedStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        msg_message_id_t msgId;
@@ -256,6 +404,17 @@ int MsgUpdateProtectedStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
                MSG_DEBUG("Command Handle Fail : MsgStoUpdateProtectedStatus()");
        }
 
+       //storage change CB
+       msg_id_list_s msgIdList;
+       msg_message_id_t msgIds[1];
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+       msgIdList.nCount = 1;
+       msgIds[0] = msgId;
+       msgIdList.msgIdList = msgIds;
+
+       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+
        // Make Event Data
        eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_UPDATE_PROTECTED, err, (void**)ppEvent);
 
@@ -267,6 +426,11 @@ int MsgDeleteMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        int extId = 0;
@@ -310,6 +474,11 @@ int MsgDeleteAllMessageInFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        msg_folder_id_t* folderId = (msg_folder_id_t*)pCmd->cmdData;
@@ -341,10 +510,59 @@ int MsgDeleteAllMessageInFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 }
 
 
+int MsgDeleteMessageByListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       int eventSize = 0;
+
+       msg_id_list_s msgIdList;
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+       msgIdList.nCount = *((int *)pCmd->cmdData);
+
+       MSG_DEBUG("msgIdList.nCount [%d]", msgIdList.nCount);
+
+       msg_message_id_t msgIds[msgIdList.nCount];
+       memset(msgIds, 0x00, sizeof(msgIds));
+
+       msgIdList.msgIdList = msgIds;
+
+       for (int i=0; i<msgIdList.nCount; i++) {
+               msgIds[i] = *(msg_message_id_t *)(((char*)pCmd->cmdData) + (sizeof(int)*(i+1)));
+       }
+
+       // Delete Message
+       err = MsgStoDeleteMessageByList(&msgIdList);
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Command Handle Success : MsgStoDeleteMessageByList()");
+               MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_DELETE, &msgIdList);
+       } else {
+               MSG_DEBUG("Command Handle Fail : MsgStoDeleteMessageByList()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_DELETE_MESSAGE_BY_LIST, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
 int MsgMoveMessageToFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        msg_message_id_t msgId;
@@ -383,6 +601,11 @@ int MsgMoveMessageToStorageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        msg_message_id_t msgId;
@@ -414,8 +637,13 @@ int MsgCountMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
@@ -450,8 +678,13 @@ int MsgCountMsgByTypeHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
@@ -486,11 +719,16 @@ int MsgGetMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        // Get Message ID
        msg_message_id_t* msgId = (msg_message_id_t*)pCmd->cmdData;
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
@@ -501,6 +739,9 @@ int MsgGetMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
        memset(&sendOptInfo, 0x00, sizeof(MSG_SENDINGOPT_INFO_S));
 
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
        err = MsgStoGetMessage(*msgId, &msgInfo, &sendOptInfo);
 
        if (err == MSG_SUCCESS)
@@ -526,7 +767,10 @@ int MsgGetMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 
 int MsgGetFolderViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
-       msg_error_t err = MSG_SUCCESS;
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        // Get Folder ID
        msg_folder_id_t folderId;
@@ -536,14 +780,15 @@ int MsgGetFolderViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        memcpy(&sortRule, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_folder_id_t)), sizeof(MSG_SORT_RULE_S));
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
+#if 0
        // Get Message Common Info
        msg_struct_list_s folderViewList;
 
-       err = MsgStoGetFolderViewList(folderId, &sortRule, &folderViewList);
+//     err = MsgStoGetFolderViewList(folderId, &sortRule, &folderViewList);
 
        if (err == MSG_SUCCESS)
        {
@@ -554,10 +799,14 @@ int MsgGetFolderViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 
                MSG_DEBUG("dataSize [%d]", dataSize);
 
-               if (folderViewList.msg_struct_info != NULL)
-               {
-                       delete [] folderViewList.msg_struct_info;
-                       folderViewList.msg_struct_info = NULL;
+               if (folderViewList.msg_struct_info) {
+                       msg_struct_s *msg_struct;
+                       for (int i = 0; i < folderViewList.nCount; i++) {
+                               msg_struct = (msg_struct_s *)folderViewList.msg_struct_info[i];
+                               delete (MSG_MESSAGE_HIDDEN_S *)msg_struct->data;
+                               delete msg_struct;
+                       }
+                       g_free(folderViewList.msg_struct_info);
                }
        }
        else
@@ -565,7 +814,7 @@ int MsgGetFolderViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
                MSG_DEBUG("Command Handle Fail : MsgStoGetFolderViewList()");
                return err;
        }
-
+#endif
        // Make Event Data
        eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_FOLDERVIEWLIST, MSG_SUCCESS, (void**)ppEvent);
 
@@ -577,6 +826,11 @@ int MsgAddFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        // Get Folder Info
@@ -605,6 +859,11 @@ int MsgUpdateFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        // Get Folder Info
@@ -633,6 +892,11 @@ int MsgDeleteFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        // Get Folder Info
@@ -661,8 +925,13 @@ int MsgGetFolderListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
@@ -678,7 +947,15 @@ int MsgGetFolderListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
                // Encoding Folder List Data
                dataSize = MsgEncodeFolderList(&folderList, &encodedData);
 
-               delete [] folderList.msg_struct_info;
+               if (folderList.msg_struct_info) {
+                       msg_struct_s *msg_struct;
+                       for (int i = 0; i < folderList.nCount; i++) {
+                               msg_struct = (msg_struct_s *)folderList.msg_struct_info[i];
+                               delete (MSG_FOLDER_INFO_S *)msg_struct->data;
+                               delete msg_struct;
+                       }
+                       g_free(folderList.msg_struct_info);
+               }
        }
        else
        {
@@ -696,6 +973,11 @@ int MsgInitSimBySatHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        // Sim Init - Later
@@ -712,8 +994,13 @@ int MsgGetMsgTypeHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
 
        int dataSize = 0, eventSize = 0;
@@ -750,21 +1037,27 @@ int MsgGetMsgTypeHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 
 int MsgGetThreadViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
+
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        MSG_SORT_RULE_S sortRule = {0};
 
        memcpy(&sortRule, pCmd->cmdData, sizeof(MSG_SORT_RULE_S));
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
-
+#if 0
        // Get Thread View List
        msg_struct_list_s msgThreadViewList;
 
-       err = MsgStoGetThreadViewList(&sortRule, &msgThreadViewList);
+       //err = MsgStoGetThreadViewList(&sortRule, &msgThreadViewList);
 
        if (err == MSG_SUCCESS)
        {
@@ -775,10 +1068,14 @@ int MsgGetThreadViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 
                MSG_DEBUG("dataSize [%d]", dataSize);
 
-               if (msgThreadViewList.msg_struct_info != NULL)
-               {
-                       delete [] msgThreadViewList.msg_struct_info;
-                       msgThreadViewList.msg_struct_info = NULL;
+               if (msgThreadViewList.msg_struct_info) {
+                       msg_struct_s *msg_struct;
+                       for (int i = 0; i < folderList.nCount; i++) {
+                               msg_struct = (msg_struct_s *)msgThreadViewList.msg_struct_info[i];
+                               delete (MSG_THREAD_VIEW_S *)msg_struct->data;
+                               delete msg_struct;
+                       }
+                       g_free(msgThreadViewList.msg_struct_info);
                }
        }
        else
@@ -786,7 +1083,7 @@ int MsgGetThreadViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
                MSG_DEBUG("Command Handle Fail : MsgStoGetThreadViewList()");
                return err;
        }
-
+#endif
        // Make Event Data
        eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_THREADVIEWLIST, err, (void**)ppEvent);
 
@@ -798,18 +1095,23 @@ int MsgGetConversationViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        msg_thread_id_t threadId;
 
        memcpy(&threadId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_thread_id_t));
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
-
+#if 0
        msg_struct_list_s convViewList;
 
-       err = MsgStoGetConversationViewList(threadId, &convViewList);
+       //err = MsgStoGetConversationViewList(threadId, &convViewList);
 
        if (err == MSG_SUCCESS)
        {
@@ -820,17 +1122,21 @@ int MsgGetConversationViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 
                MSG_DEBUG("dataSize [%d]", dataSize);
 
-               if (convViewList.msg_struct_info != NULL)
-               {
-                       delete [] convViewList.msg_struct_info;
-                       convViewList.msg_struct_info = NULL;
+               if (convViewList.msg_struct_info) {
+                       msg_struct_s *msg_struct;
+                       for (int i = 0; i < convViewList.nCount; i++) {
+                               msg_struct = (msg_struct_s *)convViewList.msg_struct_info[i];
+                               delete (MSG_CONVERSATION_VIEW_S *)msg_struct->data;
+                               delete msg_struct;
+                       }
+                       g_free(convViewList.msg_struct_info);
                }
        }
        else
        {
                MSG_DEBUG("Command Handle Fail : MsgStoGetConversationViewList()");
        }
-
+#endif
        // Make Event Data
        eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_CONVERSATIONVIEWLIST, err, (void**)ppEvent);
 
@@ -842,10 +1148,17 @@ int MsgDeleteThreadMessageListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        msg_thread_id_t threadId;
+       bool bIncludeProtect = false;
        bool isSyncMLMsg = false;
 
        memcpy(&threadId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_thread_id_t));
+       memcpy(&bIncludeProtect, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_thread_id_t)), sizeof(bool));
 
        int eventSize = 0;
 
@@ -854,7 +1167,7 @@ int MsgDeleteThreadMessageListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        msg_id_list_s msgIdList;
        memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
 
-       err = MsgStoDeleteThreadMessageList(threadId, &msgIdList);
+       err = MsgStoDeleteThreadMessageList(threadId, bIncludeProtect, &msgIdList);
 
        if (err == MSG_SUCCESS) {
                MSG_DEBUG("Command Handle Success : MsgStoDeleteThreadMessageList()");
@@ -871,6 +1184,8 @@ int MsgDeleteThreadMessageListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        else
        {
                MSG_DEBUG("Command Handle Fail : MsgStoDeleteThreadMessageList()");
+               if(msgIdList.msgIdList != NULL)
+                       delete [] (char*)msgIdList.msgIdList;
        }
 
        // Make Event Data
@@ -884,13 +1199,18 @@ int MsgCountMsgByContactHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        // Get From address
        MSG_THREAD_LIST_INDEX_S addrInfo;
 
        memcpy(&addrInfo, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(MSG_THREAD_LIST_INDEX_S));
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
@@ -924,19 +1244,26 @@ int MsgGetQuickPanelDataHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        // Get Message ID
        msg_quickpanel_type_t* type = (msg_quickpanel_type_t*)pCmd->cmdData;
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
        // Get Message
        MSG_MESSAGE_INFO_S msgInfo;
-
        memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
 
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
        err = MsgStoGetQuickPanelData(*type, &msgInfo);
 
        if (err == MSG_SUCCESS)
@@ -962,6 +1289,11 @@ int MsgResetDatabaseHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        // Reset DB
@@ -983,8 +1315,13 @@ int MsgGetMemSizeHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
@@ -1006,10 +1343,21 @@ int MsgBackupMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
+       char path[MSG_FILEPATH_LEN_MAX+1] = {0,};
+       msg_message_backup_type_t type;
+
+       memcpy(&type, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_message_backup_type_t));
+       memcpy(&path, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_message_backup_type_t)), sizeof(path));
 
-       err = MsgStoBackupMessage();
+       MSG_DEBUG("type = %d, path = %s", type, path);
 
+       err = MsgStoBackupMessage(type, path);
        if (err == MSG_SUCCESS)
                MSG_DEBUG("Command Handle Success : MsgBackupMessageHandler()");
        else
@@ -1026,14 +1374,36 @@ int MsgRestoreMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
+       msg_id_list_s *msgIdList = NULL;
+       char path[MSG_FILEPATH_LEN_MAX+1] = {0,};
+       memcpy(&path, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(path));
+       MSG_DEBUG("path = %s", path);
 
        // Reset DB
-       err = MsgStoRestoreMessage();
+       err = MsgStoRestoreMessage(path, &msgIdList);
 
-       if (err == MSG_SUCCESS)
+       if (err == MSG_SUCCESS) {
                MSG_DEBUG("Command Handle Success : MsgStoRestoreMessage()");
-       else
+
+               if (msgIdList) {
+                       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_INSERT, msgIdList);
+
+                       if (msgIdList->msgIdList)
+                               free(msgIdList->msgIdList);
+
+                       free(msgIdList);
+                       msgIdList = NULL;
+               } else {
+                       MSG_DEBUG("Not Exist msg id list to restore");
+               }
+
+       } else
                MSG_DEBUG("Command Handle Fail : MsgStoRestoreMessage()");
 
        // Make Event Data
@@ -1047,26 +1417,41 @@ int MsgGetReportStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        // Get Message ID
        msg_message_id_t* msgId = (msg_message_id_t*)pCmd->cmdData;
+       MSG_MESSAGE_TYPE_S msgType = {0,};
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
-       MSG_REPORT_STATUS_INFO_S reportStatus;
+       MSG_REPORT_STATUS_INFO_S *reportStatus = NULL;
+       int report_count = 0;
 
-       memset(&reportStatus, 0x00, sizeof(MSG_REPORT_STATUS_INFO_S));
+       if (MsgStoGetMsgType(*msgId, &msgType) != MSG_SUCCESS)
+               MSG_DEBUG("MsgStoGetMsgType is failed");
 
-       err = MsgStoGetReportStatus(*msgId, &reportStatus);
+       if (msgType.mainType == MSG_SMS_TYPE) {
+               err = MsgStoGetSmsReportStatus(*msgId, &report_count, &reportStatus);
+       } else if (msgType.mainType == MSG_MMS_TYPE) {
+               err = MsgStoGetMmsReportStatus(*msgId, &report_count, &reportStatus);
+       } else {
+               MSG_DEBUG("Message Type is unknown!");
+               err = MSG_ERR_INVALID_MSG_TYPE;
+       }
 
        if (err == MSG_SUCCESS)
        {
                MSG_DEBUG("Command Handle Success : MsgGetReportStatusHandler()");
 
                // Encoding Report Status Data
-               dataSize = MsgEncodeReportStatus(&reportStatus, &encodedData);
+               dataSize = MsgEncodeReportStatus(reportStatus, report_count, &encodedData);
        }
        else
        {
@@ -1084,18 +1469,29 @@ int MsgGetThreadIdByAddressHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        MSG_MESSAGE_INFO_S msgInfo;
        memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
 
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
        int *addrCnt = (int *)pCmd->cmdData;
        MSG_DEBUG("*addrCnt [%d]", *addrCnt);
 
        msgInfo.nAddressCnt = *addrCnt;
-       for(int i=0; i<(*addrCnt); i++)
+
+       msgInfo.addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S) * msgInfo.nAddressCnt];
+
+       for(int i=0; i<msgInfo.nAddressCnt; i++)
                memcpy(&msgInfo.addressList[i], (MSG_ADDRESS_INFO_S *)(pCmd->cmdData+sizeof(int)+(sizeof(MSG_ADDRESS_INFO_S)*i)), sizeof(MSG_ADDRESS_INFO_S));
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0, eventSize = 0;
 
@@ -1127,8 +1523,13 @@ int MsgGetThreadInfoHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        msg_error_t err = MSG_SUCCESS;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int dataSize = 0;
        int eventSize = 0;
@@ -1156,3 +1557,393 @@ int MsgGetThreadInfoHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 
        return eventSize;
 }
+
+
+#ifdef MMS_REPORT_OPERATIONS
+int MsgCheckReadReportRequestedHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       MSG_DEBUG();
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Message ID
+       msg_message_id_t* MsgId = (msg_message_id_t*)pCmd->cmdData;
+
+       // Check ReadReport Is Requested
+       bool    bReadReportRequested;
+
+       bReadReportRequested = MsgStoCheckReadReportRequested(*MsgId);
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoCheckSendReadReport()");
+
+               // Encoding ReadReportIsSent Data
+               dataSize = MsgEncodeReadReportRequested(bReadReportRequested, &encodedData);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoCheckReadReportIsSent()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeStorageEvent(encodedData, dataSize, MSG_EVENT_PLG_CHECK_READ_REPORT_REQUESTED, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgCheckReadReportIsSentHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       MSG_DEBUG();
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Message ID
+       msg_message_id_t* MsgId = (msg_message_id_t*)pCmd->cmdData;
+
+       // Check ReadReport Is Sent
+       bool    bReadReportIsSent;
+
+       MSG_DEBUG("#### MSGID = %d ####", *MsgId);
+
+       bReadReportIsSent = MsgStoCheckReadReportIsSent(*MsgId);
+       MSG_DEBUG("######## 1. bReadStatusIsSent = %d #######", bReadReportIsSent);
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoCheckReadReportIsSent()");
+
+               // Encoding ReadReportIsSent Data
+               dataSize = MsgEncodeReadReportIsSent(bReadReportIsSent, &encodedData);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoCheckReadReportIsSent()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeStorageEvent(encodedData, dataSize, MSG_EVENT_PLG_CHECK_READ_REPORT_IS_SENT, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgSetReadReportSendStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       MSG_DEBUG();
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Message ID
+       msg_message_id_t msgId;
+       int     readReportSendStatus;
+
+       memcpy(&msgId, (char*)pCmd + sizeof(MSG_CMD_TYPE_T), sizeof(msg_message_id_t));
+       memcpy(&readReportSendStatus, (char*)pCmd + sizeof(MSG_CMD_TYPE_T) + sizeof(msg_message_id_t), sizeof(int));
+
+       // Set Read Report Send Status
+       err = MsgStoSetReadReportSendStatus(msgId, readReportSendStatus);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoUpdateReadStatus()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoUpdateReadStatus()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeStorageEvent(encodedData, dataSize, MSG_EVENT_PLG_SET_READ_REPORT_SEND_STATUS, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetMmsVersionHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       MSG_DEBUG();
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Message ID
+       msg_message_id_t* MsgId = (msg_message_id_t*)pCmd->cmdData;
+
+       // Check ReadReport Is Sent
+       int     version;
+
+       MSG_DEBUG("#### MSGID = %d ####", *MsgId);
+
+       version = MsgStoGetMmsVersion(*MsgId);
+       MSG_DEBUG("######## 1. version = %x #######", version);
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoCheckReadReportIsSent()");
+
+               // Encoding ReadReportIsSent Data
+               dataSize = MsgEncodeMmsVersion(version, &encodedData);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoCheckReadReportIsSent()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeStorageEvent(encodedData, dataSize, MSG_EVENT_PLG_GET_MMS_VERSION, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetMmsStatusInfoHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       MSG_DEBUG();
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Message ID
+       msg_message_id_t* MsgId = (msg_message_id_t*)pCmd->cmdData;
+
+       MMS_STATUS_INFO_S mmsStatusInfo;
+
+       MSG_DEBUG("#### MSGID = %d ####", *MsgId);
+
+       err = MsgStoGetMmsStatusInfo(*MsgId,&mmsStatusInfo);
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgGetMmsStatusInfoHandler()");
+
+               // Encoding ReadReportIsSent Data
+               dataSize = MsgEncodeMmsStatusInfo(&mmsStatusInfo, &encodedData);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgGetMmsStatusInfoHandler()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeStorageEvent(encodedData, dataSize, MSG_EVENT_PLG_GET_MMS_STATUS_INFO, err, (void**)ppEvent);
+
+       return eventSize;
+}
+#endif
+
+
+int MsgAddPushEventHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       int eventSize = 0;
+
+       // Get Message Info
+       MSG_PUSH_EVENT_INFO_S* pPushEvent = (MSG_PUSH_EVENT_INFO_S*)pCmd->cmdData;
+
+       // Add Message
+       err = MsgStoAddPushEvent(pPushEvent);
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Command Handle Success : MsgStoAddPushEvent()");
+       } else {
+               MSG_DEBUG("Command Handle Fail : MsgStoAddPushEvent()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_ADD_PUSH_EVENT, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+int MsgDeletePushEventHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       int eventSize = 0;
+
+       // Get Message Info
+       MSG_PUSH_EVENT_INFO_S* pPushEvent = (MSG_PUSH_EVENT_INFO_S*)pCmd->cmdData;
+
+       // Add Message
+       err = MsgStoDeletePushEvent(pPushEvent);
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Command Handle Success : MsgStoDeletePushEvent()");
+       } else {
+               MSG_DEBUG("Command Handle Fail : MsgStoDeletePushEvent()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_DELETE_PUSH_EVENT, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+int MsgUpdatePushEventHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       int eventSize = 0;
+
+       // Get Message Info
+       MSG_PUSH_EVENT_INFO_S* pSrc = (MSG_PUSH_EVENT_INFO_S*)pCmd->cmdData;
+       MSG_PUSH_EVENT_INFO_S* pDst = (MSG_PUSH_EVENT_INFO_S*)(pCmd->cmdData + sizeof(MSG_PUSH_EVENT_INFO_S));
+
+       // Add Message
+       err = MsgStoUpdatePushEvent(pSrc, pDst);
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Command Handle Success : MsgStoUpdatePushEvent()");
+       } else {
+               MSG_DEBUG("Command Handle Fail : MsgStoUpdatePushEvent()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_UPDATE_PUSH_EVENT, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+int MsgAddSimMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       int eventSize = 0;
+
+       MSG_MESSAGE_INFO_S msgInfo;
+       MSG_SENDINGOPT_INFO_S sendOptInfo;
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+       memset(&sendOptInfo, 0x00, sizeof(MSG_SENDINGOPT_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       MsgDecodeMsgInfo((char *)pCmd->cmdData, &msgInfo);
+
+       int *simIdList = NULL;
+       int listSize = 0;
+       char *offset = NULL;
+       offset = ((char *)pCmd->cmdData) + sizeof(MSG_MESSAGE_INFO_S) + (sizeof(MSG_ADDRESS_INFO_S) * msgInfo.nAddressCnt);
+
+       listSize = *(int*)offset;
+       offset += sizeof(int);
+       MSG_DEBUG("listSize [%d]", listSize);
+
+       simIdList = (int *)offset;
+
+       MSG_DEBUG("simIdList[0] [%d]", simIdList[0]);
+
+       // Add Message
+#if 0 // Not to broadcast callback here.
+       bool isReplaceMsg = false;
+
+       if (msgInfo.msgId <= 0)
+               msgInfo.msgId = 0;
+       else
+               isReplaceMsg = true;
+#else
+       if (msgInfo.msgId <= 0)
+               msgInfo.msgId = 0;
+#endif
+
+       msg_message_id_t msg_id = MsgStoAddSimMessage(&msgInfo, simIdList, listSize);
+
+       if (msg_id > 0) {
+               MSG_DEBUG("Command Handle Success : MsgStoAddSimMessage()");
+
+#if 0 // Not to broadcast callback here.
+               //storage change CB
+               msg_id_list_s msgIdList;
+               msg_message_id_t msgIds[1];
+               memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+               msgIdList.nCount = 1;
+               msgIds[0] = msgInfo.msgId;
+               msgIdList.msgIdList = msgIds;
+
+               if (isReplaceMsg)
+                       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+               else
+                       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+#endif
+       } else {
+                       MSG_DEBUG("Command Handle Fail : MsgStoAddSimMessage()");
+                       err = MSG_ERR_INVALID_MESSAGE;
+       }
+
+       // Delete Temp File for Message Data
+       if (msgInfo.bTextSms == false)
+               MsgDeleteFile(msgInfo.msgData); //ipc
+
+       // Make Event Data
+       eventSize = MsgMakeEvent((const void *)&msg_id, sizeof(msg_message_id_t), MSG_EVENT_ADD_SIM_MSG, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgUpdateIMSIHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       int eventSize = 0;
+
+       int sim_idx = 0;
+       memcpy(&sim_idx, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(int));
+
+       // Add Message
+       err = MsgStoUpdateIMSI(sim_idx);
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Command Handle Success : MsgStoUpdatePushEvent()");
+       } else {
+               MSG_DEBUG("Command Handle Fail : MsgStoUpdatePushEvent()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_UPDATE_IMSI, err, (void**)ppEvent);
+
+       return eventSize;
+}
index 113e6ff..7d5e884 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <time.h>
 #include "MsgStorageHandler.h"
 #include "MsgTransManager.h"
 #include "MsgPluginManager.h"
+#include "MsgUtilStorage.h"
+#include "MsgAlarm.h"
 #include "MsgCmdHandler.h"
+#include "MsgDevicedWrapper.h"
 
-#include <alarm.h>
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
@@ -41,16 +43,26 @@ int MsgSubmitReqHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        msg_error_t err = MSG_SUCCESS;
        bool bNewMsg = true;
 
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
        int eventSize = 0;
 
        MSG_REQUEST_INFO_S reqInfo = {0,};
        MSG_PROXY_INFO_S proxyInfo = {0,};
 
+       reqInfo.msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&reqInfo.msgInfo.addressList, unique_ptr_deleter);
+
        // Get Message Request
-       memcpy(&reqInfo, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(MSG_REQUEST_INFO_S));
+       memcpy(&reqInfo.reqId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_request_id_t));
 
        // Storing Request ID, Proxy Info for Sent Status CNF
-       memcpy(&proxyInfo, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_REQUEST_INFO_S)), sizeof(MSG_PROXY_INFO_S));
+       memcpy(&proxyInfo, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_request_id_t)), sizeof(MSG_PROXY_INFO_S));
+
+       MsgDecodeMsgInfo((char *)(pCmd->cmdData+sizeof(msg_request_id_t)+sizeof(MSG_PROXY_INFO_S)), &reqInfo.msgInfo, &reqInfo.sendOptInfo);
 
        if (reqInfo.msgInfo.msgId > 0)
                bNewMsg = false;
@@ -89,7 +101,7 @@ int MsgSubmitReqHandler(const MSG_CMD_S *pCmd, char **ppEvent)
                pFileName = strstr(reqInfo.msgInfo.msgData, "MSG_");
                strncpy(trId.pduFileName, pFileName, MAX_COMMON_INFO_SIZE);
 
-               MSG_DEBUG("java MMS msg trId:%s filepath:%s ",trId.id, reqInfo.msgInfo.msgData);
+               MSG_SEC_DEBUG("java MMS msg trId:%s filepath:%s ",trId.id, reqInfo.msgInfo.msgData);
 
                MsgTransactionManager* tm = MsgTransactionManager::instance();
                tm->setJavaMMSList(&trId);
@@ -99,50 +111,37 @@ int MsgSubmitReqHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        eventSize = MsgMakeEvent(&reqId, sizeof(reqId), MSG_EVENT_SUBMIT_REQ, err, (void**)ppEvent);
 
        /* reject_msg_support */
-       if(((reqInfo.msgInfo.msgType.subType == MSG_NOTIFYRESPIND_MMS) &&
+       if (((reqInfo.msgInfo.msgType.subType == MSG_NOTIFYRESPIND_MMS) &&
                 (reqInfo.msgInfo.msgType.mainType == MSG_MMS_TYPE)))
                err = MsgStoDeleteMessage(reqInfo.msgInfo.msgId, true);
 
        /** send storage CB */
-       if ((err == MSG_SUCCESS || err != MSG_ERR_PLUGIN_STORAGE) && bNewMsg && reqInfo.msgInfo.msgPort.valid == false) {
-
-               msg_id_list_s msgIdList;
-               msg_message_id_t msgIds[1];
-               memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+       msg_id_list_s msgIdList;
+       msg_message_id_t msgIds[1];
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
 
-               msgIdList.nCount = 1;
-               msgIds[0] = reqInfo.msgInfo.msgId;
-               msgIdList.msgIdList = msgIds;
+       msgIdList.nCount = 1;
+       msgIds[0] = reqInfo.msgInfo.msgId;
+       msgIdList.msgIdList = msgIds;
 
-               MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+       if ((err == MSG_SUCCESS || err != MSG_ERR_PLUGIN_STORAGE) && reqInfo.msgInfo.msgPort.valid == false) {
+               if (bNewMsg) {
+                       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+               } else {
+                       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+               }
+       } else {
+               MSG_DEBUG("No need to broadcast storage change CB");
        }
-       return eventSize;
-}
-
 
-int MsgCancelReqHandler(const MSG_CMD_S *pCmd, char **ppEvent)
-{
-       msg_error_t err = MSG_SUCCESS;
-
-       int eventSize = 0;
-
-       // Get Request ID
-       msg_request_id_t* reqId = (msg_request_id_t*)pCmd->cmdData;
-
-       // Cancel Request
-       err = MsgCancelReq(*reqId);
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
 
-       if (err == MSG_SUCCESS)
+       MsgStoAutoDeleteConversation(reqInfo.msgInfo.threadId, &msgIdList);
+       if (msgIdList.msgIdList)
        {
-               MSG_DEBUG("Command Handle Success : MsgSubCancelReq()");
+               MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_DELETE, &msgIdList);
+               delete [] (char*)msgIdList.msgIdList;
        }
-       else
-       {
-               MSG_DEBUG("Command Handle Fail : MsgSubCancelReq()");
-       }
-
-       // Make Event Data
-       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_CANCEL_REQ, err, (void**)ppEvent);
 
        return eventSize;
 }
@@ -151,8 +150,10 @@ int MsgCancelReqHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 int MsgRegSentStatusCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        // input check
-       if( !pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        // Get Message Request
        int listenerFd = *((int*) pCmd->cmdData);
@@ -171,8 +172,10 @@ int MsgRegSentStatusCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 int MsgRegIncomingMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        // input check
-       if( !pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        // Get Message Request
        MSG_CMD_REG_INCOMING_MSG_CB_S *pCmdData = (MSG_CMD_REG_INCOMING_MSG_CB_S*) pCmd->cmdData;
@@ -191,8 +194,10 @@ int MsgRegIncomingMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 int MsgRegIncomingMMSConfMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        // input check
-       if( !pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        // Get Message Request
        MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB_S *pCmdData = (MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB_S*) pCmd->cmdData;
@@ -207,12 +212,60 @@ int MsgRegIncomingMMSConfMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEven
        return eventSize;
 }
 
+int MsgRegIncomingPushMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       // input check
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       // Get Message Request
+       MSG_CMD_REG_INCOMING_PUSH_MSG_CB_S *pCmdData = (MSG_CMD_REG_INCOMING_PUSH_MSG_CB_S*) pCmd->cmdData;
+       MSG_DEBUG("Registering incoming Push Msg CB for fd:%d mType:%d appId:%s", pCmdData->listenerFd, pCmdData->msgType, pCmdData->appId);
+
+       // storing dst fd in list
+       MsgTransactionManager::instance()->setPushMsgCB(pCmdData);
+       //MsgTransactionManager::instance()->sendPendigPushMsg(pCmdData);
+
+
+       // Make Event Data
+       int eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_REG_INCOMING_PUSH_MSG_CB, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+
+int MsgRegIncomingCBMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       // input check
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       // Get Message Request
+       MSG_CMD_REG_INCOMING_CB_MSG_CB_S *pCmdData = (MSG_CMD_REG_INCOMING_CB_MSG_CB_S*) pCmd->cmdData;
+       MSG_DEBUG("Registering incoming CB Msg CB for fd:%d mType:%d: bSave: %d", pCmdData->listenerFd, pCmdData->msgType, pCmdData->bsave);
+
+       // storing dst fd in list
+       MsgTransactionManager::instance()->setCBMsgCB(pCmdData);
+
+       // Make Event Data
+       int eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_REG_INCOMING_CB_MSG_CB, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
 
 int MsgRegIncomingSyncMLMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        // input check
-       if( !pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        // Get Message Request
        MSG_CMD_REG_INCOMING_SYNCML_MSG_CB_S *pCmdData = (MSG_CMD_REG_INCOMING_SYNCML_MSG_CB_S*) pCmd->cmdData;
@@ -231,8 +284,10 @@ int MsgRegIncomingSyncMLMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent
 int MsgRegIncomingLBSMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        // input check
-       if( !pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        // Get Message Request
        MSG_CMD_REG_INCOMING_LBS_MSG_CB_S *pCmdData = (MSG_CMD_REG_INCOMING_LBS_MSG_CB_S*) pCmd->cmdData;
@@ -251,8 +306,10 @@ int MsgRegIncomingLBSMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 int MsgRegSyncMLMsgOperationCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        // input check
-       if( !pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        // Get Message Request
        MSG_CMD_REG_SYNCML_MSG_OPERATION_CB_S *pCmdData = (MSG_CMD_REG_SYNCML_MSG_OPERATION_CB_S*) pCmd->cmdData;
@@ -271,8 +328,10 @@ int MsgRegSyncMLMsgOperationCallbackHandler(const MSG_CMD_S *pCmd, char **ppEven
 int MsgRegStorageChangeCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        // input check
-       if( !pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        // Get Message Request
        int listenerFd = *((int*) pCmd->cmdData);
@@ -288,11 +347,35 @@ int MsgRegStorageChangeCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 }
 
 
+int MsgRegIncomingReportMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       // input check
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       // Get Message Request
+       int listenerFd = *((int*) pCmd->cmdData);
+       MSG_DEBUG("Registering report msg incoming CB for %d", listenerFd);
+
+       // storing dst fd in list
+       MsgTransactionManager::instance()->setReportMsgCB(listenerFd);
+
+       // Make Event Data
+       int eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_REG_REPORT_MSG_INCOMING_CB, MsgException::SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
 int MsgSentStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        // input check
-       if (!pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        // Get Message Request
        MSG_SENT_STATUS_S* pStatus = (MSG_SENT_STATUS_S*) pCmd->cmdData;
@@ -302,9 +385,8 @@ int MsgSentStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        // storing dst fd in list
        MSG_PROXY_INFO_S* prxInfo = MsgTransactionManager::instance()->getProxyInfo(pStatus->reqId);
 
-       // when no sent status cb is found (in case of mobile tracker)
-       if (!prxInfo)
-       {
+       // when no sent status cb is found
+       if (!prxInfo) {
                return MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_SENT_STATUS_CNF, MSG_SUCCESS, (void**)ppEvent);
        }
 
@@ -344,37 +426,86 @@ int MsgIncomingMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        msg_error_t err = MSG_SUCCESS;
        int eventSize = 0;
        bool sendNoti = true;
+       bool isClass2msg = false;
 
        // input check
-       if (!pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        // Get Incoming Message
        MSG_MESSAGE_INFO_S msgInfo;
        memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
 
-       memcpy(&msgInfo, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(MSG_MESSAGE_INFO_S));
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
 
-       // normal process
-       err = MsgHandleIncomingMsg(&msgInfo, &sendNoti);
+       MsgDecodeMsgInfo((char *)pCmd->cmdData, &msgInfo);
 
        // broadcast to listener threads, here
        msg_id_list_s msgIdList;
-       msg_message_id_t msgIds[1];
+       msg_message_id_t msgIds[2];
+       msg_message_id_t class2msgId = 0;
        memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
 
-       msgIdList.nCount = 1;
-       msgIds[0] = msgInfo.msgId;
-       msgIdList.msgIdList = msgIds;
+#ifdef MSG_NOTI_INTEGRATION
+       if (msgInfo.msgType.classType == MSG_CLASS_2) {
+               class2msgId = msgInfo.msgId;
+               isClass2msg = true;
+       }
+#endif
+
+       // normal process
+       err = MsgHandleIncomingMsg(&msgInfo, &sendNoti);
+
+       if (isClass2msg == true) {
+               msgIdList.nCount = 2;
+               msgIds[0] = class2msgId;
+               msgIds[1] = msgInfo.msgId;
+               msgIdList.msgIdList = msgIds;
+               isClass2msg = false;
+       } else {
+               msgIdList.nCount = 1;
+               msgIds[0] = msgInfo.msgId;
+               msgIdList.msgIdList = msgIds;
+       }
 
        if (sendNoti == true) {
                MsgTransactionManager::instance()->broadcastIncomingMsgCB(err, &msgInfo);
-               MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+               if (msgInfo.msgType.subType > MSG_TYPE0_SMS && msgInfo.msgType.subType < MSG_WAP_SI_SMS) { // if it is replacement message.
+                       MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+               } else {
+                       MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+               }
+       } else if (msgInfo.msgPort.valid || (msgInfo.msgType.subType >= MSG_MWI_VOICE_SMS && msgInfo.msgType.subType <= MSG_MWI_OTHER_SMS)) {
+               MsgTransactionManager::instance()->broadcastIncomingMsgCB(err, &msgInfo);
        } else if (msgInfo.folderId == MSG_SPAMBOX_ID) {
                MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+       } else if (msgInfo.msgType.subType == MSG_STATUS_REPORT_SMS || msgInfo.msgType.subType == MSG_DELIVERYIND_MMS) {
+               MsgTransactionManager::instance()->broadcastReportMsgCB(err, MSG_REPORT_TYPE_DELIVERY, &msgInfo);
+       } else if (msgInfo.msgType.subType == MSG_READORGIND_MMS) {
+               MsgTransactionManager::instance()->broadcastReportMsgCB(err, MSG_REPORT_TYPE_READ, &msgInfo);
        }
 
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+       MsgStoAutoDeleteConversation(msgInfo.threadId, &msgIdList);
+       if (msgIdList.msgIdList)
+       {
+               MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_DELETE, &msgIdList);
+               delete [] (char*)msgIdList.msgIdList;
+       }
+
+#ifdef FEATURE_SMS_CDMA
+       eventSize = MsgMakeEvent(&msgInfo.msgId, sizeof(msg_message_id_t), MSG_EVENT_PLG_INCOMING_MSG_IND, err, (void**)ppEvent);
+#else
        eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_INCOMING_MSG_IND, err, (void**)ppEvent);
+#endif
+
+       if (msgInfo.bTextSms == false) {
+               MsgDeleteFile(msgInfo.msgData); //ipc
+               memset(msgInfo.msgData, 0x00, sizeof(msgInfo.msgData));
+       }
 
        MSG_END();
 
@@ -387,11 +518,21 @@ int MsgIncomingMMSConfMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        msg_error_t err = MSG_SUCCESS;
        int eventsize = 0;
 
-       MSG_MESSAGE_INFO_S msgInfo = {0};
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       MSG_MESSAGE_INFO_S msgInfo;
        msg_request_id_t reqID;
 
-       memcpy(&msgInfo, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(MSG_MESSAGE_INFO_S));
-       memcpy(&reqID, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_MESSAGE_INFO_S)), sizeof(msg_request_id_t));
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       memcpy(&reqID, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_request_id_t));
+       MsgDecodeMsgInfo((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_request_id_t), &msgInfo);
 
        MSG_DEBUG(" pMsg = %s, pReqId = %d ", msgInfo.msgData, reqID);
        MSG_DEBUG(" msgtype subtype is [%d]", msgInfo.msgType.subType);
@@ -405,21 +546,43 @@ int MsgIncomingMMSConfMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        msgIds[0] = msgInfo.msgId;
        msgIdList.msgIdList = msgIds;
 
-       err = MsgStoGetAddrInfo(msgInfo.msgId, &(msgInfo.addressList[0]));
+       MSG_ADDRESS_INFO_S *tmpAddr = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+       memset(tmpAddr, 0x00, sizeof(MSG_ADDRESS_INFO_S));
 
+       err = MsgStoGetAddrInfo(msgInfo.msgId, tmpAddr);
        if (err == MSG_SUCCESS) {
                MSG_DEBUG("MmsStoGetAddrInfo() success.");
                msgInfo.nAddressCnt = 1;
        } else {
+               msgInfo.nAddressCnt = 0;
                MSG_DEBUG("MmsStoGetAddrInfo() fail.");
        }
 
-       if(msgInfo.msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || msgInfo.msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS) {
+       if (msgInfo.msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || msgInfo.msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS) {
+
+               /* PLM P141008-05143 : Notification.Ind address is 1, but MMS retreived Conf address is correct.
+               So adding code for comparing exist address and new address and replace with new address(MMSconf) address */
+               if (msgInfo.nAddressCnt == 1 && msgInfo.networkStatus == MSG_NETWORK_RETRIEVE_SUCCESS && (g_strcmp0(tmpAddr->addressVal, msgInfo.addressList[0].addressVal) != 0)) {
+                       MSG_WARN("Address of NotiInd and MMSConf are different!!, Replace [NotiInd : %s] from [MMSConf : %s]", tmpAddr->addressVal, msgInfo.addressList[0].addressVal);
+                       memset(tmpAddr->addressVal, 0x00, MAX_ADDRESS_VAL_LEN);
+                       strncpy(tmpAddr->addressVal, msgInfo.addressList[0].addressVal, MAX_ADDRESS_VAL_LEN);
+               }
+
+               if (msgInfo.addressList) {
+                       delete[] msgInfo.addressList;
+                       msgInfo.addressList = NULL;
+               }
+
+               msgInfo.addressList = tmpAddr;
+
+               MSG_SUB_TYPE_T recv_sub_type = msgInfo.msgType.subType; // Check retrieve mode to determine broadcast type
 
                err = MsgHandleMmsConfIncomingMsg(&msgInfo, reqID);
 
-               if(err != MSG_SUCCESS)
-                       return err;
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgHandleMmsConfIncomingMsg failed.");
+                       return MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_INCOMING_MMS_CONF, err, (void**)ppEvent);
+               }
 
                MMS_RECV_DATA_S* pMmsRecvData = (MMS_RECV_DATA_S*)msgInfo.msgData;
 
@@ -431,19 +594,30 @@ int MsgIncomingMMSConfMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
                        memset(msgInfo.msgData, 0x00, sizeof(MMS_RECV_DATA_S));
                }
 
-               eventsize = MsgMakeEvent(&msgInfo, sizeof(MSG_MESSAGE_INFO_S), MSG_EVENT_PLG_INCOMING_MMS_CONF, msgInfo.networkStatus, (void**)ppEvent);
-
                // broadcast to listener threads, here
                MsgTransactionManager::instance()->broadcastMMSConfCB(msgInfo.networkStatus, &msgInfo, pMmsRecvData);
-               MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+
+               // determine broadcast type with retrieve mode
+               if (recv_sub_type == MSG_RETRIEVE_AUTOCONF_MMS)
+                       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+               else
+                       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+
+               // make return event
+               eventsize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_INCOMING_MMS_CONF, MSG_SUCCESS, (void**)ppEvent);
+
        } else if (msgInfo.msgType.subType == MSG_SENDREQ_MMS || msgInfo.msgType.subType == MSG_SENDCONF_MMS) {
+               if (msgInfo.addressList) {
+                       delete[] msgInfo.addressList;
+                       msgInfo.addressList = NULL;
+               }
+
+               msgInfo.addressList = tmpAddr;
+
                MSG_PROXY_INFO_S* prxInfo = MsgTransactionManager::instance()->getProxyInfo(reqID);
 
-               // when no sent status cb is found (in case of mobile tracker)
-               if (!prxInfo) {
-                       MSG_DEBUG("prxInfo is NULL");
-                       eventsize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_SENT_STATUS_CNF, MSG_SUCCESS, (void**)ppEvent);
-               } else {
+               // when no sent status cb is found
+               if (prxInfo) {
                        // No need to update javaMMS sent messages
                        javamms_list& listenerList = MsgTransactionManager::instance()->getJavaMMSList();
                        javamms_list::iterator it = listenerList.begin();
@@ -453,7 +627,7 @@ int MsgIncomingMMSConfMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
                        if (msgInfo.networkStatus == MSG_NETWORK_SEND_FAIL && msgInfo.msgType.subType == MSG_SENDREQ_MMS) {
                                for ( ; it != listenerList.end() ; it++) {
                                        if (strstr(it->pduFileName, "JAVA")) {
-                                               MSG_DEBUG("JAVA MMS fileName:%s", it->pduFileName);
+                                               MSG_SEC_DEBUG("JAVA MMS fileName:%s", it->pduFileName);
                                                MsgDeleteFile(it->pduFileName);         // ipc
                                                listenerList.erase(it);
                                                goto __BYPASS_UPDATE;
@@ -464,30 +638,43 @@ int MsgIncomingMMSConfMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
                                MMS_RECV_DATA_S* pMmsRecvData = (MMS_RECV_DATA_S*)msgInfo.msgData;
 
                                for ( ; it != listenerList.end() ; it++) {
-                                       if(!strcmp(it->id, pMmsRecvData->szTrID)) {
-                                               MSG_DEBUG("find sent JAVA MMS message trId:%s from listener list trId:%s",pMmsRecvData->szTrID, it->id);
+                                       if (!strcmp(it->id, pMmsRecvData->szTrID)) {
+                                               MSG_SEC_DEBUG("find sent JAVA MMS message trId:%s from listener list trId:%s",pMmsRecvData->szTrID, it->id);
                                                MsgDeleteFile(it->pduFileName); // ipc
                                                listenerList.erase(it);
                                                goto __BYPASS_UPDATE;
                                        }
                                }
                        }
+               } else {
+                       MSG_DEBUG("prxInfo is NULL");
                }
 
                err = MsgHandleMmsConfIncomingMsg(&msgInfo, reqID);
 
-               if(err != MSG_SUCCESS)
-                       return err;
+               if (err != MSG_SUCCESS) {
+                       return MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_INCOMING_MMS_CONF, err, (void**)ppEvent);
+               }
 
 __BYPASS_UPDATE:
                if (msgInfo.networkStatus == MSG_NETWORK_SEND_FAIL) {
                        MSG_DEBUG("message-dialog: send fail");
-                       MsgInsertTicker("Sending multimedia message failed.", SENDING_MULTIMEDIA_MESSAGE_FAILED);
+                       MsgInsertTicker("Sending multimedia message failed.", SENDING_MULTIMEDIA_MESSAGE_FAILED, true, msgInfo.msgId);
+//                     MsgSoundPlayer::instance()->MsgSoundPlayStart(NULL, MSG_NORMAL_SOUND_PLAY);
                } else {
                        MSG_DEBUG("message-dialog: send success");
-                       MsgInsertTicker("Multimedia message sent.", MULTIMEDIA_MESSAGE_SENT);
 
-                       MSG_DEBUG("Enter MsgAddPhoneLog() : msgInfo.addressList[0].addressVal [%s]", msgInfo.addressList[0].addressVal);
+                       bool bTTS = false;
+
+                       if (MsgSettingGetBool(VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, &bTTS) != MSG_SUCCESS) {
+                               MSG_DEBUG("MsgSettingGetBool is failed.");
+                       }
+
+                       if (bTTS) {
+                               MsgInsertTicker("Multimedia message sent.", MULTIMEDIA_MESSAGE_SENT, false, 0);
+                       }
+
+                       MSG_SEC_DEBUG("Enter MsgAddPhoneLog() : msgInfo.addressList[0].addressVal [%s]", msgInfo.addressList[0].addressVal);
                        MsgAddPhoneLog(&msgInfo);
                }
 
@@ -495,39 +682,128 @@ __BYPASS_UPDATE:
                        if (prxInfo->handleAddr == 0) {
                                // just making data which will be passed to plugin. it indicates "handling evt success"
                                MsgTransactionManager::instance()->delProxyInfo(reqID);
+                       } else {
 
-                               return MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_SENT_STATUS_CNF, MSG_SUCCESS, (void**)ppEvent);
-                       }
-
-                       unsigned int ret[3] = {0}; //3// reqid, status, object
+                               unsigned int ret[3] = {0}; //3// reqid, status, object
 
-                       ret[0] = reqID;
-                       ret[1] = msgInfo.networkStatus;
-                       ret[2] = prxInfo->handleAddr;
+                               ret[0] = reqID;
+                               ret[1] = msgInfo.networkStatus;
+                               ret[2] = prxInfo->handleAddr;
 
-                       // Make Event Data for APP
-                       eventsize = MsgMakeEvent(ret, sizeof(ret), MSG_EVENT_PLG_SENT_STATUS_CNF, MSG_SUCCESS, (void**)ppEvent);
+                               // Make Event Data for APP
+                               eventsize = MsgMakeEvent(ret, sizeof(ret), MSG_EVENT_PLG_SENT_STATUS_CNF, MSG_SUCCESS, (void**)ppEvent);
 
-                       // Send to listener thread, here
-                       MsgTransactionManager::instance()->write(prxInfo->listenerFd, *ppEvent, eventsize);
+                               // Send to listener thread, here
+                               MsgTransactionManager::instance()->write(prxInfo->listenerFd, *ppEvent, eventsize);
 
-                       MsgTransactionManager::instance()->delProxyInfo(reqID);
+                               MsgTransactionManager::instance()->delProxyInfo(reqID);
+                       }
                }
 
-               msgInfo.bTextSms = true;
+               eventsize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_INCOMING_MMS_CONF, MSG_SUCCESS, (void**)ppEvent);
                MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+       } else {
+               //To avoid prevent memory leak.. this case will not occur. eventsize will be return as 0.
+               if (tmpAddr) {
+                       delete[] tmpAddr;
+                       tmpAddr = NULL;
+               }
        }
 
        MSG_END();
        return eventsize;
 }
 
+int MsgIncomingPushMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       MSG_BEGIN();
+
+       int eventSize = 0;
+
+       // input check
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       MSG_PUSH_MESSAGE_DATA_S pushData;
+       memset(&pushData, 0x00, sizeof(MSG_PUSH_MESSAGE_DATA_S));
+
+       // Get Incoming Message
+       memcpy(&pushData, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(MSG_PUSH_MESSAGE_DATA_S));
+
+
+
+       // broadcast to listener threads, here
+       MsgTransactionManager::instance()->broadcastPushMsgCB(MSG_SUCCESS, &pushData);
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_INCOMING_PUSH_MSG_IND, MSG_SUCCESS, (void**)ppEvent);
+
+       MSG_END();
+       return eventSize;
+}
+
+int MsgIncomingCBMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+       int eventSize = 0;
+
+       // input check
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       // Get Incoming Message
+       MSG_CB_MSG_S cbMsg;
+       memset(&cbMsg, 0x00, sizeof(MSG_CB_MSG_S));
+
+       memcpy(&cbMsg, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(MSG_CB_MSG_S));
+
+       MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       MsgDecodeMsgInfo((char *)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_CB_MSG_S), &msgInfo);
+
+       MSG_DEBUG("CB MSG ADDRESS COUNT=%d", msgInfo.nAddressCnt);
+
+       if (MsgStoAddCBMsg(&msgInfo) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgStoAddCBMsg is fail");
+       }
+
+       MsgInsertNotification(&msgInfo);
+       MsgChangePmState();
+
+       msg_id_list_s msgIdList;
+       msg_message_id_t msgIds[1];
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+       msgIdList.nCount = 1;
+       msgIds[0] = (msg_message_id_t)msgInfo.msgId;
+       msgIdList.msgIdList = msgIds;
+       MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+       MsgTransactionManager::instance()->broadcastCBMsgCB(err, &cbMsg);
+
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_INCOMING_CB_MSG_IND, err, (void**)ppEvent);
+
+       MSG_END();
+
+       return eventSize;
+}
 
 int MsgIncomingSyncMLMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        // input check
-       if (!pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        MSG_SYNCML_MESSAGE_DATA_S syncMLData;
        memset(&syncMLData, 0x00, sizeof(MSG_SYNCML_MESSAGE_DATA_S));
@@ -552,8 +828,10 @@ int MsgIncomingLBSMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        int eventSize = 0;
 
        // input check
-       if (!pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        MSG_LBS_MESSAGE_DATA_S lbsData;
        memset(&lbsData, 0x00, sizeof(MSG_LBS_MESSAGE_DATA_S));
@@ -576,7 +854,7 @@ int MsgSyncMLMsgOperationHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        msg_error_t err = MSG_SUCCESS;
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int eventSize = 0;
 
@@ -584,8 +862,10 @@ int MsgSyncMLMsgOperationHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        int extId = 0;
 
        // input check
-       if (!pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        // Get Data
        memcpy(&msgId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_message_id_t));
@@ -615,8 +895,10 @@ int MsgSyncMLMsgOperationHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 int MsgStorageChangeHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 {
        // input check
-       if (!pCmd || !ppEvent)
-               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
 
        msg_storage_change_type_t storageChangeType;
 
@@ -627,12 +909,19 @@ int MsgStorageChangeHandler(const MSG_CMD_S *pCmd, char **ppEvent)
        memcpy(&storageChangeType, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_MESSAGE_INFO_S)), sizeof(msg_storage_change_type_t));
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        int eventSize = 0;
 
        MSG_DEBUG("storageChangeType : [%d], msg Id : [%d]", storageChangeType, msgInfo.msgId);
 
+       if (msgInfo.msgType.mainType == MSG_TYPE_SMS) {
+               if (storageChangeType == MSG_STORAGE_CHANGE_UPDATE)
+                       MsgStoUpdateMessage(&msgInfo, NULL);
+               else if (storageChangeType == MSG_STORAGE_CHANGE_DELETE)
+                       MsgStoDeleteMessage(msgInfo.msgId, true);
+       }
+
        // broadcast to listener threads, here
        msg_id_list_s msgIdList;
        msg_message_id_t msgIds[1];
@@ -649,3 +938,103 @@ int MsgStorageChangeHandler(const MSG_CMD_S *pCmd, char **ppEvent)
 
        return eventSize;
 }
+
+int MsgResendMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+       int eventSize = 0;
+
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       // Get the msgIdList of sending failed message.
+       int *failed_msg_list = NULL;
+       int count = 0;
+       unique_ptr<int*, void(*)(int**)> failed_list(&failed_msg_list, unique_ptr_deleter);
+
+
+       err = MsgStoGetFailedMessage(&failed_msg_list, &count);
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("MsgStoGetFailedMessage() Error!! [%d]", err);
+       }
+
+       for(int i=0; i < count ; ++i)
+       {
+               MSG_REQUEST_INFO_S reqInfo = {0};
+               reqInfo.msgInfo.addressList = NULL;
+               unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&reqInfo.msgInfo.addressList, unique_ptr_deleter);
+               reqInfo.msgInfo.msgId = failed_msg_list[i];
+               err = MsgStoGetMessage(reqInfo.msgInfo.msgId, &(reqInfo.msgInfo), &(reqInfo.sendOptInfo));
+
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgStoGetMessage() Error!! [%d]", err);
+               }
+
+               reqInfo.msgInfo.networkStatus = MSG_NETWORK_SENDING;
+
+               msg_id_list_s msgIdList;
+               msg_message_id_t msgIds[1];
+               memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+               msgIdList.nCount = 1;
+               msgIds[0] = reqInfo.msgInfo.msgId;
+               msgIdList.msgIdList = msgIds;
+
+               err = MsgSubmitReq(&reqInfo, false);
+
+               if (err == MSG_SUCCESS) {
+                       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+                       if (err == MSG_SUCCESS)
+                               MSG_DEBUG("MsgSubmitReq() Success");
+                       else
+                               MSG_DEBUG("MsgSubmitReq() Fail, [%d]", err);
+               } else {
+                       MSG_DEBUG("MsgSubmitReq() Fail, [%d]", err);
+               }
+       }
+
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_RESEND_MESSAGE, err, (void**)ppEvent);
+
+       MSG_END();
+       return eventSize;
+}
+
+#ifdef FEATURE_SMS_CDMA
+int MsgCheckUniquenessHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+       int eventSize = 0;
+
+       // input check
+       if (!pCmd || !ppEvent) {
+               MSG_DEBUG("pCmd or ppEvent is null");
+               return 0;
+       }
+
+       // Get Incoming Message
+       bool bInsert;
+       memcpy(&bInsert, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(bool));
+
+       msg_message_id_t msgId;
+       memcpy(&msgId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(bool)), sizeof(msg_message_id_t));
+
+       MSG_UNIQUE_INDEX_S p_msg;
+       memcpy(&p_msg, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(bool)+sizeof(msg_message_id_t)), sizeof(MSG_UNIQUE_INDEX_S));
+
+       MSG_DEBUG("Decoded Teleservice Msg Id = [%d]", p_msg.tele_msgId);
+       MSG_DEBUG("Decoded Address = [%s]", p_msg.address);
+       MSG_DEBUG("Decoded Sub Address = [%s]", p_msg.sub_address);
+
+       err = MsgCheckUniqueness(bInsert, msgId, &p_msg);
+
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_CHECK_UNIQUENESS, err, (void**)ppEvent);
+
+       MSG_END();
+
+       return eventSize;
+}
+#endif
index 6e23018..e6ffc38 100755 (executable)
@@ -1,23 +1,24 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
 #include <stdlib.h>
 #include <sys/socket.h>
 #include <sys/stat.h>
+#include <pthread.h>
 
 #include <security-server.h>
 
 #include "MsgIpcSocket.h"
 #include "MsgGconfWrapper.h"
 #include "MsgUtilFunction.h"
+#include "MsgUtilFile.h"
+#include "MsgLbs.h"
 #include "MsgCmdHandler.h"
 #include "MsgSettingHandler.h"
 #include "MsgStorageHandler.h"
 #include "MsgPluginManager.h"
 #include "MsgTransManager.h"
 
-/*==================================================================================================
-                                     FUNCTION IMPLEMENTATION
-==================================================================================================*/
-void MsgContactChangedCallback()
+#define MSG_CHECK_PRIVILEGE
+
+void MsgMakeErrorEvent(MSG_CMD_TYPE_T cmdType, msg_error_t errType, int *pEventSize, char **ppEvent)
 {
-       msg_id_list_s msgIdList;
-       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+       if (*ppEvent) delete [] *ppEvent;
+
+       *pEventSize = sizeof(MSG_EVENT_S);
+       *ppEvent = new char[sizeof(MSG_EVENT_S)];
 
-       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_CONTACT, &msgIdList);
+       MSG_EVENT_S* pMsgEvent = (MSG_EVENT_S*)*ppEvent;
+
+       pMsgEvent->eventType = cmdType;
+       pMsgEvent->result = errType;
 }
 
 /*==================================================================================================
@@ -53,10 +60,9 @@ MsgTransactionManager* MsgTransactionManager::pInstance = NULL;
 MsgIpcServerSocket MsgTransactionManager::servSock;
 
 
-MsgTransactionManager::MsgTransactionManager() : running(false), mx(), cv()
+MsgTransactionManager::MsgTransactionManager() : running(false), mx(), cv(), eventQueue()
 {
        sentMsgMap.clear();
-
        statusCBFdMap.clear();
        newMsgCBList.clear();
        newMMSConfMsgCBList.clear();
@@ -93,24 +99,29 @@ MsgTransactionManager::MsgTransactionManager() : running(false), mx(), cv()
        handlerMap[MSG_CMD_GET_FILTERLIST]              = &MsgGetFilterListHandler;
        handlerMap[MSG_CMD_SET_FILTER_OPERATION]        = &MsgSetFilterOperationHandler;
        handlerMap[MSG_CMD_GET_FILTER_OPERATION]        = &MsgGetFilterOperationHandler;
+       handlerMap[MSG_CMD_SET_FILTER_ACTIVATION] = &MsgSetFilterActivationHandler;
 
        handlerMap[MSG_CMD_GET_MSG_TYPE]                        = &MsgGetMsgTypeHandler;
 
        handlerMap[MSG_CMD_SUBMIT_REQ]                  = &MsgSubmitReqHandler;
-       handlerMap[MSG_CMD_CANCEL_REQ]                  = &MsgCancelReqHandler;
 
        handlerMap[MSG_CMD_REG_SENT_STATUS_CB]  = &MsgRegSentStatusCallbackHandler;
        handlerMap[MSG_CMD_REG_STORAGE_CHANGE_CB] = &MsgRegStorageChangeCallbackHandler;
        handlerMap[MSG_CMD_REG_INCOMING_MSG_CB] = &MsgRegIncomingMsgCallbackHandler;
        handlerMap[MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB]        = &MsgRegIncomingMMSConfMsgCallbackHandler;
        handlerMap[MSG_CMD_REG_INCOMING_SYNCML_MSG_CB]  = &MsgRegIncomingSyncMLMsgCallbackHandler;
+       handlerMap[MSG_CMD_REG_INCOMING_PUSH_MSG_CB]    = &MsgRegIncomingPushMsgCallbackHandler;
+       handlerMap[MSG_CMD_REG_INCOMING_CB_MSG_CB]      = &MsgRegIncomingCBMsgCallbackHandler;
        handlerMap[MSG_CMD_REG_INCOMING_LBS_MSG_CB]     = &MsgRegIncomingLBSMsgCallbackHandler;
        handlerMap[MSG_CMD_REG_SYNCML_MSG_OPERATION_CB] = &MsgRegSyncMLMsgOperationCallbackHandler;
+       handlerMap[MSG_CMD_REG_REPORT_MSG_INCOMING_CB] = &MsgRegIncomingReportMsgCallbackHandler;
 
        handlerMap[MSG_CMD_PLG_SENT_STATUS_CNF] = &MsgSentStatusHandler;
        handlerMap[MSG_CMD_PLG_STORAGE_CHANGE_IND]      = &MsgStorageChangeHandler;
        handlerMap[MSG_CMD_PLG_INCOMING_MSG_IND]        = &MsgIncomingMsgHandler;
        handlerMap[MSG_CMD_PLG_INCOMING_MMS_CONF]       = &MsgIncomingMMSConfMsgHandler;
+       handlerMap[MSG_CMD_PLG_INCOMING_PUSH_IND]       = &MsgIncomingPushMsgHandler;
+       handlerMap[MSG_CMD_PLG_INCOMING_CB_IND] = &MsgIncomingCBMsgHandler;
 
        handlerMap[MSG_CMD_PLG_INCOMING_SYNCML_IND] = &MsgIncomingSyncMLMsgHandler;
        handlerMap[MSG_CMD_PLG_INCOMING_LBS_IND] = &MsgIncomingLBSMsgHandler;
@@ -136,7 +147,6 @@ MsgTransactionManager::MsgTransactionManager() : running(false), mx(), cv()
 
        handlerMap[MSG_CMD_GET_THREAD_ID_BY_ADDRESS] = &MsgGetThreadIdByAddressHandler;
        handlerMap[MSG_CMD_GET_THREAD_INFO] = &MsgGetThreadInfoHandler;
-
        handlerMap[MSG_CMD_GET_SMSC_OPT] = &MsgGetConfigHandler;
        handlerMap[MSG_CMD_GET_CB_OPT] = &MsgGetConfigHandler;
        handlerMap[MSG_CMD_GET_SMS_SEND_OPT] = &MsgGetConfigHandler;
@@ -156,6 +166,17 @@ MsgTransactionManager::MsgTransactionManager() : running(false), mx(), cv()
        handlerMap[MSG_CMD_SET_VOICE_MSG_OPT] = &MsgSetConfigHandler;
        handlerMap[MSG_CMD_SET_GENERAL_MSG_OPT] = &MsgSetConfigHandler;
        handlerMap[MSG_CMD_SET_MSG_SIZE_OPT] = &MsgSetConfigHandler;
+
+       handlerMap[MSG_CMD_ADD_PUSH_EVENT] = &MsgAddPushEventHandler;
+       handlerMap[MSG_CMD_DELETE_PUSH_EVENT] = &MsgDeletePushEventHandler;
+       handlerMap[MSG_CMD_UPDATE_PUSH_EVENT] = &MsgUpdatePushEventHandler;
+       handlerMap[MSG_CMD_DELETE_MESSAGE_BY_LIST] = &MsgDeleteMessageByListHandler;
+       handlerMap[MSG_CMD_ADD_SIM_MSG] = &MsgAddSimMessageHandler;
+       handlerMap[MSG_CMD_PLG_RESEND_MESSAGE] = &MsgResendMessageHandler;
+#ifdef FEATURE_SMS_CDMA
+       handlerMap[MSG_CMD_PLG_CHECK_UNIQUENESS] = &MsgCheckUniquenessHandler;
+#endif
+       handlerMap[MSG_CMD_UPDATE_IMSI] = &MsgUpdateIMSIHandler;
 }
 
 
@@ -174,6 +195,11 @@ MsgTransactionManager* MsgTransactionManager::instance()
        return pInstance;
 }
 
+static void* worker_event_queue(void* arg)
+{
+       MsgTransactionManager::instance()->workerEventQueue();
+       return NULL;
+}
 
 void MsgTransactionManager::run()
 {
@@ -184,6 +210,17 @@ void MsgTransactionManager::run()
 
        MSG_DEBUG("Start Transaction Manager");
 
+       // Set Msg FW Ready Flag
+       if(MsgSettingSetBool(VCONFKEY_MSG_SERVER_READY, true) != MSG_SUCCESS)
+               MSG_DEBUG("MsgSettingSetBool FAIL : VCONFKEY_MSG_SERVER_READY");
+       MSG_INFO("### VCONFKEY_MSG_SERVER_READY ###");
+
+     /* running worker for plg task */
+       pthread_t tv;
+       if (pthread_create (&tv, NULL, &worker_event_queue, NULL) != 0) {
+               THROW(MsgException::SERVER_READY_ERROR, "cannot create thread [%d]", errno);
+       }
+
        while(1)
        {
                readfds = servSock.fdSet();
@@ -192,11 +229,10 @@ void MsgTransactionManager::run()
                MSG_DEBUG("Wait For Select() : nfds %d", nfds);
 
                // set Status;
-               setTMStatus();
+//             setTMStatus();
 
-               if( select(nfds, &readfds, NULL, NULL, NULL) == -1)
-               {
-                       THROW(MsgException::SELECT_ERROR, strerror(errno));
+               if(select(nfds, &readfds, NULL, NULL, NULL) == -1) {
+                       THROW(MsgException::SELECT_ERROR, "select error : %s", g_strerror(errno));
                }
 
                try
@@ -256,8 +292,7 @@ MSG_PROXY_INFO_S* MsgTransactionManager::getProxyInfo(int reqId)
 
        if (it == sentMsgMap.end())
        {
-               //THROW(MsgException::SENT_STATUS_ERROR, "No submit request for %d", reqId);
-               MSG_DEBUG("No sent status cb found (exception: mobile tracker)");
+               MSG_DEBUG("No sent status cb found");
                return NULL;
        }
 
@@ -277,6 +312,55 @@ void MsgTransactionManager::delProxyInfo(int reqId)
        sentMsgMap.erase(it);
 }
 
+void MsgTransactionManager::workerEventQueue()
+{
+       MSG_CMD_S* pCmd = NULL;
+       int (*pfHandler)(const MSG_CMD_S*, char**) = NULL;
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       int fd = -1;
+       int eventSize = 0;
+
+       while (1) {
+               mx.lock();
+               while (!eventQueue.front(&pCmd)) { /* if no item, wait */
+                       MSG_DEBUG ("waiting for task");
+                       cv.wait(mx.pMutex());
+               }
+               eventQueue.pop_front(); /* pop it from queue*/
+               mx.unlock();
+
+               if (!pCmd) {
+                       MSG_FATAL("pCmd NULL");
+                       continue;
+               }
+
+               memcpy (&fd, pCmd->cmdCookie, sizeof(int));
+               if (fd < 0 ) {
+                       MSG_FATAL("fd [%d] < 0", fd);
+                       g_free (pCmd); pCmd = NULL;
+                       continue;
+               }
+               pfHandler = handlerMap[pCmd->cmdType];
+               if (!pfHandler) {
+                       MSG_FATAL("No handler for %d", pCmd->cmdType);
+                       MsgMakeErrorEvent(pCmd->cmdType, MSG_ERR_INVALID_PARAMETER, &eventSize, &pEventData);
+               } else {
+                       // run handler function
+                       eventSize = pfHandler(pCmd, &pEventData);
+
+                       if (eventSize == 0 || pEventData == NULL) {
+                               MSG_FATAL("event size[%d] = 0 or event data = NULL", eventSize);
+                               MsgMakeErrorEvent(pCmd->cmdType, MSG_ERR_INVALID_PARAMETER, &eventSize, &pEventData);
+                       }
+               }
+
+               MSG_DEBUG("Replying to fd [%d], size [%d]", fd, eventSize);
+               servSock.write(fd, pEventData, eventSize);
+               g_free (pCmd); pCmd = NULL;
+       }
+}
 
 void MsgTransactionManager::handleRequest(int fd)
 {
@@ -285,8 +369,9 @@ void MsgTransactionManager::handleRequest(int fd)
        MSG_DEBUG("Event from fd %d", fd);
 
        char* buf = NULL;
-       AutoPtr<char> wrap(&buf);
-       int len;
+       unique_ptr<char*, void(*)(char**)> wrap(&buf, unique_ptr_deleter);
+
+       int len = 0;
        int ret = servSock.read(fd, &buf, &len);
 
        if( ret == CLOSE_CONNECTION_BY_SIGNAL || ret == CLOSE_CONNECTION_BY_USER || ret < 0)
@@ -296,11 +381,11 @@ void MsgTransactionManager::handleRequest(int fd)
                return;
        }
 
-       if (len == 0)
-               THROW(MsgException::INVALID_RESULT, "read buffer size = 0");
+       if (len <= 0)
+               THROW(MsgException::INVALID_RESULT, "read buffer size <= 0");
 
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        int eventSize = 0;
 
@@ -311,46 +396,64 @@ void MsgTransactionManager::handleRequest(int fd)
        if (pCmd->cmdType > MSG_CMD_NUM)
                THROW(MsgException::OUT_OF_RANGE, "request CMD is not defined");
 
-       if (pCmd->cmdType < MSG_CMD_GET_REPORT_STATUS)
-       {
-               // check privilege
-               if (checkPrivilege(pCmd->cmdType, pCmd->cmdCookie) == false)
-               {
+       // check privilege
+//     if (checkPrivilege(pCmd->cmdType, pCmd->cmdCookie) == false) {
+       if (checkPrivilege(fd, pCmd->cmdType) == false) {
+               MSG_DEBUG("No Privilege rule. Not allowed.");
 #ifdef MSG_CHECK_PRIVILEGE
-                       eventSize = sizeof(MSG_EVENT_S);
+               MsgMakeErrorEvent(pCmd->cmdType, MSG_ERR_PERMISSION_DENIED, &eventSize, &pEventData);
 
-                       pEventData = new char[eventSize];
+               MSG_DEBUG("Replying to fd [%d], size [%d]", fd, eventSize);
+               servSock.write(fd, pEventData, eventSize);
 
-                       MSG_EVENT_S* pMsgEvent = (MSG_EVENT_S*)pEventData;
-
-                       pMsgEvent->eventType = pCmd->cmdType;
-                       pMsgEvent->result = MSG_ERR_SECURITY_ERROR;
-
-                       MSG_DEBUG("Replying to fd [%d], size [%d]", fd, eventSize);
-                       servSock.write(fd, pEventData, eventSize);
-
-                       return;
+               return;
 #endif
-               }
        }
 
        // determine the handler based on pCmd->cmdType
        int (*pfHandler)(const MSG_CMD_S*, char**) = NULL;
 
-       pfHandler = handlerMap[pCmd->cmdType];
-
-       if (!pfHandler)
-               THROW(MsgException::INVALID_PARAM, "No handler for %d", pCmd->cmdType);
-
-       // run handler function
-       eventSize = pfHandler(pCmd, &pEventData);
-
-       if (eventSize == 0 || pEventData == NULL)
-               THROW(MsgException::INVALID_RESULT, "event size = 0 or event data = NULL");
-
-       MSG_DEBUG("Replying to fd [%d], size [%d]", fd, eventSize);
+       switch (pCmd->cmdType) {
+       case MSG_CMD_PLG_SENT_STATUS_CNF:
+       case MSG_CMD_PLG_STORAGE_CHANGE_IND:
+       case MSG_CMD_PLG_INCOMING_MSG_IND:
+       case MSG_CMD_PLG_INCOMING_MMS_CONF:
+       case MSG_CMD_PLG_INCOMING_SYNCML_IND:
+       case MSG_CMD_PLG_INCOMING_LBS_IND:
+       case MSG_CMD_PLG_INIT_SIM_BY_SAT:
+       case MSG_CMD_PLG_INCOMING_PUSH_IND:
+       case MSG_CMD_PLG_INCOMING_CB_IND: {
+
+               MSG_CMD_S* pCmdDup = (MSG_CMD_S*) calloc (1, len); /* pCmdDup should be freed afterward */
+               if (pCmdDup != NULL) {
+                       memcpy (pCmdDup, pCmd, len);
+                       memcpy (pCmdDup->cmdCookie, &fd, sizeof(int)); /* Now, cmdCookie keeps fd for return */
+
+                       mx.lock(); /* aquire lock before adding cmd */
+                       eventQueue.push_back(pCmdDup);
+                       cv.signal(); /* wake up worker */
+                       mx.unlock();
+               }
+               break;
+       }
+       default:
+               pfHandler = handlerMap[pCmd->cmdType];
+               if (!pfHandler) {
+                       MSG_FATAL("No handler for %d", pCmd->cmdType);
+                       MsgMakeErrorEvent(pCmd->cmdType, MSG_ERR_INVALID_PARAMETER, &eventSize, &pEventData);
+               } else {
+                       // run handler function
+                       eventSize = pfHandler(pCmd, &pEventData);
+
+                       if (eventSize == 0 || pEventData == NULL) {
+                               MSG_FATAL("event size[%d] = 0 or event data = NULL", eventSize);
+                               MsgMakeErrorEvent(pCmd->cmdType, MSG_ERR_INVALID_PARAMETER, &eventSize, &pEventData);
+                       }
+               }
 
-       servSock.write(fd, pEventData, eventSize);
+               MSG_DEBUG("Replying to fd [%d], size [%d]", fd, eventSize);
+               servSock.write(fd, pEventData, eventSize);
+       }
 
        MSG_END();
 }
@@ -380,6 +483,11 @@ void MsgTransactionManager::cleanup(int fd)
        // remove sent status callback for fd
        statusCBFdMap.erase(fd);
 
+       MSG_DEBUG("After erase fd [%d], statusCBFdMap has below.", fd);
+       fd_map::iterator it = statusCBFdMap.begin();
+       for (; it!=statusCBFdMap.end(); ++it)
+               MSG_DEBUG("[%d]", it->first);
+
        // remove all newMsgCBs for fd
        newmsg_list::iterator newmsg_it = newMsgCBList.begin();
 
@@ -440,6 +548,39 @@ void MsgTransactionManager::cleanup(int fd)
                }
        }
 
+       // remove all newPushMsgCBs for fd
+       pushmsg_list::iterator pushmsg_it = newPushMsgCBList.begin();
+
+       while (pushmsg_it != newPushMsgCBList.end())
+       {
+               if (pushmsg_it->listenerFd == fd)
+               {
+                       pushmsg_it = newPushMsgCBList.erase(pushmsg_it);
+               }
+               else
+               {
+                       ++pushmsg_it;
+               }
+       }
+
+       // remove all newCBMsgCBs for fd
+       cbmsg_list::iterator cbmsg_it = newCBMsgCBList.begin();
+       //bool bSave = false;
+
+       while (cbmsg_it != newCBMsgCBList.end())
+       {
+               if (cbmsg_it->listenerFd == fd)
+               {
+                       cbmsg_it = newCBMsgCBList.erase(cbmsg_it);
+               }
+               else
+               {
+                       //if (cbmsg_it->bsave == true)
+                       //      bSave = true;
+                       ++cbmsg_it;
+               }
+       }
+
        // remove all operationSyncMLMsgCBs for fd
        syncmlop_list::iterator syncmlop_it = operationSyncMLMsgCBList.begin();
 
@@ -458,75 +599,115 @@ void MsgTransactionManager::cleanup(int fd)
        // remove storage change callback for fd
        storageChangeFdMap.erase(fd);
 
-       MSG_END();
-}
+       MSG_DEBUG("After erase fd [%d], storageChangeFdMap has below.", fd);
+       it = storageChangeFdMap.begin();
+       for (; it!=storageChangeFdMap.end(); ++it)
+               MSG_DEBUG("[%d]", it->first);
 
+       // remove report msg incoming callback for fd
+       reportMsgCBFdMap.erase(fd);
 
-bool MsgTransactionManager::checkPrivilege(MSG_CMD_TYPE_T CmdType, const char *pCookie)
-{
-       if (CmdType >= MSG_CMD_PLG_SENT_STATUS_CNF && CmdType <= MSG_CMD_PLG_INIT_SIM_BY_SAT)
-       {
-               MSG_DEBUG("Request from Plug-in");
-               return true;
-       }
+       MSG_DEBUG("After erase fd [%d], reportMsgCBFdMap has below.", fd);
+       it = reportMsgCBFdMap.begin();
+       for (; it!=reportMsgCBFdMap.end(); ++it)
+               MSG_DEBUG("[%d]", it->first);
 
-       // Get Cookie from APP
-       if (pCookie == NULL)
-       {
-               MSG_DEBUG("Cookie is NULL");
-               return false;
-       }
-
-       // Check Cookie
-       size_t cookieSize;
-       gid_t gid;
-
-       cookieSize = security_server_get_cookie_size();
-
-       MSG_DEBUG("cookie size : [%d]", cookieSize);
+       MSG_END();
+}
 
-//     char cookie[MAX_COOKIE_LEN];
 
-       // Get GID
-       if (CmdType == MSG_CMD_REG_INCOMING_SYNCML_MSG_CB)
-       {
-               MSG_DEBUG("get GID for message_sync");
-               gid = security_server_get_gid("message_sync");
-       }
-       else if (CmdType == MSG_CMD_REG_INCOMING_LBS_MSG_CB)
+bool MsgTransactionManager::checkPrivilege(int fd, MSG_CMD_TYPE_T CmdType)
+{
+       bool bAllowed = true;
+       switch(CmdType)
        {
-               MSG_DEBUG("get GID for message_lbs");
-               gid = security_server_get_gid("message_lbs");
-       }
-       else
+       case MSG_CMD_GET_MSG:
+       case MSG_CMD_COUNT_MSG:
+       case MSG_CMD_COUNT_BY_MSGTYPE:
+       case MSG_CMD_REG_INCOMING_MSG_CB:
+       case MSG_CMD_REG_INCOMING_CB_MSG_CB:
+       case MSG_CMD_REG_INCOMING_PUSH_MSG_CB:
+       case MSG_CMD_REG_SENT_STATUS_CB:
+       case MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB:
+       case MSG_CMD_REG_INCOMING_SYNCML_MSG_CB:
+       case MSG_CMD_REG_INCOMING_LBS_MSG_CB:
+       case MSG_CMD_REG_SYNCML_MSG_OPERATION_CB:
+       case MSG_CMD_REG_REPORT_MSG_INCOMING_CB:
+       case MSG_CMD_GET_CONTACT_COUNT:
+       case MSG_CMD_GET_FOLDERLIST:
+       case MSG_CMD_GET_QUICKPANEL_DATA:
+       case MSG_CMD_GET_MEMSIZE:
+       case MSG_CMD_BACKUP_MESSAGE:
+       case MSG_CMD_REG_STORAGE_CHANGE_CB:
+       case MSG_CMD_GET_REPORT_STATUS:
+       case MSG_CMD_GET_THREAD_ID_BY_ADDRESS:
+       case MSG_CMD_GET_THREAD_INFO:
+       case MSG_CMD_SYNCML_OPERATION:
+       case MSG_CMD_GET_FILTERLIST:
+       case MSG_CMD_GET_FILTER_OPERATION:
+       case MSG_CMD_GET_SMSC_OPT:
+       case MSG_CMD_GET_CB_OPT:
+       case MSG_CMD_GET_SMS_SEND_OPT:
+       case MSG_CMD_GET_MMS_SEND_OPT:
+       case MSG_CMD_GET_MMS_RECV_OPT:
+       case MSG_CMD_GET_PUSH_MSG_OPT:
+       case MSG_CMD_GET_VOICE_MSG_OPT:
+       case MSG_CMD_GET_GENERAL_MSG_OPT:
+       case MSG_CMD_GET_MSG_SIZE_OPT:
        {
-               MSG_DEBUG("get GID for message");
-               gid = security_server_get_gid("message");
+               int ret = security_server_check_privilege_by_sockfd(fd, "msg-service::read", "rw");
+               if (ret == SECURITY_SERVER_API_ERROR_ACCESS_DENIED) {
+                       MSG_DEBUG("No msg-service::read rw rule.");
+                       bAllowed = false;
+               }
        }
-
-       MSG_DEBUG("gid [%d]", gid);
-
-       int retVal = 0;
-
-       retVal = security_server_check_privilege(pCookie, gid);
-
-       if (retVal < 0)
+       break;
+       case MSG_CMD_SUBMIT_REQ:
+       case MSG_CMD_SET_CB_OPT:
+       case MSG_CMD_ADD_PUSH_EVENT:
+       case MSG_CMD_DELETE_PUSH_EVENT:
+       case MSG_CMD_UPDATE_PUSH_EVENT:
+       case MSG_CMD_ADD_MSG:
+       case MSG_CMD_ADD_SYNCML_MSG:
+       case MSG_CMD_UPDATE_MSG:
+       case MSG_CMD_UPDATE_READ:
+       case MSG_CMD_UPDATE_PROTECTED:
+       case MSG_CMD_DELETE_MSG:
+       case MSG_CMD_DELALL_MSGINFOLDER:
+       case MSG_CMD_MOVE_MSGTOFOLDER:
+       case MSG_CMD_MOVE_MSGTOSTORAGE:
+       case MSG_CMD_DELETE_THREADMESSAGELIST:
+       case MSG_CMD_ADD_FOLDER:
+       case MSG_CMD_UPDATE_FOLDER:
+       case MSG_CMD_DELETE_FOLDER:
+       case MSG_CMD_RESET_DB:
+       case MSG_CMD_RESTORE_MESSAGE:
+       case MSG_CMD_DELETE_MESSAGE_BY_LIST:
+       case MSG_CMD_UPDATE_THREAD_READ:
+       case MSG_CMD_ADD_FILTER:
+       case MSG_CMD_UPDATE_FILTER:
+       case MSG_CMD_DELETE_FILTER:
+       case MSG_CMD_SET_FILTER_OPERATION:
+       case MSG_CMD_SET_FILTER_ACTIVATION:
+       case MSG_CMD_SET_SMSC_OPT:
+       case MSG_CMD_SET_SMS_SEND_OPT:
+       case MSG_CMD_SET_MMS_SEND_OPT:
+       case MSG_CMD_SET_MMS_RECV_OPT:
+       case MSG_CMD_SET_PUSH_MSG_OPT:
+       case MSG_CMD_SET_VOICE_MSG_OPT:
+       case MSG_CMD_SET_GENERAL_MSG_OPT:
+       case MSG_CMD_SET_MSG_SIZE_OPT:
        {
-               if (retVal == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
-               {
-                       MSG_DEBUG("access denied !! [%d]", retVal);
+               int ret = security_server_check_privilege_by_sockfd(fd, "msg-service::write", "rw");
+               if (ret == SECURITY_SERVER_API_ERROR_ACCESS_DENIED) {
+                       MSG_DEBUG("No msg-service::write rw rule.");
+                       bAllowed = false;
                }
-               else
-               {
-                       MSG_DEBUG("fail to check privilege [%d]", retVal);
-               }
-
-               return false;
+       }
+       break;
        }
 
-       MSG_DEBUG("privilege check success !!");
-
-       return true;
+       return bAllowed;
 }
 
 
@@ -585,6 +766,60 @@ void MsgTransactionManager::setMMSConfMsgCB(MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB
 }
 
 
+void MsgTransactionManager::setPushMsgCB(MSG_CMD_REG_INCOMING_PUSH_MSG_CB_S *pCbInfo)
+{
+       if (!pCbInfo)
+       {
+               MSG_FATAL("cbinfo NULL");
+               return;
+       }
+
+       pushmsg_list::iterator it = newPushMsgCBList.begin();
+
+       for (; it != newPushMsgCBList.end(); it++)
+       {
+               if ((it->listenerFd == pCbInfo->listenerFd) && (it->msgType == pCbInfo->msgType) && !strncmp(it->appId, pCbInfo->appId, MAX_WAPPUSH_ID_LEN))
+               {
+                       MSG_DEBUG("Duplicated messageCB info fd %d, mType %d", it->listenerFd, it->msgType);
+                       return;
+               }
+       }
+
+       newPushMsgCBList.push_back(*pCbInfo);
+}
+
+void MsgTransactionManager::setCBMsgCB(MSG_CMD_REG_INCOMING_CB_MSG_CB_S *pCbInfo)
+{
+       MSG_BEGIN();
+       if (!pCbInfo)
+       {
+               MSG_FATAL("cbinfo NULL");
+               return;
+       }
+
+       cbmsg_list::iterator it = newCBMsgCBList.begin();
+
+       for (; it != newCBMsgCBList.end(); it++)
+       {
+               if ((it->listenerFd == pCbInfo->listenerFd) && (it->msgType == pCbInfo->msgType))
+               {
+                       MSG_DEBUG("Duplicated messageCB info fd %d, mType %d", it->listenerFd, it->msgType);
+                       return;
+               }
+       }
+       MSG_DEBUG("bSave : [%d]", pCbInfo->bsave);
+
+       if(pCbInfo->bsave)
+               if(MsgSettingSetBool(CB_SAVE, pCbInfo->bsave) != MSG_SUCCESS)
+                       MSG_DEBUG("MsgSettingSetBool FAIL: CB_SAVE");
+
+
+       newCBMsgCBList.push_back(*pCbInfo);
+
+       MSG_END();
+}
+
+
 void MsgTransactionManager::setSyncMLMsgCB(MSG_CMD_REG_INCOMING_SYNCML_MSG_CB_S *pCbInfo)
 {
        if (!pCbInfo)
@@ -645,7 +880,7 @@ void MsgTransactionManager::setJavaMMSList(MSG_CMD_REG_INCOMING_JAVAMMS_TRID_S *
        {
                if (!strcmp(it->id, pTrId->id))
                {
-                       MSG_DEBUG("Duplicated javaMMS transaction Id:%s", it->id);
+                       MSG_SEC_DEBUG("Duplicated javaMMS transaction Id:%s", it->id);
                        return;
                }
        }
@@ -686,6 +921,15 @@ void MsgTransactionManager::setStorageChangeCB(int listenerFd)
 }
 
 
+void MsgTransactionManager::setReportMsgCB(int listenerFd)
+{
+       if (listenerFd <= 0)
+               THROW(MsgException::INVALID_PARAM,"InParam Error: listenerFd %d", listenerFd);
+
+       reportMsgCBFdMap[listenerFd] = true;
+}
+
+
 javamms_list& MsgTransactionManager::getJavaMMSList()
 {
        return javaMMSList;
@@ -696,10 +940,35 @@ void MsgTransactionManager::broadcastIncomingMsgCB(const msg_error_t err, const
 {
        MSG_BEGIN();
 
+       if ((msgInfo->msgPort.valid == true) && (msgInfo->msgPort.dstPort == MSG_LBS_PORT)) {
+               MSG_DEBUG("Message for LBS.");
+
+               if (msgInfo->bTextSms == false) {
+                       MSG_DEBUG("msgInfo->bTextSms == false");
+
+                       int fileSize = 0;
+
+                       char* pFileData = NULL;
+                       unique_ptr<char*, void(*)(char**)> buf(&pFileData, unique_ptr_deleter);
+
+                       if (MsgOpenAndReadFile(msgInfo->msgData, &pFileData, &fileSize) == true)
+                               MsgLbsSms(pFileData, fileSize);
+                       else
+                               MSG_DEBUG("MsgOpenAndReadFile failed.");
+               } else {
+                       MsgLbsSms(msgInfo->msgText, (int)msgInfo->dataSize);
+               }
+               return;
+       }
+
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
-       int eventSize = MsgMakeEvent(msgInfo, sizeof(MSG_MESSAGE_INFO_S), MSG_EVENT_PLG_INCOMING_MSG_IND, err, (void**)(&pEventData));
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+       int dataSize = MsgEncodeMsgInfo(msgInfo, &encodedData);
+
+       int eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_PLG_INCOMING_MSG_IND, err, (void**)(&pEventData));
 
        MSG_DEBUG("valid %d dstport %d", msgInfo->msgPort.valid, msgInfo->msgPort.dstPort);
 
@@ -709,13 +978,10 @@ void MsgTransactionManager::broadcastIncomingMsgCB(const msg_error_t err, const
        {
                MSG_DEBUG("fd %d dstport %d",it->listenerFd, it->port);
 
-               if ((msgInfo->msgPort.valid == false) && (it->port == 0))
-               {
+               if ((msgInfo->msgPort.valid == false) && (it->port == 0)) {
                        MSG_DEBUG("Send incoming normal msg to listener %d", it->listenerFd);
                        write(it->listenerFd, pEventData, eventSize);
-               }
-               else if ((msgInfo->msgPort.valid == true) && (it->port == msgInfo->msgPort.dstPort))
-               {
+               } else if ((msgInfo->msgPort.valid == true) && (it->port == msgInfo->msgPort.dstPort)) {
                        MSG_DEBUG("Send incoming port msg to listener %d", it->listenerFd);
                        write(it->listenerFd, pEventData, eventSize);
                }
@@ -730,9 +996,13 @@ void MsgTransactionManager::broadcastMMSConfCB(const msg_error_t err, const MSG_
        MSG_BEGIN();
 
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+       int dataSize = MsgEncodeMsgInfo(msgInfo, &encodedData);
 
-       int eventSize = MsgMakeEvent(msgInfo, sizeof(MSG_MESSAGE_INFO_S), MSG_EVENT_PLG_INCOMING_MMS_CONF, err, (void**)(&pEventData));
+       int eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_PLG_INCOMING_MMS_CONF, err, (void**)(&pEventData));
 
        mmsconf_list::iterator it = newMMSConfMsgCBList.begin();
 
@@ -762,13 +1032,56 @@ void MsgTransactionManager::broadcastMMSConfCB(const msg_error_t err, const MSG_
        MSG_END();
 }
 
+void MsgTransactionManager::broadcastPushMsgCB(const msg_error_t err, const MSG_PUSH_MESSAGE_DATA_S *pushData)
+{
+       MSG_BEGIN();
+
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       int eventSize = MsgMakeEvent(pushData, sizeof(MSG_PUSH_MESSAGE_DATA_S), MSG_EVENT_PLG_INCOMING_PUSH_MSG_IND, err, (void**)(&pEventData));
+
+       pushmsg_list::iterator it = newPushMsgCBList.begin();
+
+       for (; it != newPushMsgCBList.end(); it++)
+       {
+               MSG_DEBUG("registered_appid : %s, incoming_appid: %s", it->appId, pushData->pushAppId);
+               if (!strcmp(it->appId, pushData->pushAppId))
+               {
+                       MSG_DEBUG("Send incoming Push information to listener %d", it->listenerFd);
+                       write(it->listenerFd, pEventData, eventSize);
+               }
+       }
+
+       MSG_END();
+}
+
+void MsgTransactionManager::broadcastCBMsgCB(const msg_error_t err, const MSG_CB_MSG_S *cbMsg)
+{
+       MSG_BEGIN();
+
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       int eventSize = MsgMakeEvent(cbMsg, sizeof(MSG_CB_MSG_S), MSG_EVENT_PLG_INCOMING_CB_MSG_IND, err, (void**)(&pEventData));
+
+       cbmsg_list::iterator it = newCBMsgCBList.begin();
+
+       for (; it != newCBMsgCBList.end(); it++)
+       {
+               MSG_DEBUG("Send incoming CB information to listener %d", it->listenerFd);
+               write(it->listenerFd, pEventData, eventSize);
+       }
+
+       MSG_END();
+}
 
 void MsgTransactionManager::broadcastSyncMLMsgCB(const msg_error_t err, const MSG_SYNCML_MESSAGE_DATA_S *syncMLData)
 {
        MSG_BEGIN();
 
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        int eventSize = MsgMakeEvent(syncMLData, sizeof(MSG_SYNCML_MESSAGE_DATA_S), MSG_EVENT_PLG_INCOMING_SYNCML_MSG_IND, err, (void**)(&pEventData));
 
@@ -788,8 +1101,9 @@ void MsgTransactionManager::broadcastLBSMsgCB(const msg_error_t err, const MSG_L
 {
        MSG_BEGIN();
 
+#if 0
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        int eventSize = MsgMakeEvent(lbsData, sizeof(MSG_LBS_MESSAGE_DATA_S), MSG_EVENT_PLG_INCOMING_LBS_MSG_IND, err, (void**)(&pEventData));
 
@@ -800,7 +1114,9 @@ void MsgTransactionManager::broadcastLBSMsgCB(const msg_error_t err, const MSG_L
                MSG_DEBUG("Send incoming LBS msg to listener %d", it->listenerFd);
                write(it->listenerFd, pEventData, eventSize);
        }
-
+#else
+       MsgLbsWapPush(lbsData->pushHeader, lbsData->pushBody, lbsData->pushBodyLen);
+#endif
        MSG_END();
 }
 
@@ -810,10 +1126,10 @@ void MsgTransactionManager::broadcastSyncMLMsgOperationCB(const msg_error_t err,
        MSG_BEGIN();
 
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        // Encoding Storage Change Data
        int dataSize = MsgEncodeSyncMLOperationData(msgId, extId, &encodedData);
@@ -846,10 +1162,10 @@ void MsgTransactionManager::broadcastStorageChangeCB(const msg_error_t err, cons
        int dataSize = 0;
 
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        char* encodedData = NULL;
-       AutoPtr<char> buf(&encodedData);
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
 
        // Encoding Storage Change Data
        dataSize = MsgEncodeStorageChangeData(storageChangeType, pMsgIdList, &encodedData);
@@ -868,6 +1184,42 @@ void MsgTransactionManager::broadcastStorageChangeCB(const msg_error_t err, cons
 }
 
 
+void MsgTransactionManager::broadcastReportMsgCB(const msg_error_t err, const msg_report_type_t reportMsgType, const MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       if(pMsgInfo == NULL) {
+               MSG_DEBUG("pMsgInfo is NULL.");
+               return;
+       }
+
+       MSG_DEBUG("reportMsgType [%d]", reportMsgType);
+
+       int dataSize = 0;
+
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+
+       // Encoding Storage Change Data
+       dataSize = MsgEncodeReportMsgData(reportMsgType, pMsgInfo, &encodedData);
+
+       int eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_PLG_REPORT_MSG_INCOMING_IND, err, (void**)(&pEventData));
+
+       fd_map::iterator it = reportMsgCBFdMap.begin();
+
+       for (; it != reportMsgCBFdMap.end(); it++)
+       {
+               MSG_DEBUG("Send Report Message Incoming Callback to listener %d", it->first);
+               write(it->first, pEventData, eventSize);
+       }
+
+       MSG_END();
+}
+
+
 void MsgTransactionManager::setTMStatus()
 {
        MSG_BEGIN();
diff --git a/image/messaging_image001.png b/image/messaging_image001.png
deleted file mode 100755 (executable)
index 0c575c4..0000000
Binary files a/image/messaging_image001.png and /dev/null differ
index 4439c7b..9710252 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_CMD_TYPES_H
@@ -96,74 +96,93 @@ enum _MSG_CMD_TYPE_E
 
        MSG_CMD_GET_MSG_TYPE,
        MSG_CMD_SUBMIT_REQ,
-       MSG_CMD_CANCEL_REQ,
        MSG_CMD_REG_SENT_STATUS_CB,
        MSG_CMD_REG_STORAGE_CHANGE_CB,
+       MSG_CMD_REG_INCOMING_MSG_CB,
 
 // 30
-       MSG_CMD_REG_INCOMING_MSG_CB,
        MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB,
        MSG_CMD_REG_INCOMING_SYNCML_MSG_CB,
        MSG_CMD_REG_INCOMING_LBS_MSG_CB,
        MSG_CMD_PLG_SENT_STATUS_CNF,
-
        MSG_CMD_PLG_STORAGE_CHANGE_IND,
+
        MSG_CMD_PLG_INCOMING_MSG_IND,
        MSG_CMD_PLG_INCOMING_MMS_CONF,
        MSG_CMD_PLG_INCOMING_SYNCML_IND,
        MSG_CMD_PLG_INCOMING_LBS_IND,
+       MSG_CMD_PLG_INIT_SIM_BY_SAT,
 
 // 40
-       MSG_CMD_PLG_INIT_SIM_BY_SAT,
        MSG_CMD_GET_THREADVIEWLIST,
        MSG_CMD_GET_CONVERSATIONVIEWLIST,
        MSG_CMD_DELETE_THREADMESSAGELIST,
        MSG_CMD_GET_CONTACT_COUNT,
-
        MSG_CMD_GET_QUICKPANEL_DATA,
+
        MSG_CMD_COUNT_BY_MSGTYPE,
        MSG_CMD_RESET_DB,
        MSG_CMD_GET_MEMSIZE,
        MSG_CMD_BACKUP_MESSAGE,
+       MSG_CMD_RESTORE_MESSAGE,
 
 // 50
-       MSG_CMD_RESTORE_MESSAGE,
        MSG_CMD_UPDATE_THREAD_READ,
        MSG_CMD_REG_SYNCML_MSG_OPERATION_CB,
        MSG_CMD_SYNCML_OPERATION,
        MSG_CMD_GET_REPORT_STATUS,
-
        MSG_CMD_GET_THREAD_ID_BY_ADDRESS,
+
        MSG_CMD_GET_THREAD_INFO,
        MSG_CMD_GET_SMSC_OPT,
        MSG_CMD_GET_CB_OPT,
        MSG_CMD_GET_SMS_SEND_OPT,
+       MSG_CMD_GET_MMS_SEND_OPT,
 
 // 60
-       MSG_CMD_GET_MMS_SEND_OPT,
        MSG_CMD_GET_MMS_RECV_OPT,
        MSG_CMD_GET_PUSH_MSG_OPT,
        MSG_CMD_GET_VOICE_MSG_OPT,
        MSG_CMD_GET_GENERAL_MSG_OPT,
-
        MSG_CMD_GET_MSG_SIZE_OPT,
+
        MSG_CMD_SET_SMSC_OPT,
        MSG_CMD_SET_CB_OPT,
        MSG_CMD_SET_SMS_SEND_OPT,
        MSG_CMD_SET_MMS_SEND_OPT,
+       MSG_CMD_SET_MMS_RECV_OPT,
 
 // 70
-       MSG_CMD_SET_MMS_RECV_OPT,
        MSG_CMD_SET_PUSH_MSG_OPT,
        MSG_CMD_SET_VOICE_MSG_OPT,
        MSG_CMD_SET_GENERAL_MSG_OPT,
        MSG_CMD_SET_MSG_SIZE_OPT,
-
+       MSG_CMD_REG_INCOMING_PUSH_MSG_CB,
+
+       MSG_CMD_PLG_INCOMING_PUSH_IND,
+       MSG_CMD_REG_INCOMING_CB_MSG_CB,
+       MSG_CMD_PLG_INCOMING_CB_IND,
+       MSG_CMD_ADD_PUSH_EVENT,
+       MSG_CMD_DELETE_PUSH_EVENT,
+
+// 80
+       MSG_CMD_UPDATE_PUSH_EVENT,
+       MSG_CMD_DELETE_MESSAGE_BY_LIST,
+       MSG_CMD_SET_FILTER_ACTIVATION,
+       MSG_CMD_ADD_SIM_MSG,
+       MSG_CMD_PLG_RESEND_MESSAGE,
+
+// 85
+       MSG_CMD_REG_REPORT_MSG_INCOMING_CB,
+       MSG_CMD_UPDATE_IMSI,
+
+#ifdef FEATURE_SMS_CDMA
+       MSG_CMD_PLG_CHECK_UNIQUENESS,
+#endif
 // end of MSG_CMD; new CMD should be defined before MSG_CMD_NUM
        MSG_CMD_NUM
 };
 
-
 enum _MSG_EVENT_TYPE_E
 {
        MSG_EVENT_OPEN_HANDLE = 0,
@@ -200,72 +219,98 @@ enum _MSG_EVENT_TYPE_E
 
        MSG_EVENT_GET_MSG_TYPE,
        MSG_EVENT_SUBMIT_REQ,
-       MSG_EVENT_CANCEL_REQ,
        MSG_EVENT_REG_SENT_STATUS_CB,
+       MSG_EVENT_REG_STORAGE_CHANGE_CB,
        MSG_EVENT_REG_INCOMING_MSG_CB,
 
 // 30
        MSG_EVENT_REG_INCOMING_MMS_CONF_MSG_CB,
        MSG_EVENT_REG_INCOMING_SYNCML_MSG_CB,
        MSG_EVENT_REG_INCOMING_LBS_MSG_CB,
-       MSG_EVENT_REG_STORAGE_CHANGE_CB,
        MSG_EVENT_PLG_SENT_STATUS_CNF,
-
        MSG_EVENT_PLG_STORAGE_CHANGE_IND,
+
        MSG_EVENT_PLG_INCOMING_MSG_IND,
        MSG_EVENT_PLG_INCOMING_MMS_CONF,
        MSG_EVENT_PLG_INCOMING_SYNCML_MSG_IND,
        MSG_EVENT_PLG_INCOMING_LBS_MSG_IND,
+       MSG_EVENT_PLG_INIT_SIM_BY_SAT,
 
 // 40
-       MSG_EVENT_PLG_INIT_SIM_BY_SAT,
        MSG_EVENT_GET_THREADVIEWLIST,
        MSG_EVENT_GET_CONVERSATIONVIEWLIST,
        MSG_EVENT_DELETE_THREADMESSAGELIST,
        MSG_EVENT_GET_CONTACT_COUNT,
-
        MSG_EVENT_GET_QUICKPANEL_DATA,
+
        MSG_EVENT_COUNT_BY_MSGTYPE,
        MSG_EVENT_RESET_DB,
        MSG_EVENT_GET_MEMSIZE,
        MSG_EVENT_BACKUP_MESSAGE,
+       MSG_EVENT_RESTORE_MESSAGE,
 
 // 50
-       MSG_EVENT_RESTORE_MESSAGE,
        MSG_EVENT_UPDATE_THREAD_READ,
        MSG_EVENT_REG_SYNCML_MSG_OPERATION_CB,
        MSG_EVENT_SYNCML_OPERATION,
        MSG_EVENT_GET_REPORT_STATUS,
-
        MSG_EVENT_GET_THREAD_ID_BY_ADDRESS,
+
        MSG_EVENT_GET_THREAD_INFO,
        MSG_EVENT_GET_SMSC_OPT,
        MSG_EVENT_GET_CB_OPT,
        MSG_EVENT_GET_SMS_SEND_OPT,
+       MSG_EVENT_GET_MMS_SEND_OPT,
 
 // 60
-       MSG_EVENT_GET_MMS_SEND_OPT,
        MSG_EVENT_GET_MMS_RECV_OPT,
        MSG_EVENT_GET_PUSH_MSG_OPT,
        MSG_EVENT_GET_VOICE_MSG_OPT,
        MSG_EVENT_GET_GENERAL_MSG_OPT,
-
        MSG_EVENT_GET_MSG_SIZE_OPT,
+
        MSG_EVENT_SET_SMSC_OPT,
        MSG_EVENT_SET_CB_OPT,
        MSG_EVENT_SET_SMS_SEND_OPT,
        MSG_EVENT_SET_MMS_SEND_OPT,
+       MSG_EVENT_SET_MMS_RECV_OPT,
 
 // 70
-       MSG_EVENT_SET_MMS_RECV_OPT,
        MSG_EVENT_SET_PUSH_MSG_OPT,
        MSG_EVENT_SET_VOICE_MSG_OPT,
        MSG_EVENT_SET_GENERAL_MSG_OPT,
        MSG_EVENT_SET_MSG_SIZE_OPT,
+       MSG_EVENT_REG_INCOMING_PUSH_MSG_CB,
+
+       MSG_EVENT_PLG_INCOMING_PUSH_MSG_IND,
+       MSG_EVENT_REG_INCOMING_CB_MSG_CB,
+       MSG_EVENT_PLG_INCOMING_CB_MSG_IND,
+       MSG_EVENT_ADD_PUSH_EVENT,
+       MSG_EVENT_DELETE_PUSH_EVENT,
+
+// 80
+       MSG_EVENT_UPDATE_PUSH_EVENT,
+       MSG_EVENT_DELETE_MESSAGE_BY_LIST,
+       MSG_EVENT_SET_FILTER_ACTIVATION,
+       MSG_EVENT_ADD_SIM_MSG,
+       MSG_EVENT_PLG_RESEND_MESSAGE,
+
+// 85
+       MSG_EVENT_REG_REPORT_MSG_INCOMING_CB,
+       MSG_EVENT_UPDATE_IMSI,
+
+#ifdef FEATURE_SMS_CDMA
+       MSG_EVENT_PLG_CHECK_UNIQUENESS,
+#endif
+
+// Enums that does not match _MSG_CMD_TYPE_E
+       MSG_EVENT_PLG_REPORT_MSG_INCOMING_IND,
 
 // end of MSG_EVENT; new EVENT should be defined before MSG_EVENT_NUM
        MSG_EVENT_NUM
 };
 
+
+
 #endif // MSG_CMD_TYPES_H
 
index 04fbd80..1e5f4a2 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef __MSG_CPP_TYPES_H__
                                          INCLUDE FILES
 ==================================================================================================*/
 #include <stdio.h>
-#include <vector>
+#include <memory>
 
-typedef std::vector<char> CharVector;
+template <typename T>
+void unique_ptr_deleter( T **ptr ) {
+       if (ptr && *ptr )       delete[] *ptr;
+}
 
 template <class T>
 
index 047f0b1..cb453eb 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_FILTER_TYPES_H
@@ -54,7 +54,8 @@ typedef struct
 {
        msg_filter_id_t                 filterId;                       /**< Indicates the filter ID. */
        msg_filter_type_t               filterType;             /**< Indicates the filter type. */
-       char                                            filterValue[MAX_FILTER_VALUE_LEN+1];    /**< The value of a filter. */
+       char                                                    filterValue[MAX_FILTER_VALUE_LEN+1];    /**< The value of a filter. */
+       bool                                                    bActive;
 } MSG_FILTER_S;
 
 
index cb208ea..13cae23 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_INTERNAL_TYPES_H
 /*==================================================================================================
                                     DEFINES
 ==================================================================================================*/
-#define MSG_DATA_ROOT_PATH             "/opt/data/msg-service/"
+#define MSG_DATA_ROOT_PATH             "/opt/usr/data/msg-service/"
 #define MSG_DATA_PATH                          MSG_DATA_ROOT_PATH"msgdata/"
 #define MSG_SMIL_FILE_PATH             MSG_DATA_ROOT_PATH"smildata/"
 #define MSG_IPC_DATA_PATH                      MSG_DATA_ROOT_PATH"ipcdata/"
 #define MSG_THUMBNAIL_PATH             MSG_DATA_PATH"thumbnails/"
+
+
+// temporary
+#define MSG_NATIONAL_SIM       "memory/private/msg-service/national_sim"
+#define MSG_SIM_MSISDN "memory/private/msg-service/msisdn"
+#define MSG_SIM_ICCID  "memory/private/msg-service/iccid"
+#define MSG_FMM_SIM_CHANGE_NUM "db/SyncML/oma-dm-service/fmmSimChangeNum"
+
 #define MAX_FULL_PATH_SIZE             320     // max length for internal file path
-#define VALID_ADDRESS_LEN              8
-#define MAX_PRECONFIG_NUM              8
 #define MAX_THREAD_ADDR_LEN    40
 #define MAX_THREAD_NAME_LEN    195
 #define MAX_THREAD_DATA_LEN    128
-
-#define SMS_MINIMUM_SPACE      (3 * 1024)
-#define MMS_MINIMUM_SPACE      (600 * 1024)
+#define MAX_CB_MSG_TEXT_LEN    4200    // 1page max char(93)*max page(15)*max bytes of UTF8 1 char(3)
+#define MAX_CB_MSG_LANGUAGE_TYPE_LEN   3
+#define MAX_ETWS_WARNING_SECURITY_INFO_LEN     50
+#define MAX_ME_IMEI_LEN                20
+#define MAX_SIM_MSISDN_LEN     26
+#define MAX_COMMON_INFO_SIZE   20
+#define MAX_VCONFKEY_NAME_LEN  128
+#define MAX_SIM_IMSI_LEN               16
+#define MAX_TAPI_SIM_API_TIMEOUT 70
+
+#define SMS_MINIMUM_SPACE      (1 * 1024 * 1024)
+#define MMS_MINIMUM_SPACE      (1 * 1024 * 1024)
 
 /*vconf keys*/
-#define MSG_SIM_IMSI                   "memory/private/msg-service/sim_imsi"
-#define MSG_SIM_CHANGED        "memory/private/msg-service/sim_changed"
+#define DEFAULT_SETTING_PATH                           "db/private/msg-service"
+#define DEFAULT_MSG_MEMORY_PATH                                "memory/private/msg-service"
 
+#define MSG_SIM_IMSI                   DEFAULT_MSG_MEMORY_PATH"/sim_imsi"
+#define MSG_SIM_CHANGED                DEFAULT_MSG_MEMORY_PATH"/sim_changed"
 
-#define DEFAULT_SETTING_PATH                           "db/private/msg-service"
+#define MSG_SIM_SERVICE_TABLE          DEFAULT_MSG_MEMORY_PATH"/sim_st"
+#define MSG_SIM_MO_CONTROL             DEFAULT_MSG_MEMORY_PATH"/sim_mo_ctrl"
+#define MSG_NETWORK_SIM                DEFAULT_MSG_MEMORY_PATH"/default_network_sim"
 
 #define DEFAULT_GENERAL_OPT_PATH               DEFAULT_SETTING_PATH"/general"
 #define DEFAULT_SMS_SEND_OPT_PATH      DEFAULT_SETTING_PATH"/sms_send"
 #define DEFAULT_SIM_COUNT_PATH                 DEFAULT_SETTING_PATH"/sim_count"
 
 #define MSG_KEEP_COPY                          DEFAULT_GENERAL_OPT_PATH"/keep_copy"
-#define MSG_ALERT_TONE                         VCONFKEY_SETAPPL_NOTI_MSG_ALERT_REP_TYPE_INT
+#define MSG_ALERT_REP_TYPE                     DEFAULT_GENERAL_OPT_PATH"/alert_rep_type"
 #define MSG_AUTO_ERASE                         DEFAULT_GENERAL_OPT_PATH"/auto_erase"
 #define MSG_BLOCK_MESSAGE              DEFAULT_GENERAL_OPT_PATH"/block_msg"
 #define CONTACT_SYNC_TIME              DEFAULT_GENERAL_OPT_PATH"/contact_sync_time"
+#define MSG_SEARCH_TAGS                        DEFAULT_GENERAL_OPT_PATH"/search_tags"
+
+#define MSG_BLOCK_UNKNOWN_MSG          DEFAULT_GENERAL_OPT_PATH"/block_unknown_msg"
+#define MSG_SMS_LIMIT                          DEFAULT_GENERAL_OPT_PATH"/sms_limit"
+#define MSG_MMS_LIMIT                          DEFAULT_GENERAL_OPT_PATH"/mms_limit"
+#define MSG_SETTING_NOTIFICATION       DEFAULT_GENERAL_OPT_PATH"/notification"
+#define MSG_SETTING_VIBRATION          DEFAULT_GENERAL_OPT_PATH"/vibration"
+#define MSG_SETTING_PREVIEW                    DEFAULT_GENERAL_OPT_PATH"/preview"
+#define MSG_SETTING_RINGTONE_PATH                      DEFAULT_GENERAL_OPT_PATH"/ringtone_path"
+#define MSG_SETTING_RINGTONE_TYPE                      DEFAULT_GENERAL_OPT_PATH"/ringtone_type"
+#define MSG_MMS_UA_PROFILE                             DEFAULT_GENERAL_OPT_PATH"/ua_profile"
+#define MSG_MMS_UA_AGENT                               DEFAULT_GENERAL_OPT_PATH"/ua_agent"
 
 #define SMS_SEND_DCS                                                   DEFAULT_SMS_SEND_OPT_PATH"/dcs"
 #define SMS_SEND_NETWORK_MODE  VCONFKEY_MESSAGE_NETWORK_MODE
 #define PUSH_SERVICE_TYPE                              DEFAULT_PUSH_MSG_OPT_PATH"/service_load"
 
 #define CB_RECEIVE                                             DEFAULT_CB_MSG_OPT_PATH"/receive"
-#define CB_ALL_CHANNEL                         DEFAULT_CB_MSG_OPT_PATH"/all_channel"
+#define CB_SAVE                                                DEFAULT_CB_MSG_OPT_PATH"/save"
 #define CB_MAX_SIM_COUNT                       DEFAULT_CB_MSG_OPT_PATH"/max_sim_count"
-#define CB_CHANNEL_COUNT                       DEFAULT_CB_MSG_OPT_PATH"/channel_count"
 #define CB_CHANNEL_ACTIVATE            DEFAULT_CB_MSG_OPT_PATH"/channel_activate"
 #define CB_CHANNEL_ID_FROM             DEFAULT_CB_MSG_OPT_PATH"/channel_id_from"
 #define CB_CHANNEL_ID_TO               DEFAULT_CB_MSG_OPT_PATH"/channel_id_to"
 #define CB_LANGUAGE                                    DEFAULT_CB_MSG_OPT_PATH"/language"
 
 #define VOICEMAIL_NUMBER                               DEFAULT_VOICE_MAIL_OPT_PATH"/voice_mail_number"
+#define VOICEMAIL_COUNT                                DEFAULT_VOICE_MAIL_OPT_PATH"/voice_mail_count"
+#define VOICEMAIL_ALPHA_ID                             DEFAULT_VOICE_MAIL_OPT_PATH"/voice_mail_alphaid"
+#define VOICEMAIL_DEFAULT_NUMBER       ""
+#define VOICEMAIL_DEFAULT_ALPHA_ID     ""
 
 #define MSGSIZE_OPTION                                 DEFAULT_MSGSIZE_OPT_PATH"/msg_size"
 
 #define SIM_USED_COUNT                                 DEFAULT_SIM_COUNT_PATH"/used_cnt"
 #define SIM_TOTAL_COUNT                                DEFAULT_SIM_COUNT_PATH"/total_cnt"
+#ifdef FEATURE_SMS_CDMA
+#define MSG_MESSAGE_ID_COUNTER                 DEFAULT_GENERAL_OPT_PATH"/msg_id_counter"
+#endif
+
+#define MSG_DEFAULT_APP_ID                     "org.tizen.message"
+#define MSG_QUICKPANEL_APP_ID          "org.tizen.quickpanel"
 
+#define MSG_TELEPHONY_FEATURE       "http://tizen.org/feature/network.telephony"
+#define MSG_TELEPHONY_MMS_FEATURE   "http://tizen.org/feature/network.telephony.mms"
 
 /*==================================================================================================
                                          TYPES
@@ -169,6 +211,15 @@ typedef unsigned char MSG_SUB_TYPE_T;
 
 
 /**
+ *     @brief  Represents a message tag type. \n
+ *     Each main type of a message can be divided into some tag types. \n
+ *     For instance of SMS, the message sub type can be one of the Priority, Finance, and so on. \n
+ *     The values for this type SHOULD be in _MSG_SUB_TYPE_E.
+ */
+typedef unsigned int MSG_TAG_TYPE_T;
+
+
+/**
  *     @brief  Represents a message class. \n
  *     The values for this type SHOULD be in _MSG_CLASS_TYPE_E.
  */
@@ -202,31 +253,35 @@ typedef struct
  */
 typedef struct
 {
-       msg_message_id_t                        msgId;                                                                                                                          /**< Indicates the message ID of this message. */
-       msg_thread_id_t                         threadId;                                                                                                                       /**< Indicates the thread ID. */
-       msg_folder_id_t                         folderId;                                                                                                                       /**< Indicates the folder ID. */
-       MSG_MESSAGE_TYPE_S              msgType;                                                                                                                        /**< Indicates the message type such as SMS and MMS */
-       msg_storage_id_t                        storageId;                                                                                                                      /**< Indicates where the message is saved. */
-       int                                                                             nAddressCnt;                                                                                                    /**< Indicates the count of addresses. */
-       MSG_ADDRESS_INFO_S              addressList[MAX_TO_ADDRESS_CNT];                                /**< Indicates the address information list. */
-       char                                                                            replyAddress[MAX_PHONE_NUMBER_LEN+1];   /**< Indicates the reply address. */
-       char                                                                            subject[MAX_SUBJECT_LEN+1];                                             /**< Indicates the message subject. */
-       time_t                                                                  displayTime;                                                                                                    /**< Indicates the display time related to the specific operation. */
-       msg_network_status_t    networkStatus;                                                                                                  /**< Indicates the network status of the message. */
-       msg_encode_type_t               encodeType;                                                                                                     /**< Indicates the string encoding type. */
-       bool                                                                            bRead;                                                                                                                          /**< Indicates whether the message is read or not. */
-       bool                                                                            bProtected;                                                                                                             /**< Indicates whether the message is protected or not. */
-       bool                                                                            bBackup;                                                                                                                        /**< Indicates whether the message was restored from PC. */
-       msg_priority_type_t             priority;                                                                                                                       /**< Indicates the priority of the message. */
-       msg_direction_type_t    direction;                                                                                                                      /**< Indicates whether the message is MO or MT (affecting address). */
-       MSG_PORT_INFO_S                         msgPort;                                                                                                                        /**< Indicates the port number information. */
-       bool                                                                            bTextSms;                                                                                                               /**< Indicates whether the message is just a text message or not. */
-       size_t                                                                  dataSize;                                                                                                                       /**< Indicates the data size. The unit is byte. */
-       char                                                                            msgData[MAX_MSG_DATA_LEN+1];                                    /**< Indicates the message payload information as a body. */
-       char                                                                            msgText[MAX_MSG_TEXT_LEN+1];
-       char                                                                            thumbPath[MSG_FILEPATH_LEN_MAX];
+       msg_message_id_t                msgId;                                                                                  /**< Indicates the message ID of this message. */
+       msg_thread_id_t                 threadId;                                                                               /**< Indicates the thread ID. */
+       msg_folder_id_t                 folderId;                                                                               /**< Indicates the folder ID. */
+       MSG_MESSAGE_TYPE_S              msgType;                                                                                /**< Indicates the message type such as SMS and MMS */
+       msg_storage_id_t                storageId;                                                                              /**< Indicates where the message is saved. */
+       int                                             nAddressCnt;                                                                    /**< Indicates the count of addresses. */
+//     MSG_ADDRESS_INFO_S              addressList[MAX_TO_ADDRESS_CNT];                                /**< Indicates the address information list. */
+       MSG_ADDRESS_INFO_S              *addressList;                           /**< Indicates the address information list. */
+       char                                    replyAddress[MAX_PHONE_NUMBER_LEN+1];                   /**< Indicates the reply address. */
+       char                                    subject[MAX_SUBJECT_LEN+1];                                             /**< Indicates the message subject. */
+       time_t                                  displayTime;                                                                    /**< Indicates the display time related to the specific operation. */
+       msg_network_status_t    networkStatus;                                                                  /**< Indicates the network status of the message. */
+       msg_encode_type_t               encodeType;                                                                             /**< Indicates the string encoding type. */
+       bool                                    bRead;                                                                                  /**< Indicates whether the message is read or not. */
+       bool                                    bProtected;                                                                             /**< Indicates whether the message is protected or not. */
+       bool                                    bBackup;                                                                                /**< Indicates whether the message was restored from PC. */
+       msg_priority_type_t             priority;                                                                               /**< Indicates the priority of the message. */
+       msg_direction_type_t    direction;                                                                              /**< Indicates whether the message is MO or MT (affecting address). */
+       MSG_PORT_INFO_S                 msgPort;                                                                                /**< Indicates the port number information. */
+       bool                                    bTextSms;                                                                               /**< Indicates whether the message is just a text message or not. */
+       size_t                                  dataSize;                                                                               /**< Indicates the data size. The unit is byte. */
+       char                                    msgData[MAX_MSG_DATA_LEN+1];                                    /**< Indicates the message payload information as a body. */
+       char                                    msgText[MAX_MSG_TEXT_LEN+1];
+       char                                    thumbPath[MSG_FILEPATH_LEN_MAX+1];
+       bool                                    bStore;                                                                                 /**< Indicates whether the message is stored or not if it is MWI message. */
+       int                                             sim_idx;
 } MSG_MESSAGE_INFO_S;
 
+
 typedef struct
 {
        msg_message_id_t                msgId;                                                                  /**< Indicates the message ID of this message. */
@@ -237,6 +292,7 @@ typedef struct
        MSG_CLASS_TYPE_T                classType;                                                              /**< Message class type. See enum _MSG_CLASS_TYPE_E */
        msg_storage_id_t                storageId;                                                              /**< Indicates where the message is saved. see enum _MSG_FOLDER_TYPE_E*/
        msg_struct_list_s               *addr_list;
+       GList                   *addressList;
        char                                    replyAddress[MAX_PHONE_NUMBER_LEN+1];   /**< Indicates the reply address. */
        char                                    subject[MAX_SUBJECT_LEN+1];                             /**< Indicates the message subject. */
        time_t                                  displayTime;                                                    /**< Indicates the display time related to the specific operation. */
@@ -251,12 +307,15 @@ typedef struct
        unsigned short                  dstPort;                                                                /**< Recipient port number, not greater than 16 bit */
        unsigned short                  srcPort;                                                                /**< Sender port number, not greater than 16 bit */
        int                                             attachCount;                                                    /**< Indicates the count of attached files in mms. */
-       char                                    thumbPath[MSG_FILEPATH_LEN_MAX];
+       char                                    thumbPath[MSG_FILEPATH_LEN_MAX+1];
        size_t                                  dataSize;                                                               /**< Indicates the data size. The unit is byte. */
        void                                    *pData;                                                                 /**< Indicates the message payload information as a body. default character encoding is UTF-8*/
        void                                    *pMmsData;                                                              /**< Indicates the message payload information as a body. default character encoding is UTF-8*/
+       size_t                                  mmsDataSize;
+       int                                             simIndex;
 } MSG_MESSAGE_HIDDEN_S;
 
+
 /**
  *     @brief  Represents message information for thread view.
  */
@@ -272,10 +331,60 @@ typedef struct
        int                                             unreadCnt;                                                                                                              /**< Indicates the unread messages from the Peer. */
        int                                             smsCnt;                                                                                                                 /**< Indicates the SMS messages from the Peer. */
        int                                             mmsCnt;                                                                                                                 /**< Indicates the MMS messages from the Peer. */
+       bool                                            bProtected;                                                                                                             /**< Indicates whether the thread includes protected messages.  */
+       bool                                            bDraft;
+       bool                                            bSendFailed;
+       bool                                            bSending;
+       int                                                     simIndex;
 } MSG_THREAD_VIEW_S;
 
 
 /**
+ *     @brief  Represents message information for conversation view.
+ */
+typedef struct
+{
+       msg_message_id_t                        msgId;                                                                  /**< Indicates the message ID of this message. */
+       msg_thread_id_t                 threadId;                                                               /**< Indicates the thread ID of this peer. */
+       MSG_MAIN_TYPE_T                 mainType;                                                       /**< Message main type. See enum _MSG_MAIN_TYPE_E */
+       MSG_SUB_TYPE_T                  subType;                                                                /**< Message sub type. See enum _MSG_SUB_TYPE_E */
+       msg_folder_id_t                 folderId;                                                               /**< Indicates the folder ID. see enum _MSG_FOLDER_TYPE_E */
+       msg_storage_id_t                                storageId;                                                              /**< Indicates where the message is saved. see enum _MSG_FOLDER_TYPE_E*/
+       time_t                                                          displayTime;                                            /**< Indicates the display time related to the specific operation. */
+       time_t                                                          scheduledTime;                                  /**< Indicates the time to send scheduled message. */
+       msg_network_status_t            networkStatus;                                          /**< Indicates the network status of the message. */
+       bool                                                                    bRead;                                                                  /**< Indicates whether the message is read or not. */
+       bool                                                                    bProtected;                                                     /**< Indicates whether the message is protected or not. */
+       msg_direction_type_t            direction;                                                              /**< Indicates whether the message is MO or MT, affecting address. */
+       int                                                                     pageCount;                                              /**< Indicates the count of pageCount in mms. */
+       int                                                                     attachCount;                                            /**< Indicates the count of attached files in mms. */
+       char                                                                    attachFileName[MSG_FILENAME_LEN_MAX+1]; /**< Indicates the thumbnail path. */
+       char                                                                    audioFileName[MSG_FILENAME_LEN_MAX+1];  /**< Indicates the thumbnail path. */
+       char                                                                    imageThumbPath[MSG_FILEPATH_LEN_MAX+1]; /**< Indicates the thumbnail path. */
+       char                                                                    videoThumbPath[MSG_FILEPATH_LEN_MAX+1];         /**< Indicates the thumbnail path. */
+       char                                                                    subject[MAX_SUBJECT_LEN+1];                                                     /**< Indicates the message subject. */
+       size_t                                                          textSize;                                                               /**< Indicates the data size. The unit is byte. */
+       char                                                                    *pText;                                                                 /**< Indicates the message payload information as a body. default character encoding is UTF-8*/
+       int tcs_bc_level;
+       char                                                                    firstMediaPath[MSG_FILEPATH_LEN_MAX+1]; // First Media Path in mms;
+       msg_list_handle_t multipart_list;
+       int                                                             simIndex;
+} MSG_CONVERSATION_VIEW_S;
+
+typedef struct
+{
+       MimeType        type;   /**< Indicates the multipart mime type. see enum MimeType */
+       char            szContentType[MSG_MSG_ID_LEN + 1];              /**< Indicates the content type */
+       char            szFileName[MSG_FILENAME_LEN_MAX + 1];           /**< Indicates the file name */
+       char            szFilePath[MSG_FILEPATH_LEN_MAX + 1];           /**< Indicates the file path */
+       char            szContentID[MSG_MSG_ID_LEN + 1];                /**< Indicates the content id */
+       char            szContentLocation[MSG_MSG_ID_LEN + 1];  /**< Indicates the content Location */
+
+       int             tcs_bc_level;   /** detect malware type **/
+       char            szThumbFilePath[MSG_FILEPATH_LEN_MAX + 1];      /**< Indicates the thumbnail file path */
+} MSG_MMS_MULTIPART_S;
+
+/**
  *     @brief  Represents sim message informatioin list.
  */
 typedef struct
@@ -323,6 +432,13 @@ typedef struct
        unsigned short          port;
 } MSG_CMD_REG_INCOMING_MSG_CB_S;
 
+typedef struct
+{
+       int                             listenerFd;
+       MSG_MAIN_TYPE_T         msgType;
+       bool                            bsave;
+} MSG_CMD_REG_CB_INCOMING_MSG_CB_S;
+
 
 /**
  *     @brief  Aux data structure for MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB. \n
@@ -380,6 +496,21 @@ typedef struct
        MSG_MAIN_TYPE_T         msgType;
 } MSG_CMD_REG_SYNCML_MSG_OPERATION_CB_S;
 
+typedef struct
+{
+       int                             listenerFd;
+       MSG_MAIN_TYPE_T         msgType;
+       char appId[MAX_WAPPUSH_ID_LEN+1];
+       char content_type[MAX_WAPPUSH_CONTENT_TYPE_LEN+1];
+} MSG_CMD_REG_INCOMING_PUSH_MSG_CB_S;
+
+typedef struct
+{
+       int                             listenerFd;
+       MSG_MAIN_TYPE_T         msgType;
+       bool                            bsave;
+} MSG_CMD_REG_INCOMING_CB_MSG_CB_S;
+
 
 typedef struct
 {
@@ -387,6 +518,43 @@ typedef struct
        MSG_REQUEST_INFO_S              reqInfo;
 }MSG_SCHEDULED_MSG_S;
 
+/**
+ *     @brief  Represents a CB message in the framework.
+ */
+typedef struct
+{
+       MSG_SUB_TYPE_T                  type;
+       time_t                                  receivedTime;
+
+       unsigned short                  serialNum;
+       unsigned short                  messageId;      // Message Identifier
+       unsigned char                   dcs;            // data coding scheme
+       int                                             cbTextLen;      // length of cbText
+       unsigned char                   cbText[MAX_CB_MSG_TEXT_LEN];// cb message text (UTF8)
+
+       unsigned short                  etwsWarningType;
+       unsigned char                   etwsWarningSecurityInfo[MAX_ETWS_WARNING_SECURITY_INFO_LEN];
+       unsigned char                   language_type[MAX_CB_MSG_LANGUAGE_TYPE_LEN];
+} MSG_CB_MSG_S;
+
+#ifdef FEATURE_SMS_CDMA
+typedef struct _MSG_UNIQUE_INDEX_S
+{
+       unsigned short          tele_msgId;
+       char                                    address[MAX_ADDRESS_VAL_LEN+1];
+       char                                    sub_address[MAX_ADDRESS_VAL_LEN+1];
+       char                                    time_stamp[MAX_COMMON_INFO_SIZE+1];
+       int                                             telesvc_id;
+} MSG_UNIQUE_INDEX_S;
+
+typedef struct
+{
+       time_t                                  receivedTime;
+       unsigned short                  serialNum;
+       unsigned short                  messageId;      // Message Identifier
+} MSG_CB_DUPLICATE_S;
+#endif
+
 
 /*==================================================================================================
                                          ENUMS
@@ -455,8 +623,20 @@ enum _MSG_SUB_TYPE_E
        MSG_FORWARDCONF_MMS,                    /**< MMS Forward Confirm message */
        MSG_READREPLY_MMS,                              /**< MMS Read Reply message */
        MSG_SENDREQ_JAVA_MMS,                   /**< MMS Send Request message for JAVA MMS */
+
+       MSG_ETWS_SMS,
+       MSG_MWI_VOICE2_SMS,                     /**< MWI Message Voice for line 2(CPHS)*/
+
+       MSG_CMAS_PRESIDENTIAL,          /**< CMAS CLASS */
+       MSG_CMAS_EXTREME,
+       MSG_CMAS_SEVERE,
+       MSG_CMAS_AMBER,
+       MSG_CMAS_TEST,
+       MSG_CMAS_EXERCISE,
+       MSG_CMAS_OPERATOR_DEFINED,
 };
 
+
 /**
  *     @brief  Represents the values of a message transaction type. \n
  *     This enum is used as the value of MSG_MMS_TRANSACTION_TYPE_T.
@@ -468,5 +648,21 @@ enum _MSG_MMS_TRANSACTION_TYPE_E
        MSG_MMS_UNKNOWN,
 };
 
+/**
+ *     @brief  Represents the values of File Type of MMS. \n
+ *     This enum is used as the value of .
+ */
+enum _MSG_MMS_ITEM_TYPE_E
+{
+       MSG_MMS_ITEM_TYPE_IMG,                  /**< Indicates the image media */
+       MSG_MMS_ITEM_TYPE_AUDIO,                /**< Indicates the audio media */
+       MSG_MMS_ITEM_TYPE_VIDEO,                /**< Indicates the video media */
+       MSG_MMS_ITEM_TYPE_ATTACH,               /**< Indicates the attach file */
+       MSG_MMS_ITEM_TYPE_PAGE, /**< Indicates the page count */
+       MSG_MMS_ITEM_TYPE_MALWARE,              /**< Indicates the tcs bc level*/
+       MSG_MMS_ITEM_TYPE_1ST_MEDIA,    /**< Indicates the 1st media path*/
+};
+
+
 #endif
 
index df41c2d..2ce1da6 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_MMS_TYPES_H
@@ -45,6 +45,7 @@
  *     @{
  */
 
+typedef GList MMSList;
 
 /*==================================================================================================
                                          STRUCTURES
@@ -54,8 +55,8 @@
  *     @brief  Represents text information.
  */
 typedef struct  {
-       char                    szTransInId[MAX_SMIL_TRANSIN_ID];  /**< Indicates the In SMIL transition id */
-       char                    szTransOutId[MAX_SMIL_TRANSOUT_ID]; /**< Indicates the Out SMIL transition id */
+       char                    szTransInId[MAX_SMIL_TRANSIN_ID + 1];  /**< Indicates the In SMIL transition id */
+       char                    szTransOutId[MAX_SMIL_TRANSOUT_ID + 1]; /**< Indicates the Out SMIL transition id */
        int                             nRepeat; /**< Indicates the text needs to be displayed repeatedly */
        int                             nBegin;  /**< Indicates the begin time */
        int                             nEnd;   /**< Indicates the end time */
@@ -74,8 +75,8 @@ typedef struct  {
  *     @brief  Represents video information.
  */
 typedef struct {
-       char                    szTransInId[MAX_SMIL_TRANSIN_ID]; /**< Indicates the In SMIL transition id */
-       char                    szTransOutId[MAX_SMIL_TRANSOUT_ID];  /**< Indicates the Out SMIL transition id */
+       char                    szTransInId[MAX_SMIL_TRANSIN_ID + 1]; /**< Indicates the In SMIL transition id */
+       char                    szTransOutId[MAX_SMIL_TRANSOUT_ID + 1];  /**< Indicates the Out SMIL transition id */
        int                             nRepeat; /**< Indicates the video needs to be displayed repeatedly */
        int                             nBegin;  /**< Indicates the begin time */
        int                             nEnd;   /**< Indicates the end time */
@@ -90,19 +91,22 @@ typedef struct
 {
        MmsSmilMediaType        mediatype; /**< Indicates the SMIL media type. see enum MmsSmilMediaType */
 
-       char                    szSrc[MSG_FILEPATH_LEN_MAX];/**< Indicates the media source name */
-       char                    szFileName[MSG_FILENAME_LEN_MAX]; /**< Indicates the file name */
-       char                    szFilePath[MSG_FILEPATH_LEN_MAX]; /**< Indicates the file path */
-       char                    szContentID[MSG_MSG_ID_LEN+1]; /**< Indicates the content id */
-       char                    regionId[MAX_SMIL_REGION_ID]; /**< Indicates the region id */
-       char                    szAlt[MAX_SMIL_ALT_LEN]; /**< Indicates the alternative text to be displayed in failure case */
+       char                    szSrc[MSG_FILEPATH_LEN_MAX + 1];/**< Indicates the media source name */
+       char                    szFileName[MSG_FILENAME_LEN_MAX + 1]; /**< Indicates the file name */
+       char                    szFilePath[MSG_FILEPATH_LEN_MAX + 1]; /**< Indicates the file path */
+       char                    szContentID[MSG_MSG_ID_LEN + 1]; /**< Indicates the content id */
+       char                    regionId[MAX_SMIL_REGION_ID + 1]; /**< Indicates the region id */
+       char                    szAlt[MAX_SMIL_ALT_LEN + 1]; /**< Indicates the alternative text to be displayed in failure case */
        MsgDrmType              drmType; /**< Indicates the drm type. see enum MsgDrmType */
-       char                    szDrm2FullPath[MSG_FILEPATH_LEN_MAX];  /**< Indicates the fullpath of the DRM */
+       char                    szDrm2FullPath[MSG_FILEPATH_LEN_MAX + 1];  /**< Indicates the fullpath of the DRM */
        union{
                MmsSmilText     sText;  /**< Indicates the text attributes */
                MmsSmilAVI      sAVI; /**< Indicates the video attributes */
        } sMedia;
-}MMS_MEDIA_S;
+
+       char szContentType[MSG_MSG_ID_LEN + 1];
+       char szContentLocation[MSG_MSG_ID_LEN + 1];
+} MMS_MEDIA_S;
 
 /**
  *     @brief  Represents attachment information.
@@ -110,12 +114,14 @@ typedef struct
 typedef struct
 {
        MimeType        mediatype;      /**< Indicates the file mime type. see enum MimeType */
-       char            szFileName[MSG_FILENAME_LEN_MAX]; /**< Indicates the file name */
-       char            szFilePath[MSG_FILEPATH_LEN_MAX]; /**< Indicates the file path */
+       char            szFileName[MSG_FILENAME_LEN_MAX + 1]; /**< Indicates the file name */
+       char            szFilePath[MSG_FILEPATH_LEN_MAX + 1]; /**< Indicates the file path */
        int             fileSize;        /**< Indicates the size of the file */
        MsgDrmType      drmType; /**< Indicates the drm type. see enum MsgDrmType */
-       char            szDrm2FullPath[MSG_FILEPATH_LEN_MAX]; /**< Indicates the fullpath of the DRM */
-}MMS_ATTACH_S;
+       char            szDrm2FullPath[MSG_FILEPATH_LEN_MAX + 1]; /**< Indicates the fullpath of the DRM */
+       char szContentType[MSG_MSG_ID_LEN + 1];
+
+} MMS_ATTACH_S;
 
 /**
  *     @brief  Represents SMIL page information.
@@ -140,22 +146,23 @@ typedef struct
 {
        bool    bUnitPercent; /**< Indicates the length is in percentage(%) or not */
        int     value;  /**< Indicates the value for length */
-}MMS_LENGTH;
+} MMS_LENGTH;
 
 /**
  *     @brief  Represents SMIL region information.
  */
 typedef struct
 {
-       char                            szID[MAX_SMIL_REGION_ID]; /**< Indicates the ID of region information */
+       char                            szID[MAX_SMIL_REGION_ID + 1]; /**< Indicates the ID of region information */
        MMS_LENGTH              nLeft; /**< Indicates the left co-ordinate of the region */
        MMS_LENGTH              nTop; /**< Indicates the top co-ordinate of the region */
        MMS_LENGTH              width; /**< Indicates the width of the region */
        MMS_LENGTH              height; /**< Indicates the width of the region */ // '%' rate should be supported
+       bool                    bBgColor;       /**< Indicates the background color set in the region */
        int                             bgColor;        /**< Indicates the background color of the region */
        REGION_FIT_TYPE_T       fit;    /**< Indicates the fit type. see enum REGION_FIT_TYPE_T */
 
-}MMS_SMIL_REGION;
+} MMS_SMIL_REGION;
 
 /**
  *     @brief  Represents SMIL root layout information.
@@ -164,6 +171,7 @@ typedef struct
 {
        MMS_LENGTH      width;          /**< Indicates the width of the root layout */
        MMS_LENGTH      height;         /**< Indicates the height of the root layout */ // '%' rate should be supported
+       bool            bBgColor;       /**< Indicates the background color set in the root layout */
        int                     bgColor;                /**< Indicates the background color of the root layout */
 }MMS_SMIL_ROOTLAYOUT;
 
@@ -173,10 +181,10 @@ typedef struct
  */
 typedef struct
 {
-       char                    szID[MAX_SMIL_TRANSITION_ID];   /**< Indicates the ID of transition information */
-       MmsSmilTransType        nType;                                  /**< Indicates the transition type. see enum MmsSmilTransType */
+       char                                    szID[MAX_SMIL_TRANSITION_ID + 1];       /**< Indicates the ID of transition information */
+       MmsSmilTransType                nType;                                  /**< Indicates the transition type. see enum MmsSmilTransType */
        MmsSmilTransSubType     nSubType;                               /**< Indicates the transition sub type. see enum MmsSmilTransSubType */
-       int                     nDur;                                   /**< Indicates the transition duration */
+       int                                     nDur;                                   /**< Indicates the transition duration */
 }MMS_SMIL_TRANSITION;
 
 
@@ -185,9 +193,9 @@ typedef struct
  */
 typedef struct
 {
-       char            szID[MAX_SMIL_META_ID];                         /**< Indicates the ID of meta information */
-       char            szName[MAX_SMIL_META_NAME];             /**< Indicates the Name */
-       char            szContent[MAX_SMIL_META_CONTENT];       /**< Indicates the content */
+       char            szID[MAX_SMIL_META_ID + 1];                             /**< Indicates the ID of meta information */
+       char            szName[MAX_SMIL_META_NAME + 1];         /**< Indicates the Name */
+       char            szContent[MAX_SMIL_META_CONTENT + 1];   /**< Indicates the content */
 }MMS_SMIL_META;
 
 
@@ -197,8 +205,8 @@ typedef struct
 typedef struct
 {
        bool                    valid;                                                                          /**< Indicates whether application id information is used or not. */
-       char                    appId[MAX_MMS_JAVA_APPID_LEN+1];                        /**< application id, it should not exceed 32 chars */
-       char                    replyToAppId[MAX_MMS_JAVA_APPID_LEN+1]; /**< reply to application id, application id, it should not exceeded 32 chars */
+       char                    appId[MAX_MMS_JAVA_APPID_LEN + 1];                      /**< application id, it should not exceed 32 chars */
+       char                    replyToAppId[MAX_MMS_JAVA_APPID_LEN + 1];       /**< reply to application id, application id, it should not exceeded 32 chars */
 }MMS_APPID_INFO_S;
 
 
@@ -207,19 +215,117 @@ typedef struct
 
 typedef struct
 {
-       char                                    szMsgID[MMS_MSG_ID_LEN+1];
-       char                                    retrievedFilePath[MAX_FULL_PATH_SIZE_S];
-       char                                    szTrID[MMS_TR_ID_LEN+1];
+       char                                    szMsgID[MMS_MSG_ID_LEN + 1];
+       char                                    retrievedFilePath[MAX_FULL_PATH_SIZE_S + 1];
+       char                                    szTrID[MMS_TR_ID_LEN + 1];
        MMS_APPID_INFO_S        msgAppId;
 }MMS_RECV_DATA_S;
 
+typedef struct _MMS_ADDRESS_DATA_S {
+       int address_type;
+       char *address_val;
+} MMS_ADDRESS_DATA_S;
+
+/**
+ *     @brief  Represents MMS header data.
+ */
+typedef struct _MMS_HEADER_DATA_S
+{
+       MMSList *bcc;// Bcc
+       MMSList *cc;//  Cc
+       char contentLocation[MMS_LOCATION_LEN + 1];
+       char szContentType[MSG_MSG_ID_LEN + 1];//string : ex) application/vnd.wap.multipart.related
+       unsigned long int date;
+       bool bDeliveryReport; //        X-Mms-Delivery-Report
+       MmsTimeStruct delivery; //      X-Mms-Delivery-Time
+       MmsTimeStruct expiry;
+       char szFrom[254 * 3  + 11]; //"/TYPE=PLMN", /"TYPE=IPv4", "/TYPE=IPv6" //       From
+       int messageClass;//Personal | Advertisement | Informational | Auto
+       char messageID[MSG_MSG_ID_LEN + 1];
+       int messageType;//MmsMsgType : ex) sendreq
+       int mmsVersion;//1.0 1.3
+       int messageSize; //X-Mms-Message-Size
+       int mmsPriority;//_MSG_PRIORITY_TYPE_E : Low | Normal | High
+       bool bReadReport;//     X-Mms-Read-Report
+//     X-Mms-Report-Allowed
+//     X-Mms-Response-Status
+//     X-Mms-Response-Text
+       bool bHideAddress;//    X-Mms-Sender-Visibility
+       msg_delivery_report_status_t mmsStatus;//       X-Mms-Status
+       char szSubject[MAX_SUBJECT_LEN + 1];//  Subject
+       MMSList *to;//  Cc//    To
+       char trID[MSG_MSG_ID_LEN + 1];
+//     X-Mms-Retrieve-Status
+//     X-Mms-Retrieve-Text
+//     X-Mms-Read-Status
+//     X-Mms-Reply-Charging
+//     X-Mms-Reply-Charging-Deadline
+//     X-Mms-Reply-Charging-ID
+//     X-Mms-Reply-Charging-Size
+//     X-Mms-Previously-Sent-By
+//     X-Mms-Previously-Sent-Date
+//     X-Mms-Store
+//     X-Mms-MM-State
+//     X-Mms-MM-Flags
+//     X-Mms-Store-Status
+//     X-Mms-Store-Status-Text
+//     X-Mms-Stored
+//     X-Mms-Attributes
+//     X-Mms-Totals
+//     X-Mms-Mbox-Totals
+//     X-Mms-Quotas
+//     X-Mms-Mbox-Quotas
+//     X-Mms-Message-Count
+//     Content
+//     X-Mms-Start
+//     Additional-headers
+//     X-Mms-Distribution-Indicator
+//     X-Mms-Element-Descriptor
+//     X-Mms-Limit
+//     X-Mms-Recommended-Retrieval-Mode
+//     X-Mms-Recommended-Retrieval-Mode-Text
+//     X-Mms-Status-Text
+//     X-Mms-Applic-ID
+//     X-Mms-Reply-Applic-ID
+//     X-Mms-Aux-Applic-Info
+       int contentClass;//text | image-basic| image-rich | video-basic | video-rich | megapixel | content-basic | content-rich
+//     X-Mms-DRM-Content
+//     X-Mms-Adaptation-Allowed
+//     X-Mms-Replace-ID
+//     X-Mms-Cancel-ID
+//     X-Mms-Cancel-Status
+//------------------------------------------------------------------
+       int contentType;//MimeType : ex) application/vnd.wap.multipart.related
+
+} MMS_HEADER_DATA_S;
+
+/**
+ *     @brief  Represents MMS multipart data.
+ */
+typedef struct
+{
+       MimeType        type;   /**< Indicates the multipart mime type. see enum MimeType */
+       char            szContentType[MSG_MSG_ID_LEN + 1];              /**< Indicates the content type */
+       char            szFileName[MSG_FILENAME_LEN_MAX + 1];           /**< Indicates the file name */
+       char            szContentID[MSG_MSG_ID_LEN + 1];                /**< Indicates the content id */
+       char            szContentLocation[MSG_MSG_ID_LEN + 1];  /**< Indicates the content Location */
+       MsgDrmType              drmType; /**< Indicates the drm type. see enum MsgDrmType */
+
+       char            szFilePath[MSG_FILEPATH_LEN_MAX + 1];           /**< Indicates the file path */
+       char *pMultipartData;
+       size_t nMultipartDataLen;
+       int             tcs_bc_level;   /** detect malware type **/
+       int     malware_allow;
+       char            szThumbFilePath[MSG_FILEPATH_LEN_MAX + 1];              /**< Indicates the thubnail file path */
+} MMS_MULTIPART_DATA_S;
 
 /**
  *     @brief  Represents MMS message data.
  */
 typedef struct _MMS_MESSAGE_DATA_S
 {
-       char                                    szSmilFilePath[MSG_FILEPATH_LEN_MAX];   /**< Indicates the SMIL file path */
+       int                                     backup_type; //normal = 0|| backup = 1;
+       char                                    szSmilFilePath[MSG_FILEPATH_LEN_MAX + 1];       /**< Indicates the SMIL file path */
        int                                             pageCnt;        /**< The count of the SMIL pages */
        GList                                   *pagelist;      /**< The pointer to SMIL pages list */
        int                                             regionCnt;      /**< The count of the SMIL regions */
@@ -232,13 +338,19 @@ typedef struct _MMS_MESSAGE_DATA_S
        GList                                   *metalist;      /**< The pointer to SMIL meta list */
        MMS_SMIL_ROOTLAYOUT             rootlayout;     /**< Indicates the root layout information */
        MMS_APPID_INFO_S                msgAppId;
-}MMS_MESSAGE_DATA_S;
+       MMS_HEADER_DATA_S header;//use for scloud
+       MMS_MULTIPART_DATA_S smil;//use for scloud
+} MMS_MESSAGE_DATA_S;
 
 /**
- *     @}
+ *     @brief  Represents MMS message data.
  */
-
-
+typedef struct
+{
+       int backup_type; //none = 0 || scloud backup = 1 || kies backup = 2;
+       MMS_HEADER_DATA_S *header; /**< The header struct of MMS*/
+       MMS_MULTIPART_DATA_S *smil;
+       MMSList *multipartlist; /**< list of MMS_MULTIPART_DATA_S*/
+} MMS_DATA_S;
 
 #endif
-
index efdf960..a761501 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
  /**
@@ -524,7 +524,11 @@ typedef msg_error_t (*MsgPlgSaveSimMessage)(const MSG_MESSAGE_INFO_S *pMsgInfo,
  *
  */
 /*================================================================================================*/
+#ifdef FEATURE_SMS_CDMA
 typedef msg_error_t (*MsgPlgDeleteSimMessage)(msg_sim_id_t SimMsgId);
+#else
+typedef msg_error_t (*MsgPlgDeleteSimMessage)(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId);
+#endif
 
 
  /**
@@ -565,8 +569,11 @@ typedef msg_error_t (*MsgPlgDeleteSimMessage)(msg_sim_id_t SimMsgId);
  *
  */
 /*================================================================================================*/
+#ifdef FEATURE_SMS_CDMA
 typedef msg_error_t (*MsgPlgSetReadStatus)(msg_sim_id_t SimMsgId);
-
+#else
+typedef msg_error_t (*MsgPlgSetReadStatus)(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId);
+#endif
 
  /**
 
@@ -606,8 +613,11 @@ typedef msg_error_t (*MsgPlgSetReadStatus)(msg_sim_id_t SimMsgId);
  *
  */
 /*================================================================================================*/
+#ifdef FEATURE_SMS_CDMA
 typedef msg_error_t (*MsgPlgSetMemoryStatus)(msg_error_t Error);
-
+#else
+typedef msg_error_t (*MsgPlgSetMemoryStatus)(msg_sim_slot_id_t sim_idx, msg_error_t Error);
+#endif
 
 // Setting API
  /**
@@ -891,7 +901,6 @@ typedef msg_error_t (*MsgPlgUpdateMessage)(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SEN
 *
 * \param output - pMsg is information of MMS message.
 * \param output - pSendOptInfo is information of sending options.
-* \param output - pMmsMsg is information of MMS messages detail data.
 * \param output - pDestMsg is file path of MMS message.
 *
 * \return Return Type (int(msg_error_t)) \n
@@ -909,7 +918,7 @@ typedef msg_error_t (*MsgPlgUpdateMessage)(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SEN
 *
 */
 /*================================================================================================*/
-typedef msg_error_t (*MsgPlgGetMmsMessage)(MSG_MESSAGE_INFO_S* pMsg,   MSG_SENDINGOPT_INFO_S* pSendOptInfo, MMS_MESSAGE_DATA_S* pMmsMsg, char** pDestMsg);
+typedef msg_error_t (*MsgPlgGetMmsMessage)(MSG_MESSAGE_INFO_S* pMsg,   MSG_SENDINGOPT_INFO_S* pSendOptInfo, char** pDestMsg);
 
 
 /**
@@ -1035,6 +1044,10 @@ typedef msg_error_t (*MsgPlgComposeReadReport)(MSG_MESSAGE_INFO_S *pMsgInfo);
 /*================================================================================================*/
 typedef msg_error_t (*MsgPlgRestoreMsg)(MSG_MESSAGE_INFO_S *pMsg, char* pRcvdBody, int rcvdBodyLen, char* filePath);
 
+typedef msg_error_t (*MsgPlgGetMeImei) (char *pImei);
+
+typedef msg_error_t (*MsgPlgGetDefaultNetworkSimId) (int *simId);
+
 
 // framework defined callbacks.
 typedef void (*MsgPlgOnSentStatus)(MSG_SENT_STATUS_S *pSentStatus);
@@ -1043,21 +1056,36 @@ typedef msg_error_t (*MsgPlgOnMsgIncoming)(MSG_MESSAGE_INFO_S *pMsgInfo);
 typedef msg_error_t (*MsgPlgOnInitSimBySat)(void);
 typedef msg_error_t (*MsgPlgOnSyncMLMsgIncoming)(MSG_SYNCML_MESSAGE_DATA_S *pSyncMLData);
 typedef msg_error_t (*MsgPlgOnLBSMsgIncoming)(MSG_LBS_MESSAGE_DATA_S *pLBSData);
+typedef msg_error_t (*MsgPlgOnPushMsgIncoming)(MSG_PUSH_MESSAGE_DATA_S *pPushData);
+typedef msg_error_t (*MsgPlgOnCBMsgIncoming)(MSG_CB_MSG_S *pCbMsg, MSG_MESSAGE_INFO_S *pMsgInfo);
 typedef msg_error_t (*MsgPlgOnMmsConfIncoming)(MSG_MESSAGE_INFO_S *pMsgInfo, msg_request_id_t *pRequest);
-
+typedef msg_error_t (*MsgPlgOnSimMessageIncoming)(MSG_MESSAGE_INFO_S *pMsgInfo, int *simIdList, msg_message_id_t *retMsgId, int listSize);
+typedef msg_error_t (*MsgPlgOnResendMessage)(void);
+#ifdef FEATURE_SMS_CDMA
+typedef bool (*MsgPlgCheckUniqueness)(MSG_UNIQUE_INDEX_S *p_msg, msg_message_id_t msgId, bool ischecked);
+#endif
+typedef msg_error_t (*MsgPlgOnInitImsi)(int sim_idx);
 
 /*==================================================================================================
                                          STRUCTURES
 ==================================================================================================*/
 struct _MSG_PLUGIN_LISTENER_S
 {
-       MsgPlgOnSentStatus                      pfSentStatusCb;                 /** The function pointer of sent status callback. */
-       MsgPlgOnStorageChange           pfStorageChangeCb;              /** The function pointer of storage change callback. */
-       MsgPlgOnMsgIncoming                     pfMsgIncomingCb;                        /** The function pointer of receive message callback. */
-       MsgPlgOnInitSimBySat                    pfInitSimBySatCb;                       /** The function pointer of init SIM callback. */
+       MsgPlgOnSentStatus                                      pfSentStatusCb;                                 /** The function pointer of sent status callback. */
+       MsgPlgOnStorageChange                   pfStorageChangeCb;                      /** The function pointer of storage change callback. */
+       MsgPlgOnMsgIncoming                             pfMsgIncomingCb;                                /** The function pointer of receive message callback. */
+       MsgPlgOnInitSimBySat                            pfInitSimBySatCb;                               /** The function pointer of init SIM callback. */
        MsgPlgOnSyncMLMsgIncoming       pfSyncMLMsgIncomingCb;  /** The function pointer of receive syncML message callback. */
-       MsgPlgOnLBSMsgIncoming          pfLBSMsgIncomingCb;             /** The function pointer of receive LBS message callback. */
-       MsgPlgOnMmsConfIncoming         pfMmsConfIncomingCb;    /** The function pointer of receive MMS conf */
+       MsgPlgOnLBSMsgIncoming                  pfLBSMsgIncomingCb;                     /** The function pointer of receive LBS message callback. */
+       MsgPlgOnPushMsgIncoming         pfPushMsgIncomingCb;            /** The function pointer of receive Push message callback. */
+       MsgPlgOnCBMsgIncoming                   pfCBMsgIncomingCb;                      /** The function pointer of receive cb message callback. */
+       MsgPlgOnMmsConfIncoming                 pfMmsConfIncomingCb;            /** The function pointer of receive MMS conf */
+       MsgPlgOnSimMessageIncoming      pfSimMsgIncomingCb;                     /** The function pointer of sim message callback */
+       MsgPlgOnResendMessage           pfResendMessageCb;
+#ifdef FEATURE_SMS_CDMA
+       MsgPlgCheckUniqueness           pfCheckUniquenessCb;
+#endif
+       MsgPlgOnInitImsi                        pfSimInitImsiCb;
 };
 
 
@@ -1066,15 +1094,11 @@ struct _MSG_PLUGIN_HANDLER_S
        MsgPlgInitialize                                pfInitialize;                           /**< The function pointer of initialize. */
        MsgPlgFinalize                                  pfFinalize;                             /**< The function pointer of finalize. */
        MsgPlgRegisterListener                  pfRegisterListener;                     /**< The function pointer of register listener. */
-       MsgPlgCheckSimStatus                    pfCheckSimStatus;               /**< The function pointer of check SIM status. */
-       MsgPlgCheckDeviceStatus         pfCheckDeviceStatus;            /**< The function pointer of check device status. */
        MsgPlgSubmitRequest                     pfSubmitRequest;                /**< The function pointer of submit request. */
-       MsgPlgInitSimMessage                    pfInitSimMessage;                       /**< The function pointer of initialize SIM msg. */
        MsgPlgSaveSimMessage                    pfSaveSimMessage;               /**< The function pointer of save SIM msg. */
        MsgPlgDeleteSimMessage          pfDeleteSimMessage;             /**< The function pointer of delete SIM msg. */
        MsgPlgSetReadStatus                     pfSetReadStatus;                        /**< The function pointer of set read status. */
        MsgPlgSetMemoryStatus           pfSetMemoryStatus;              /**< The function pointer of set memory status. */
-       MsgPlgInitConfigData                    pfInitConfigData;                       /**< The function pointer of initialize of setting. */
        MsgPlgSetConfigData                     pfSetConfigData;                        /**< The function pointer of save setting. */
        MsgPlgGetConfigData                     pfGetConfigData;                        /**< The function pointer of get setting. */
        MsgPlgRestoreMsg                                pfRestoreMsg;
@@ -1084,6 +1108,7 @@ struct _MSG_PLUGIN_HANDLER_S
        MsgPlgGetMmsMessage                     pfGetMmsMessage;
        MsgPlgUpdateRejectStatus                pfUpdateRejectStatus;
        MsgPlgComposeReadReport                 pfComposeReadReport;
+       MsgPlgGetDefaultNetworkSimId    pfGetDefaultNetworkSimId;
 };
 
 #ifdef __cplusplus
index 3869ddc..69cb8f2 100755 (executable)
@@ -1,30 +1,31 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef __MsgThdSafeQ_H__
 #define __MsgThdSafeQ_H__
 
-#include <queue>
 #include "MsgMutex.h"
 #include <list>
 
-template <typename T> class MsgThdSafeQ
+
+template <typename T> 
+class MsgSimpleQ
 {
 public:
-       MsgThdSafeQ(){};
+       MsgSimpleQ(){};
        void pop_front ();
        bool front(T* qItem);
        void push_front(T const & input);
@@ -32,28 +33,23 @@ public:
        int size();
        bool empty();
        void clear();
+       bool checkExist(T const & qItem, bool(cmp)(T const &, T const &));
+       void remove(T const & qItem, bool(cmp)(T const &, T const &) );
 private:
-       Mutex mx;
        std::list <T> q;
 };
 
-/*
-       mx variable guarantees atomic operation in multi-threaded environment.
-       For example, when a thread is executing Pop(), other threads
-       trying to execute one of Pop, Push, Size, Empty are locked.
-*/
-
-template <typename T> void MsgThdSafeQ<T>::pop_front()
+template <typename T> 
+void MsgSimpleQ<T>::pop_front()
 {
-       MutexLocker lock(mx);
        if( q.empty() ) return;
 
        q.pop_front();
 }
 
-template <typename T> bool MsgThdSafeQ<T>::front(T* qItem)
+template <typename T> 
+bool MsgSimpleQ<T>::front(T* qItem)
 {
-       MutexLocker lock(mx);
        if( qItem == NULL || q.empty() )
                return false; // Fail
 
@@ -63,36 +59,59 @@ template <typename T> bool MsgThdSafeQ<T>::front(T* qItem)
 }
 
 
-template <typename T> void MsgThdSafeQ<T>::push_back(T const & qItem)
+template <typename T> 
+void MsgSimpleQ<T>::push_back(T const & qItem)
 {
-       MutexLocker lock(mx);
        q.push_back(qItem);
 }
 
-template <typename T> void MsgThdSafeQ<T>::push_front(T const & qItem)
+template <typename T> void 
+MsgSimpleQ<T>::push_front(T const & qItem)
 {
-       MutexLocker lock(mx);
        q.push_front(qItem);
 }
 
 
-template <typename T> int MsgThdSafeQ<T>::size()
+template <typename T> 
+int MsgSimpleQ<T>::size()
 {
-       MutexLocker lock(mx);
        return q.size();
 }
 
-template <typename T> bool MsgThdSafeQ<T>::empty()
+template <typename T> 
+bool MsgSimpleQ<T>::empty()
 {
-       MutexLocker lock(mx);
        return q.empty();
 }
 
-template <typename T> void MsgThdSafeQ<T>::clear()
+template <typename T> 
+void MsgSimpleQ<T>::clear()
 {
-       MutexLocker lock(mx);
        q.clear();
 }
 
+template <typename T> 
+bool MsgSimpleQ<T>::checkExist(T const & qItem, bool(cmp)(T const &, T const &))
+{
+       for(typename list<T>::iterator iterPos = q.begin(); iterPos != q.end(); ++iterPos)      {
+
+               if (cmp(qItem, *iterPos) == true)
+                       return true;
+       }
+
+       return false;
+}
+
+template <typename T>
+void MsgSimpleQ<T>::remove(T const & qItem, bool(cmp)(T const &, T const &))
+{
+       for(typename list<T>::iterator iterPos = q.begin(); iterPos != q.end(); )       {
+
+               if (cmp(qItem, *iterPos) == true)
+                       q.erase(iterPos++);
+               else
+                       ++iterPos;
+       }
+}
 #endif // __MsgThdSafeQ_H__
 
index 9b5bd40..733096d 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_SETTING_TYPES_H
@@ -34,6 +34,7 @@
                                          INCLUDE FILES
 ==================================================================================================*/
 #include "MsgTypes.h"
+#include "MsgStorageTypes.h"
 
 /**
  *     @ingroup                MESSAGING_FRAMEWORK
@@ -179,11 +180,18 @@ typedef unsigned char MSG_CB_LANGUAGE_TYPE_T;
 
 /**
  *     @brief  Represents the SIM status from telephony. \n
- *     The values for this type SHOULD be in \ref _MSG_SIM_STATUS_E.
+ *     The values for this type SHOULD be in _MSG_SIM_STATUS_E.
  */
 typedef unsigned char MSG_SIM_STATUS_T;
 
 
+/**
+ *     @brief  Represents the ringtone type of message. \n
+ *     The values for this type SHOULD be in _MSG_RINGTONE_TYPE_E.
+ */
+typedef int MSG_RINGTONE_TYPE_T;
+
+
 /*==================================================================================================
                                          STRUCTURES
 ==================================================================================================*/
@@ -210,25 +218,32 @@ typedef struct
        MSG_SMSC_ADDRESS_S              smscAddr;                                       /**< SMSC address structure */
 } MSG_SMSC_DATA_S;
 
+
 /**
  *     @brief  Represents an SMSC list.
  */
 typedef struct
 {
-       int                                             selected;                                                       /**< Selected SMSC index */
+       int                                             index;                                          /**< SMSC index for Updating information */
+       int                                             selected;                                       /**< Selected SMSC index */
        int                                             totalCnt;                                                       /**< The count of total SMSC addresses */
-       MSG_SMSC_DATA_S                 smscData[SMSC_LIST_MAX];                        /**< SMSC data information list*/
+       MSG_SMSC_DATA_S                 smscData[SMSC_LIST_MAX];                /**< SMSC data information list*/
+       msg_sim_slot_id_t               simIndex;
 }MSG_SMSC_LIST_S;
 
+
 /**
  *     @brief  Represents an SMSC list.
  */
 typedef struct
 {
+       int                                             index;                                  /**< SMSC index for Updating information */
        int                                             selected;                               /**< Selected SMSC index */
-       msg_struct_list_s               *smsc_list;                             /**< SMSC data information list*/
+       msg_struct_list_s               *smsc_list;                     /**< SMSC data information list*/
+       msg_sim_slot_id_t               simIndex;
 }MSG_SMSC_LIST_HIDDEN_S;
 
+
 /**
  *     @brief  Represents the information of a cell broadcasting channel.
  */
@@ -237,6 +252,8 @@ typedef struct
        bool                    bActivate;                                                      /**< Indicates whether the CB channel is activate or passive. */
        unsigned int    from;                                                           /**< Indicates the start ID of a CB channel range. */
        unsigned int    to;                                                                     /**< Indicates the end ID of a CB channel range. */
+       unsigned short ctg;                                                             /**< Indicates the category of a CB. (for 3gpp2)*/
+       unsigned short lang;                                                            /**< Indicates the language of a CB. (for 3gpp2)*/
        char                    name[CB_CHANNEL_NAME_MAX+1];            /**< Indicates the name of a CB channel. */
 } MSG_CB_CHANNEL_INFO_S;
 
@@ -250,14 +267,24 @@ typedef struct
        MSG_CB_CHANNEL_INFO_S   channelInfo[CB_CHANNEL_MAX];    /**< The structure of CB channel information */
 } MSG_CB_CHANNEL_S;
 
+
 /**
  *     @brief  Represents an general option.
  */
 typedef struct
 {
-       bool                                                    bKeepCopy;                      /**< Indicates whether the SMS message copy is kept or not. */
-       MSG_ALERT_TONE_T                        alertTone;                      /**< Indicates the period of playing alert tone. */
-       bool                                                    bAutoErase;                     /**< Indicates whether the auto-erase option is enabled or not. */
+       bool                                    bKeepCopy;                      /**< Indicates whether the SMS message copy is kept or not. */
+       MSG_ALERT_TONE_T                alertTone;                      /**< Indicates the period of playing alert tone. */
+       bool                                    bAutoErase;                     /**< Indicates whether the auto-erase option is enabled or not. */
+       bool                                    bBlockUnknownMsg;               /**< Indicates whether unknown sender message is blocked or not. */
+       int                                             smsLimitCnt;            /**< Indicates the count limitation of sms messages in one conversation */
+       int                                             mmsLimitCnt;            /**< Indicates the count limitation of sms messages in one conversation */
+       bool                                    bNotification;          /**< Indicates whether notification for incoming message is shown or not. */
+       bool                                    bVibration;             /**< Indicates whether vibration for incoming message is run or not. */
+       bool                                    bPreview;                       /**< Indicates whether preview for incoming message is shown or not. */
+       char                                    ringtonePath[MSG_FILEPATH_LEN_MAX+1];           /**< Indicates the message ringtone path */
+       int                                     ringtoneType;           /**< Indicates the message ringtone type. */
+       int                                             searchTags;                     /**< Indicates the tags to be enabled for search ex) MSG_MESSAGE_TAG_PRIMARY | MSG_MESSAGE_TAG_PROMOTION.  See enum _MSG_TAG_TYPE_E  */
 }MSG_GENERAL_OPT_S;
 
 
@@ -356,6 +383,7 @@ typedef struct
        int                                     maxSimCnt;              /**< Indicates the number of channels which can be stored in SIM. */
        MSG_CB_CHANNEL_S        channelData;            /**< Indicates the cell broadcasting channel information. */
        bool                            bLanguage[CB_LANG_TYPE_MAX];            /**< Indicates whether the language name of a cell broadcasting message is set or not. */
+       msg_sim_slot_id_t                                       simIndex;
 } MSG_CBMSG_OPT_S;
 
 typedef struct
@@ -364,14 +392,19 @@ typedef struct
        int                                     maxSimCnt;              /**< Indicates the number of channels which can be stored in SIM. */
        msg_struct_list_s       *channelData;           /**< Indicates the cell broadcasting channel information. */
        bool                                    bLanguage[CB_LANG_TYPE_MAX];            /**< Indicates whether the language name of a cell broadcasting message is set or not. */
+       msg_sim_slot_id_t                                       simIndex;
 } MSG_CBMSG_OPT_HIDDEN_S;
 
+
 /**
  *     @brief  Represents a voice mail number option.
  */
 typedef struct
 {
        char mailNumber[MAX_PHONE_NUMBER_LEN+1];
+       char alpahId[MAX_SIM_XDN_ALPHA_ID_LEN+1];
+       msg_sim_slot_id_t                                       simIndex;
+       int voiceCnt;
 } MSG_VOICEMAIL_OPT_S;
 
 
diff --git a/include/common/MsgSmil.h b/include/common/MsgSmil.h
new file mode 100755 (executable)
index 0000000..6537e0e
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MSG_SMIL_H
+#define MSG_SMIL_H
+
+#include "MsgMmsTypes.h"
+
+/**    @fn     bool MsgSmilParseSmilDoc(MMS_MESSAGE_DATA_S *pstMsgMmsBody, const char *pSmilDoc)
+ *     @brief  Parse Smil Document using MMS_MESSAGE_DATA_S struct.
+ *     @param[in]      pstMsgMmsBody
+ *     @param[in]      pSmilDoc
+ *     @retval TRUE    In case of Success.
+ *     @retval FALSE   In case of failure.
+ */
+bool MsgSmilParseSmilDoc(MMS_MESSAGE_DATA_S *pstMsgMmsBody, const char *pSmilDoc);
+
+/**    @fn     bool MsgSmilGenerateSmilDoc(MMS_MESSAGE_DATA_S *pstMsgMmsBody, char **ppSmilDoc)
+ *     @brief  Generate Smil Document using MMS_MESSAGE_DATA_S struct.
+ *     @param[in]      pstMsgMmsBody
+ *     @param[out]     ppSmilDoc
+ *     @retval TRUE    In case of Success.
+ *     @retval FALSE   In case of failure.
+ */
+bool MsgSmilGenerateSmilDoc(MMS_MESSAGE_DATA_S *pstMsgMmsBody, char **ppSmilDoc);
+
+#endif//MSG_SMIL_H
index aef5f1e..ca6c3d0 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_STORAGE_TYPES_H
  *     @defgroup       MESSAGING_STORAGE_TYPES Messaging Storage Types
  *     @{
  */
-
-/*==================================================================================================
-                                    DEFINES
-==================================================================================================*/
-#define MAX_SEGMENT_NUM                        15
-
-
 /*==================================================================================================
                                          STRUCTURES
 ==================================================================================================*/
@@ -98,10 +91,15 @@ typedef struct
 typedef struct
 {
        msg_contact_id_t        contactId;                                                      /**< Indicates the unique contact ID. */
-       char                            displayName[MAX_DISPLAY_NAME_LEN+1];    /**< Indicates the display name of contact. */
-       char                            firstName[MAX_DISPLAY_NAME_LEN+1];              /**< Indicates the first name of contact. */
-       char                            lastName[MAX_DISPLAY_NAME_LEN+1];               /**< Indicates the last name of contact. */
-       char                            imagePath[MAX_IMAGE_PATH_LEN+1];                /**< Indicates the image path of contact. */
+       int                                             addrbookId;                                                     /**< Indicates the address book ID. */
+       char                                    firstName[MAX_DISPLAY_NAME_LEN+1];              /**< Indicates the first name of contact. */
+       char                                    lastName[MAX_DISPLAY_NAME_LEN+1];               /**< Indicates the last name of contact. */
+       char                                    middleName[MAX_DISPLAY_NAME_LEN+1];             /**< Indicates the middle name of contact. */
+       char                                    prefix[MAX_DISPLAY_NAME_LEN+1];         /**< Indicates the prefix of contact. */
+       char                                    suffix[MAX_DISPLAY_NAME_LEN+1];         /**< Indicates the suffix of contact. */
+       char                                    imagePath[MAX_IMAGE_PATH_LEN+1];                /**< Indicates the image path of contact. */
+       char                                            alerttonePath[MSG_FILEPATH_LEN_MAX+1];          /**< Indicates the message alert tone path of contact. */
+       char                                            vibrationPath[MSG_FILEPATH_LEN_MAX+1];          /**< Indicates the vibration path of contact. */
 } MSG_CONTACT_INFO_S;
 
 
@@ -112,7 +110,7 @@ typedef struct
  */
 typedef struct
 {
-       msg_sort_type_t sortType;               /**< Indicates the sort type */
+       msg_sort_type_t sortType;               /**< Indicates the sort type, See enum _MSG_SORT_TYPE_E */
        bool                                    bAscending;             /**< Indicates the sort order which is ascending or descending */
 }MSG_SORT_RULE_S;
 
@@ -150,5 +148,34 @@ typedef struct
 } MSG_SEARCH_CONDITION_S;
 
 
+/**
+ *     @brief  Represents Message list condition values.
+ */
+typedef struct
+{
+       msg_folder_id_t                 folderId;
+       msg_thread_id_t                 threadId;
+       msg_storage_id_t                        storageId;
+       msg_message_type_t      msgType;
+       bool                                                            bProtected;
+       bool                                                            bScheduled;
+       char                                                            *pAddressVal;
+       char                                                            *pTextVal;
+       bool                                                            bAnd;
+       time_t                                                  fromTime;
+       time_t                                                  toTime;
+       int                                                             offset;
+       int                                                             limit;
+       msg_struct_t                                    sortRule;
+       int                                                     simIndex;
+} MSG_LIST_CONDITION_S;
+
+
+typedef struct
+{
+       int appcode;
+       char appid[MAX_WAPPUSH_ID_LEN];
+} PUSH_APPLICATION_INFO_S;
+
 #endif // MSG_STORAGE_TYPES_H
 
index 454d1b5..c3c5ed6 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef __MSG_THREAD_H__
index 2ecd7fc..e4cf048 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_TRANSPORT_TYPES_H
index fd33621..ae49fde 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_TYPES_H
  */
 #define        MMS_V1_2                                                                // MMS Version : MMS_V1_0 / MMS_V1_1 / MMS_V1_2
 
+
 /**
- *     @brief  Defines the enabled DRM support
+ * @brief Defines the notification method
  */
-#define        __SUPPORT_DRM__
+#define MSG_NOTI_INTEGRATION
 
 /**
- *     @brief  Defines the enabled JAVA MMS Application Id
+ * @brief Defines the enabled drm
  */
-#define FEATURE_JAVA_MMS
-
+#define MSG_DRM_SUPPORT        (0)
 
 /**
  *     @brief  Defines message struct handle.
@@ -247,9 +247,9 @@ typedef struct
        unsigned long                   received;
        unsigned long                   created;
        unsigned long                   expires;
-       char                                    id[MAX_WAPPUSH_ID_LEN];
-       char                                    href[MAX_WAPPUSH_HREF_LEN];
-       char                                    contents[MAX_WAPPUSH_CONTENTS_LEN];
+       char                                    id[MAX_WAPPUSH_ID_LEN + 1];
+       char                                    href[MAX_WAPPUSH_HREF_LEN + 1];
+       char                                    contents[MAX_WAPPUSH_CONTENTS_LEN + 1];
 } MSG_PUSH_MESSAGE_S;
 
 
@@ -260,8 +260,8 @@ typedef struct
 {
        int             invalObjectCnt;
        int             invalServiceCnt;
-       char            invalObjectUrl[MAX_PUSH_CACHEOP_INVALID_OBJECT_MAX][MAX_PUSH_CACHEOP_MAX_URL_LEN];
-       char            invalServiceUrl[MAX_PUSH_CACHEOP_INVALID_SERVICE_MAX][MAX_PUSH_CACHEOP_MAX_URL_LEN];
+       char            invalObjectUrl[MAX_PUSH_CACHEOP_INVALID_OBJECT_MAX][MAX_PUSH_CACHEOP_MAX_URL_LEN + 1];
+       char            invalServiceUrl[MAX_PUSH_CACHEOP_INVALID_SERVICE_MAX][MAX_PUSH_CACHEOP_MAX_URL_LEN + 1];
 } MSG_PUSH_CACHEOP_S;
 
 
@@ -283,9 +283,10 @@ typedef struct
 {
        msg_syncml_message_type_t       syncmlType;
        int                                                     pushBodyLen;
-       char                                                    pushBody[MAX_WAPPUSH_CONTENTS_LEN];
+       char                                                    pushBody[MAX_WAPPUSH_CONTENTS_LEN + 1];
        int                                                             wspHeaderLen;
-       char                                                    wspHeader[MAX_WAPPUSH_CONTENTS_LEN];
+       char                                                    wspHeader[MAX_WAPPUSH_CONTENTS_LEN + 1];
+       int                                                     simIndex;
 }MSG_SYNCML_MESSAGE_DATA_S;
 
 
@@ -294,23 +295,49 @@ typedef struct
  */
  typedef struct
 {
-       char                                                    pushHeader[MAX_WAPPUSH_CONTENTS_LEN];
+       char                                                    pushHeader[MAX_WAPPUSH_CONTENTS_LEN + 1];
        int                                                     pushBodyLen;
-       char                                                    pushBody[MAX_WAPPUSH_CONTENTS_LEN];
+       char                                                    pushBody[MAX_WAPPUSH_CONTENTS_LEN + 1];
 }MSG_LBS_MESSAGE_DATA_S;
 
 
+typedef struct
+{
+       char                                                    pushHeader[MAX_WAPPUSH_CONTENTS_LEN + 1];
+       int                                                     pushBodyLen;
+       char                                                    pushBody[MAX_WAPPUSH_CONTENTS_LEN + 1];
+       char                                                    pushAppId[MAX_WAPPUSH_ID_LEN + 1];
+       char                                                    pushContentType[MAX_WAPPUSH_CONTENT_TYPE_LEN + 1];
+}MSG_PUSH_MESSAGE_DATA_S;
+
 /**
  *     @brief  Represents the Report Status Data.
  */
- typedef struct
+typedef struct
 {
-       msg_delivery_report_status_t    deliveryStatus;         /**< Indicates the message ID of this message. */
-       time_t                                                  deliveryStatusTime;     /**< Indicates the display time related to the specific operation. */   //MAX_DISPLAY_TIME_LEN
-       msg_read_report_status_t                readStatus;                     /**< Indicates the message ID of this message. */
-       time_t                                                  readStatusTime;         /**< Indicates the display time related to the specific operation. */   //MAX_DISPLAY_TIME_LEN
-}MSG_REPORT_STATUS_INFO_S;
+       char addressVal[MAX_ADDRESS_VAL_LEN + 1];
+       int type;
+       int status;
+       time_t statusTime;
+} MSG_REPORT_STATUS_INFO_S;
+
+
+typedef struct
+{
+       char contentType[MAX_WAPPUSH_CONTENT_TYPE_LEN + 1];
+       char appId[MAX_WAPPUSH_ID_LEN + 1];
+       char pkgName[MSG_FILEPATH_LEN_MAX + 1];
+       bool bLaunch;
+}MSG_PUSH_EVENT_INFO_S;
+
 
+typedef struct
+{
+       msg_message_id_t msg_id;
+       char mime_type[MAX_MIME_TYPE_LEN+1];
+       char media_item[MSG_FILEPATH_LEN_MAX+1];
+       char thumb_path[MSG_FILEPATH_LEN_MAX+1];
+} MSG_MEDIA_INFO_S;
 
 /**
  *     @}
diff --git a/include/externals/MsgAlarm.h b/include/externals/MsgAlarm.h
new file mode 100755 (executable)
index 0000000..954b147
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MSG_ALARM_H
+#define MSG_ALARM_H
+
+#include <time.h>
+#include "MsgTypes.h"
+
+/*==================================================================================================
+                                       DEFINES
+==================================================================================================*/
+
+typedef void (*msg_alarm_cb)(int alarmId);
+
+/*==================================================================================================
+                                       FUNCTION PROTOTYPES
+==================================================================================================*/
+msg_error_t MsgAlarmRegistration(struct tm *timeInfo, msg_alarm_cb userCB, int *alarmId);
+msg_error_t MsgAlarmRemove(int alarmId);
+
+#endif // MSG_ALARM_H
diff --git a/include/externals/MsgDevicedWrapper.h b/include/externals/MsgDevicedWrapper.h
new file mode 100644 (file)
index 0000000..e405e3d
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MSG_DEVICED_WRAPPER_H
+#define MSG_DEVICED_WRAPPER_H
+
+
+void MsgDisplayLock();
+void MsgDisplayUnlock();
+void MsgChangePmState();
+
+#endif /* MSG_DEVICED_WRAPPER_H */
diff --git a/include/externals/MsgLbs.h b/include/externals/MsgLbs.h
new file mode 100755 (executable)
index 0000000..ff24ebf
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MSGLBS_H_
+#define MSGLBS_H_
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+
+/*==================================================================================================
+                                         DEFINES
+==================================================================================================*/
+#define MSG_LBS_PORT 7275
+
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+void MsgLbsSms(const char *msgBody, int msgSize);
+void MsgLbsWapPush(const char *pushHeader, const char *pushBody, int pushBodySize);
+
+
+#endif /* MSGLBS_H_ */
diff --git a/include/externals/MsgNotificationWrapper.h b/include/externals/MsgNotificationWrapper.h
new file mode 100755 (executable)
index 0000000..85ab130
--- /dev/null
@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MSG_NOTIFICATION_WRAPPER_H
+#define MSG_NOTIFICATION_WRAPPER_H
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgInternalTypes.h"
+#include "MsgSqliteWrapper.h"
+
+/*==================================================================================================
+                                         DEFINES
+==================================================================================================*/
+#define MSG_APP_PACKAGE_NAME   "message"
+
+#define MSG_APP_LOCALEDIR                      "/usr/apps/"MSG_DEFAULT_APP_ID"/res/locale"
+
+#define MSG_NOTIFICATION_ICON_DIR                      MSG_QUICKPANEL_APP_ID"/shared/res/noti_icons/Message"
+
+// notification icon
+#define MSG_NORMAL_ICON_PATH   "/usr/apps/"MSG_NOTIFICATION_ICON_DIR"/noti_message.png"
+#define MSG_SIM_ICON_PATH      "/usr/apps/"MSG_NOTIFICATION_ICON_DIR"/noti_message_sim-card.png"
+#define MSG_VOICE_ICON_PATH            "/usr/apps/"MSG_NOTIFICATION_ICON_DIR"/noti_voice_mail.png"
+#define MSG_CB_ICON_PATH                       "/usr/apps/"MSG_NOTIFICATION_ICON_DIR"/noti_message_cb-msg.png"
+#define MSG_READ_ICON_PATH             "/usr/apps/"MSG_NOTIFICATION_ICON_DIR"/noti_message_read_report.png"
+#define MSG_DELIVERY_ICON_PATH "/usr/apps/"MSG_NOTIFICATION_ICON_DIR"/noti_message_delivery_report.png"
+#define MSG_REPLY_ICON_PATH                    "/usr/apps/"MSG_NOTIFICATION_ICON_DIR"/noti_message_reply.png"
+#define MSG_SMS_SENDING_FAILED_ICON_PATH               "/usr/apps/"MSG_NOTIFICATION_ICON_DIR"/noti_message_failed.png"
+#define MSG_MMS_SENDING_FAILED_ICON_PATH               "/usr/apps/"MSG_NOTIFICATION_ICON_DIR"/noti_message_mms_failed.png"
+#define MSG_MMS_RETRIVE_FAILED_ICON_PATH               "/usr/apps/"MSG_NOTIFICATION_ICON_DIR"/noti_message_mms_problem.png"
+#define MSG_EMERGENCY_ICON_PATH                "/usr/apps/"MSG_DEFAULT_APP_ID"/res/icons/default/small/noti_emergency_mode.png"
+
+// status bar icon
+#define MSG_NORMAL_STATUS_ICON                         "/usr/apps/"MSG_DEFAULT_APP_ID"/res/icons/default/small/status_bar_message.png"
+#define MSG_FAILED_STATUS_ICON                         "/usr/apps/"MSG_DEFAULT_APP_ID"/res/icons/default/small/status_bar_cancel_message.png"
+#define MSG_DELIVER_REPORT_STATUS_ICON "/usr/apps/"MSG_DEFAULT_APP_ID"/res/icons/default/small/status_bar_delivery_report_message.png"
+#define MSG_READ_REPORT_STATUS_ICON            "/usr/apps/"MSG_DEFAULT_APP_ID"/res/icons/default/small/status_bar_read_report_message.png"
+#define MSG_VOICE_MSG_STATUS_ICON                      "/usr/apps/"MSG_DEFAULT_APP_ID"/res/icons/default/small/status_bar_voicemail.png"
+#define MSG_SIM_FULL_STATUS_ICON               "/usr/apps/"MSG_DEFAULT_APP_ID"/res/icons/default/small/status_bar_sim_card_full.png"
+
+#ifndef TIZEN_I586_ENABLED
+// system string
+#define NEW_MESSAGE                    "IDS_MSGF_POP_NEW_MESSAGE"
+#define NEW_MESSAGES                   "IDS_MSGF_POP_NEW_MESSAGES"
+#define MSG_UNKNOWN_SENDER     "IDS_MSGF_BODY_UNKNOWN"
+#define MSG_NO_SUBJECT                 "IDS_MSGF_BODY_NO_SUBJECT"
+
+
+// message app string for ticker noti
+#define SENDING_MULTIMEDIA_MESSAGE_FAILED      "IDS_MSGF_POP_SENDING_MULTIMEDIA_MESSAGE_FAILED"
+#define MULTIMEDIA_MESSAGE_SENT                                        "IDS_MSGF_POP_MULTIMEDIA_MESSAGE_SENT"
+#define RETRIEVING_MESSAGE_FAILED                                      "IDS_MSGF_POP_RETRIEVING_MESSAGE_FAILED"
+#define MESSAGE_RETRIEVED                                                              "IDS_MSGF_BODY_MESSAGE_RETRIEVED"
+#define SMS_MESSAGE_SENT                                                               "IDS_MSGC_POP_MESSAGESENT"
+#define SMS_MESSAGE_SENDING_FAIL                                       "IDS_MSGF_POP_SENDING_MESSAGE_FAILED"
+#define SMS_MESSAGE_SENDING_PENDING                                    "IDS_MSG_POP_UNABLE_TO_SEND_MESSAGE_IT_WILL_BE_SENT_WHEN_SERVICE_AVAILABLE"
+#define SMS_MESSAGE_SIM_MESSAGE_FULL                           "IDS_MSGF_BODY_SIM_MEMORY_FULL_DELETE_SOME_ITEMS"
+#define SMS_MESSAGE_MEMORY_FULL                        "IDS_MSGF_POP_NOT_ENOUGH_MEMORY_DELETE_SOME_ITEMS"
+#define SMS_FDN_RESTRICTED                             "IDS_MSGF_POP_FDN_ENABLED_CANT_SEND_MSG"
+#define SMS_SIM_CARD_FULL                              "IDS_MSG_HEADER_SIM_CARD_FULL"
+#define SMS_MESSAGE_SIZE_OVER_SIM_SLOT_SIZE    "IDS_MSGF_BODY_MESSAGE_IS_TOO_LARGE_TO_STORE_AS_A_SINGLE_MESSAGE_TO_SIM_CARD"
+
+// message app string for quickpanel noti
+#define MSG_MESSAGE            "IDS_MSGF_BODY_MESSAGE"
+#define VOICE_MAIL                                     "IDS_MSGF_BODY_VOICEMAIL"
+#define NEW_VOICE_MAIL                 "IDS_MSGF_BODY_NEW_VOICEMAIL"
+#define APP_NEW_MESSAGE "IDS_MSGF_POP_NEW_MESSAGE"
+#define APP_NEW_MESSAGES "IDS_MSGF_POP_NEW_MESSAGES"
+#define CB_MESSAGE "IDS_MSGF_BODY_CB_MESSAGES"
+#define PUSH_MESSAGE "IDS_MSGF_BODY_PUSH_MESSAGES"
+#define DELIVERY_MESSAGE "IDS_MSGF_BODY_DELIVERY_REPORT"
+#define READ_REPORT_MESSAGE "IDS_MSGF_POP_READ_REPORT"
+#define EXPIRED_MESSAGE "IDS_MSGF_BODY_MESSAGE_HAS_EXPIRED"
+#define REJECTED_MESSAGE "IDS_MSGF_BODY_MMSDELIVERYMSGREJECTED"
+#define DEFERRED_MESSAGE "IDS_MSGF_POP_MESSAGE_DEFERRED"
+#define UNRECOGNISED_MESSAGE "IDS_MSGF_POP_MESSAGE_UNRECOGNISED"
+#define INDETEMINATE_MESSAGE "IDS_MSGF_POP_INDETERMINATE"
+#define UNREACHABLE_MESSAGE "IDS_MSGF_POP_UNREACHABLE"
+#define DELIVERED_MESSAGE "IDS_MSGF_BODY_MESSAGE_DELIVERED"
+#define VOICE_1_MESSAGE        "IDS_MSGF_BODY_1_MESSAGE"
+#define VOICE_N_MESSAGE        "IDS_MSGF_BODY_PD_MESSAGES"
+#define SIM_CARD_MESSAGE               "IDS_MSGF_BODY_SIM_CARD_MESSAGES"
+#define READ_REPORT_READ               "IDS_COM_BODY_READ"
+#define READ_REPORT_DELETE     "IDS_COM_POP_DELETED"
+#define FAILED_MSG_EXIST       "IDS_MSG_BODY_FAILED_MESSAGES_EXIST"
+#define ENABLE_EMERGENCY_MODE  "IDS_MSG_BODY_ENABLE_EMERGENCY_MODE_JPN_DCM"
+#define EMERGENCY_MODE_DESCRIPTION     "IDS_MSG_SBODY_TAP_HERE_TO_ENABLE_EMERGENCY_MODE_TO_SAVE_BATTERY_POWER_JPN_DCM"
+#define FAILED_TO_SEND_MESSAGE "IDS_MSG_TPOP_FAILED_TO_SEND_MESSAGE_ABB"
+#else
+// system string
+#define NEW_MESSAGE                    "New message"
+#define NEW_MESSAGES                   "New messages"
+#define MSG_UNKNOWN_SENDER     "New message from Unknown."
+#define MSG_NO_SUBJECT                 "No subject"
+
+
+// message app string for ticker noti
+#define SENDING_MULTIMEDIA_MESSAGE_FAILED      "Sending multimedia message failed"
+#define MULTIMEDIA_MESSAGE_SENT                                        "Multimedia message sent."
+#define RETRIEVING_MESSAGE_FAILED                                      "Retrieving message failed"
+#define MESSAGE_RETRIEVED                                                              "Message retrieved"
+#define SMS_MESSAGE_SENT                                                               "Message sent."
+#define SMS_MESSAGE_SENDING_FAIL                                       "Sending message failed."
+#define SMS_MESSAGE_SENDING_PENDING                                    "Unable to send message. It will be sent when service available."
+#define SMS_MESSAGE_SIM_MESSAGE_FULL                           "SIM memory full. Delete some items."
+#define SMS_MESSAGE_MEMORY_FULL                        "Not enough memory. Delete some items."
+#define SMS_FDN_RESTRICTED                             "Unable to send the message while Fixed dialling mode is enabled."
+#define SMS_SIM_CARD_FULL                              "SIM card full"
+#define SMS_MESSAGE_SIZE_OVER_SIM_SLOT_SIZE    "Message is too large to store as a single message to SIM card." //
+
+// message app string for quickpanel noti
+#define MSG_MESSAGE            "Message"
+#define VOICE_MAIL                                     "Voicemail"
+#define NEW_VOICE_MAIL                 "New voicemail"
+#define APP_NEW_MESSAGE "New message"
+#define APP_NEW_MESSAGES "New messages"
+#define CB_MESSAGE "CB messages"
+#define PUSH_MESSAGE "Push messages"
+#define DELIVERY_MESSAGE "Delivery report"
+#define READ_REPORT_MESSAGE "Read report"
+#define EXPIRED_MESSAGE "Message expired."
+#define REJECTED_MESSAGE "Message rejected."
+#define DEFERRED_MESSAGE "Message deferred"
+#define UNRECOGNISED_MESSAGE "Message unrecognised"
+#define INDETEMINATE_MESSAGE "Indeterminate."
+#define UNREACHABLE_MESSAGE "Unreachable"
+#define DELIVERED_MESSAGE "Message delivered"
+#define VOICE_1_MESSAGE        "1 message"
+#define VOICE_N_MESSAGE        "%d messages"
+#define SIM_CARD_MESSAGE               "SIM card messages"
+#define READ_REPORT_READ               "Read"
+#define READ_REPORT_DELETE     "Deleted."
+#define FAILED_MSG_EXIST       "Failed messages exist."
+#define ENABLE_EMERGENCY_MODE  "Enable Emergency mode"
+#define EMERGENCY_MODE_DESCRIPTION     "Tap here to enable Emergency mode to save battery power."
+#define FAILED_TO_SEND_MESSAGE "Failed to send message." //
+#endif
+
+#define NOTIFICATION_PRIV_ID   DEFAULT_SETTING_PATH"/notification_priv_id"
+#define VOICE_NOTI_ID_1                DEFAULT_SETTING_PATH"/voice_noti_id1"
+#define VOICE_NOTI_ID_2                        DEFAULT_SETTING_PATH"/voice_noti_id2"
+#define CB_NOTI_PRIV_ID                DEFAULT_SETTING_PATH"/cb_noti_priv_id"
+#define SIM_MSG_NOTI_PRIV_ID   DEFAULT_SETTING_PATH"/sim_msg_noti_priv_id"
+#define EMERGENCY_MODE_NOTI_ID         DEFAULT_SETTING_PATH"/emergency_noti_id"
+#define MSG_SENTFAIL_NOTI_ID           DEFAULT_SETTING_PATH"/sentfail_noti_id"
+#define SIM_FULL_NOTI_PRIV_ID  DEFAULT_SETTING_PATH"/sim_full_noti_id"
+
+#define MSG_NOTI_TEXT_LEN      (512)
+#define MSG_NOTI_TEXT_LEN_S    (256)
+
+enum _msg_notification_type_e
+{
+       MSG_NOTI_TYPE_ALL = 0x00,
+
+       // Refresh single/multiple notification
+       MSG_NOTI_TYPE_NORMAL,
+       MSG_NOTI_TYPE_CB,
+       MSG_NOTI_TYPE_SIM,
+       MSG_NOTI_TYPE_FAILED,
+
+       // Add only single notification
+       MSG_NOTI_TYPE_VOICE_1,
+       MSG_NOTI_TYPE_VOICE_2,
+       MSG_NOTI_TYPE_MWI,
+       MSG_NOTI_TYPE_CLASS0,
+       MSG_NOTI_TYPE_SMS_DELIVERY_REPORT,
+       MSG_NOTI_TYPE_MMS_READ_REPORT,
+       MSG_NOTI_TYPE_MMS_DELIVERY_REPORT,
+
+       MSG_NOTI_TYPE_SIM_FULL,
+};
+
+typedef unsigned char msg_notification_type_t; //_msg_notification_type_e
+
+msg_error_t MsgInsertNotification(MSG_MESSAGE_INFO_S *msg_info);
+
+msg_error_t MsgAddNotification(msg_notification_type_t noti_type, MSG_MESSAGE_INFO_S *msg_info);
+msg_error_t MsgRefreshNotification(msg_notification_type_t noti_type, bool bFeedback, bool bTicker);
+msg_error_t MsgAddReportNotification(msg_notification_type_t noti_type, MSG_MESSAGE_INFO_S *msg_info);
+msg_error_t MsgDeleteReportNotification(const char *addr);
+
+msg_error_t MsgInsertTicker(const char* pTickerMsg, const char* pLocaleTickerMsg, bool bPlayFeedback, int msgId);
+msg_error_t MsgInsertInstantMessage(msg_notification_type_t noti_type);
+msg_error_t MsgInitNoti();
+msg_error_t MsgInsertBadge(unsigned int unreadMsgCnt);
+msg_error_t MsgDeleteNoti(msg_notification_type_t noti_type, int simIndex);
+
+void MsgRefreshAllNotification(bool bWithSimNoti, bool bFeedback, bool bTickerNoti);
+void MsgDeleteNotification(msg_notification_type_t noti_type, int simIndex);
+void MsgInitReportNotiList();
+
+char *getTranslateText(const char *pkg_name, const char *locale_dir, const char *text);
+
+#endif
diff --git a/include/externals/MsgSensorWrapper.h b/include/externals/MsgSensorWrapper.h
new file mode 100755 (executable)
index 0000000..ab1e279
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MSG_SENSOR_H
+#define MSG_SENSOR_H
+
+
+#include "MsgTypes.h"
+
+/*==================================================================================================
+                                       DEFINES
+==================================================================================================*/
+
+typedef void (*msg_sensor_cb)();
+
+/*==================================================================================================
+                                       FUNCTION PROTOTYPES
+==================================================================================================*/
+
+msg_error_t MsgSensorConnect();
+void MsgSensorDisconnect();
+msg_error_t MsgRegSensorCB(msg_sensor_cb cb);
+
+#endif // MSG_SENSOR_H
diff --git a/include/externals/MsgSoundPlayer.h b/include/externals/MsgSoundPlayer.h
new file mode 100755 (executable)
index 0000000..0aec565
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MSG_SOUND_PLAYER_H
+#define MSG_SOUND_PLAYER_H
+
+
+/*==================================================================================================
+                                         TYPES
+==================================================================================================*/
+typedef unsigned char MSG_SOUND_TYPE_T;
+
+/*==================================================================================================
+                                         ENUMS
+==================================================================================================*/
+enum _MSG_SOUND_TYPE_E
+{
+       MSG_SOUND_PLAY_DEFAULT = 0,
+       MSG_SOUND_PLAY_USER,
+       MSG_SOUND_PLAY_EMERGENCY,
+       MSG_SOUND_PLAY_VOICEMAIL,
+};
+
+/*==================================================================================================
+                                CLASS DEFINITIONS
+==================================================================================================*/
+class MsgSoundPlayer
+{
+public:
+       static MsgSoundPlayer* instance();
+
+       void MsgSoundPlayStart(const MSG_ADDRESS_INFO_S *pAddrInfo, MSG_SOUND_TYPE_T soundType);
+       void MsgSoundPlayStop();
+
+       void MsgSoundInitRepeatAlarm();
+       void MsgSoundPlayDtmf();
+
+       void MsgGetRingtonePath(char *userRingtonePath, char **msg_tone_file_path_p);
+       void MsgGetPlayStatus(bool bVoiceMail, bool *bPlaySound, bool *bPlayVibration, bool *bOnCall);
+
+private:
+       MsgSoundPlayer();
+       ~MsgSoundPlayer();
+
+       void MsgSoundPlayMelody(char *pMsgToneFilePath);
+       void MsgSoundPlayVibration(char *vibrationPath, bool isOnCall);
+
+       void MsgSoundSetRepeatAlarm();
+       void MsgSoundCreateRepeatAlarm(int RepeatTime);
+       int MsgSoundGetUnreadMsgCnt();
+
+       static MsgSoundPlayer* pInstance;
+
+       bool bPlaying;
+       bool bVibrating;
+       bool bFeedbackInit;
+
+       int g_alarmId;
+
+       char *defaultRingtonePath;
+};
+
+#endif // MSG_SOUND_PLAYER_H
+
similarity index 56%
rename from include/utils/MsgSpamFilter.h
rename to include/externals/MsgSpamFilter.h
index d776c8e..ea67d8e 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_SPAM_FILTER_H
@@ -33,5 +33,6 @@ msg_error_t MsgSetFilterOperation(bool bSetFlag);
 msg_error_t MsgGetFilterOperation(bool *pSetFlag);
 
 bool MsgCheckFilter(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S *pMsgInfo);
+bool MsgCheckFilterByWord(MsgDbHandler *pDbHandle, const char *pMsgText);
 
 #endif // MSG_SPAM_FILTER_H
index 1906581..eb8fe6d 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_CMD_HANDLER_H
@@ -35,6 +35,7 @@ int MsgUpdateThreadReadStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgUpdateProtectedStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgDeleteMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgDeleteAllMessageInFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgDeleteMessageByListHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgMoveMessageToFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgMoveMessageToStorageHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgCountMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent);
@@ -69,19 +70,23 @@ int MsgSetConfigHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgGetConfigHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 
 int MsgSubmitReqHandler(const MSG_CMD_S *pCmd, char **ppEvent);
-int MsgCancelReqHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 
 int MsgRegSentStatusCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgRegIncomingMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgRegIncomingMMSConfMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgRegIncomingPushMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgRegIncomingCBMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgRegIncomingSyncMLMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgRegIncomingLBSMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgRegSyncMLMsgOperationCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgRegStorageChangeCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgStorageChangeHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgRegIncomingReportMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 
 int MsgSentStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgIncomingMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgIncomingPushMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgIncomingCBMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgIncomingSyncMLMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgIncomingLBSMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgSyncMLMsgOperationHandler(const MSG_CMD_S *pCmd, char **ppEvent);
@@ -93,14 +98,16 @@ int MsgDeleteFilterHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgGetFilterListHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgSetFilterOperationHandler(const MSG_CMD_S *pCmd, char **ppEvent);
 int MsgGetFilterOperationHandler(const MSG_CMD_S *pCmd, char **ppEvent);
-
-int MsgGetSMSCListHandler(const MSG_CMD_S *pCmd, char **ppEvent);
-int MsgGetCBInfoHandler(const MSG_CMD_S *pCmd, char **ppEvent);
-int MsgGetSmsSendOptHandler(const MSG_CMD_S *pCmd, char **ppEvent);
-int MsgGetMmsSendOptHandler(const MSG_CMD_S *pCmd, char **ppEvent);
-int MsgGetMmsRecvOptHandler(const MSG_CMD_S *pCmd, char **ppEvent);
-int MsgGetPushMsgOptHandler(const MSG_CMD_S *pCmd, char **ppEvent);
-int MsgGetVoiceMsgOptHandler(const MSG_CMD_S *pCmd, char **ppEvent);
-int MsgGetGeneralOptHandler(const MSG_CMD_S *pCmd, char **ppEvent);
-
+int MsgSetFilterActivationHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+
+int MsgAddPushEventHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgDeletePushEventHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgUpdatePushEventHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+
+int MsgAddSimMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgResendMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgUpdateIMSIHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+#ifdef FEATURE_SMS_CDMA
+int MsgCheckUniquenessHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+#endif
 #endif // MSG_CMD_HANDLER_H
index 0f0100b..c8f3cb8 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_DELIVER_HANDLER_H
@@ -29,7 +29,7 @@
 ==================================================================================================*/
 msg_error_t MsgHandleMmsConfIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_request_id_t reqID);
 msg_error_t MsgHandleIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti);
-msg_error_t MsgHandleSMS(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti);
+msg_error_t MsgHandleSMS(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti, bool *bOnlyNoti);
 msg_error_t MsgHandleMMS(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti);
 
 /*==================================================================================================
diff --git a/include/framework/MsgPluginConfig.h b/include/framework/MsgPluginConfig.h
deleted file mode 100755 (executable)
index d07d2e3..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#ifndef MSG_PLUGIN_CONFIG_H
-#define MSG_PLUGIN_CONFIG_H
-
-
-/*==================================================================================================
-                                         INCLUDE FILES
-==================================================================================================*/
-#include <map>
-#include <list>
-#include <stdio.h>
-#include <string.h>
-#include "MsgDebug.h"
-#include "MsgTypes.h"
-#include "MsgCppTypes.h"
-
-class MsgPlgToken
-{
-       int tokenType; // not defined 0, title: 1, msgtype: 2, libpath: 3
-       char tokenVal[256]; // null-terminated char array
-
-public:
-       MsgPlgToken(char* pstr=NULL) : tokenType(TOK_UNDEFINED)
-       {
-               if(pstr)
-               {
-                       tokenize(pstr);
-               }
-               else
-               {
-                       bzero(tokenVal, 256);
-               }
-       }
-
-       MsgPlgToken& operator = (const MsgPlgToken& rhs)
-       {
-               if (this != &rhs)
-               {
-                       tokenType = rhs.tokenType;
-                       strncpy(tokenVal, rhs.tokenVal, 255);
-               }
-
-               return *this;
-       }
-
-       int getType() const { return tokenType; } // not defined 0, title: 1, msgtype: 2, libpath: 3
-       const char* getVal(void) const { return tokenVal; }
-       void getVal(CharVector& vec) const { vec.assign(tokenVal, tokenVal+strlen(tokenVal));}
-       int tokenize(char* pStr);
-
-       enum { TOK_UNDEFINED=0, TOK_PLG_TITLE, TOK_PLG_TYPE, TOK_PLG_PATH };
-
-       void reset() { tokenType = TOK_UNDEFINED; }
-       operator void*() const {
-               return (tokenType==TOK_UNDEFINED)? NULL:(void*) this;
-       }
-};
-
-typedef std::vector<MsgPlgToken> MsgPlgTokenVec;
-typedef std::map<CharVector, MsgPlgTokenVec> MsgConfigMap;
-
-class MsgPlgConfig
-{
-       MsgConfigMap configMap;
-       void insert(const MsgPlgToken& tokTitle, const MsgPlgToken& tokMsgType, const MsgPlgToken& tokLibPath);
-
-public:
-       MsgPlgConfig(FILE* fp);
-
-       /* access method for tokens */
-       const CharVector& title(unsigned int pos);// const; // iteration with ith position i=0, .. , itemCount-1
-       inline int titleCount() const { return configMap.size(); }
-
-       void token(const CharVector& key, unsigned int pos, MsgPlgToken& retTok);// const;
-       void token(int i, unsigned int pos, MsgPlgToken& retTok);// const;
-       int tokenCount(const CharVector& key) { return configMap[key].size(); } // const leads to error why?
-};
-
-#endif // MSG_PLUGIN_CONFIG_H
index 551efb9..9d49a33 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_PLUGIN_MANAGER_H
 
 #include "MsgTypes.h"
 #include "MsgPluginInterface.h"
-#include "MsgPluginConfig.h"
-
+#include "MsgCppTypes.h"
 
 /*==================================================================================================
                                     DEFINES
 ==================================================================================================*/
-#define MSG_PLUGIN_CFG_PATH    "/usr/share/msg-service/"
-#define MSG_PLUGIN_CFG_NAME    "plugin.cfg"
 
 
 /*==================================================================================================
@@ -48,24 +45,27 @@ public:
 
        msg_error_t submitReq(MSG_REQUEST_INFO_S *pReqInfo);
        msg_error_t registerListener(MSG_PLUGIN_LISTENER_S *pListener);
-       msg_error_t checkSimStatus(MSG_SIM_STATUS_T *pStatus);
-       msg_error_t checkDeviceStatus();
 
-       msg_error_t initSimMessage();
        msg_error_t saveSimMessage(MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList);
+#ifndef FEATURE_SMS_CDMA
+       msg_error_t deleteSimMessage(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId);
+       msg_error_t setReadStatus(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId);
+       msg_error_t setMemoryStatus(msg_sim_slot_id_t sim_idx, msg_error_t Error);
+#else
        msg_error_t deleteSimMessage(msg_sim_id_t SimMsgId);
        msg_error_t setReadStatus(msg_sim_id_t SimMsgId);
        msg_error_t setMemoryStatus(msg_error_t Error);
-
-       msg_error_t initConfigData(MSG_SIM_STATUS_T SimStatus);
+#endif
        msg_error_t setConfigData(const MSG_SETTING_S *pSetting);
        msg_error_t getConfigData(MSG_SETTING_S *pSetting);
 
+       msg_error_t getDefaultNetworkSimId(int *simId);
+
        // MMS handlers
        msg_error_t addMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData);
        msg_error_t updateMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData);
        msg_error_t processReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST_INFO_S *pRequest, bool *bReject);
-       msg_error_t getMmsMessage(MSG_MESSAGE_INFO_S *pMsg,  MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_MESSAGE_DATA_S *pMmsMsg, char **pDestMsg);
+       msg_error_t getMmsMessage(MSG_MESSAGE_INFO_S *pMsg,  MSG_SENDINGOPT_INFO_S *pSendOptInfo, char **pDestMsg);
        msg_error_t updateRejectStatus(MSG_MESSAGE_INFO_S *pMsgInfo);
        msg_error_t composeReadReport(MSG_MESSAGE_INFO_S *pMsgInfo);
 
@@ -79,14 +79,24 @@ private:
        MSG_MAIN_TYPE_T                         mSupportedMsg;
        MSG_PLUGIN_HANDLER_S    mPlgHandler;
 
-        void*                                  mLibHandler;    // plugin library pointer
+       void    *mLibHandler;    // plugin library pointer
 };
 
 
 /*==================================================================================================
                                      GLOBAL VARIABLES
 ==================================================================================================*/
-typedef std::map<MSG_MAIN_TYPE_T, MsgPlugin> MsgPluginMap;
+typedef std::map<MSG_MAIN_TYPE_T, MsgPlugin*> MsgPluginMap;
+
+typedef struct {
+       MSG_MAIN_TYPE_T type;
+       const char *path;
+} MSG_PLG_TABLE_T;
+
+const static MSG_PLG_TABLE_T __msg_plg_items[] = {
+       { MSG_SMS_TYPE, "/usr/lib/libmsg_sms_plugin.so" },
+       { MSG_MMS_TYPE, "/usr/lib/libmsg_mms_plugin.so" }
+};
 
 
 /*==================================================================================================
@@ -99,8 +109,8 @@ public:
 
        void initialize();
        void finalize();
+       MsgPlugin* checkPlugin(MSG_MAIN_TYPE_T mainType);
        MsgPlugin* getPlugin(MSG_MAIN_TYPE_T mainType);
-       void loadPlugins(const char* path);
 
 private:
        MsgPluginManager();
index 7b6823d..54ba7ba 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_SETTING_HANDLER_H
@@ -27,8 +27,6 @@
 /*==================================================================================================
                                        FUNCTION PROTOTYPES
 ==================================================================================================*/
-msg_error_t MsgInitSimConfig(MSG_SIM_STATUS_T SimStatus);
-
 msg_error_t MsgSetConfigData(const MSG_SETTING_S *pSetting);
 msg_error_t MsgGetConfigData(MSG_SETTING_S *pSetting);
 
@@ -40,7 +38,8 @@ msg_error_t MsgSetMMSRecvOpt(const MSG_SETTING_S *pSetting);
 msg_error_t MsgSetMMSStyleOpt(const MSG_SETTING_S *pSetting);
 msg_error_t MsgSetPushMsgOpt(const MSG_SETTING_S *pSetting);
 msg_error_t MsgSetCBMsgOpt(const MSG_SETTING_S *pSetting, bool bSetSim);
-msg_error_t MsgSetVoiceMailOpt(const MSG_SETTING_S *pSetting);
+
+msg_error_t MsgSetVoiceMailOpt(const MSG_SETTING_S *pSetting, bool bSetSim);
 msg_error_t MsgSetMsgSizeOpt(const MSG_SETTING_S *pSetting);
 
 void MsgGetGeneralOpt(MSG_SETTING_S *pSetting);
@@ -51,10 +50,12 @@ void MsgGetMMSRecvOpt(MSG_SETTING_S *pSetting);
 void MsgGetMMSStyleOpt(MSG_SETTING_S *pSetting);
 void MsgGetPushMsgOpt(MSG_SETTING_S *pSetting);
 void MsgGetCBMsgOpt(MSG_SETTING_S *pSetting);
+
 void MsgGetVoiceMailOpt(MSG_SETTING_S *pSetting);
 void MsgGetMsgSizeOpt(MSG_SETTING_S *pSetting);
 
 msg_error_t MsgSetConfigInSim(const MSG_SETTING_S *pSetting);
+msg_error_t MsgGetConfigInSim(MSG_SETTING_S *pSetting);
 
 //void MsgSetDefaultConfig();
 
index 68d97fd..a6dae82 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_STORAGE_HANDLER_H
@@ -34,6 +34,7 @@ msg_error_t MsgStoConnectDB();
 msg_error_t MsgStoDisconnectDB();
 
 msg_error_t MsgStoInitDB(bool bSimChanged);
+void MsgfreeMmapMutex();
 
 msg_error_t MsgCreateConversationTable();
 msg_error_t MsgCreateAddressTable();
@@ -50,39 +51,35 @@ msg_error_t MsgAddDefaultFolders();
 msg_error_t MsgAddDefaultAddress();
 msg_error_t MsgStoResetDatabase();
 
-msg_error_t MsgStoBackupMessage();
-msg_error_t MsgStoRestoreMessage();
+msg_error_t MsgStoBackupMessage(msg_message_backup_type_t type, const char *filepath);
+msg_error_t MsgStoRestoreMessage(const char *filepath, msg_id_list_s**result_id_list);
 
 msg_error_t MsgStoAddMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S* pSendOptInfo);
+msg_error_t MsgStoRestoreMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo);
 msg_error_t MsgStoUpdateMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S* pSendOptInfo);
 msg_error_t MsgStoUpdateReadStatus(msg_message_id_t MsgId, bool bRead);
-msg_error_t MsgStoUpdateThreadReadStatus(msg_thread_id_t ThreadId);
+msg_error_t MsgStoUpdateThreadReadStatus(msg_thread_id_t ThreadId, msg_id_list_s *pMsgIdList);
 msg_error_t MsgStoUpdateProtectedStatus(msg_message_id_t MsgId, bool bProtected);
 msg_error_t MsgStoDeleteMessage(msg_message_id_t MsgId, bool bCheckIndication);
 msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t FolderId, bool bOnlyDB, msg_id_list_s *pMsgIdList);
+msg_error_t MsgStoDeleteMessageByList(msg_id_list_s *pMsgIdList);
 msg_error_t MsgStoMoveMessageToFolder(msg_message_id_t MsgId, msg_folder_id_t DestFolderId);
 msg_error_t MsgStoMoveMessageToStorage(const msg_message_id_t MsgId, const msg_storage_id_t DestStorageId);
 msg_error_t MsgStoCountMessage(msg_folder_id_t FolderId, MSG_COUNT_INFO_S *pCountInfo);
 msg_error_t MsgStoCountMsgByType(const MSG_MESSAGE_TYPE_S *pMsgType, int *pMsgCount);
 msg_error_t MsgStoGetMessage(msg_message_id_t MsgId, MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S* pSendOptInfo);
-msg_error_t MsgStoGetFolderViewList(msg_folder_id_t FolderId, const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pMsgFolderViewList);
 msg_error_t MsgStoAddSyncMLMessage(MSG_MESSAGE_INFO_S *pMsgInfo, int ExtId, int PinCode);
 msg_error_t MsgStoGetMsgType(msg_message_id_t msgId, MSG_MESSAGE_TYPE_S* pMsgType);
 msg_error_t MsgStoGetText(msg_message_id_t MsgId, char *pSubject, char *pMsgText);
 msg_error_t MsgStoGetQuickPanelData(msg_quickpanel_type_t Type, MSG_MESSAGE_INFO_S *pMsg);
-msg_error_t MsgStoGetThreadViewList(const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pThreadViewList);
-msg_error_t MsgStoGetConversationViewList(msg_thread_id_t ThreadId, msg_struct_list_s *pConvViewList);
-msg_error_t MsgStoDeleteThreadMessageList(msg_thread_id_t ThreadId, msg_id_list_s *pMsgIdList);
+msg_error_t MsgStoDeleteThreadMessageList(msg_thread_id_t ThreadId, bool bIncludeProtect, msg_id_list_s *pMsgIdList);
 msg_error_t MsgStoCountMsgByContact(const MSG_THREAD_LIST_INDEX_S *pAddrInfo, MSG_THREAD_COUNT_INFO_S *pThreadCountInfo);
-msg_error_t MsgStoSearchMessage(const char *pSearchString, msg_struct_list_s *pThreadViewList);
-msg_error_t MsgStoSearchMessage(const MSG_SEARCH_CONDITION_S *pSearchCon, int offset, int limit, msg_struct_list_s *pMsgList);
-msg_error_t MsgStoGetRejectMsgList(const char *pNumber, msg_struct_list_s *pRejectMsgList);
-msg_error_t MsgStoGetReportStatus(msg_message_id_t msgId, MSG_REPORT_STATUS_INFO_S* pReportStatus);
+msg_error_t MsgStoGetSmsReportStatus(msg_message_id_t msgId, int *count, MSG_REPORT_STATUS_INFO_S **pReportStatus);
+msg_error_t MsgStoGetMmsReportStatus(msg_message_id_t msgId, int *count, MSG_REPORT_STATUS_INFO_S **pReportStatus);
 msg_error_t MsgStoGetThreadIdByAddress(const MSG_MESSAGE_INFO_S *pMsg, msg_thread_id_t *pThreadId);
 msg_error_t MsgStoGetThreadUnreadCnt(msg_thread_id_t ThreadId, int *cnt);
-msg_error_t MsgStoGetAddressList(const msg_thread_id_t threadId, msg_struct_list_s *pAddrList);
+
 msg_error_t MsgStoGetThreadInfo(msg_thread_id_t threadId, MSG_THREAD_VIEW_S *pThreadInfo);
-msg_error_t MsgStoGetMessageList(msg_folder_id_t folderId, msg_thread_id_t threadId, msg_message_type_t msgType, msg_storage_id_t storageId, msg_struct_list_s *pMsgList);
 
 // Folder
 msg_error_t MsgStoAddFolder(const MSG_FOLDER_INFO_S *pFolderInfo);
@@ -95,14 +92,13 @@ msg_error_t MsgStoAddFilter(const MSG_FILTER_S *pFilter);
 msg_error_t MsgStoUpdateFilter(const MSG_FILTER_S *pFilter);
 msg_error_t MsgStoDeleteFilter(msg_filter_id_t FilterId);
 msg_error_t MsgStoGetFilterList(msg_struct_list_s *pFilterList);
+msg_error_t MsgStoSetFilterActivation(msg_filter_id_t filterId, bool bActive);
 
 // Sim Operation related Functions
-msg_error_t MsgInitSimMessage(MSG_SIM_STATUS_T SimStatus);
 msg_error_t MsgStoClearSimMessageInDB();
 
 // Internal Function
-msg_error_t MsgMakeSortRule(const MSG_SORT_RULE_S *pSortRule, char *pSqlSort);
-msg_error_t MsgStoGetSmsSendOpt(msg_message_id_t MsgId, MSG_SENDINGOPT_INFO_S* pSendOpt);
+msg_error_t MsgStoGetSmsSendOpt(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S* pSendOpt);
 msg_error_t MsgStoGetMmsSendOpt(msg_message_id_t MsgId, MSG_SENDINGOPT_INFO_S* pSendOpt);
 
 // SyncML Msg
@@ -112,12 +108,11 @@ bool MsgStoCheckSyncMLMsgInThread(msg_thread_id_t threadId);
 msg_error_t MsgStoUpdateMMSMessage(MSG_MESSAGE_INFO_S *pMsg);
 msg_error_t MsgStoGetContentLocation(MSG_MESSAGE_INFO_S* pMsgInfo);
 msg_error_t MsgStoSetReadReportSendStatus(msg_message_id_t msgId, int readReportSendStatus);
-
+msg_error_t MsgStoGetReadReportSendStatus(msg_message_id_t msgId, int *pReadReportSendStatus);
 
 ///////////////////////////////////////////////////////////////////////////////////
 // For MMS - will be removed
 msg_error_t MsgStoGetOrgAddressList(MSG_MESSAGE_INFO_S *pMsg);
-msg_error_t MsgStoUpdateNetworkStatus(MSG_MESSAGE_INFO_S *pMsgInfo, msg_network_status_t Status);
 msg_error_t MsgStoGetSubject(msg_message_id_t MsgId, char* pSubject);
 msg_error_t MsgStoGetRecipientList(msg_message_id_t msgId, MSG_RECIPIENTS_LIST_S *pRecipientList);
 msg_error_t MsgStoGetReadStatus(msg_message_id_t MsgId, bool *pReadStatus);
@@ -126,8 +121,30 @@ msg_error_t MsgStoGetAddrInfo(msg_message_id_t MsgId, MSG_ADDRESS_INFO_S *pAddrI
 ///////////////////////////////////////////////////////////////////////////////////
 
 msg_error_t MsgStoResetNetworkStatus();
+#if 0
+msg_error_t MsgStoResetCBMessage();
+#endif
 msg_error_t MsgStoCleanAbnormalMmsData();
 msg_error_t MsgStoCheckReadReportStatus(msg_message_id_t msgId);
+msg_error_t MsgStoAutoDeleteConversation(msg_thread_id_t threadId, msg_id_list_s *msgIdList);
+
+msg_error_t MsgStoAddPushEvent(MSG_PUSH_EVENT_INFO_S* pPushEvent);
+msg_error_t MsgStoDeletePushEvent(MSG_PUSH_EVENT_INFO_S* pPushEvent);
+msg_error_t MsgStoUpdatePushEvent(MSG_PUSH_EVENT_INFO_S* pSrc, MSG_PUSH_EVENT_INFO_S* pDst);
+
+msg_message_id_t MsgStoAddSimMessage(MSG_MESSAGE_INFO_S *pMsg, int *simIdList, int listSize);
+msg_error_t MsgStoGetFailedMessage(int **failed_msg_list, int *count);
+
+msg_error_t MsgStoGetReplaceMsgId(MSG_MESSAGE_INFO_S *pMsgInfo);
+msg_error_t MsgStoAddWAPMsg(MSG_MESSAGE_INFO_S *pMsgInfo);
+msg_error_t MsgStoAddCOWAPMsg(MSG_MESSAGE_INFO_S *pMsgInfo);
+msg_error_t MsgStoAddCBMsg(MSG_MESSAGE_INFO_S *pMsgInfo);
+msg_error_t MsgStoCheckPushMsgValidation(MSG_PUSH_MESSAGE_S *pPushMsg, bool *pbProceed);
+msg_error_t MsgStoUpdateAllAddress();
+#ifdef FEATURE_SMS_CDMA
+msg_error_t MsgCheckUniqueness(bool bInsert, msg_message_id_t msgId, MSG_UNIQUE_INDEX_S *p_msg);
+#endif
+msg_error_t MsgStoUpdateIMSI(int sim_idx);
 
 #endif // MSG_STORAGE_HANDLER_H
 
index c3f42b9..d3d9591 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_SUBMIT_HANDLER_H
index 554b7d6..e8294a6 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_TRANSACTION_MANAGER_H
@@ -25,6 +25,7 @@
 #include <map>
 
 #include "MsgMutex.h"
+#include "MsgQueue.h"
 #include "MsgIpcSocket.h"
 #include "MsgCmdTypes.h"
 #include "MsgInternalTypes.h"
@@ -32,6 +33,7 @@
 
 
 
+
 /*==================================================================================================
                                          DEFINITION
 ==================================================================================================*/
@@ -40,6 +42,8 @@ typedef std::map<int, MSG_PROXY_INFO_S> sentmsg_map;
 typedef std::map<int, bool> fd_map;
 typedef std::list<MSG_CMD_REG_INCOMING_MSG_CB_S> newmsg_list;
 typedef std::list<MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB_S>      mmsconf_list;
+typedef std::list<MSG_CMD_REG_INCOMING_PUSH_MSG_CB_S> pushmsg_list;
+typedef std::list<MSG_CMD_REG_INCOMING_CB_MSG_CB_S> cbmsg_list;
 typedef std::list<MSG_CMD_REG_INCOMING_SYNCML_MSG_CB_S> syncmlmsg_list;
 typedef std::list<MSG_CMD_REG_INCOMING_LBS_MSG_CB_S> lbsmsg_list;
 typedef std::list<MSG_CMD_REG_INCOMING_JAVAMMS_TRID_S> javamms_list;
@@ -47,11 +51,6 @@ typedef std::list<MSG_CMD_REG_SYNCML_MSG_OPERATION_CB_S> syncmlop_list;
 
 
 /*==================================================================================================
-                                     FUNCTION PROTOTYPES
-==================================================================================================*/
-void MsgContactChangedCallback();
-
-/*==================================================================================================
                                      CLASS DEFINITIONS
 ==================================================================================================*/
 class MsgTransactionManager
@@ -60,6 +59,7 @@ public:
        static MsgTransactionManager* instance();
 
        void run();
+      void workerEventQueue();
        void write(int fd, const char* buf, int len);
 
        // methods for sent status event
@@ -70,21 +70,26 @@ public:
        void setSentStatusCB(int listenerFd);
        void setIncomingMsgCB(MSG_CMD_REG_INCOMING_MSG_CB_S *pCbInfo);
        void setMMSConfMsgCB(MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB_S *pCbinfo);
+       void setPushMsgCB(MSG_CMD_REG_INCOMING_PUSH_MSG_CB_S *pCbinfo);
+       void setCBMsgCB(MSG_CMD_REG_INCOMING_CB_MSG_CB_S *pCbInfo);
        void setSyncMLMsgCB(MSG_CMD_REG_INCOMING_SYNCML_MSG_CB_S *pCbinfo);
        void setLBSMsgCB(MSG_CMD_REG_INCOMING_LBS_MSG_CB_S *pCbinfo);
        void setJavaMMSList(MSG_CMD_REG_INCOMING_JAVAMMS_TRID_S *pTrId);
        void setSyncMLMsgOperationCB(MSG_CMD_REG_SYNCML_MSG_OPERATION_CB_S *pCbinfo);
        void setStorageChangeCB(int listenerFd);
+       void setReportMsgCB(int listenerFd);
 
        javamms_list& getJavaMMSList();
 
        void broadcastIncomingMsgCB(const msg_error_t err, const MSG_MESSAGE_INFO_S *msgInfo);
        void broadcastMMSConfCB(const msg_error_t err, const MSG_MESSAGE_INFO_S *msgInfo, const MMS_RECV_DATA_S *mmsRecvData);
+       void broadcastPushMsgCB(const msg_error_t err, const MSG_PUSH_MESSAGE_DATA_S *pushData);
+       void broadcastCBMsgCB(const msg_error_t err, const MSG_CB_MSG_S *cbMsg);
        void broadcastSyncMLMsgCB(const msg_error_t err, const MSG_SYNCML_MESSAGE_DATA_S *syncMLData);
        void broadcastLBSMsgCB(const msg_error_t err, const MSG_LBS_MESSAGE_DATA_S *lbsData);
        void broadcastSyncMLMsgOperationCB(const msg_error_t err, const int msgId, const int extId);
        void broadcastStorageChangeCB(const msg_error_t err, const msg_storage_change_type_t storageChangeType, const msg_id_list_s *pMsgIdList);
-
+       void broadcastReportMsgCB(const msg_error_t err, const msg_report_type_t reportMsgType, const MSG_MESSAGE_INFO_S *pMsgInfo);
        void setTMStatus();
        void getTMStatus();
 
@@ -94,7 +99,8 @@ private:
 
        void handleRequest(int fd);
        void cleanup(int fd);
-       bool checkPrivilege(MSG_CMD_TYPE_T CmdType, const char *pCookie);
+//     bool checkPrivilege(MSG_CMD_TYPE_T CmdType, const char *pCookie);
+       bool checkPrivilege(int fd, MSG_CMD_TYPE_T CmdType);
 
        static MsgTransactionManager* pInstance;
 
@@ -102,21 +108,24 @@ private:
        bool running;
 
        handler_map handlerMap;
-
        sentmsg_map sentMsgMap;                 // req_id, listener_fd, msghandle_addr
        fd_map statusCBFdMap;           // src_fd, true if registered
 
        newmsg_list newMsgCBList;       // src_fd, msgType, port if registered
        mmsconf_list newMMSConfMsgCBList;       // src_fd, msgType, port if registered
+       pushmsg_list newPushMsgCBList;  // src_fd, msgType, port if registered
+       cbmsg_list newCBMsgCBList;      // src_fd, msgType, port if registered
        syncmlmsg_list newSyncMLMsgCBList;      // src_fd, msgType, port if registered
        lbsmsg_list newLBSMsgCBList;    // src_fd, msgType, port if registered
        javamms_list javaMMSList; // trId list to distinguish sent Java MMS msg when sendconf received
        syncmlop_list operationSyncMLMsgCBList;         // src_fd, msgType, port if registered
 
        fd_map storageChangeFdMap;      // src_fd, true if registered
+       fd_map reportMsgCBFdMap;        // src_fd, true if registered
 
        Mutex mx;
        CndVar cv;
+       MsgSimpleQ<MSG_CMD_S*> eventQueue;
 };
 
 #endif //MSG_TRANSACTION_MANAGER_H
index cf23937..4ded743 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_H_
 
 #include "msg_types.h"
 
+/*==================================================================================================
+                                    DEFINES
+==================================================================================================*/
+
+/**
+ *     @brief  Defines macro for privilege name http://tizen.org/privilege/message.read
+ */
+#define MSG_SERVICE_READ_PRIV_NAME             "http://tizen.org/privilege/message.read"
+
+/**
+ *     @brief  Defines macro for privilege name http://tizen.org/privilege/message.write
+ */
+#define MSG_SERVICE_WRITE_PRIV_NAME            "http://tizen.org/privilege/message.write"
+
 #ifdef __cplusplus
 extern "C"
 {
 #endif
 
-/**
- *     @ingroup                MESSAGING_FRAMEWORK
- *     @defgroup       MESSAGING_CONTROL_API   Messaging Control API
- *     @{
- */
-
 /*==================================================================================================
                                      FUNCTION PROTOTYPES
 ==================================================================================================*/
 
 /**
-
- * \par Description:
- * Opens a channel between an application and messaging framework.
+ * @internal
+ * @ingroup MSG_SERVICE_FRAMEWORK
+ * @defgroup MSG_SERVICE_FRAMEWORK_CONTROL_MODULE Control API
+ * @brief The Control API provides functions to manage message handle and set or get each structure.
  *
- * \par Purpose:
- * For application to utilize the services of Messaging Framework, this API should be called to establish connection between the application and Messaging Framework.
+ * @internal
+ * @addtogroup MSG_SERVICE_FRAMEWORK_CONTROL_MODULE
+ * @{
  *
- * \par Typical use case:
- * Any application which utilizes the services of Messaging Framework needs to call this API.
+ * @section MSG_SERVICE_FRAMEWORK_CONTROL_MODULE_HEADER Required Header
+ *   \#include <msg.h>
  *
- * \par Method of function operation:
- * Check for Message Server ready status. If ready connect to the Messaging Server socket and pass the handle application.
+ * @section MSG_SERVICE_FRAMEWORK_CONTROL_MODULE_OVERVIEW Overview
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * The CONTROL API provides the following functionalities:
+ * - Handles message handle
+ * - Get/Set message and setting values
  *
- * \par Important notes:
- * - The handle parameter returned must be used by application for further API calls to Messaging Service \n
- * - memory for the handle need not be allocated by the application \n
- * - An error will be returned in case Messaging Service is not running.
+ * @section MSG_SERVICE_FRAMEWORK_CONTROL_MODULE_FEATURE Related Features
+ * This API is related with the following features:\n
+ *  - http://tizen.org/feature/network.telephony\n
  *
- * \param msg_handle_t    input - handle to be passed for all Messaging Services .
+ * It is recommended to design feature related codes in your application for reliability.\n
  *
- * \return Return Type (int) \n
- * - MSG_SUCCESS       - Successfully connected to Messaging Service \n
- * - MSG_ERR_NULL_POINTER      -       Input parameter is NULL.
- * - MSG_ERR_MEMORY_ERROR -    Memory error.
- * - MSG_ERR_COMMUNICATION_ERROR       - Communication error between client and server \n
+ * You can check if a device supports the related features for this API by using @ref CAPI_SYSTEM_SYSTEM_INFO_MODULE, thereby controlling the procedure of your application.\n
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * To ensure your application is only running on the device with specific features, please define the features in your manifest file using the manifest editor in the SDK.\n
  *
- * \par Related functions:
- * None
+ * More details on featuring your application can be found from <a href="../org.tizen.mobile.native.appprogramming/html/ide_sdk_tools/feature_element.htm"><b>Feature Element</b>.</a>
  *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * msg_error_t err = MSG_SUCCESS;
+ */
+
+/**
+ * @brief Opens a channel between an application and messaging framework.
+ * @details For application to utilize the services of Messaging Framework, this API should be called to establish
+ *          connection between the application and Messaging Framework.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * err = msg_open_msg_handle(&msgHandle);
+ * @remarks The handle parameter returned must be used by application for further API calls to Messaging Service.
+ * @remarks The memory for the handle need not be allocated by the application.
+ * @remarks An error will be returned in case Messaging Service is not running.
  *
- * if (err != MSG_SUCCESS)
- * {
- *     sprintf(str, "msg_open_msg_handle() Fail [%d]", err);
- *     print(str);
+ * @param[in] handle The Message handle to be passed for all messaging services
  *
- *     return err; // if success, return OPERATION_SUCCESS. Or if fail, return related error code.
- * }
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS                 Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER   Input parameter is invalid
+ * @retval MSG_ERR_MEMORY_ERROR        Memory error
+ * @retval MSG_ERR_COMMUNICATION_ERROR Communication error between client and server
+ * @retval MSG_ERR_PERMISSION_DENIED   The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED       Not supported
  */
-/*================================================================================================*/
+
 int msg_open_msg_handle(msg_handle_t *handle);
 
 
 /**
-
- * \par Description:
- * Closes the channel between application and messaging framework.
+ * @brief Closes the channel between application and messaging framework.
+ * @details Once application utilizes services of Messaging Service, this API needs to be invoked
+ *          to close the channel between application and Messaging Service.
  *
- * \par Purpose:
- * Once application utilizes services of Messaging Service, this API needs to be invoked the close the channel between application and Messaging Service.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Typical use case:
- * Any application which has completed using services of Messaging Framework needs to call this API.
+ * @remarks The handle parameter returned must be used by application for further API calls to Messaging Service.
+ * @remarks The memory for the handle need not be allocated by the application \n
+ * @remarks An error will be returned in case Messaging Service is not running.
  *
- * \par Method of function operation:
- * Closes the connection to Messaging Service and deleted the reference to the handle object
+ * @param[in] handle The Message handle to be passed for all messaging services
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @return @c 0 on success,
+ *       otherwise a negative error value
  *
- * \par Important notes:
- * - The handle parameter returned must be used by application for further API calls to Messaging Service \n
- * - memory for the handle need not be allocated by the application \n
- * - An error will be returned in case Messaging Service is not running.
+ * @retval MSG_SUCCESS                 Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER   Input parameter is invalid
+ * @retval MSG_ERR_COMMUNICATION_ERROR Communication error between client and server
+ * @retval MSG_ERR_PERMISSION_DENIED   The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED       Not supported
+ */
+
+int msg_close_msg_handle(msg_handle_t *handle);
+
+
+/**
+ * @brief Create structure pointer to get/set message framework data.
+ * @details Get/set message framework data with this structure pointer.
  *
- * \param msg_handle_t    input - handle to be passed for all Messaging Services .
+ * @since_tizen 2.3
  *
- * \return Return Type (int) \n
- * - MSG_SUCCESS       - Successfully connected to Messaging Service \n
- * - MSG_ERR_NULL_POINTER      -       Input parameter is NULL.
- * - MSG_ERR_COMMUNICATION_ERROR       - Communication error between client and server \n
+ * @remarks It should use defined enumerations.
+ * @remarks You must release handle after operations.
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @param[in] field The enumerations to create the structure pointer
  *
- * \par Related functions:
- * None
+ * @return The created structure pointer on success,
+ *         otherwise null value
  *
- * \par Known issues/bugs:
- * None
+ * @retval #msg_struct_t Successfully created structure pointer
+ * @retval NULL          Invalid parameter
+ * @retval MSG_ERR_NOT_SUPPORTED       Not supported
  *
- * \par Sample code:
- * \code
- * ...
+ */
+
+msg_struct_t msg_create_struct(int field);
+
+
+/**
+ * @brief Release memory for message data structure.
+ * @details You must release memory of message data structure that is allocated by msg_create_struct().
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks It should not be used after this API.
+ *
+ * @param[in] msg_struct_handle The structure pointer to release
  *
- * msg_handle_t msgHandle = NULL;
- * msg_error_t err = MSG_SUCCESS;
+ * @return @c 0 on success,
+ *         otherwise a negative error value
  *
- * ...
+ * @retval MSG_SUCCESS          Success in operation
+ * @retval MSG_ERR_NULL_POINTER      Input parameter is NULL
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
+int msg_release_struct(msg_struct_t *msg_struct_handle);
+
+
+/**
+ * @brief Release memory for list structure.
+ * @details You must release memory of list structure that is allocated by getting list API.
  *
- * err = msg_open_msg_handle(&msgHandle);
+ * @since_tizen 2.3
  *
- * ...
+ * @remarks It should not be used after this API
  *
- * err = msg_close_msg_handle(&msgHandle);
+ * @param[in] msg_struct_list The list structure pointer to release
  *
- * if (err != MSG_SUCCESS)
- * {
- *     sprintf(str, "msg_close_msg_handle() Fail [%d]", err);
- *     print(str);
+ * @return @c 0 on success,
+ *       otherwise a negative error value
  *
- *     return err; // if success, return OPERATION_SUCCESS. Or if fail, return related error code.
- * }
+ * @retval MSG_SUCCESS          Success in operation
+ * @retval MSG_ERR_NULL_POINTER      Input parameter is NULL
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  *
- * ...
- * \endcode
  */
-/*================================================================================================*/
-int msg_close_msg_handle(msg_handle_t *handle);
 
+int msg_release_list_struct(msg_struct_list_s *msg_struct_list);
 
 
-msg_struct_t msg_create_struct(int field);
-int msg_release_struct(msg_struct_t *msg_struct_handle);
-int msg_release_list_struct(msg_struct_list_s *msg_struct_list);
+/**
+ * @brief Get a specific integer value from message structure data.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid enumerations.
+ *
+ * @param[in]  msg_struct_handle  A pointer of message structure type
+ * @param[in]  field              The enumeration to get a value of specific field
+ * @param[out] value              The requested integer value
+ *
+ * @return @c 0 on success,
+ *       otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter (msg_struct_handle/value) is NULL
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter (field) is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
 
 int msg_get_int_value(msg_struct_t msg_struct_handle, int field, int *value);
+
+
+/**
+ * @brief Gets a specific string value from message structure data.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid enumerations.
+ *
+ * @param[in]  msg_struct_handle A pointer of message structure type
+ * @param[in]  field             The enumeration to get a value of specific field
+ * @param[out] value             The requested string value
+ * @param[in]  size              The allocated buffer size of application side
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter (msg_struct_handle/value) is NULL
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter (field) is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
 int msg_get_str_value(msg_struct_t msg_struct_handle, int field, char *value, int size);
+
+
+/**
+ * @brief Gets a specific boolean value from message structure data.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid enumerations.
+ *
+ * @param[in]  msg_struct_handle  A pointer of message structure type
+ * @param[in]  field              The enumeration to get a value of specific field
+ * @param[out] value              The requested boolean value
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter (msg_struct_handle/value) is NULL
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter (field) is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
 int msg_get_bool_value(msg_struct_t msg_struct_handle, int field, bool *value);
+
+
+/**
+ * @brief Gets an inner structure handle from message structure data.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid enumerations.
+ *
+ * @param[in]  msg_struct_handle  A pointer of message structure type
+ * @param[in]  field              The enumeration to get a value of specific field
+ * @param[out] value              The requested structure handle
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter (msg_struct_handle/value) is NULL
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter (field) is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
 int msg_get_struct_handle(msg_struct_t msg_struct_handle, int field, msg_struct_t *value);
+
+
+/**
+ * @brief Gets a list handle from message structure data.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid enumerations.
+ *
+ * @param[in]  msg_struct_handle A pointer of message structure type
+ * @param[in]  field             The enumeration to get a value of specific field
+ * @param[out] value             The requested list handle
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter (msg_struct_handle/value) is NULL
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter (field) is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+/*================================================================================================*/
 int msg_get_list_handle(msg_struct_t msg_struct_handle, int field, void **value);
 
+
+/**
+ * @brief Sets a specific integer value to message structure data.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid enumerations.
+ *
+ * @param[in]  msg_struct_handle A pointer of message structure type
+ * @param[in]  field             The enumeration to get a value of specific field
+ * @param[out] value             The requested integer value
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter (msg_struct_handle/value) is NULL
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter (field) is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
 int msg_set_int_value(msg_struct_t msg_struct_handle, int field, int value);
+
+
+/**
+ * @brief Sets a specific string to message structure data.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid enumerations.
+ *
+ * @param[in]  msg_struct_handle A pointer of message structure type
+ * @param[in]  field             The enumeration to get a value of specific field
+ * @param[out] value             The requested string
+ * @param[in]  size              The requested size of string to set
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter (msg_struct_handle/value) is NULL
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter (field) is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
 int msg_set_str_value(msg_struct_t msg_struct_handle, int field, char *value, int size);
+
+
+/**
+ * @brief Sets a specific boolean value to message structure data.
+ *
+ * @since_tizen 2.3
+ *
+ * @details Set a specific boolean value to message structure data.
+ *
+ * @remarks Use valid enumerations.
+ *
+ * @param[in]  msg_struct_handle  A pointer of message structure type
+ * @param[in]  field              The enumeration to get a value of specific field
+ * @param[out] value              The requested boolean value
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter (msg_struct_handle/value) is NULL
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter (field) is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
 int msg_set_bool_value(msg_struct_t msg_struct_handle, int field, bool value);
+
+
+/**
+ * @brief Sets a inner structure handle to message structure data.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid enumerations.
+ *
+ * @param[in]  msg_struct_handle A pointer of message structure type
+ * @param[in]  field             The enumeration to get a value of specific field
+ * @param[out] value             The requested structure handle to set
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter (msg_struct_handle/value) is NULL
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter (field) is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
 int msg_set_struct_handle(msg_struct_t msg_struct_handle, int field, msg_struct_t value);
+
+
+/**
+ * @brief Set a list handle to message structure data.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid enumerations.
+ *
+ * @param[in]  msg_struct_handle A pointer of message structure type
+ * @param[in]  field             The enumeration to get a value of specific field
+ * @param[out] value             The requested list handle to set
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter (msg_struct_handle/value) is NULL
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter (field) is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
 int msg_set_list_handle(msg_struct_t msg_struct_handle, int field, void *value);
 
-int msg_mms_add_item(msg_struct_t msg_struct_handle, int field, msg_struct_t *item);
+
+/**
+ * @brief Gets a MMS structure handle from message structure.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid structure handle.
+ *
+ * @param[in]  msg_struct_handle  A pointer of message structure type
+ * @param[out] mms_struct_handle  The MMS structure handle to get
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
 
 int msg_get_mms_struct(msg_struct_t msg_struct_handle, msg_struct_t mms_struct_handle);
+
+
+/**
+ * @brief Sets a MMS structure handle to message structure.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid structure handle.
+ *
+ * @param[in]  msg_struct_handle  A pointer of message structure type
+ * @param[out] mms_struct_handle  The MMS structure handle to set
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
 int msg_set_mms_struct(msg_struct_t msg_struct_handle, msg_struct_t mms_struct_handle);
 
-//list
+
+/**
+ * @brief Adds an item to list handle of message structure type.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid list_handle.
+ *
+ * @param[in] msg_struct_handle A pointer of message structure type
+ * @param[in] field             The field to set item
+ * @param[in] item              The #msg_struct_t structure to be added to list handle
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
+int msg_list_add_item(msg_struct_t msg_struct_handle, int field, msg_struct_t *item);
+
+
+/**
+ * @brief Gets n-th data from list handle.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid list_handle.
+ *
+ * @param[in] list_handle A pointer of message structure type
+ * @param[in] index       The index of list structure
+ *
+ * @return  #msg_struct_t value on success,
+ *          otherwise @c NULL value
+ *
+ * @retval #msg_struct_t Successfully done
+ * @retval NULL          Input parameter (list_handle) is not valid
+ * @retval MSG_ERR_NOT_SUPPORTED       Not supported
+ *
+ */
+
 msg_struct_t msg_list_nth_data(msg_list_handle_t list_handle, int index);
+
+
+/**
+ * @brief Gets the length(count) of list handle.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid list_handle.
+ *          If there is an error, it will be returned as below values.
+ *
+ * @param[in] list_handle A pointer of message structure type
+ *
+ * @return The length of message list (int)
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
 int msg_list_length(msg_list_handle_t list_handle);
 
-// filter
+
+/**
+ * @brief Releases entire data of list handle in message structure.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks Use valid msg_struct_handle and enumeration.
+ *
+ * @param[in] msg_struct_handle A pointer of message structure type
+ * @param[in] field             The enumeration to release (list handle)
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter is NULL
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
+int msg_list_clear(msg_struct_t msg_struct_handle, int field);
+
+
+/**
+ * @brief Releases entire data of a list handle and the list.
+ *
+ * @since_tizen 2.3.1
+ *
+ * @remarks #msg_list_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] list_handle A pointer of message structure type
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_NULL_POINTER      Input parameter is NULL
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
+int msg_list_free(msg_list_handle_t list_handle);
+
+
+/**
+ * @brief Adds a filter to block messages by address or word.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_struct_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle  The message handle
+ * @param[in] filter  A pointer to message filter structure
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_FILTER_ERROR      Filter operation error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_add_filter(msg_handle_t handle, const msg_struct_t filter);
+
+
+/**
+ * @brief  Updates filter to block messages by address or word.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ * @remarks #msg_struct_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle The message handle
+ * @param[in] filter A pointer to message filter structure
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_FILTER_ERROR      Filter operation error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_update_filter(msg_handle_t handle, const msg_struct_t filter);
+
+
+/**
+ * @brief Deletes the filter to block messages by address or word.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @param[in] handle    The message handle
+ * @param[in] filter_id The filter index to delete from filter DB
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_FILTER_ERROR      Filter operation error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_delete_filter(msg_handle_t handle, msg_filter_id_t filter_id);
+
+
+/**
+ * @brief Gets all filter list.
+ * @details This API is used to get a filter list that is already added filter set.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in]  handle      The message handle
+ * @param[out] filter_list A pointer to list of message filter structure
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_FILTER_ERROR      Filter operation error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_get_filter_list(msg_handle_t handle, msg_struct_list_s *filter_list);
+
+
+/**
+ * @brief Sets the flag of message blocking.
+ * @details This API is used to set a flag of block operation.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle    The message handle
+ * @param[in] set_flag  Set @c true to enable block operation,
+ *                      otherwise set @c false to disable block operation
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_FILTER_ERROR      Filter operation error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_set_filter_operation(msg_handle_t handle, bool set_flag);
+
+
+/**
+ * @brief Gets the flag value of message blocking.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in]  handle    The message handle
+ * @param[out] set_flag  @c true if message blocking is enabled,
+ *                       otherwise @c false if message blocking is not enabled
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_FILTER_ERROR      Filter operation error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_get_filter_operation(msg_handle_t handle, bool *set_flag);
 
-//setting
+
+/**
+ * @brief Sets the flag of message blocking for specific filter.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle    The message handle
+ * @param[in] filter_id The specific index to set flag
+ * @param[in] active    Set @c true to enable the block operation,
+ *                      otherwise @c false to not enable the block operation
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_FILTER_ERROR      Filter operation error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_set_filter_active(msg_handle_t handle, msg_filter_id_t filter_id, bool active);
+
+
+/**
+ * @brief Gets SMSC list and informations.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of SMSC data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_get_smsc_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+
+/**
+ * @brief Sets SMSC list and informations.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of SMSC data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_set_smsc_opt(msg_handle_t handle, msg_struct_t msg_struct);
 
+
+
+/**
+ * @brief Gets CB channel list and informations.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of CB data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_get_cb_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+
+/**
+ * @brief Sets CB channel list and informations.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of CB data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_set_cb_opt(msg_handle_t handle, msg_struct_t msg_struct);
 
+
+/**
+ * @brief Gets SMS sending options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of sending option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_get_sms_send_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+
+/**
+ * @brief Sets SMS sending options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of sending option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_set_sms_send_opt(msg_handle_t handle, msg_struct_t msg_struct);
 
+
+/**
+ * @brief Gets MMS sending options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of sending option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_get_mms_send_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+
+/**
+ * @brief Sets MMS sending options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of sending option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_set_mms_send_opt(msg_handle_t handle, msg_struct_t msg_struct);
 
+
+/**
+ * @brief Gets MMS receiving options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of receiving option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_get_mms_recv_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+
+/**
+ * @brief Sets MMS receiving options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of receiving option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_set_mms_recv_opt(msg_handle_t handle, msg_struct_t msg_struct);
 
+
+/**
+ * @brief Gets push message options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of push message option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_get_push_msg_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+
+/**
+ * @brief Sets push message options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of push message option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_set_push_msg_opt(msg_handle_t handle, msg_struct_t msg_struct);
 
+
+/**
+ * @brief Gets voice message options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of voice message option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_get_voice_msg_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+
+/**
+ * @brief Sets voice message options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of voice message option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_set_voice_msg_opt(msg_handle_t handle, msg_struct_t msg_struct);
 
+
+/**
+ * @brief Gets message general options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of message general option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_get_general_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+
+/**
+ * @brief Sets message general options.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of message general option data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_set_general_opt(msg_handle_t handle, msg_struct_t msg_struct);
 
+
+/**
+ * @brief Gets message size.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of message size data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_get_msgsize_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+
+/**
+ * @brief Sets message size.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in] handle     The message handle
+ * @param[in] msg_struct A structure pointer of message size data
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
 int msg_set_msgsize_opt(msg_handle_t handle, msg_struct_t msg_struct);
 
+
+/**
+ * @brief Calculates input text length by encode type.
+ *
+ * @since_tizen 2.3
+ *
+ * @remarks #msg_handle_t MUST be valid, otherwise the function will fail.
+ *
+ * @param[in]  msg_text            The string to calculate length
+ * @param[in]  msg_encode_type_to  The current encode type
+ * @param[out] text_size           The calculated text size
+ * @param[out] segment_size        The message segment size
+ * @param[out] msg_encode_type_in  The encode type it should be changed to
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Successfully done
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is not valid.
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ *
+ */
+
+int msg_util_calculate_text_length(const char* msg_text, msg_encode_type_t msg_encode_type_to, unsigned int *text_size, unsigned int *segment_size, msg_encode_type_t *msg_encode_type_in);
+
+
+/**
+ * @}
+*/
+
+
 #ifdef __cplusplus
 }
 #endif
index 13e0312..92168ba 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_PRIVATE_H_
                                          INCLUDE FILES
 ==================================================================================================*/
 
+#include "MsgDebug.h"
+#include "MsgGconfWrapper.h"
 #include "MsgTypes.h"
 #include "MsgStorageTypes.h"
 #include "MsgTransportTypes.h"
 #include "MsgMmsTypes.h"
 #include "MsgFilterTypes.h"
 #include "MsgSettingTypes.h"
+#include "MsgUtilFunction.h"
 
+/*==================================================================================================
+                                    DEFINES
+==================================================================================================*/
+
+#define CHECK_MSG_SUPPORTED(feature_name) \
+       do { \
+               bool bSupported = false; \
+               bSupported = MsgCheckFeatureSupport(feature_name); \
+               if (bSupported == false) {\
+                       MSG_ERR("Feature [%s] not supported", feature_name);\
+                       return MSG_ERR_NOT_SUPPORTED; \
+               } \
+       } while(0)
+
+#define CHECK_MSG_SUPPORTED_RETURN_NULL(feature_name) \
+       do { \
+               bool bSupported = false; \
+               bSupported = MsgCheckFeatureSupport(feature_name); \
+               if (bSupported == false) {\
+                       MSG_ERR("Feature [%s] not supported", feature_name);\
+                       return NULL; \
+               } \
+       } while(0)
 
 /*==================================================================================================
                                                                         FUNCTION PROTOTYPES
@@ -50,10 +76,20 @@ int msg_message_set_struct_hnd(void *data, int field, void *value);
 
 void msg_message_copy_message(MSG_MESSAGE_HIDDEN_S *pSrc, MSG_MESSAGE_HIDDEN_S *pDst);
 
+int msg_cb_message_get_int_value(void *data, int field, int *value);
+int msg_cb_message_get_str_value(void *data, int field, char *value, int size);
+
+int msg_message_list_append(msg_struct_t msg_struct_handle, int field, msg_struct_t *item);
+int msg_message_list_clear(msg_struct_t msg_struct_handle, int field);
+
+
+
 
 // filter
+bool msg_get_filter_info_bool(void *filter, int field);
 int msg_get_filter_info_int(void *filter, int field);
 char *msg_get_filter_info_str(void *filter, int field);
+int msg_set_filter_info_bool(void *filter, int field, bool value);
 int msg_set_filter_info_int(void *filter, int field, int value);
 int msg_set_filter_info_str(void *filter, int field, char *value, int size);
 
@@ -75,9 +111,12 @@ int msg_mms_set_bool_value(msg_struct_s *msg_struct, int field, bool value);
 int msg_mms_set_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s *value);
 int msg_mms_set_list_handle(msg_struct_s *msg_struct, int field, msg_list_handle_t value);
 
+int msg_mms_list_append(msg_struct_t msg_struct_handle, int field, msg_struct_t *item);
+
 void convert_to_mmsdata(const msg_struct_s *pSrc, MMS_MESSAGE_DATA_S *pDest);
 void convert_from_mmsdata(const MMS_MESSAGE_DATA_S *pSrc, msg_struct_s *pDest);
-
+void convert_to_hidden_mmsdata(MMS_DATA_S *pSrc, msg_struct_s *pDest);
+void convert_from_hidden_mmsdata(msg_struct_s *pSrc, MMS_DATA_S *pDest);
 // setting
 int msg_setting_get_int_value(msg_struct_s *msg_struct, int field, int *value);
 int msg_setting_get_str_value(msg_struct_s *msg_struct, int field, char *src, int size);
@@ -130,6 +169,8 @@ int msg_set_push_msg_opt_int(void *push_msg_opt, int field, int value);
 bool msg_get_push_msg_opt_bool(void *push_msg_opt, int field);
 int msg_set_push_msg_opt_bool(void *push_msg_opt, int field, bool value);
 
+int msg_get_voice_msg_opt_int(void *voice_msg_opt, int field);
+int msg_set_voice_msg_opt_int(void *voice_msg_opt, int field, int value);
 char *msg_get_voice_msg_opt_str(void *voice_msg_opt, int field);
 int msg_set_voice_msg_opt_str(void *voice_msg_opt, int field, char *val, int size);
 
@@ -137,11 +178,18 @@ int msg_get_general_opt_int(void *general_opt, int field);
 int msg_set_general_opt_int(void *general_opt, int field, int value);
 bool msg_get_general_opt_bool(void *general_opt, int field);
 int msg_set_general_opt_bool(void *general_opt, int field, bool value);
-
+char *msg_get_general_opt_str(void *general_opt, int field);
+int msg_set_general_opt_str(void *general_opt, int field, char *val, int size);
 
 int msg_get_msgsize_opt_int(void *size_opt, int field);
 int msg_set_msgsize_opt_int(void *size_opt, int field, int value);
 
+/* Wap Push */
+char* msg_push_config_get_str(void *event_info, int field, int size);
+bool msg_push_config_get_bool(void *event_info, int field);
+int msg_push_config_set_str(void *event_info, int field, char *value, int size);
+int msg_push_config_set_bool(void *event, int field, bool value);
+
 /* added internal apis for new managed api (storage) */
 int msg_syncml_info_get_int(void *syncml_info, int field);
 int msg_count_info_get_int(void *count_info, int field);
@@ -150,16 +198,25 @@ int msg_thread_index_get_int(void *index_info, int field);
 int msg_sortrule_get_int(void *sort_info, int field);
 int msg_folder_info_get_int(void *folder_info, int field);
 int msg_thread_info_get_int(void *data, int field);
+int msg_conv_info_get_int(void *data, int field);
 int msg_search_condition_get_int(void *condition_info, int field);
+int msg_list_condition_get_int(void *condition_info, int field);
 int msg_report_status_get_int(void *report_info, int field);
+char* msg_report_status_get_str(void *report_info, int field);
 char* msg_folder_info_get_str(void *folder_info, int field);
 char *msg_thread_info_get_str(void *data, int field);
+char *msg_conv_info_get_str(void *data, int field);
 char* msg_search_condition_get_str(void *condition_info, int field, int size);
+char* msg_list_condition_get_str(void *condition_info, int field, int size);
 bool msg_sendopt_get_bool(void *send_opt, int field);
 bool msg_sortrule_get_bool(void *sort_rule, int field);
+bool msg_conv_get_bool(void *data, int field);
+bool msg_thread_info_get_bool(void *data, int field);
+bool msg_list_condition_get_bool(void *data, int field);
 int msg_sendopt_get_struct_handle(msg_struct_s *msg_struct, int field, void **value);
 int msg_syncml_get_struct_handle(msg_struct_s *msg_struct, int field, void **value);
 int msg_thread_index_get_struct_handle(msg_struct_s *msg_struct, int field, void **value);
+int msg_list_condition_get_struct_handle(msg_struct_s *msg_struct, int field, void **value);
 int msg_address_info_get_int(void *addr_info, int field);
 int msg_mms_sendopt_get_int(void *opt_info, int field);
 int msg_reject_message_get_int(void *msg_info, int field);
@@ -175,18 +232,23 @@ int msg_thread_index_set_int(void *index_info, int field, int value);
 int msg_sortrule_set_int(void *sort_info, int field, int value);
 int msg_folder_info_set_int(void *folder_info, int field, int value);
 int msg_search_condition_set_int(void *condition_info, int field, int value);
+int msg_list_condition_set_int(void *condition_info, int field, int value);
 int msg_report_status_set_int(void *report_info, int field, int value);
 int msg_folder_info_set_str(void *folder_info, int field, char *value, int size);
 int msg_search_condition_set_str(void *condition_info, int field, char *value, int size);
+int msg_list_condition_set_str(void *condition_info, int field, char *value, int size);
 int msg_sendopt_set_bool(void *send_opt, int field, bool value);
 int msg_sortrule_set_bool(void *sort_rule, int field, bool value);
+int msg_list_condition_set_bool(void *data, int field, bool value);
 int msg_sendopt_set_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s *value);
 int msg_syncml_set_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s *value);
 int msg_thread_index_set_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s *value);
+int msg_list_condition_set_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s *value);
 int msg_address_info_set_int(void *addrinfo, int field, int value);
 int msg_mms_sendopt_set_int(void *opt_info, int field, int value);
 int msg_reject_message_set_int(void *msg_info, int field, int value);
 int msg_address_info_set_str(void *addr_info, int field, char *value, int size);
+int msg_media_info_set_str(void *media_info, int field, char *value, int size);
 int msg_reject_message_set_str(void *msg_info, int field, char *value, int size);
 int msg_mms_sendopt_set_bool(void *option, int field, bool value);
 int msg_sms_sendopt_set_bool(void *option, int field, bool value);
@@ -198,5 +260,11 @@ int msg_request_set_int(void *request_info, int field, int value);
 int msg_request_set_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s *value);
 int msg_sent_status_get_int(MSG_SENT_STATUS_S *sent_status_info, int field);
 
+char* msg_media_item_get_str(void *data, int field, int size);
+int msg_media_item_get_int(void *data, int field, int *value);
 
+int msg_conversation_get_list_hnd(void *data, int field, void **value);
+int msg_multipart_get_str_value(void *data, int field, char *value, int size);
+int msg_multipart_get_int_value(void *data, int field, int *value);
+int msg_multipart_set_str_value(void *data, int field, char *value, int size);
 #endif /* MSG_PRIVATE_H_ */
index 796f70f..837af02 100755 (executable)
@@ -1,35 +1,22 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-/**
- *     @file           MapiStorage.h
- *     @brief          Defines storage API of messaging framework
- *     @version        1.0
- */
-
 #ifndef MAPI_STORAGE_H
 #define MAPI_STORAGE_H
 
-/**
- *     @section                Introduction
- *     - Introduction : Overview on Messaging Storage API
- *     @section                Program
- *     - Program : Messaging Storage API Reference
- */
-
 /*==================================================================================================
                                          INCLUDE FILES
 ==================================================================================================*/
@@ -41,2059 +28,1103 @@ extern "C"
 {
 #endif
 
-/**
- *     @ingroup                MESSAGING_FRAMEWORK
- *     @defgroup       MESSAGING_STORAGE_API   Messaging Storage API
- *     @{
- */
-
-/*==================================================================================================
-                                     FUNCTION PROTOTYPES
-==================================================================================================*/
 
 /**
-
- * \par Description:
- * Saves a message to the database.
- *
- * \par Purpose:
- * This API is used to save Message object to the database.
+ * @internal
+ * @ingroup MSG_SERVICE_FRAMEWORK
+ * @defgroup MSG_SERVICE_FRAMEWORK_STORAGE_MODULE Storage API
+ * @brief The Storage API provides functions to get message information with multiple types.
  *
- * \par Typical use case:
- * Save Message feature is used when the message is to be stored to persistent memory for later reference.
+ * @internal
+ * @addtogroup MSG_SERVICE_FRAMEWORK_STORAGE_MODULE
+ * @{
  *
- * \par Method of function operation:
- * Sets up the database connection and inserts the message to message table.
+ * @section MSG_SERVICE_FRAMEWORK_STORAGE_MODULE_HEADER Required Header
+ *   \#include <msg_storage.h>
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @section MSG_SERVICE_FRAMEWORK_STORAGE_MODULE_OVERVIEW Overview
  *
- * \par Important notes:
- * - Mandatory fields of a message structure MUST be valid, otherwise the function will be failed.
+ * The Storage API provides the following functionalities:
  *
- * \param input - msg_handle_t  handle is Message handle.
- * \param input - msg_message_t  msg is a pointer to an msg_message_t structure.
- * \param input - send_opt is a pointer to an MSG_SENDINGOPT_S structure.
+ * - Get message information
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Successfully connected to Messaging Service \n
- * - MSG_ERR_NULL_POINTER      - Input parameter is NULL.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
+ * @section MSG_SERVICE_FRAMEWORK_STORAGE_MODULE_FEATURE Related Features
+ * This API is related with the following features:\n
+ *  - http://tizen.org/feature/network.telephony\n
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * It is recommended to design feature related codes in your application for reliability.\n
  *
- * \par Related functions:
- * None
+ * You can check if a device supports the related features for this API by using @ref CAPI_SYSTEM_SYSTEM_INFO_MODULE, thereby controlling the procedure of your application.\n
  *
- * \par Known issues/bugs:
- * None
+ * To ensure your application is only running on the device with specific features, please define the features in your manifest file using the manifest editor in the SDK.\n
  *
- * \par Sample code:
- * \code
- * ...
+ * More details on featuring your application can be found from <a href="../org.tizen.mobile.native.appprogramming/html/ide_sdk_tools/feature_element.htm"><b>Feature Element</b>.</a>
  *
- * msg_handle_t msgHandle = NULL;
- * msg_message_t               msg;
- * MSG_SENDINGOPT_S sendingOpt = {0};
+ */
+
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+
+/**
+ * @brief Saves a message to the database.
  *
- * ...
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * err = msg_open_msg_handle(&msgHandle);
+ * @remarks Mandatory fields of a message structure MUST be valid, otherwise the function will fail.
  *
- * ...
+ * @param[in] handle    The Message handle
+ * @param[in] msg       A pointer to a message structure
+ * @param[in] send_opt  A pointer to a message structure for sending option
  *
- * err = msg_add_message(handle, (msg_message_t) &msg, &sendingOpt);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
+ * @return  The message ID on success,
+ *       otherwise a negative error value
  *
- * ...
- * \endcode
+ * @retval MESSAGE_ID                    Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER(-9) Invalid parameter
+ * @retval MSG_ERR_STORAGE_ERROR         Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED     The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED         Not supported
  */
-/*================================================================================================*/
+
 int msg_add_message(msg_handle_t handle, const msg_struct_t msg, const msg_struct_t send_opt);
 
 
 /**
-
- * \par Description:
- * Adds a SyncML message to the database.
- *
- * \par Purpose:
- * This API is used to save  a SyncML message to the database.
- *
- * \par Typical use case:
- * Save Message feature is used when the message is to be stored to persistent memory for later reference.
+ * @brief Adds a SyncML message to the database.
  *
- * \par Method of function operation:
- * Sets up the database connection and inserts the syncml message to message table.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @remarks Mandatory fields of a message structure MUST be valid, otherwise the function will fail.
  *
- * \par Important notes:
- * - Mandatory fields of a message structure MUST be valid, otherwise the function will be failed.
+ * @param[in] handle      The Message handle
+ * @param[in] syncml_msg  A pointer to a syncml message structure
  *
- * \param input - msg_handle_t  handle is Message handle.
- * \param input - MSG_SYNCML_MESSAGE_S  syncml_msg is a pointer to an MSG_SYNCML_MESSAGE_S structure.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_NULL_POINTER - pMsg is NULL.
- * - MSG_ERR_INVALID_MSGHANDLE - Message handle is invalid.
- * - MSG_ERR_MSGHANDLE_NOT_CONNECTED - Message handle is not connected.
- * - MSG_ERR_STORAGE_FULL - Storage is FULL.
- * - MSG_ERR_COMMUNICATION_ERROR - Communication between client and server is error.
- * - MSG_ERR_MEMORY_ERROR - Memory is error.
- * - MSG_ERR_MAX_NUMBER_REACHED - Max number is reached.
- * - MSG_ERR_PLUGIN - Generic error code for plugin.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * MSG_SYNCML_MESSAGE_S syncMLMsg;
- *
- * ...
- *
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- *
- * int err = msg_add_syncml_message(msgHandle, &syncMLMsg);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_add_syncml_message(msg_handle_t handle, const msg_struct_t syncml_msg);
 
 
 /**
-
- * \par Description:
- * Updates a message in the database.
- *
- * \par Purpose:
- * This API is used to update a message in the database.
- *
- * \par Typical use case:
- * Update message feature is used when a previously saved message is to be updated.
- *
- * \par Method of function operation:
- * Sets up the database connection and set the message's new values to message table.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - The function is to update message data for the message indentified by the given msgId as long as the given values are valid.
- * - msg->msgId MUST NOT be updated because msg->msgId is a unique Id on platform.
- * - If applications want to move a message between folders, applications SHOULD call msg_move_to_folder.
- * - msg->storageId MUST NOT be updated.
- * - The function will return MSG_ERR_INVALID_MESSAGE, if inputting a new msg->storageId.
- * - If applications want to move the message between storages, applications SHOULD call msg_move_to_storage.
- *
- * \param input - handle is Message handle.
- * \param input - msg is a pointer to an msg_message_t structure.
- * \param input - send_opt is a pointer to an MSG_SENDINGOPT_S structure.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * MSG_SYNCML_MESSAGE_S syncMLMsg;
- * MSG_SENDINGOPT_S sendingOpt = {0};
- *
- * ...
- *
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- *
- * err = msg_update_message(hMsgHandle, pMsg, &sendOpt);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @brief Updates a message in the database.
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @remarks The function is to update message data for the message identified by the given msgId as long as the given values are valid.
+ * @remarks Message ID MUST NOT be updated because that is a unique ID on platform.
+ * @remarks If applications want to move a message between folders, applications SHOULD call msg_move_to_folder().
+ * @remarks Storage ID MUST NOT be updated.
+ * @remarks If applications want to move the message between storages, applications SHOULD call msg_move_to_storage().
+ *
+ * @param[in] handle   The Message handle
+ * @param[in] msg      A pointer to a message structure
+ * @param[in] send_opt A pointer to a message sending option structure
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_update_message(msg_handle_t handle, const msg_struct_t msg, const msg_struct_t send_opt);
 
 
 /**
-
- * \par Description:
- * Updates a message's read status in the database.
- *
- * \par Purpose:
- * This API is used to Updates a message's read status in the database.
- *
- * \par Typical use case:
- * Update message's read status for a previously saved message.
- *
- * \par Method of function operation:
- * Sets up the database connection and updates the message's read status to message table.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input - handle is Message handle.
- * \param input - msg_id is Message ID.
- * \parem input - read is boolean for indicating whether a message is read or not.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * MSG_SYNCML_MESSAGE_S syncMLMsg;
- * MSG_SENDINGOPT_S sendingOpt = {0};
+ * @brief Updates a message's read status in the database.
  *
- * ...
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * err = msg_open_msg_handle(&msgHandle);
+ * @param[in] handle  The message handle
+ * @param[in] msg_id  The message ID
+ * @param[in] read    Set @c true if the message is read,
+ *                    otherwise set @c false if the message is not read
  *
- * ...
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * err = msg_update_message(hMsgHandle, pMsg, &sendOpt);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_update_read_status(msg_handle_t handle, msg_message_id_t msg_id, bool read);
 
 
 /**
-
- * \par Description:
- * Updates a message's protected status in the database.
- *
- * \par Purpose:
- * This API is used to Updates a message's protected status in the database.
- *
- * \par Typical use case:
- * Update message's protected status for a previously saved message.
- *
- * \par Method of function operation:
- * Sets up the database connection and updates the message's protected status to message table.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input - handle is Message handle.
- * \param input - msg_id is Message ID.
- * \parem input - is_protected is boolean for indicating whether a message is protected or not.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
+ * @brief Updates a message's protected status in the database.
  *
- * msg_handle_t msgHandle = NULL;
- * MSG_SYNCML_MESSAGE_S syncMLMsg;
- * MSG_SENDINGOPT_S sendingOpt = {0};
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * ...
+ * @param[in] handle        The message handle
+ * @param[in] msg_id        The message ID
+ * @parem[in] is_protected  Set @c true if a message is protected,
+ *                          otherwise set @c false if message is not protected
  *
- * err = msg_open_msg_handle(&msgHandle);
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * ...
- *
- * err = msg_update_protected_status(hMsgHandle, 0, true);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_update_protected_status(msg_handle_t handle, msg_message_id_t msg_id, bool is_protected);
 
 
 /**
-
- * \par Description:
- * Deletes a message by Message ID from the database.
- *
- * \par Purpose:
- * This API is used to delete a message by Message ID from the database.
- *
- * \par Typical use case:
- * Deletes a previously saved message from the database.
- *
- * \par Method of function operation:
- * Sets up the database connection and deletes a message by Message ID from the message table.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input - handle is Message handle.
- * \param input - msg_id is the ID of the Message to be deleted.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
+ * @brief Deletes a message by Message ID from the database.
  *
- * \par Sample code:
- * \code
- * ...
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * msg_handle_t msgHandle = NULL;
- * MSG_SYNCML_MESSAGE_S syncMLMsg;
- * MSG_SENDINGOPT_S sendingOpt = {0};
+ * @param[in] handle  The message handle
+ * @param[in] msg_id  The message ID of the message to be deleted
  *
- * ...
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- *
- * err = msg_delete_message(msgHandle, 0);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_delete_message(msg_handle_t handle, msg_message_id_t msg_id);
 
 
 /**
-
- * \par Description:
- * Deletes all messages in the specified folder from the database.
- *
- * \par Purpose:
- * This API is used to delete all messages in the specified folder from the database.
- *
- * \par Typical use case:
- * Deletes all messages in the specified folder from the database.
- *
- * \par Method of function operation:
- * Sets up the database connection and Deletes all messages in the specified folder from the message table.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input - handle is Message handle.
- * \param input - folder_id is the ID of the folder to be deleted.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
+ * @brief Deletes all messages in the specified folder from the database.
  *
- * \par Known issues/bugs:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in] handle   Message handle
+ * @param[in] msg_id   Message ID of the message to be deleted
+ * @param[in] bOnlyDB  Set @c true to not delete messages in SIM,
+ *                     otherwise set @c false to delete messages in SIM
  *
- * msg_handle_t msgHandle = NULL;
- * MSG_SYNCML_MESSAGE_S syncMLMsg;
- * MSG_SENDINGOPT_S sendingOpt = {0};
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * ...
- *
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- *
- * err = msg_delete_all_msgs_in_folder(msgHandle, MSG_DRAFT_ID);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_delete_all_msgs_in_folder(msg_handle_t handle, msg_folder_id_t folder_id, bool bOnlyDB);
 
 
 
 /**
-
- * \par Description:
- * Moves a message to the specified folder in the database.
- *
- * \par Purpose:
- * This API is used to move a message to the specified folder the database.
- *
- * \par Typical use case:
- * Deletes all messages in the specified folder from the database.
- *
- * \par Method of function operation:
- * Sets up the database connection and Deletes all messages in the specified folder from the message table.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input - handle is Message handle.
- * \param input - msg_id is the ID of the message to be moved.
- * \param input - dest_folder_id is the ID of the destination folder.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
+ * @brief Moves a message to the specified folder in the database.
  *
- * \par Known issues/bugs:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in] handle         The message handle
+ * @param[in] msg_id         The message ID of the message to be moved
+ * @param[in] dest_folder_id The ID of the destination folder
  *
- * msg_handle_t msgHandle = NULL;
- * MSG_SYNCML_MESSAGE_S syncMLMsg;
- * MSG_SENDINGOPT_S sendingOpt = {0};
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * ...
- *
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- *
- * err = msg_move_msg_to_folder(hMsgHandle, 0, MSG_OUTBOX_ID);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_move_msg_to_folder(msg_handle_t handle, msg_message_id_t msg_id, msg_folder_id_t dest_folder_id);
 
 
 /**
-
- * \par Description:
- * Moves a message to the other storage.
- *
- * \par Purpose:
- * This API is usd to move a message to the other storage.
- *
- * \par Typical use case:
- * Moves a message to the other storage type.
- *
- * \par Method of function operation:
- * Sets up the database connection and  moves a messages to specified storage type.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input - handle is Message handle.
- * \param input - msg_id is the ID of the message to be moved.
- * \param input - storage_id is the ID of the destination storage.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @brief Moves a message to the other storage.
  *
- * \par Related functions:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Known issues/bugs:
- * None
+ * @param[in] handle      The message handle
+ * @param[in] msg_id      The message ID of the message to be moved
+ * @param[in] storage_id  The ID of the destination storage
  *
- * \par Sample code:
- * \code
- * ...
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * msg_handle_t msgHandle = NULL;
- * MSG_SYNCML_MESSAGE_S syncMLMsg;
- * MSG_SENDINGOPT_S sendingOpt = {0};
- *
- * ...
- *
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- *
- * err = msg_move_msg_to_storage( msgHandle, 0, MSG_STORAGE_PHONE);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_move_msg_to_storage(msg_handle_t handle, msg_message_id_t msg_id, msg_storage_id_t storage_id);
 
 
 /**
-
- * \par Description:
- * Gets the number of messages in the specified folder from the database.
- *
- * \par Purpose:
- * This API is used to get the number of messages in the specified folder from the database.
- *
- * \par Typical use case:
- * Gets the number of messages in the specified folder from the database.
- *
- * \par Method of function operation:
- * Sets up the database connection and Gets the number of messages in the specified folder from the message table.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input - handle is Message handle.
- * \param input - folder_id is the ID of the folder to be counted.
- * \param output - count_info is a pointer to an MSG_COUNT_INFO_S structure.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
+ * @brief Gets the number of messages in the specified folder from the database.
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Related functions:
- * None
+ * @param[in]  handle      The message handle
+ * @param[in]  msg_id      The message ID of the message to be counted
+ * @param[out] count_info  A pointer to an #MSG_COUNT_INFO_S structure
  *
- * \par Known issues/bugs:
- * None
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * MSG_COUNT_INFO_S countInfo;
- *
- * ...
- *
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- *
- * err = msg_count_message(msgHandle, MSG_OUTBOX_ID, &countInfo)
-* if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_count_message(msg_handle_t handle, msg_folder_id_t folder_id, msg_struct_t count_info);
 
 
 /**
-
- * \par Description:
- * Gets the number of messages of specific message type.
- *
- * \par Purpose:
- * This API is used to get the number of messages of specific type.
- *
- * \par Typical use case:
- * Gets the count of message of specific types such as SMS, MMS.
- *
- * \par Method of function operation:
- * Sets up the database connection and queries the number of messages in the specified folder from the message table based on required message type.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input - handle is Message handle.
- * \param input - msg_type is the message type to be counted.
- * \param output - msg_count is a pointer to the number of message.
+ * @brief Gets the number of messages of specific message type.
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @param[in]  handle     The message handle
+ * @param[in]  msg_type   The message type to be counted
+ * @param[out] msg_count  A pointer to the number of message
  *
- * \par Related functions:
- * None
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * MSG_COUNT_INFO_S countInfo;
- *
- * ...
- *
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- *
- * err = msg_count_msg_by_type(msgHandle, MSG_TYPE_SMS, &countInfo);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_count_msg_by_type(msg_handle_t handle, msg_message_type_t msg_type, int *msg_count);
 
 
 /**
-
- * \par Description:
- * Gets the number of messages of specific address.
- *
- * \par Purpose:
- * This API is used to get the number of messages from a specific address.
- *
- * \par Typical use case:
- * Get the count of messages from the specified address
- *
- * \par Method of function operation:
- * Sets up the database connection and queries the number of messages based on address from the message table.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - If addr_info is NULL, nothing happens.
+ * @brief Gets the number of messages of specific address.
  *
- * \param input - handle is Message handle.
- * \param input - addr_info is a pointer to an MSG_ADDRESS_INFO_LIST_S structure.
- * \param input - msg_thread_count_list is a pointer to an MSG_THREAD_COUNT_INFO_S structure.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
+ * @remarks If @a addr_info is @c NULL, nothing happens.
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @param[in] handle                 The message handle
+ * @param[in] addr_info              A pointer to an address list information structure
+ * @param[in] msg_thread_count_list  A pointer to an thread count information structure
  *
- * \par Related functions:
- * None
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * MSG_COUNT_INFO_S countInfo;
- *
- * ...
- *
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- *
- * err = msg_count_msg_by_type(msgHandle, MSG_TYPE_SMS, &countInfo);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_count_msg_by_contact(msg_handle_t handle, const msg_struct_t addr_info, msg_struct_t msg_thread_count_list);
 
 
 /**
-
- * \par Description:
- * Gets the detail information of a message from the database.
- *
- * \par Purpose:
- * This API is used to get the number of messages from a specific address.
- *
- * \par Typical use case:
- * Get the count of messages from the specified address
- *
- * \par Method of function operation:
- * Sets up the database connection and queries the number of messages based on address from the message table.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - If addr_info is NULL, nothing happens.
- * - Applications need to call msg_release_message to free the memory.
- * - However, if this function is failed, the memory for the message is NOT allocated in this function.
+ * @brief Gets the detail information of a message from the database.
+ * @details This API is used to get the detail information of message by message ID.
  *
-handle is Message handle.
- * \param input - handle is Message handle.
- * \param input - msg_id is the ID of the Message to be returned.
- * \param output - msg is a pointer to an msg_message_t structure.
- * \param input - send_opt is a pointer to an MSG_SENDINGOPT_S structure.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
+ * @remarks Applications need to call msg_release_struct() to free the memory.
+ * @remarks However, if this function fails, the memory for the message is NOT allocated in this function.
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @param[in]  handle    The Message handle
+ * @param[in]  msg_id    The ID of the Message to be returned
+ * @param[out] msg       A pointer to a #msg_struct_t message structure
+ * @param[in]  send_opt  A pointer to a #msg_struct_t sending option structure
  *
- * \par Related functions:
- * - None
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- *
- * ...
- * msg_message_t msg = msg_new_message();
- * MSG_SENDINGOPT_S sendOpt = {0, };
- * ...
- * err = msg_get_message(msgHandle, 0, msg, &sendOpt);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_get_message(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_t msg, msg_struct_t send_opt);
 
 
 /**
-
- * \par Description:
- * Returns the common information list of messages with selected folder id.
- *
- * \par Purpose:
- * This API is used to get the common information list of messages with selected folder id from database.
+ * @brief Gets the detail information of a message on conversation list.
+ * @details This API is used to get the conversation informations of message by message ID.
  *
- * \par Typical use case:
- * Get the common information from the specified folder from database.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Method of function operation:
- * Sets up the database connection and queries the common information based on selected folder id from the message and folder tables.
+ * @param[in]  handle  The Message handle
+ * @param[in]  msg_id  The ID of the Message to be returned
+ * @param[out] conv    A pointer to a #msg_struct_t of message structure
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Important notes:
- * - The memory for a message will be allocated in this function.
- * - Applications need to call msg_release_folder_view_list to free the memory.
- * - However, if this function is failed, the memory for the message is NOT allocated in this function.
- *
- * \param input - handle is Message handle.
- * \param input - folder_id is the ID of the folder to be returned.
- * \param input - sort_rule indicates a sort type and sort order for querying messages.
- * \param output - msg_folder_view_list is a pointer to an MSG_FOLDER_VIEW_LIST_S structure.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * - None
- *
- * \par Known issues/bugs:
- * None
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_get_conversation(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_t conv);
+
+
+/**
+ * @brief Gets the v-object data of message.
+ * @details This API is used to get the v-object data of message by message ID.
  *
- * \par Sample code:
- * \code
- * ...
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * msg_handle_t msgHandle = NULL;
+ * @param[in]  handle        The Message handle
+ * @param[in]  msg_id        The ID of the Message to be returned
+ * @param[out] encoded_data  A pointer to a encoded v-object data of message
  *
- * ...
- * MSG_FOLDER_VIEW_LIST_S folderViewList;
- * ...
- * err = msg_get_folder_view_list(hMsgHandle, 0, NULL, &folderViewList);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_get_folder_view_list(msg_handle_t handle, msg_folder_id_t folder_id, const msg_struct_t sort_rule, msg_struct_list_s *msg_folder_view_list);
 
+int msg_get_vobject_data(msg_handle_t handle, msg_message_id_t msg_id, void** encoded_data);
 
-/**
 
- * \par Description:
- * Returns the information of all peers to whom messages have been sent or recieved.
- *
- * \par Purpose:
- * This API is used to get the information of all peers to whom messages have been sent or recieved.
- *
- * \par Typical use case:
- * Get the common information from the specified folder from database.
- *
- * \par Method of function operation:
- * Frees the memory occupied by MSG_FOLDER_VIEW_LIST_S object and its members.
+/**
+ * @brief Gets the information of all peers to whom messages have been sent or received.
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Important notes:
- * - The memory for a list will be allocated in this function.
- * - Applications need to call msg_release_thread_view_list to free the memory.
- * - However, if this function is failed, the memory for a list is NOT allocated in this function.
+ * @remarks The memory for a list will be allocated in this function.
+ * @remarks Applications need to call msg_release_thread_view_list() to free the memory.
+ * @remarks However, if this function fails, the memory for a list is NOT allocated in this function.
  *
- * \param input - handle is Message handle.
- * \param input - sort_rule indicates a sort type and sort order for querying messages.
- * \param output - msg_thread_view_list is a pointer to an msg_struct_list_s structure.
+ * @param[in]  handle                The Message handle
+ * @param[in]  sourt_rule            This indicates a sort type and sort order for querying messages
+ * @param[out] msg_thread_view_list  A pointer to an #msg_struct_list_s structure
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_get_thread_view_list(msg_handle_t handle, const msg_struct_t sort_rule, msg_struct_list_s *msg_thread_view_list);
+
+
+/**
+ * @briefs Gets the common information list of messages with the selected thread ID.
  *
- * \par Related functions:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Known issues/bugs:
- * None
+ * @remarks The memory for a list will be allocated in this function.
+ * @remarks Applications need to call msg_release_conversation_view_list() to free the memory.
+ * @remarks However, if this function is failed, the memory for a list is NOT allocated in this function.
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in]  hMsgHandle          The Message handle
+ * @param[in]  thread_id           The ID of the thread to be returned
+ * @param[out] msg_conv_view_list  A pointer to a structure of conversational message list
  *
- * msg_handle_t msgHandle = NULL;
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * ...
- * msg_struct_list_s threadViewList;
- * ...
- * err = msg_get_thread_view_list(hMsgHandle, NULL, &threadViewList);
- * ...
- * msg_release_thread_view_list(&threadViewList);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_get_thread_view_list(msg_handle_t handle, const msg_struct_t sort_rule, msg_struct_list_s *msg_thread_view_list);
-
-
-/**
 
- * \par Description:
- * Returns the common information list of messages with selected thread_id.
- *
- * \par Purpose:
- * This API is used to get the common information list of messages with selected thread_id.
- *
- * \par Typical use case:
- * Gets the common information list of messages with the selected thread id from the database.
- *
- * \par Method of function operation:
- * Connects to the database and queries the common infomation of  list messages with the provided thread id.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - The memory for a list will be allocated in this function.
- * - Applications need to call msg_release_conversation_view_list to free the memory.
- * - However, if this function is failed, the memory for a list is NOT allocated in this function.
- *
- * \param input - hMsgHandle is Message handle.
- * \param input - thread_id is the ID of the thread to be returned.
- * \param output - msg_conv_view_list is a pointer to an MSG_CONV_VIEW_LIST_S structure.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * - None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * msg_error_t err = MSG_SUCCESS;
- * ...
- * MSG_CONV_VIEW_LIST_S convViewList;
- * ...
- * err = msg_get_conversation_view_list(hMsgHandle, ThreadId, &convViewList);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * msg_release_conversation_view_list(&convViewList);
- * ...
- * \endcode
- */
-/*================================================================================================*/
 int msg_get_conversation_view_list(msg_handle_t handle, msg_thread_id_t thread_id, msg_struct_list_s *msg_conv_view_list);
 
 
 /**
-
- * \par Description:
- * Deletes all the Messages Sent/Received from the selected list.
- *
- * \par Purpose:
- * This API is used to delete all the Messages Sent/Received from the selected list.
- *
- * \par Typical use case:
- * Deletes all messages sent/received from the selected list.
- *
- * \par Method of function operation:
- * Sets up the database connection and deletes all messages sent/received from a selected list.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - If addr_info is NULL, nothing happens.
- *
- * \param input - handle is Message handle.
- * \param input - thread_id is the ID of the thread to be deleted.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
+ * @brief Deletes all the Messages Sent/Received from the selected list.
  *
- * \par Known issues/bugs:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in] handle                 The Message handle
+ * @param[in] thread_id              The ID of the thread to be deleted
+ * @param[in] include_protected_msg  Set @c true to delete protected messages,
+ *                                   otherwise @c false to not delete protected messages
  *
- * msg_handle_t msgHandle = NULL;
- * MSG_SYNCML_MESSAGE_S syncMLMsg;
- * MSG_SENDINGOPT_S sendingOpt = {0};
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * ...
- *
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- *
- * err = msg_delete_thread_message_list(hMsgHandle, 0);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_delete_thread_message_list(msg_handle_t handle, msg_thread_id_t thread_id);
 
+int msg_delete_thread_message_list(msg_handle_t handle, msg_thread_id_t thread_id, bool include_protected_msg);
 
-/**
 
- * \par Description:
- * Adds a new folder.
- *
- * \par Purpose:
- * This API is used to add a new folder.
- *
- * \par Typical use case:
- * Adds a new folder with the specified folder info
- *
- * \par Method of function operation:
- * Sets up the database connection and add a new folder to the folder table.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None.
- *
- * \param - handle is Message handle.
- * \param - folder_info is a pointer to an MSG_FOLDER_INFO_S structure.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
+/**
+ * @brief Adds a new folder.
  *
- * \par Sample code:
- * \code
- * ...
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * msg_handle_t msgHandle = NULL;
- *  Make Folder
- * MSG_FOLDER_INFO_S folderInfo;
- * ...
- * err = msg_open_msg_handle(&msgHandle);
+ * @param[in] handle      The Message handle
+ * @param[in] folder_info A pointer to an #MSG_FOLDER_INFO_S structure
  *
- * folderInfo.folderId = 1;
- * folderInfo.folderType = MSG_FOLDER_TYPE_USER_DEF;
- * ...
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * err = msg_add_folder(hMsgHandle, &folderInfo);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_add_folder(msg_handle_t handle, const msg_struct_t folder_info);
 
 
 /**
-
- * \par Description:
- * Updates the folder info.
- *
- * \par Purpose:
- * This API is used to add a new folder.
- *
- * \par Typical use case:
- * Adds a new folder with the specified folder info
- *
- * \par Method of function operation:
- * Sets up the database connection and add a new folder to the folder table.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @brief Updates the folder info.
  *
- * \par Important notes:
- * - None.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \param - handle is Message handle.
- * \param - folder_info is a pointer to an MSG_FOLDER_INFO_S structure.
+ * @param[in] handle       The Message handle
+ * @param[in] folder_info  A pointer to an #MSG_FOLDER_INFO_S structure
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- *  Make Folder
- * MSG_FOLDER_INFO_S folderInfo;
- * ...
- * err = msg_open_msg_handle(&msgHandle);
- *
- * folderInfo.folderId = 2;
- * folderInfo.folderType = MSG_FOLDER_TYPE_USER_DEF;
- * ...
- * err = msg_update_folder(msgHandle, &folderInfo);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_update_folder(msg_handle_t handle, const msg_struct_t folder_info);
 
 
 /**
-
- * \par Description:
- * Deletes an exisiting folder.
+ * @brief Deletes an existing folder.
  *
- * \par Purpose:
- * This API is used to delete an existing folder.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Typical use case:
- * Deletes an existing folder.
+ * @param[in] handle    The Message handle
+ * @param[in] folder_id The ID of the folder to be deleted
  *
- * \par Method of function operation:
- * Sets up the database connection and deletes an existing folder to the folder table.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None.
- *
- * \param input - handle is Message handle.
- * \param input - folder_id is the ID of the folder to be deleted.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- * err = msg_delete_folder(hMsgHandle, MSG_INBOX_ID);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_delete_folder(msg_handle_t handle, msg_folder_id_t folder_id);
 
 
 /**
-
- * \par Description:
- * Returns the information list of folders.
- *
- * \par Purpose:
- * This API is used to get the information list of folders.
- *
- * \par Typical use case:
- * Gets the folder list information.
- *
- * \par Method of function operation:
- * Sets up the database connection and queries for the folder list information.
+ * @brief Gets the information list of folders.
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Important notes:
- * - None.
+ * @param[in]  handle       The Message handle
+ * @param[out] folder_list  A pointer to a #msg_struct_list_s structure
  *
- * \param input - handle is Message handle.
- * \param output - folder_list is a pointer to an msg_struct_list_s structure.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- *  msg_struct_list_s folderList;
-
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- * err = msg_get_folder_list(msgHandle, &folderList);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * msg_release_folder_list(&folderList);
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_get_folder_list(msg_handle_t handle, msg_struct_list_s *folder_list);
 
 
 /**
-
- * \par Description:
- * Creates the specified number of messages in database.
- *
- * \par Purpose:
- * This API is used to generate specified number of messages in the database
- *
- * \par Typical use case:
- * Generate large number of messages in the database.
- *
- * \par Method of function operation:
- * Creates the specified number of messages in database for specified message type in the specified folder
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input - handle is Message handle.
- * \param input - msg_type is one of enum _MSG_MESSAGE_TYPE_E.
- * \param input - folder_id is the folder for the test messages.
- * \param input - num_msg is the number of messages.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_MSGHANDLE Parameter is invalid.
- * - MSG_ERR_INVALID_FOLDER_ID Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- *  msg_struct_list_s folderList;
-
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- * err = msg_generate_message(msgHandle, MSG_TYPE_SMS, MSG_INBOX_ID, 100);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * \endcode
+ * @brief Creates the specified number of messages in database.
+ * @details This API is used to generate specified number of messages in the database
+ *
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
+ *
+ * @param[in] handle     The Message handle
+ * @param[in] msg_type   The message type \n
+ *                       One of enum _MSG_MESSAGE_TYPE_E.
+ * @param[in] folder_id  The folder for the test messages
+ * @param[in] num_msg    The number of messages
+ *
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
+ *
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_MSGHANDLE Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_generate_message(msg_handle_t handle, msg_message_type_t msg_type, msg_folder_id_t folder_id, unsigned int num_msg);
-int msg_generate_sms(msg_handle_t handle, msg_folder_id_t folder_id, unsigned int num_msg) DEPRECATED;
 
 
 /**
-
- * \par Description:
- * Returns the Message Data to be used by the Quick Panel.
- *
- * \par Purpose:
- * This API is used to get the Message Datato be used by the Quick Panel.
- *
- * \par Typical use case:
- * Quick panel needs the message information to show new message notification.
- *
- * \par Method of function operation:
- * Connects to database and queries for information needed by the quick panel.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @brief Returns the Message Data to be used by the Quick Panel.
  *
- * \par Important notes:
- * - None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \param input - handle is Message handle.
- * \param input - type is the type of message that Quick Panel need.
- * \param output - msg is a pointer to an msg_message_t structure.
+ * @param[in]  handle  The Message handle
+ * @param[in]  type    The type of message that Quick Panel needs
+ * @param[out] msg     A pointer to a #msg_struct_t structure
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_MSGHANDLE Parameter is invalid.
- * - MSG_ERR_INVALID_FOLDER_ID Storage is error.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * msg_message_t msgInfo;
-
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- * err = msg_get_quick_panel_data(msgHandle, MSG_QUICKPANEL_SMS, msgInfo);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS                   Success in operation
+ * @retval MSG_ERR_DB_STEP               There is no Quick Panel message
+ * @retval MSG_ERR_INVALID_PARAMETER(-9) Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR         Storage  error
+ * @retval MSG_ERR_PERMISSION_DENIED     The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_get_quick_panel_data(msg_handle_t handle, msg_quickpanel_type_t type, msg_struct_t msg);
 
 
 /**
-
- * \par Description:
- * Resets the Messaging database.
- *
- * \par Purpose:
- * This API is used to reset the messaging database.
- *
- * \par Typical use case:
- * Completely delete the messaging database.
- *
- * \par Method of function operation:
- * Connects to database and deletes all the messaging tables.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input - handle is Message handle.
+ * @brief Resets the Messaging database.
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_PARAMETER Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR             Storage is error.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @param[in] handle The Message handle
  *
- * \par Related functions:
- * None
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * msg_error_t err = MSG_SUCCESS;
- * err = msg_open_msg_handle(&msgHandle);
- *
- * ...
- * err = msg_reset_database(msgHandle);
- * if (err != MSG_SUCCESS)
- *{
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_reset_database(msg_handle_t handle);
 
 
 /**
-
- * \par Description:
- * Returns the total size used for message contents.
- *
- * \par Purpose:
- * This API is used to get the total size used for message contents.
- *
- * \par Typical use case:
- * To get the total space used by message contents.
- *
- * \par Method of function operation:
- * Uses linux system calls to query the space used by message contents.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input - handle is Message handle.
- * \param output -     memsize is a pointer to the size.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_PARAMETER Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR             Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
+ * @brief Gets the total size used for message contents.
  *
- * \par Known issues/bugs:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in]  handle    The Message handle
+ * @param[out] memsize   A pointer to the size
  *
- * msg_handle_t msgHandle = NULL;
- * int memsize = 0;
- * err = msg_open_msg_handle(&msgHandle);
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * ...
- * err = msg_get_mem_size(msgHandle, &memsize);
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_get_mem_size(msg_handle_t handle, unsigned int* memsize);
 
 /**
-
- * \par Description:
- * Backup messages to storage.
- *
- * \par Purpose:
- * This API is used to backup messages to storage.
- *
- * \par Typical use case:
- * Backup messages to storage.
- *
- * \par Method of function operation:
- * Reads all the messages from Messaging database and writes to storage in V-Message format
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * None
- *
- * \param input - msg_handle_t  handle is Message handle.
+ * @brief Backs up messages to storage.
  *
- * \return Return Type int (msg_error_t) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_PARAMETER Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR             Storage is error.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @param[in] handle          The Message handle
+ * @param[in] type            The backup type
+ * @param[in] backup_filepath The path to backup message
  *
- * \par Related functions:
- * None
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * msg_handle_t msgHandle = NULL;
- * msg_error_t err;
- *
- * ...
- * err = msg_backup_message(&msgHandle);
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_backup_message(msg_handle_t handle);
 
+int msg_backup_message(msg_handle_t handle, msg_message_backup_type_t type, const char *backup_filepath);
 
-/**
 
- * \par Description:
- * Restore messages from backed up messages.
- *
- * \par Purpose:
- * This API is used to restore messages from backed up messages.
- *
- * \par Typical use case:
- * Restore messages from previously backed up messages.
- *
- * \par Method of function operation:
- * Reads the previously backup up messages and restores the database.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * None
- *
- * \param input - msg_handle_t  handle is Message handle.
- *
- * \return Return Type int (msg_error_t) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_PARAMETER Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR             Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+/**
+ * @brief Restores messages from backed up messages.
  *
- * \par Related functions:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Known issues/bugs:
- * None
+ * @param[in] handle          The Message handle
+ * @param[in] backup_filepath The path to backup message
  *
- * \par Sample code:
- * \code
- * ...
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * msg_handle_t msgHandle = NULL;
- * msg_error_t err;
-  * ...
- * err = msg_restore_message(&msgHandle);
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_restore_message(msg_handle_t handle);
 
+int msg_restore_message(msg_handle_t handle, const char *backup_filepath);
 
-/**
 
- * \par Description:
- * Search messages or addresses which including a string that applcation want to find.
+/**
+ * @brief Searches messages or addresses for the specified string.
+ * @details This API is used to search messages or addresses from storage.
  *
- * \par Purpose:
- * This API is used to search messages or addresses from storage.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Typical use case:
- * Search messages or addresses from storage.
+ * @param[in]  handle               The Message handle
+ * @param[in]  search_string        The string to search
+ * @param[out] msg_thread_view_list A pointer to an #msg_struct_list_s structure
  *
- * \par Method of function operation:
- * search messages or addresses from storage.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_search_message_for_thread_view(msg_handle_t handle, const char *search_string, msg_struct_list_s *msg_thread_view_list);
+
+
+/**
+ * @brief Gets reject message list by phone number.
+ * @details This API is used to get reject message list from storage.
  *
- * \par Important notes:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \param input - msg_handle_t  handle is Message handle.
- * \param input - search_string is the string to search.
- * \param output - msg_thread_view_list is a pointer to an msg_struct_list_s structure.
+ * @param[in]  handle               The Message handle
+ * @param[in]  phone_num            The string of phone number to find
+ * @param[out] msg_reject_msg_list  A pointer to a #msg_struct_list_s structure
  *
- * \return Return Type int (msg_error_t) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_PARAMETER Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR             Storage is error.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_get_reject_msg_list(msg_handle_t handle, const char* phone_num, msg_struct_list_s *msg_reject_msg_list);
+
+
+/**
+ * @brief Registers a callback function about the change of storage status to Message handle.
+ * @details This API is used to register a callback function about the change of storage status "msg_storage_change_cb" to Message handle.
  *
- * \par Related functions:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Known issues/bugs:
- * None
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in] handle      The Message handle
+ * @param[in] cb          The function to be called
+ * @param[in] user_param  A pointer to user data
  *
- * msg_handle_t msgHandle = NULL;
- * msg_error_t err = MSG_SUCCESS;
- * ...
- * char* search_string = "hello";
- * msg_struct_list_s threadViewList;
- * ...
- * err = msg_search_message_for_thread_view(&msgHandle, search_string, &threadViewList);
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_MSGHANDLE_NOT_CONNECTED Message handle is not connected
+ * @retval MSG_ERR_MEMORY_ERROR         Memory is error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_search_message_for_thread_view(msg_handle_t handle, const char *search_string, msg_struct_list_s *msg_thread_view_list);
 
+int msg_reg_storage_change_callback(msg_handle_t handle, msg_storage_change_cb cb, void *user_param);
 
-/**
 
- * \par Description:
- * Search messages or addresses which including a string that applcation want to find.
- *
- * \par Purpose:
- * This API is used to search messages or addresses from storage.
- *
- * \par Typical use case:
- * Search messages or addresses from storage.
- *
- * \par Method of function operation:
- * search messages or addresses from storage.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+/**
+ * @brief Gets the report status information of message.
  *
- * \par Important notes:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \param input - msg_handle_t  handle is Message handle.
- * \param input - search_string is the string to search.
- * \param input - offset is the offset of the search result.
- * \param input - limit is the limit of the search result.
- * \param output - msg_list is a pointer to an msg_struct_list_s structure.
+ * @param[in]  handle        The Message handle
+ * @param[in]  msg_id        The ID of the message
+ * @param[out] report_status A pointer to a #msg_struct_list_s structure
  *
- * \return Return Type int (msg_error_t) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_PARAMETER Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR             Storage is error.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_get_report_status(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_list_s *report_list);
+
+
+/**
+ * @brief Gets the address list for specific thread ID.
  *
- * \par Related functions:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Known issues/bugs:
- * None
+ * @param[in]  handle           The Message handle
+ * @param[in]  msg_id           The ID of the message
+ * @param[out] msg_address_list A pointer to a #msg_struct_list_s structure
  *
- * \par Sample code:
- * \code
- * ...
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * msg_handle_t msgHandle = NULL;
- * msg_error_t err = MSG_SUCCESS;
- * ...
- * msg_struct_list_s msg_list;
- * int offset = 0;
- * int limit = 10;
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_get_address_list(msg_handle_t handle, msg_thread_id_t thread_id, msg_struct_list_s *msg_address_list);
+
+
+/**
+ * @brief Gets the thread ID by address.
  *
- * MSG_SEARCH_CONDITION_S searchCon;
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * searchCon.msgType = MSG_TYPE_SMS;
- * searchCon.folderId = MSG_INBOX_ID;
- * searchCon.pSearchVal = "keyString";
- * searchCon.pAddressVal = "01000000000";
+ * @param[in]  handle           The Message handle
+ * @param[in]  msg_address_list A pointer to a #msg_struct_list_s structure
+ * @param[out] thread_id        The thread ID of the message
  *
- * ...
- * err = msg_search_message(hMsgHandle, &searchCon, offset, limit, &msgList);
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_search_message(msg_handle_t handle, const msg_struct_t msg_search_conditions, int offset, int limit, msg_struct_list_s *msg_list);
 
-/**
+int msg_get_thread_id_by_address(msg_handle_t handle, msg_struct_list_s *msg_address_list, msg_thread_id_t *thread_id);
 
- * \par Description:
- * Get reject message list that application wants to find by phone number.
- *
- * \par Purpose:
- * This API is used to get reject message list from storage.
- *
- * \par Typical use case:
- * Get reject message list from storage.
+/**
+ * @brief Gets the thread ID by address.
  *
- * \par Method of function operation:
- * Get reject message list from storage.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @param[in]  handle            The Message handle
+ * @param[in]  msg_address_list  A pointer to a #msg_list_handle structure
+ * @param[out] thread_id         The thread ID of the message
  *
- * \par Important notes:
- * None
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \param input - msg_handle_t  handle is Message handle.
- * \param input - phone_num is the string of phone number to find.
- * \param output - msg_reject_msg_list is a pointer to an msg_struct_list_s structure.
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
 
- * \return Return Type int (msg_error_t) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_PARAMETER Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR             Storage is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
+int msg_get_thread_id_by_address2(msg_handle_t handle, msg_list_handle_t msg_address_list, msg_thread_id_t *thread_id);
+
+
+
+/**
+ * @brief Gets the thread information.
  *
- * \par Known issues/bugs:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in]  handle      The Message handle
+ * @param[in]  thread_id   The ID of the thread
+ * @param[out] msg_thread  A pointer to a #msg_struct_t structure
  *
- * msg_handle_t msgHandle = NULL;
- * msg_error_t err = MSG_SUCCESS;
- * ...
- * char* phone_num = "01030016057";
- * msg_struct_list_s rejectMsgList;
- * ...
- * err = msg_get_reject_msg_list(hMsgHandle, phone_num, &rejectMsgList);
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_get_reject_msg_list(msg_handle_t handle, const char* phone_num, msg_struct_list_s *msg_reject_msg_list);
 
+int msg_get_thread(msg_handle_t handle, msg_thread_id_t thread_id, msg_struct_t msg_thread);
 
-/**
 
- * \par Description:
- * Registers a callback function about the change of storage status to Message handle.
- *
- * \par Purpose:
- * This API is used to register a callback function about the change of storage status "msg_storage_change_cb" to Message handle.
+/**
+ * @brief Gets the information list of messages.
  *
- * \par Typical use case:
- * Register a callback function about the change of storage status.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Method of function operation:
- * Adds the msg_storage_change_cb API to a callback function list.
+ * @param[in]  handle               The Message handle
+ * @param[in]  msg_list_conditions  A pointer to a #msg_struct_t structure for getting conditions
+ * @param[out] msg_list             A pointer to a #msg_struct_list_s structure
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Important notes:
- *     This function MUST be called after Message handle is opened.
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_get_message_list2(msg_handle_t handle, const msg_struct_t msg_list_conditions, msg_struct_list_s *msg_list);
+
+
+/**
+ * @brief A function to get media list of a chat room.
  *
- * \param input - handle is Message handle.
- * \param input - cb is a function to be called.
- * \param input - user_param is a pointer to user data.
+ * @since_tizen 2.3.1
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                                       Success in operation.
- * - MSG_ERR_MSGHANDLE_NOT_CONNECTED   Message handle is not connected.
- * - MSG_ERR_MEMORY_ERROR                              Memory is error.
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @param[in] handle        The Message handle
+ * @param[in] thread_id     The thread id of conversation to get media list
+ * @param[out] msg_list     The media file list in a conversation
  *
- * \par Related functions:
- * None
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \par Known issues/bugs:
- * None
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_CALLBACK_ERROR    Callback registration error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ */
+
+int msg_get_media_list(msg_handle_t handle, msg_thread_id_t thread_id, msg_list_handle_t *msg_list);
+
+
+/**
+ * @brief Adds a new push event.
  *
- * \par Sample code:
- * \code
- * ...
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * int err = MSG_SUCCESS;
+ * @param[in] handle     The Message handle
+ * @param[in] push_event A pointer to a #msg_struct_t structure for push event
  *
- * err = msg_reg_storage_change_callback(msgHandle, &storageCB, NULL);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- * return;
- * }
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * void storageCB(msg_handle_t handle, msg_thread_id_t threadId, msg_message_id_t msgId, void *user_param)
- * {
- *     ...
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_reg_storage_change_callback(msg_handle_t handle, msg_storage_change_cb cb, void *user_param);
 
+int msg_add_push_event(msg_handle_t handle, const msg_struct_t push_event);
 
-/**
 
- * \par Description:
- * Gets the report status information of message.
- *
- * \par Purpose:
- * This API is used to get the report status information of specified message.
+/**
+ * @brief Deletes a push event.
  *
- * \par Typical use case:
- * Gets the report status information of specified message from the database.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Method of function operation:
- * Sets up the database connection and Gets the report status information of specified message from the report table.
+ * @param[in] handle     The Message handle
+ * @param[in] push_event A pointer to a #msg_struct_t structure for push event
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Important notes:
- * - None
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_delete_push_event(msg_handle_t handle, const msg_struct_t push_event);
+
+
+/**
+ * @brief Updates a push event.
  *
- * \param input - handle is Message handle.
- * \param input - msg_id is the ID of the message.
- * \param output - report_status is a pointer to a MSG_REPORT_STATUS_INFO_S structure.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS       - Success in operation.
- * - MSG_ERR_INVALID_PARAMETER - Parameter is invalid.
- * - MSG_ERR_STORAGE_ERROR - Storage is error.
+ * @param[in] handle    The Message handle
+ * @param[in] src_event A pointer to a #msg_struct_t structure for source push event
+ * @param[in] dst_event A pointer to a #msg_struct_t structure for destination push event
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * \par Related functions:
- * None
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_update_push_event(msg_handle_t handle, const msg_struct_t src_event, const msg_struct_t dst_event);
+
+
+/**
+ * @brief Deletes messages by Message ID list from the database.
  *
- * \par Known issues/bugs:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in] handle      sThe Message handle
+ * @param[in] msg_id_list The message ID list to be deleted
  *
- * msg_handle_t msgHandle = NULL;
- * MSG_REPORT_STATUS_INFO_S reportStatus;
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * ...
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_delete_msgs_by_list(msg_handle_t handle, msg_id_list_s *msg_id_list);
+
+
+/**
+ * @brief Marks a conversation given by thread ID as read.
  *
- * err = msg_open_msg_handle(&msgHandle);
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * ...
+ * @param[in] handle    The Message handle
+ * @param[in] thread_id The thread ID to be updated
  *
- * err = msg_get_report_status(msgHandle, msgID, &reportStatus)
-* if( err != MSG_SUCCESS )
- * {
- *     printf("err [%d]", err);
- *     return err;
- * }
+ * @return  @c 0 on success,
+ *        otherwise a negative error value
  *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Parameter is invalid
+ * @retval MSG_ERR_STORAGE_ERROR     Storage error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_get_report_status(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_t report_status);
-
-
-
-
-int msg_get_address_list(msg_handle_t handle, msg_thread_id_t thread_id, msg_struct_list_s *msg_address_list);
-
-
-int msg_get_thread_id_by_address(msg_handle_t handle, msg_struct_list_s *msg_address_list, msg_thread_id_t *thread_id);
-
-
-int msg_get_thread(msg_handle_t handle, msg_thread_id_t thread_id, msg_struct_t msg_thread);
-
-
-int msg_get_message_list(msg_handle_t handle, msg_folder_id_t folder_id, msg_thread_id_t thread_id, msg_message_type_t msg_type, msg_storage_id_t storage_id, msg_struct_list_s *msg_list);
 
+int msg_set_conversation_to_read(msg_handle_t handle,  msg_thread_id_t thread_id);
 /**
  *     @}
  */
index 7f0c9ba..792d6ef 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_STORAGE_TYPES_H_
 ==================================================================================================*/
 
 /**
- *     @brief  Represents message id list.
+ * @internal
+ * @addtogroup MSG_SERVICE_FRAMEWORK_STORAGE_MODULE
+ * @{
+ */
+
+
+/**
+ *     @brief  The structure type that represents message ID list.
  */
 typedef struct
 {
-       int                                     nCount;                         /**< The count of message id informatioin */
-       msg_message_id_t        *msgIdList;                     /**< The pointer to message id informatioin */
+       int                                     nCount;                         /**< The count of message ID informatioin */
+       msg_message_id_t        *msgIdList;                     /**< The pointer to message ID informatioin */
 }msg_id_list_s;
 
 
@@ -42,46 +49,50 @@ typedef struct
 ==================================================================================================*/
 
 /**
- *     @brief  Represents a folder type. \n
- *     The values for this type SHOULD be in _MSG_FOLDER_TYPE_E.
+ *     @brief  The structure type that represents a folder type. \n
+ *     The values for this type SHOULD be in @ref _MSG_FOLDER_TYPE_E.
  */
 typedef unsigned char msg_folder_type_t;
 
 
 /**
- *     @brief  Represents a sort type. \n
- *     The values for this type SHOULD be in \ref _MSG_SORT_TYPE_E.
+ *     @brief  The structure type that represents a sort type. \n
+ *     The values for this type SHOULD be in @ref _MSG_SORT_TYPE_E.
  */
 typedef unsigned char msg_sort_type_t;
 
 
 /**
- *     @brief  Represents a Saved SIM message ID.
+ *     @brief  The structure type that represents a saved SIM message ID.
  */
 typedef signed short msg_sim_id_t;
 
+/**
+ *     @brief  The structure type that represents a Saved SIM slot ID.
+ */
+typedef int msg_sim_slot_id_t;
+
 
 /**
- *     @brief  Represents a message type for quick panel. \n
- *     The values for this type SHOULD be in \ref _MSG_QUICKPANEL_TYPE_E.
+ *     @brief  The structure type that represents a message type for quick panel. \n
+ *     The values for this type SHOULD be in @ref _MSG_QUICKPANEL_TYPE_E.
  */
 typedef unsigned char msg_quickpanel_type_t;
 
 
 /**
- *     @brief  Represents a storage change CB type. \n
- *     The values for this type SHOULD be in \ref _MSG_STORAGE_CHANGE_TYPE_E.
+ *     @brief  The structure type that represents a storage change CB type. \n
+ *     The values for this type SHOULD be in @ref _MSG_STORAGE_CHANGE_TYPE_E.
  */
 typedef unsigned char msg_storage_change_type_t;
 
 
-/** @brief     Prototype of the function that will be called when the database of message framework is changed.
- *     Applications SHOULD implement this callback function and register it into Message handle.
- *     For how to register this callback function, please refer to msg_reg_storage_change_callback.
- *     The callback function runs in the application process, not in the framework process.
- *     @param[in]      handle is Message handle.
- *     @param[in]      user_param is a pointer to user data.
- *     @return void
+/** @brief     Called when the database of message framework is changed.
+ *          Applications SHOULD implement this callback function and register it into Message handle.
+ *             For how to register this callback function, please refer to msg_reg_storage_change_callback().
+ *             The callback function runs in the application process, not in the framework process.
+ * @param[in]  handle      The Message handle.
+ * @param[in]  user_param  A pointer to user data
  */
 typedef void (*msg_storage_change_cb)(msg_handle_t handle, msg_storage_change_type_t storageChangeType, msg_id_list_s *pMsgIdList, void *user_param);
 
@@ -91,121 +102,129 @@ typedef void (*msg_storage_change_cb)(msg_handle_t handle, msg_storage_change_ty
 ==================================================================================================*/
 
 /**
- *     @brief  Represents the values of a storage type. \n
- *     This enum is used as the value of msg_storage_id_t.
+ *     @brief Enumeration for the values of a storage type. \n
+ *            This enum is used as the value of msg_storage_id_t.
  */
 enum _MSG_STORAGE_ID_E
 {
-       MSG_STORAGE_UNKNOWN = 0,                /**< Storage Id is unknown. */
-       MSG_STORAGE_PHONE,                      /**< Storage Id is Phone. */
-       MSG_STORAGE_SIM,                                /**< Storage Id is SIM card. */
+       MSG_STORAGE_UNKNOWN = 0,                /**< Storage ID is unknown. */
+       MSG_STORAGE_PHONE,                          /**< Storage ID is Phone. */
+       MSG_STORAGE_SIM,                                /**< Storage ID is SIM card in slot 1. */
+       MSG_STORAGE_SIM2,                               /**< Storage ID is SIM card in slot 2. */
 };
 
 
 /**
- *     @brief  Represents the values of a storage type. \n
- *     This enum is used as the value of msg_folder_id_t.
+ *     @brief  Enumeration for the values of a storage type. \n
+ *             This enum is used as the value of msg_folder_id_t.
  */
 enum _MSG_FOLDER_ID_E
 {
-       MSG_IOSBOX_ID = -1,                     /**< Indicates INBOX, OUTBOX and SENTBOX group folder id. (Only for search option.) */
-       MSG_ALLBOX_ID = 0,                              /**< Indicates INBOX, OUTBOX, SENTBOX and DRAFTBOX group folder id. (Only for search option.) */
-       MSG_INBOX_ID = 1,
-       MSG_OUTBOX_ID = 2,
-       MSG_SENTBOX_ID = 3,
-       MSG_DRAFT_ID = 4,
-       MSG_CBMSGBOX_ID = 5,
-       MSG_SPAMBOX_ID = 6,
-       MSG_SMS_TEMPLATE_ID = 7,
-       MSG_MMS_TEMPLATE_ID = 8,
-
-       // new folder should be placed here
-
-       MSG_MAX_FOLDER_ID
+       MSG_IOSBOX_ID = -1,                         /**< Indicates INBOX, OUTBOX and SENTBOX group folder ID. (Only for search option.) */
+       MSG_ALLBOX_ID = 0,                              /**< Indicates INBOX, OUTBOX, SENTBOX and DRAFTBOX group folder ID. (Only for search option.) */
+       MSG_INBOX_ID = 1,                               /**< Indicates INBOX folder ID */
+       MSG_OUTBOX_ID = 2,                              /**< Indicates OUTBOX folder ID */
+       MSG_SENTBOX_ID = 3,                             /**< Indicates SENTBOX folder ID */
+       MSG_DRAFT_ID = 4,                               /**< Indicates DRAFT folder ID */
+       MSG_CBMSGBOX_ID = 5,                    /**< Indicates CALLBACK message folder ID */
+       MSG_SPAMBOX_ID = 6,                             /**< Indicates SPAM message folder ID */
+       MSG_MAX_FOLDER_ID                               /**< Indicates MAX folder ID. Folder ID to be accessed should be smaller than this */
 };
 
 
 /**
- *     @brief  Represents the values of a folder type. \n
- *     This enum is used as the value of msg_folder_type_t.
+ *     @brief  Enumeration for the values of a folder type. \n
+ *             This enum is used as the value of msg_folder_type_t.
  */
 enum _MSG_FOLDER_TYPE_E
 {
        MSG_FOLDER_TYPE_INBOX = 1,              /**< Inbox folder */
-       MSG_FOLDER_TYPE_OUTBOX,         /**< Outbox folder */
-       MSG_FOLDER_TYPE_DRAFT,          /**< Draft folder */
+       MSG_FOLDER_TYPE_OUTBOX,             /**< Outbox folder */
+       MSG_FOLDER_TYPE_DRAFT,              /**< Draft folder */
        MSG_FOLDER_TYPE_SPAMBOX,                /**< Spambox folder */
-       MSG_FOLDER_TYPE_TEMPLATE,               /**< Template folder */
        MSG_FOLDER_TYPE_USER_DEF                /**< Folder which is created by a user */
 };
 
 
 /**
- *     @brief  Represents the values of a sort type. \n
- *     This enum is used as the value of msg_sort_type_t.
+ *     @brief  Enumeration for the values of a sort type. \n
+ *             This enum is used as the value of msg_sort_type_t.
  */
 enum _MSG_SORT_TYPE_E
 {
        MSG_SORT_BY_UNKNOWN = 0,                        /**< Unknown sort type */
-       MSG_SORT_BY_DISPLAY_FROM,               /**< Sort by display from */
-       MSG_SORT_BY_DISPLAY_TO,                 /**< Sort by display to */
+       MSG_SORT_BY_DISPLAY_FROM,                   /**< Sort by display from */
+       MSG_SORT_BY_DISPLAY_TO,                     /**< Sort by display to */
        MSG_SORT_BY_DISPLAY_TIME,                       /**< Sort by display time */
        MSG_SORT_BY_MSG_TYPE,                           /**< Sort by msg type */
        MSG_SORT_BY_READ_STATUS,                        /**< Sort by read status */
-       MSG_SORT_BY_STORAGE_TYPE,               /**< Sort by storage type */
+       MSG_SORT_BY_STORAGE_TYPE,                   /**< Sort by storage type */
        MSG_SORT_BY_THREAD_NAME,                        /**< Sort by name for thread view*/
        MSG_SORT_BY_THREAD_DATE,                        /**< Sort by date for thread view*/
-       MSG_SORT_BY_THREAD_COUNT,               /**< Sort by count for thread view*/
+       MSG_SORT_BY_THREAD_COUNT,                   /**< Sort by count for thread view*/
 };
 
 
 /**
- *     @brief  Represents the values of a message type for quick panel. \n
- *     This enum is used as the value of msg_quickpanel_type_t.
+ *     @brief  Enumeration for the values of a message type for quick panel. \n
+ *             This enum is used as the value of msg_quickpanel_type_t.
  */
 enum _MSG_QUICKPANEL_TYPE_E
 {
-       MSG_QUICKPANEL_SMS = 0,
-       MSG_QUICKPANEL_MMS,
-       MSG_QUICKPANEL_DELIVER_REP,
-       MSG_QUICKPANEL_READ_REP,
-       MSG_QUICKPANEL_VOICEMAIL,
-       MSG_QUICKPANEL_MMS_NOTI,
+       MSG_QUICKPANEL_SMS = 0,                         /**< Quickpanel SMS */
+       MSG_QUICKPANEL_MMS,                                     /**< Quickpanel MMS */
+       MSG_QUICKPANEL_DELIVER_REP,                     /**< Quickpanel delivery report */
+       MSG_QUICKPANEL_READ_REP,                        /**< Quickpanel message read report */
+       MSG_QUICKPANEL_VOICEMAIL,                       /**< Quickpanel voicemail */
+       MSG_QUICKPANEL_MMS_NOTI,                        /**< Quickpanel MMS notification */
 };
 
+
 /**
- *     @}
+ *     @brief  Enumeration for the values of a count limit for each mailbox.
  */
 enum _MSG_COUNT_LIMIT_MAILBOX_TYPE_E
 {
-       MSG_COUNT_LIMIT_INBOX_TYPE,
-       MSG_COUNT_LIMIT_OUTBOX_TYPE,
-       MSG_COUNT_LIMIT_SENTBOX_TYPE,
-       MSG_COUNT_LIMIT_DRAFTBOX_TYPE,
-       MSG_COUNT_LIMIT_CBMSGBOX_TYPE,
-       MSG_COUNT_LIMIT_MAILBOX_TYPE_MAX,
+       MSG_COUNT_LIMIT_INBOX_TYPE,                             /**< Message count limit of inbox folder*/
+       MSG_COUNT_LIMIT_OUTBOX_TYPE,                    /**< Message count limit of outbox folder*/
+       MSG_COUNT_LIMIT_SENTBOX_TYPE,                   /**< Message count limit of sentbox folder*/
+       MSG_COUNT_LIMIT_DRAFTBOX_TYPE,                  /**< Message count limit of draftbox folder*/
+       MSG_COUNT_LIMIT_CBMSGBOX_TYPE,                  /**< Message count limit of call-back-message-box folder */
+       MSG_COUNT_LIMIT_MAILBOX_TYPE_MAX,               /**< Indicates the maximum number of types of folder message count limits */
 };
 
+
+/**
+ *     @brief  Enumeration for the values of a count limit for each message type.
+ */
 enum _MSG_COUNT_LIMIT_MSG_TYPE_E
 {
-       MSG_COUNT_LIMIT_SMS_TYPE,
-       MSG_COUNT_LIMIT_MMS_TYPE,
-       MSG_COUNT_LIMIT_CB_TYPE,
-       MSG_COUNT_LIMIT_WAPPUSH_TYPE,
-       MSG_COUNT_LIMIT_PROVISION_TYPE,
-       MSG_COUNT_LIMIT_MSG_TYPE_MAX,
+       MSG_COUNT_LIMIT_SMS_TYPE,                               /**< Message count limit for SMS */
+       MSG_COUNT_LIMIT_MMS_TYPE,                               /**< Message count limit for MMS */
+       MSG_COUNT_LIMIT_CB_TYPE,                                /**< Message count limit for callback messages */
+       MSG_COUNT_LIMIT_WAPPUSH_TYPE,                   /**< Message count limit for wappush messages */
+       MSG_COUNT_LIMIT_PROVISION_TYPE,                 /**< Message count limit for provision messages */
+       MSG_COUNT_LIMIT_MSG_TYPE_MAX,                   /**< Indicates maximum number of types of message count limits */
 };
 
+
+/**
+ *     @brief  Enumeration for the values of a storage change type. \n
+ *             This enum is used with storage change callback functions.
+ */
 enum _MSG_STORAGE_CHANGE_TYPE_E
 {
        // msg data
-       MSG_STORAGE_CHANGE_INSERT = 1,
-       MSG_STORAGE_CHANGE_UPDATE,
-       MSG_STORAGE_CHANGE_DELETE,
+       MSG_STORAGE_CHANGE_INSERT = 1,                  /**< Indicates storage change by an INSERT operation*/
+       MSG_STORAGE_CHANGE_UPDATE,                              /**< Indicates storage change by an UPDATE operation*/
+       MSG_STORAGE_CHANGE_DELETE,                              /**< Indicates storage change by a DELETE operation*/
 
        // thread data
-       MSG_STORAGE_CHANGE_CONTACT,
+       MSG_STORAGE_CHANGE_CONTACT,                             /**< Indicates storage change by a CHANGE CONTACT operation*/
 };
 
+/**
+ * @}
+ */
 
 #endif /* MSG_STORAGE_TYPES_H_ */
index f5b9e0d..16c1ec4 100755 (executable)
@@ -1,35 +1,22 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-/**
- *     @file           MapiTransport.h
- *     @brief          Defines transport API of messaging framework
- *     @version        1.0
- */
-
 #ifndef MAPI_TRANSPORT_H
 #define MAPI_TRANSPORT_H
 
-/**
- *     @section                Introduction
- *     - Introduction : Overview on Messaging Transport API
- *     @section                Program
- *     - Program : Messaging Transport API Reference
- */
-
 /*==================================================================================================
                                          INCLUDE FILES
 ==================================================================================================*/
@@ -42,933 +29,522 @@ extern "C"
 #endif
 
 /**
- *     @ingroup                MESSAGING_FRAMEWORK
- *     @defgroup       MESSAGING_TRANSPORT_API Messaging Transport API
- *     @{
- */
-
-/*==================================================================================================
-                                     FUNCTION PROTOTYPES
-==================================================================================================*/
-
-/**
-
- * \par Description:
- * Submits a request to the Messaging Framework.
- *
- * \par Purpose:
- * This API is used to submit a request to the Messaging Framework.
+ * @internal
+ * @ingroup MSG_SERVICE_FRAMEWORK
+ * @defgroup MSG_SERVICE_FRAMEWORK_TRANSPORT_MODULE Transport API
+ * @brief The Transport API provides functions to send SMS/MMS and register incoming/sending/syncML/report callback.
  *
- * \par Typical use case:
- * Submit a request to Messaging Service such as Send Message, Forward etc.
+ * @internal
+ * @addtogroup MSG_SERVICE_FRAMEWORK_TRANSPORT_MODULE
+ * @{
  *
- * \par Method of function operation:
- * Sets up the database connection and inserts the message to message table.
+ * @section MSG_SERVICE_FRAMEWORK_TRANSPORT_MODULE_HEADER Required Header
+ *   \#include <msg_transport.h>
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @section MSG_SERVICE_FRAMEWORK_TRANSPORT_MODULE_OVERVIEW Overview
  *
- * \par Important notes:
- * - The result information will be sent back by using the callback function, msg_sent_status_cb.
- * - Applications MUST fill in the valid message type.
- * -  reqId will be filled in the framework.
+ * The Transport API provides the following functionalities:
  *
- * \param input  - handle is Message handle.
- * \param input  - req is a pointer to an MSG_REQUEST_S structure.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_MSGHANDLE Message handle is invalid.
- * - MSG_ERR_NULL_POINTER                      Pointer is NULL.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * - Sending SMS/MMS messages
+ * - Register incoming message callback
+ * - Register sent status callback
+ * - Register push message application
+ * - Register syncML message callback
+ * - Managing the registration
  *
- * \par Related functions:
- * None
+ * @section MSG_SERVICE_FRAMEWORK_TRANSPORT_MODULE_FEATURE Related Features
+ * This API is related with the following features:\n
+ *  - http://tizen.org/feature/network.telephony\n
+ *  - http://tizen.org/feature/network.telephony.mms\n
  *
- * \par Known issues/bugs:
- * None
+ * It is recommended to design feature related codes in your application for reliability.\n
  *
- * \par Sample code:
- * \code
- * ...
+ * You can check if a device supports the related features for this API by using @ref CAPI_SYSTEM_SYSTEM_INFO_MODULE, thereby controlling the procedure of your application.\n
  *
- * int err = MSG_SUCCESS;
- * MSG_REQUEST_S req;
+ * To ensure your application is only running on the device with specific features, please define the features in your manifest file using the manifest editor in the SDK.\n
  *
- * req.msg = msg;
- * req.sendOpt = sendOpt;
-
- * err = msg_submit_req(msgHandle, &req);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
+ * More details on featuring your application can be found from <a href="../org.tizen.mobile.native.appprogramming/html/ide_sdk_tools/feature_element.htm"><b>Feature Element</b>.</a>
  *
- * ...
- * \endcode
  */
-/*================================================================================================*/
-int msg_submit_req(msg_handle_t handle, msg_struct_t req);
 
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
 
 /**
-
- * \par Description:
- * Registers sent status callback function to Message handle.
+ * @brief Submits a request to the Messaging Framework.
  *
- * \par Purpose:
- * This API is used to register sent status callback function "msg_sent_status_cb" to Message handle.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Typical use case:
- * Register for sent status callback.
+ * @remarks The result information will be sent back by using the callback function, msg_sent_status_cb().
+ * @remarks Applications MUST fill in the valid message type.
+ * @remarks reqId will be filled in the framework.
  *
- * \par Method of function operation:
- * Adds the msg_sent_status_cb API to sent status callback list.
+ * @param[in] handle  The message handle
+ * @param[in] req     The pointer to an #MSG_REQUEST_S structure
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \par Important notes:
- *     This function MUST be called after Message handle is opened.
- *
- * \param input - handle is Message handle.
- * \param input - cb is a function to be called.
- * \param input - user_param is a pointer to user data.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_MSGHANDLE Message handle is invalid.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_TRANSPORT_ERROR   Transport error
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_submit_req(msg_handle_t handle, msg_struct_t req);
+
+
+/**
+ * @brief Registers sent status callback function to Message handle.
+ * @details This API is used to register sent status callback function msg_sent_status_cb() to Message handle.
  *
- * \par Related functions:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Known issues/bugs:
- * None
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in] handle      The message handle
+ * @param[in] cb          The function to be called
+ * @param[in] user_param  A pointer to user data
  *
- * int err = MSG_SUCCESS;
- * MSG_REQUEST_S req;
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * req.msg = msg;
- * req.sendOpt = sendOpt;
-
- * err = msg_reg_sent_status_callback(msgHandle, &sentStatusCB, (void*)"sent status callback");
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- * return;
- * }
-
- * void sentStatusCB(msg_handle_t Handle, MSG_SENT_STATUS_S *pStatus, void *pUserParam)
- * {
- *     ...
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_CALLBACK_ERROR    Callback registration error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_reg_sent_status_callback(msg_handle_t handle, msg_sent_status_cb cb, void *user_param);
 
 
 /**
-
- * \par Description:
- * Registers incoming SMS callback to Message handle.
- *
- * \par Purpose:
- * This API is used to Registers incoming SMS callback function "msg_sms_incoming_cb" to Message handle.
- *
- * \par Typical use case:
- * Register incoming SMS message callback.
- *
- * \par Method of function operation:
- * Adds the msg_sms_incoming_cb API to incoming SMS callback list.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- *     This function MUST be called after Message handle is opened.
- *
- * \param input - handle is Message handle.
- * \param input - cb is a function to be called.
- * \param input - port is used for listening. If port is not used, please assign 0 to it.
- * \param input - user_param is a pointer to user data.
+ * @brief Registers incoming SMS callback to Message handle.
+ * @details This API is used to Registers incoming SMS callback function msg_sms_incoming_cb() to Message handle.
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_MSGHANDLE Message handle is invalid.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in] handle      The message handle
+ * @param[in] cb          The function to be called
+ * @param[in] port        The port used for listening \n
+ *                        If port is not used, set to @c 0.
+ * @param[in] user_param  A pointer to user data
  *
- * int err = MSG_SUCCESS;
- * MSG_REQUEST_S req;
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * req.msg = msg;
- * req.sendOpt = sendOpt;
-
- * err = msg_reg_sms_message_callback(msgHandle, &incomingSmsCB, 0, (void*)"sms message callback");
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- * return;
- * }
- *
- * void incomingSmsCB(msg_handle_t Handle, msg_message_t msg, void *pUserParam)
- * {
- *     ...
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_CALLBACK_ERROR    Callback registration error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_reg_sms_message_callback(msg_handle_t handle, msg_sms_incoming_cb cb, unsigned short port, void *user_param);
 
 
 /**
-
- * \par Description:
- * Registers incoming MMS callback to Message handle.
- *
- * \par Purpose:
- * This API is used to Registers incoming MMS callback function "msg_mms_conf_msg_incoming_cb" to Message handle.
- *
- * \par Typical use case:
- * Register incoming SMS message callback.
- *
- * \par Method of function operation:
- * Adds the msg_mms_conf_msg_incoming_cb API to incoming MMS callback list.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- *     This function MUST be called after Message handle is opened.
- *
- * \param input - handle is Message handle.
- * \param input - handle is Message handle.
- * \param input - cb is a function to be called.
- * \param input - app_id is used for listening. If appId is not used, please assign NULL to it.
- * \param input - user_param is a pointer to user data.
+ * @brief Registers incoming MMS conf callback to Message handle.
+ * @details This API is used to Registers incoming MMS conf callback function msg_mms_conf_msg_incoming_cb() to Message handle.
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_MSGHANDLE Message handle is invalid.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in] handle      The message handle
+ * @param[in] cb          The function to be called
+ * @param[in] app_id      The app ID used for listening \n
+ *                        If appId is not used, set to @c NULL.
+ * @param[in] user_param  A pointer to user data
  *
- * int err = MSG_SUCCESS;
- * MSG_REQUEST_S req;
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * req.msg = msg;
- * req.sendOpt = sendOpt;
-
- * err = msg_reg_mms_conf_message_callback(msgHandle, &incomingMmsConfCB, NULL, NULL);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- * return;
- * }
- *
- * void incomingMmsConfCB(msg_handle_t Handle, msg_message_t msg, void *pUserParam)
- * {
- *     ...
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_CALLBACK_ERROR    Callback registration error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_reg_mms_conf_message_callback(msg_handle_t handle, msg_mms_conf_msg_incoming_cb cb, const char *app_id, void *user_param);
 
 
 /**
-
- * \par Description:
- * Registers incoming SyncML Message callback to Message handle.
- *
- * \par Purpose:
- * This API is used to Registers incoming SyncML Message callback function "msg_syncml_msg_incoming_cb" to Message handle.
- *
- * \par Typical use case:
- * Register incoming SMS message callback.
- *
- * \par Method of function operation:
- * Adds the msg_syncml_msg_incoming_cb API to incoming SyncML callback list.
- *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- *     This function MUST be called after Message handle is opened.
- *
- * \param input - handle is Message handle.
- * \param input - cb is a function to be called.
- * \param input - user_param is a pointer to user data.
+ * @brief Registers incoming SyncML Message callback to Message handle.
+ * @details This API is used to register incoming SyncML Message callback function msg_syncml_msg_incoming_cb() to Message handle.
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                                       Success in operation.
- * - MSG_ERR_MSGHANDLE_NOT_CONNECTED   Message handle is not connected.
- * - MSG_ERR_MEMORY_ERROR                              Memory is error.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * \par Sample code:
- * \code
- * ...
+ * @param[in] handle      The message handle
+ * @param[in] cb          The function to be called
+ * @param[in] user_param  A pointer to user data
  *
- * int err = MSG_SUCCESS;
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * err = err = msg_reg_syncml_message_callback(msgHandle, &syncMLCB, NULL);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- * return;
- * }
- *
- * void syncMLCB(msg_handle_t hMsgHandle, msg_syncml_message_type_t msgType, const char* pPushHeader, int PushHeaderLen, const char* pPushBody, int PushBodyLen, void *pUserParam)
- * {
- *     ...
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_CALLBACK_ERROR    Callback registration error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_reg_syncml_message_callback(msg_handle_t handle,  msg_syncml_msg_incoming_cb cb, void *user_param);
 
 
 /**
-
- * \par Description:
- * Registers incoming LBS Message callback to Message handle.
+ * @brief Registers incoming LBS Message callback to Message handle.
+ * @details This API is used to register incoming LBS Message callback function msg_lbs_msg_incoming_cb() to Message handle.
  *
- * \par Purpose:
- * This API is used to Registers incoming LBS Message callback function "msg_lbs_msg_incoming_cb" to Message handle.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Typical use case:
- * Register incoming SMS message callback.
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * \par Method of function operation:
- * Adds the msg_lbs_msg_incoming_cb API to incoming LBS Message callback list.
+ * @param[in] handle      The message handle
+ * @param[in] cb          The function to be called
+ * @param[in] user_param  A pointer to user data
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \par Important notes:
- *     This function MUST be called after Message handle is opened.
- *
- * \param input - handle is Message handle.
- * \param input - cb is a function to be called.
- * \param input - user_param is a pointer to user data.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                                       Success in operation.
- * - MSG_ERR_MSGHANDLE_NOT_CONNECTED   Message handle is not connected.
- * - MSG_ERR_MEMORY_ERROR                              Memory is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * int err = MSG_SUCCESS;
- *
- * err = msg_reg_lbs_message_callback(msgHandle, &lbsCB, NULL);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- * return;
- * }
- *
- * void lbsCB(msg_handle_t hMsgHandle, const char* pPushHeader, const char* pPushBody, int pushBodyLen, void *pUserParam)
- * {
- *     ...
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_CALLBACK_ERROR    Callback registration error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_reg_lbs_message_callback(msg_handle_t handle, msg_lbs_msg_incoming_cb cb, void *user_param);
 
 
 /**
-
- * \par Description:
- * Registers incoming LBS Message callback to Message handle.
- *
- * \par Purpose:
- * This API is used to Registers incoming LBS Message callback function "msg_lbs_msg_incoming_cb" to Message handle.
+ * @brief Registers SyncML operation callback to Message handle.
+ * @details This API is used to register SyncML operation callback function msg_syncml_msg_operation_cb() to Message handle.
  *
- * \par Typical use case:
- * Register incoming SMS message callback.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Method of function operation:
- * Adds the msg_lbs_msg_incoming_cb API to incoming LBS Message callback list.
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @param[in] handle      The message handle
+ * @param[in] cb          The function to be called
+ * @param[in] user_param  A pointer to user data
  *
- * \par Important notes:
- *     This function MUST be called after Message handle is opened.
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \param input - handle is Message handle.
- * \param input - cb is a function to be called.
- * \param input - user_param is a pointer to user data.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                                       Success in operation.
- * - MSG_ERR_MSGHANDLE_NOT_CONNECTED   Message handle is not connected.
- * - MSG_ERR_MEMORY_ERROR                              Memory is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * int err = MSG_SUCCESS;
- *
- * err = msg_reg_lbs_message_callback(msgHandle, &lbsCB, NULL);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- * return;
- * }
- *
- * void lbsCB(msg_handle_t hMsgHandle, const char* pPushHeader, const char* pPushBody, int pushBodyLen, void *pUserParam)
- * {
- *     ...
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_CALLBACK_ERROR    Callback registration error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_reg_syncml_message_operation_callback(msg_handle_t handle,  msg_syncml_msg_operation_cb cb, void *user_param);
 
 
 /**
-
- * \par Description:
- * Registers incoming LBS Message callback to Message handle.
- *
- * \par Purpose:
- * This API is used to Registers incoming LBS Message callback function "msg_lbs_msg_incoming_cb" to Message handle.
- *
- * \par Typical use case:
- * Register incoming SMS message callback.
+ * @brief Registers incoming push Message callback to Message handle.
+ * @details This API is used to register incoming push Message callback function msg_push_msg_incoming_cb() to Message handle.
  *
- * \par Method of function operation:
- * Adds the msg_lbs_msg_incoming_cb API to incoming LBS Message callback list.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * \par Important notes:
- *     This function MUST be called after Message handle is opened.
+ * @param[in] handle      The message handle
+ * @param[in] cb          The function to be called
+ * @param[in] app_id      The app ID for listening \n
+ *                        If appId is not used, set to @c NULL.
+ * @param[in] user_param  A pointer to user data
  *
- * \param input - handle is Message handle.
- * \param input - cb is a function to be called.
- * \param input - user_param is a pointer to user data.
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                                       Success in operation.
- * - MSG_ERR_MSGHANDLE_NOT_CONNECTED   Message handle is not connected.
- * - MSG_ERR_MEMORY_ERROR                              Memory is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_CALLBACK_ERROR    Callback registration error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_reg_push_message_callback(msg_handle_t handle,  msg_push_msg_incoming_cb cb, const char *app_id, void *user_param);
+
+
+/**
+ * @brief Registers incoming CB Message callback to Message handle.
+ * @details This API is used to register incoming CB Message callback function msg_cb_incoming_cb() to Message handle.
  *
- * \par Known issues/bugs:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Sample code:
- * \code
- * ...
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * int err = MSG_SUCCESS;
+ * @param[in] handle      The message handle
+ * @param[in] cb          The function to be called
+ * @param[in] bsave       A bool flag to indicate whether CB message is to be saved or not \n
+ *                        CB message will be saved if this flag is true
+ * @param[in] user_param  A pointer to user data
  *
- * err = msg_reg_lbs_message_callback(msgHandle, &lbsCB, NULL);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- * return;
- * }
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * void lbsCB(msg_handle_t hMsgHandle, const char* pPushHeader, const char* pPushBody, int pushBodyLen, void *pUserParam)
- * {
- *     ...
- * }
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_CALLBACK_ERROR    Callback registration error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_syncml_message_operation(msg_handle_t handle,  msg_message_id_t msgId);
 
+int msg_reg_cb_message_callback(msg_handle_t handle, msg_cb_incoming_cb  cb, bool bsave, void *user_param);
 
-/**
 
- * \par Description:
- * Sends SMS. It is a synchronous API which has been blocked until sent status arrives.
- *
- * \par Purpose:
- * This API is used to sends SMS.
- *
- * \par Typical use case:
- * Sends a SMS Message
- *
- * \par Method of function operation:
- * It is a synchronous API which has been blocked until sent status arrives.
+
+/**
+ * @brief Registers incoming Report Message callback to Message handle.
+ * @details This API is used to register incoming Report Message callback function msg_report_msg_incoming_cb() to Message handle.
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Important notes:
- * - None
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * \param input  - phone_num is the list of phone numbers. It is separated by ",".
- * \param input  - sms_text is a SMS text.
- * \param input  - cb is a function to be called.
- * \param input  - user_param is for user data.
+ * @param[in] handle      The message handle
+ * @param[in] cb          The function to be called
+ * @param[in] user_param  A pointer to user data
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                               Success in operation.
- * - MSG_ERR_NULL_POINTER              Invalid parameter.
- * - MSG_ERR_MEMORY_ERROR      Memory is error.
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_CALLBACK_ERROR    Callback registration error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
+ */
+
+int msg_reg_report_message_callback(msg_handle_t handle, msg_report_msg_incoming_cb cb, void *user_param);
+
+
+/**
+ * @brief Operates SyncML message.
+ * @details This API is used to run SyncML operation.
  *
- * \par Known issues/bugs:
- * None
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.read
  *
- * \par Sample code:
- * \code
- * ...
+ * @remarks This function MUST be called after Message handle is opened.
  *
- * int err = MSG_SUCCESS;
+ * @param[in] handle  The message handle
+ * @param[in] msgId   The message ID to run SycnML operation
  *
- * err = msg_sms_send("01000000000,01000000000", "1234567890", sentStatusCB, NULL);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_TRANSPORT_ERROR   Transport error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
-int msg_sms_send(const char *phone_num, const char *sms_text, msg_simple_sent_status_cb cb, void *user_param);
 
+int msg_syncml_message_operation(msg_handle_t handle,  msg_message_id_t msgId);
 
-/**
 
- * \par Description:
- * Submits request to send SMS message.
- *
- * \par Purpose:
- * This API is used to submit request to send SMS message.
- *
- * \par Typical use case:
- * Submits request to send SMS message.
- *
- * \par Method of function operation:
- * Submits a request to send SMS.
+/**
+ * @brief Sends SMS.
+ * @details This API is used to send SMS. It is a synchronous API which has been blocked until sent status arrives.
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Important notes:
- * - None
+ * @param[in] phone_num   The list of phone numbers \n
+ *                        It is separated by ",".
+ * @param[in] sms_text    The SMS text
+ * @param[in] cb          The function to be called
+ * @param[in] user_param  The user data
  *
- * \param input  - phone_num is the list of phone numbers. It is separated by ",".
- * \param input  - sms_text is a SMS text.
- * \param input  - cb is a function to be called.
- * \param input  - user_param is for user data.
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                               Success in operation.
- * - MSG_ERR_NULL_POINTER              Invalid parameter.
- * - MSG_ERR_MEMORY_ERROR      Memory is error.
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_MEMORY_ERROR      Memory error
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  *
  * \par Prospective clients:
  * External/Native Apps using Messaging Services.
  *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
+ */
+
+int msg_sms_send(const char *phone_num, const char *sms_text, msg_simple_sent_status_cb cb, void *user_param);
+
+
+/**
+ * @brief Submits request to send SMS message.
+ * @details This API is used to submit request to send SMS message.
  *
- * int err = MSG_SUCCESS;
- * MSG_REQUEST_S req;
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * req.msg = msg;
- * req.sendOpt = sendOpt;
+ * @param[in] handle The message handle
+ * @param[in] req    A pointer to #msg_struct_t structure for SMS request information
  *
- * err = msg_sms_send_message(msgHandle, &req);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_NULL_POINTER      Null parameter
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_sms_send_message(msg_handle_t handle, msg_struct_t req);
 
 
 /**
-
- * \par Description:
- * Submits request to send MMS message.
- *
- * \par Purpose:
- * This API is used to submit request to send MMS message.
+ * @brief Submits request to send MMS message.
+ * @details This API is used to submit request to send MMS message.
  *
- * \par Typical use case:
- * Submits request to send MMS message.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Method of function operation:
- * Submits a request to send MMS.
+ * @param[in] handle The message handle
+ * @param[in] req    A pointer to #msg_struct_t structure for MMS request information
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \par Important notes:
- * - None
- *
- * \param input  - handle is Message handle.
- * \param input  - req is a pointer to an MSG_REQUEST_S structure.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                               Success in operation.
- * - MSG_ERR_NULL_POINTER              Invalid parameter.
- * - MSG_ERR_MEMORY_ERROR      Memory is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * int err = MSG_SUCCESS;
- * MSG_REQUEST_S req;
- *
- * req.msg = msg;
- * req.sendOpt = sendOpt;
- *
- * err = msg_mms_send_message(msgHandle, &req);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_mms_send_message(msg_handle_t handle, msg_struct_t req);
 
 
 /**
-
- * \par Description:
- * Submits request to send MMS read report request.
+ * @brief Submits request to send MMS read report request.
+ * @details This API is used to submit request to send MMS read report request.
  *
- * \par Purpose:
- * This API is used to submit request to send MMS read report request.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Typical use case:
- * Submits request to send MMS read report request.
+ * @param[in] handle          The message handle
+ * @param[in] msg_id          The message ID \n
+ *                            This is a positive integer.
+ * @param[in] mms_read_status This is status whether message was read or not
  *
- * \par Method of function operation:
- * Submits a request to send MMS read report request.
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input  - handle is Message handle.
- * \param input  - msg_id is a message id, which is a positive integer.
- * \param input  - mms_read_status is status whether message was read or not.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                               Success in operation.
- * - MSG_ERR_NULL_POINTER              Invalid parameter.
- * - MSG_ERR_MEMORY_ERROR      Memory is error.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * int err = MSG_SUCCESS;
- *
- * err = err = msg_mms_send_read_report(NULL, 0, MSG_READ_REPORT_IS_READ);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_mms_send_read_report(msg_handle_t handle, msg_message_id_t msgId, msg_read_report_status_t mms_read_status);
 
 
 /**
-
- * \par Description:
- * Submits request to send forward MMS request.
+ * @brief Submits request to send forward MMS request.
+ * @details This API is used to submit request to send forward MMS request.
  *
- * \par Purpose:
- * This API is used to submit request to send forward MMS request.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Typical use case:
- * Submits request to send forward MMS request.
+ * @param[in] handle The message handle
+ * @param[in] req    A pointer to #msg_struct_t structure for MMS
  *
- * \par Method of function operation:
- * Submits a request to send forward MMS request.
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input  - handle is Message handle.
-  * \param input  - req is a pointer to an MSG_REQUEST_S structure.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_MSGHANDLE         Message handle is invalid.
- * - MSG_ERR_NULL_POINTER                              Pointer is NULL.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * int err = MSG_SUCCESS;
- *
- * err = err = msg_mms_send_read_report(NULL, 0, MSG_READ_REPORT_IS_READ);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_mms_forward_message(msg_handle_t handle, msg_struct_t req);
 
 
 /**
-
- * \par Description:
- * Submits request to retrieve MMS request.
+ * @brief Submits request to retrieve MMS request.
+ * @details This API is used to submit request to retrieve MMS request.
  *
- * \par Purpose:
- * This API is used to submit request to retrieve MMS request.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Typical use case:
- * Submits request to retrieve MMS request.
+ * @param[in] handle  The message handle
+ * @param[in] req     A pointer to #msg_struct_t structure for MMS
  *
- * \par Method of function operation:
- * Submits a request to send forward MMS request.
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input  - handle is Message handle.
-  * \param input  - req is a pointer to an MSG_REQUEST_S structure.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_MSGHANDLE         Message handle is invalid.
- * - MSG_ERR_NULL_POINTER                              Pointer is NULL.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * int err = MSG_SUCCESS;
- *
- * err = msg_mms_retrieve_message(handle, &req);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_mms_retrieve_message(msg_handle_t handle, msg_struct_t req);
 
 
-/* reject_msg_support */
 /**
-
- * \par Description:
- * Submits request to reject MMS message.
+ * @brief Submits request to reject MMS message.
+ * @details This API is used to submit request to reject MMS message.
  *
- * \par Purpose:
- * This API is used to submit request to reject MMS message.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/message.write
  *
- * \par Typical use case:
- * Submits request to reject MMS message.
+ * @param[in] handle  The message handle
+ * @param[in] req     A pointer to #msg_struct_t structure for MMS
  *
- * \par Method of function operation:
- * Submits a request to send forward reject MMS message.
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
  *
- * \par Sync (or) Async:
- * This is a Synchronous API.
- *
- * \par Important notes:
- * - None
- *
- * \param input  - handle is Message handle.
-  * \param input  - req is a pointer to an MSG_REQUEST_S structure.
- *
- * \return Return Type (int(msg_error_t)) \n
- * - MSG_SUCCESS                                       Success in operation.
- * - MSG_ERR_INVALID_MSGHANDLE         Message handle is invalid.
- * - MSG_ERR_NULL_POINTER                              Pointer is NULL.
- *
- * \par Prospective clients:
- * External/Native Apps using Messaging Services.
- *
- * \par Related functions:
- * None
- *
- * \par Known issues/bugs:
- * None
- *
- * \par Sample code:
- * \code
- * ...
- *
- * int err = MSG_SUCCESS;
- *
- * err = msg_mms_reject_message(handle, &req);
- * if (err != MSG_SUCCESS)
- * {
- * ...
- * }
- *
- * ...
- * \endcode
+ * @retval MSG_SUCCESS               Success in operation
+ * @retval MSG_ERR_INVALID_PARAMETER Input parameter is invalid
+ * @retval MSG_ERR_PERMISSION_DENIED The application does not have the privilege to call this method
+ * @retval MSG_ERR_NOT_SUPPORTED     Not supported
  */
-/*================================================================================================*/
+
 int msg_mms_reject_message(msg_handle_t handle, msg_struct_t req);
 
 /**
index 58229a5..d27811f 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_TRANSPORT_TYPES_H_
 #include "msg_types.h"
 #include "msg_storage_types.h"
 
+/**
+ * @internal
+ * @addtogroup MSG_SERVICE_FRAMEWORK_TRANSPORT_MODULE
+ * @{
+ */
+
 
 /*==================================================================================================
                                     DEFINES
 ==================================================================================================*/
 
-/**    @brief  Prototype of the function that will be called when the status of the message which is already sent is changed.
- *     Applications SHOULD implement this callback function and register it into Message handle.
- *     For how to register this callback function, please refer to msg_reg_sent_status_callback.
- *     If the application sends a message, this callback function will be called to report its sending status.
- *     The application can get the request ID from sent_status to know which request is bound.
- *     The callback function runs in the application process, not in the framework process.
- *     The memory of sent_status is managed by MAPI, when the callback function is finished.
- *     @param[in]      handle is Message handle.
- *     @param[in]      sent_status is a pointer to an MSG_SENT_STATUS_S structure.
- *     @param[in]      user_param is a pointer to user data.
- *     @return void
+/**    @brief  Called when the status of the message which is already sent is changed.
+ *              Applications SHOULD implement this callback function and register it into Message handle.
+ *              For how to register this callback function, please refer to msg_reg_sent_status_callback().
+ *              If the application sends a message, this callback function will be called to report its sending status.
+ *              The application can get the request ID from sent_status to know which request is bound.
+ *              The callback function runs in the application process, not in the framework process.
+ *              The memory of @a sent_status is managed by MAPI, when the callback function is finished.
+ *
+ * @param[in]  handle       The Message handle
+ * @param[in]  sent_status  A pointer to #msg_struct_t structure for sent status
+ * @param[in]  user_param   The user data
  */
 typedef void (*msg_sent_status_cb)(msg_handle_t handle, msg_struct_t sent_status, void *user_param);
 
 
-/**    @brief  Prototype of the function that will be called when the status of the message which is already sent is changed.
- *     Applications SHOULD implement this callback function and register it into Message handle.
- *     For how to register this callback function, please refer to msg_reg_sent_status_callback.
- *     If the application sends a message, this callback function will be called to report its sending status.
- *     The application can get the request ID from sent_status to know which request is bound.
- *     The callback function runs in the application process, not in the framework process.
- *     The memory of sent_status is managed by MAPI, when the callback function is finished.
- *     @param[in]      sent_status is a pointer to an MSG_SENT_STATUS_S structure.
- *     @param[in]      user_param is a pointer to user data.
- *     @return void
+/**    @brief  Called when the status of the message which is already sent is changed.
+ *              Applications SHOULD implement this callback function and register it into Message handle.
+ *              For how to register this callback function, please refer to msg_reg_sent_status_callback().
+ *              If the application sends a message, this callback function will be called to report its sending status.
+ *              The application can get the request ID from sent_status to know which request is bound.
+ *              The callback function runs in the application process, not in the framework process.
+ *              The memory of @a sent_status is managed by MAPI, when the callback function is finished.
+ *
+ * @param[in]  sent_status  A pointer to #msg_struct_t structure for sent status
+ * @param[in]  user_param   The pointer to user data
  */
 typedef void (*msg_simple_sent_status_cb)(msg_struct_t sent_status, void *user_param);
 
 
-/** @brief     Prototype of the function that will be called when a new message is received.
- *     Applications SHOULD implement this callback function and register it into Message handle.
- *     For how to register this callback function, please refer to msg_reg_sms_message_callback.
- *     This callback function will be called when a new message is received and the message satisfies the filter list.
- *     The callback function runs in the application process, not in the framework process.
- *     The memory for msg is managed by MAPI, when the callback function is finished.
- *     @param[in]      handle is Message handle.
- *     @param[in]      msg is a pointer to an msg_message_t structure.
- *     @param[in]      user_param is a pointer to user data.
- *     @return void
+/** @brief     Called when a new message is received.
+ *              Applications SHOULD implement this callback function and register it into Message handle.
+ *              For how to register this callback function, please refer to msg_reg_sms_message_callback().
+ *              This callback function will be called when a new message is received and the message satisfies the filter list.
+ *              The callback function runs in the application process, not in the framework process.
+ *              The memory for msg is managed by MAPI, when the callback function is finished.
+ *
+ * @param[in]  handle       The Message handle
+ * @param[in]  msg          A pointer to #msg_struct_t structure for message details
+ * @param[in]  user_param   The user data
  */
 typedef void (*msg_sms_incoming_cb)(msg_handle_t handle, msg_struct_t msg, void *user_param);
 
 
-/** @brief     Prototype of the function that will be called when a new MMS message is received.
- *     Applications SHOULD implement this callback function and register it into Message handle.
- *     For how to register this callback function, please refer to msg_reg_mms_conf_message_callback.
- *     This callback function will be called when a new MMS message is received and the message satisfies the filter list.
- *     The callback function runs in the application process, not in the framework process.
- *     The memory for msg is managed by MAPI, when the callback function is finished.
- *     @param[in]      handle is Message handle.
- *     @param[in]      msg is a pointer to an msg_message_t structure.
- *     @param[in]      user_param is a pointer to user data.
- *     @return void
+/** @brief     Called when a new MMS message is received.
+ *              Applications SHOULD implement this callback function and register it into Message handle.
+ *              For how to register this callback function, please refer to msg_reg_mms_conf_message_callback().
+ *              This callback function will be called when a new MMS message is received and the message satisfies the filter list.
+ *              The callback function runs in the application process, not in the framework process.
+ *              The memory for @a msg is managed by MAPI, when the callback function is finished.
+ *
+ * @param[in]  handle      The Message handle
+ * @param[in]  msg         A pointer to #msg_struct_t structure for message details
+ * @param[in]  user_param  The user data
  */
 typedef void (*msg_mms_conf_msg_incoming_cb)(msg_handle_t handle, msg_struct_t msg, void *user_param);
 
 
-/** @brief     Prototype of the function that will be called when a new SyncML message is received.
- *     Applications SHOULD implement this callback function and register it into Message handle.
- *     For how to register this callback function, please refer to msg_reg_syncml_message_callback.
- *     This callback function will be called when a new message is received and the message satisfies the filter list.
- *     The callback function runs in the application process, not in the framework process.
- *     @param[in]      handle is Message handle.
- *     @param[in]      msg_type is msg_syncml_message_type_t structure.
- *     @param[in]      push_body is WAP Push body data.
- *     @param[in]      push_body_len is the length of WAP Push body data.
- *     @param[in]      user_param is a pointer to user data.
- *     @return void
+/** @brief     Called when a new SyncML message is received.
+ *              Applications SHOULD implement this callback function and register it into Message handle.
+ *              For how to register this callback function, please refer to msg_reg_syncml_message_callback().
+ *              This callback function will be called when a new message is received and the message satisfies the filter list.
+ *              The callback function runs in the application process, not in the framework process.
+ *
+ * @param[in]  handle         The Message handle
+ * @param[in]  msg_type       The #msg_syncml_message_type_t structure
+ * @param[in]  push_body      The WAP Push body data
+ * @param[in]  push_body_len  The length of WAP Push body data
+ * @param[in]  sim_index      The index of the sim on which message is received.
+ * @param[in]  user_param     The user data
  */
-typedef void (*msg_syncml_msg_incoming_cb)(msg_handle_t handle, msg_syncml_message_type_t msg_type, const char *push_body, int push_body_len, const char* wsp_header, int wsp_header_len, void *user_param);
-
-
-/** @brief     Prototype of the function that will be called when a new LBS message is received.
- *     Applications SHOULD implement this callback function and register it into Message handle.
- *     For how to register this callback function, please refer to msg_reg_lbs_message_callback.
- *     This callback function will be called when a new message is received and the message satisfies the filter list.
- *     The callback function runs in the application process, not in the framework process.
- *     @param[in]      hMsgHandle is Message handle.
- *     @param[in]      push_header is push message header data.
- *     @param[in]      push_body is push message body data.
- *     @param[in]      push_body_len is push message body length.
- *     @param[in]      user_param is a pointer to user data.
- *     @return void
+typedef void (*msg_syncml_msg_incoming_cb)(msg_handle_t handle, msg_syncml_message_type_t msg_type, const char *push_body, int push_body_len, const char* wsp_header, int wsp_header_len, int sim_index, void *user_param);
+
+
+/** @brief     Called when a new LBS message is received.
+ *              Applications SHOULD implement this callback function and register it into Message handle.
+ *              For how to register this callback function, please refer to msg_reg_lbs_message_callback().
+ *              This callback function will be called when a new message is received and the message satisfies the filter list.
+ *              The callback function runs in the application process, not in the framework process.
+ *
+ * @param[in]  hMsgHandle     The Message handle
+ * @param[in]  push_header    The push message header data
+ * @param[in]  push_body      The push message body data
+ * @param[in]  push_body_len  The push message body length
+ * @param[in]  user_param     The user data
  */
 typedef void (*msg_lbs_msg_incoming_cb)(msg_handle_t handle, const char *push_header, const char *push_body, int push_body_len, void *user_param);
 
 
-/** @brief     Prototype of the function that will be called when a new SyncML message is received.
- *     Applications SHOULD implement this callback function and register it into Message handle.
- *     For how to register this callback function, please refer to msg_reg_syncml_message_callback.
- *     This callback function will be called when a new message is received and the message satisfies the filter list.
- *     The callback function runs in the application process, not in the framework process.
- *     @param[in]      handle is Message handle.
- *     @param[in]      user_param is a pointer to user data.
- *     @return void
+/** @brief     Called when a new SyncML message is received.
+ *              Applications SHOULD implement this callback function and register it into Message handle.
+ *              For how to register this callback function, please refer to msg_reg_syncml_message_callback().
+ *              This callback function will be called when a new message is received and the message satisfies the filter list.
+ *              The callback function runs in the application process, not in the framework process.
+ *
+ * @param[in]  handle      The Message handle
+ * @param[in]  msgId       The message ID
+ * @param[in]  extId       The external ID
+ * @param[in]  user_param  The user data
  */
 typedef void (*msg_syncml_msg_operation_cb)(msg_handle_t handle, int msgId, int extId, void *user_param);
 
 
+/** @brief     Called when a new push message is received.
+ *              Applications SHOULD implement this callback function and register it into Message handle.
+ *              For how to register this callback function, please refer to msg_reg_push_message_callback().
+ *              This callback function will be called when a new message is received and the message satisfies the filter list.
+ *              The callback function runs in the application process, not in the framework process.
+ *
+ * @param[in]  handle         The Message handle
+ * @param[in]  push_header    The push message header data
+ * @param[in]  push_body      The push message body data
+ * @param[in]  push_body_len  The push message body length
+ * @param[in]  user_param     The user data
+ */
+typedef void (*msg_push_msg_incoming_cb)(msg_handle_t handle, const char *push_header, const char *push_body, int push_body_len, void *user_param);
+
+
+/** @brief     Called when a new CB message is received.
+ *              Applications SHOULD implement this callback function and register it into Message handle.
+ *              For how to register this callback function, please refer to msg_reg_cb_message_callback().
+ *              This callback function will be called when a new message is received and the message satisfies the filter list.
+ *              The callback function runs in the application process, not in the framework process.
+ *
+ * @param[in]  handle      The Message handle
+ * @param[in]  msg         A pointer to #msg_struct_t structure for message details
+ * @param[in]  user_param  The user data
+ */
+typedef void (*msg_cb_incoming_cb)(msg_handle_t handle, msg_struct_t msg, void *user_param);
+
+
+/** @brief     Called when a report message is received.
+ *              Applications SHOULD implement this callback function and register it into Message handle.
+ *              For how to register this callback function, please refer to msg_reg_report_message_callback().
+ *              This callback function will be called when a new message is received and the message satisfies the filter list.
+ *              The callback function runs in the application process, not in the framework process.
+ *
+ * @param[in]  handle         The Message handle
+ * @param[in]  reportMsgType  The message type of incoming report message
+ * @param[in]  MsgId          The message ID of reported message
+ * @param[in]  addr_len       The incoming report message's address length
+ * @param[in]  addr_val       The incoming report message's address value
+ * @param[in]  user_param     The user data
+ */
+typedef void (*msg_report_msg_incoming_cb)(msg_handle_t handle, msg_report_type_t reportMsgType, msg_message_id_t MsgId, int addr_len, const char *addr_val, void *user_param);
+
+/**
+ * @}
+ */
 
 #endif /* MSG_TRANSPORT_TYPES_H_ */
index 491c2f6..3cfa5ab 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_TYPES_H_
 #define EXPORT_API __attribute__ ((visibility("default")))
 #endif
 
-#define MAX_TO_ADDRESS_CNT             10
-#define MAX_PHONE_NUMBER_LEN   20
+/**
+ * @internal
+ * @addtogroup MSG_SERVICE_FRAMEWORK
+ * @{
+ */
+
+/**
+ * @brief      Definition for maximum address count
+ */
+#define MAX_TO_ADDRESS_CNT 10
+
+/**
+ * @brief      Definition for maximum phone number length
+ */
+#define MAX_PHONE_NUMBER_LEN 20
+
+/**
+ * @brief      Definition for maximum XDN alpha ID length
+ */
+#define MAX_SIM_XDN_ALPHA_ID_LEN 30
+/**
+ * @brief      Definition for maximum address value length
+ */
 #define MAX_ADDRESS_VAL_LEN    254
-#define MAX_SIGN_VAL_LEN               128
-#define MAX_SUBJECT_LEN                        120
-#define MAX_DISPLAY_NAME_LEN   195
-#define MAX_IMAGE_PATH_LEN             1024
-#define MAX_MSG_DATA_LEN               320
-#define MAX_MSG_TEXT_LEN               1530
-#define MAX_FILTER_VALUE_LEN   40
-#define MAX_COMMAND_LEN                1024
-#define MAX_FOLDER_NAME_SIZE           20
-
-#define MAX_WAPPUSH_ID_LEN                     40
-#define MAX_WAPPUSH_HREF_LEN           300
-#define MAX_WAPPUSH_CONTENTS_LEN       2048
 
+/**
+ * @brief      Definition for maximum subject length
+ */
+#define MAX_SUBJECT_LEN 120
+
+/**
+ * @brief      Definition for maximum display length length
+ */
+#define MAX_DISPLAY_NAME_LEN 195
+
+/**
+ * @brief      Definition for maximum image path length
+ */
+#define MAX_IMAGE_PATH_LEN 1024
+
+/**
+ * @brief      Definition for maximum message data length
+ */
+#define MAX_MSG_DATA_LEN 320
+
+/**
+ * @brief      Definition for maximum message text length
+ */
+#define MAX_MSG_TEXT_LEN 1530
+
+/**
+ * @brief      Definition for maximum filter value length
+ */
+#define MAX_FILTER_VALUE_LEN 128
+
+/**
+ * @brief      Definition for maximum command length
+ */
+#define MAX_COMMAND_LEN 1024
+
+/**
+ * @brief      Definition for maximum folder name size
+ */
+#define MAX_FOLDER_NAME_SIZE 20
+
+/**
+ * @brief      Definition for maximum ID length of push message
+ */
+#define MAX_WAPPUSH_ID_LEN 100
+
+/**
+ * @brief      Definition for maximum content type length of push message
+ */
+#define MAX_WAPPUSH_CONTENT_TYPE_LEN 100
+
+/**
+ * @brief      Definition for maximum href length of push message
+ */
+#define MAX_WAPPUSH_HREF_LEN 300
+
+/**
+ * @brief      Definition for maximum contents length of push message
+ */
+#define MAX_WAPPUSH_CONTENTS_LEN 2048
+
+/**
+ * @brief      Definition for maximum invalid object count of push message(CO)
+ */
 #define MAX_PUSH_CACHEOP_INVALID_OBJECT_MAX    5
-#define MAX_PUSH_CACHEOP_INVALID_SERVICE_MAX   5
-#define MAX_PUSH_CACHEOP_MAX_URL_LEN                   200
 
-#define MAX_COMMON_INFO_SIZE   20
+/**
+ * @brief      Definition for maximum invalid service count of push message(CO)
+ */
+#define MAX_PUSH_CACHEOP_INVALID_SERVICE_MAX 5
 
 /**
- *     @brief  Defines the maximum file path length
+ * @brief      Definition for maximum URL length of push message(CO)
  */
-#define        MSG_FILEPATH_LEN_MAX    1024
+#define MAX_PUSH_CACHEOP_MAX_URL_LEN 200
+
+/**
+ * @brief      Definition for maximum segment count
+ */
+#define MAX_SEGMENT_NUM 15
+
+/**
+ * @brief      Definition for maximum file path length
+ */
+#define        MSG_FILEPATH_LEN_MAX 1024
 
 // setting
-#define SMSC_NAME_MAX                  127             /* Max SMSC Name Length */
-#define SMSC_ADDR_MAX                  20              /* Max SMSC Adress Length  */
-#define SMSC_LIST_MAX                  5               /* Max List Count of SMSC */
-#define CB_CHANNEL_NAME_MAX    32              /* cb channel name max size */
-#define CB_CHANNEL_MAX                 30              /* cb channel max count */
-#define CB_LANG_TYPE_MAX               10
+/**
+ * @brief      Definition for maximum SMSC name length
+ */
+#define SMSC_NAME_MAX 127
 
 /**
- *     @brief  Defines the maximum file name length
+ * @brief      Definition for maximum SMSC address length
  */
-#define        MSG_FILENAME_LEN_MAX            255
+#define SMSC_ADDR_MAX 21
 
 /**
- *     @brief  Defines the maximum message id length
+ * @brief      Definition for maximum SMSC list count
  */
-#define        MSG_MSG_ID_LEN                  100
+#define SMSC_LIST_MAX 5
 
 /**
- *     @brief  Defines the maximum in transition id length
+ * @brief      Definition for maximum CB channel name length
  */
-#define MAX_SMIL_TRANSIN_ID            100
+#define CB_CHANNEL_NAME_MAX 32
 
 /**
- *     @brief  Defines the maximum out transition id length
+ * @brief      Definition for maximum CB channel count
  */
-#define MAX_SMIL_TRANSOUT_ID   100
+#define CB_CHANNEL_MAX 30
 
 /**
- *     @brief  Defines the maximum region id length
+ * @brief      Definition for maximum CB language type count
  */
-#define        MAX_SMIL_REGION_ID              151
+#define CB_LANG_TYPE_MAX 10
 
 /**
- *     @brief  Defines the maximum transition id length
+ * @brief      Definition for maximum file name length
  */
-#define MAX_SMIL_TRANSITION_ID         151
+#define        MSG_FILENAME_LEN_MAX 1024
 
 /**
- *     @brief  Defines the maximum meta id length
+ * @brief      Definition for maximum message id length
  */
-#define MAX_SMIL_META_ID               151
+#define        MSG_MSG_ID_LEN 1024
 
 /**
- *     @brief  Defines the maximum meta name length
+ * @brief      Definition for maximum in transition id length
  */
-#define MAX_SMIL_META_NAME             100
+#define MAX_SMIL_TRANSIN_ID 100
 
 /**
- *     @brief  Defines the maximum meta content length
+ * @brief      Definition for maximum out transition id length
  */
-#define MAX_SMIL_META_CONTENT          255
+#define MAX_SMIL_TRANSOUT_ID 100
 
 /**
- *     @brief  Defines the maximum fit size
+ * @brief      Definition for maximum region id length
  */
-#define        MAX_SMIL_FIT_SIZE               31
+#define        MAX_SMIL_REGION_ID 151
 
 /**
- *     @brief  Defines the maximum pages in a MMS
+ * @brief      Definition for maximum transition id length
  */
-#define        MMS_PAGE_MAX                    20
+#define MAX_SMIL_TRANSITION_ID 151
 
 /**
- *     @brief  Defines the maximum media in a MMS
+ * @brief      Definition for maximum meta id length
  */
-#define        MMS_MEDIA_MAX                   60
+#define MAX_SMIL_META_ID 151
 
 /**
- *     @brief  Defines the maximum alternate text length
+ * @brief      Definition for maximum meta name length
  */
-#define        MAX_SMIL_ALT_LEN                255
+#define MAX_SMIL_META_NAME 100
 
+/**
+ * @brief      Definition for maximum meta content length
+ */
+#define MAX_SMIL_META_CONTENT 255
+
+/**
+ * @brief      Definition for maximum fit size
+ */
+#define        MAX_SMIL_FIT_SIZE 31
+
+/**
+ * @brief      Definition for maximum pages in a MMS
+ */
+#define        MMS_PAGE_MAX 20
+
+/**
+ * @brief      Definition for maximum media in a MMS
+ */
+#define        MMS_MEDIA_MAX 60
 
-//font size
 /**
- *     @brief  Defines the small font size
+ * @brief      Definition for maximum alternate text length
  */
-#define        MMS_SMIL_FONT_SIZE_SMALL                24
+#define        MAX_SMIL_ALT_LEN 255
 
+
+//font size
 /**
- *     @brief  Defines the normal font size
+ * @brief      Definition for small font size
  */
-#define        MMS_SMIL_FONT_SIZE_NORMAL               30
+#define        MMS_SMIL_FONT_SIZE_SMALL 24
 
 /**
- *     @brief  Defines the large font size
+ * @brief      Definition for normal font size
  */
-#define        MMS_SMIL_FONT_SIZE_LARGE                36
+#define        MMS_SMIL_FONT_SIZE_NORMAL 30
 
-#define MAX_SMIL_ANIMATE_ATTRIBUTE_NAME 100
-#define MAX_SMIL_ANIMATE_ATTRIBUTE_TYPE 100
-#define MAX_SMIL_ANIMATE_TARGET_ELEMENT 100
-#define MAX_SMIL_ANIMATE_CALC_MODE 100
+/**
+ * @brief      Definition for large font size
+ */
+#define        MMS_SMIL_FONT_SIZE_LARGE 36
 
+/**
+ * @brief      Definition for maximum length of java app ID
+ */
 #define MAX_MMS_JAVA_APPID_LEN 32
 
-#define CONV_THUMB_WIDTH       250
-#define CONV_THUMB_HEIGHT 170
+/**
+ * @brief      Definition for maximum length of MMS transaction ID
+ */
+#define MMS_TR_ID_LEN 40
+
+/**
+ * @brief      Definition for maximum length of MMS message ID
+ */
+#define MMS_MSG_ID_LEN 40
+
+/**
+ * @brief      Definition for maximum length of MMS contents location
+ */
+#define MMS_LOCATION_LEN 100
+
+/**
+ * @brief      Definition for maximum mimeType length
+ */
+#define MAX_MIME_TYPE_LEN 64
 
-#define MMS_TR_ID_LEN          40
-#define MMS_MSG_ID_LEN         40
-#define MMS_LOCATION_LEN       100
 /*==================================================================================================
                                          TYPES
 ==================================================================================================*/
 
-typedef struct opq_msg_svc_s *                 msg_handle_t;
-typedef struct opq_struct_s *                          msg_struct_t;
+/**
+ * @brief      The structure type representing an opaque pointer to message handle.
+ */
+typedef struct opq_msg_svc_s *msg_handle_t;
 
+/**
+ * @brief      The structure type representing an opaque pointer to message structure type.
+ */
+typedef struct opq_struct_s *msg_struct_t;
 
+/**
+ * @brief      The structure type representing a pointer to message list handle.
+ */
 typedef struct msg_list_handle *msg_list_handle_t;
 
-
+/**
+ * @brief      The structure type representing a message structure list.
+ */
 typedef struct {
-       int                                     nCount;                         /**< Indicates the count of msg_struct_t. */
-       msg_struct_t            *msg_struct_info;       /**< Indicates the msg_struct_t information list. */
+    int             nCount;            /**< The count of #msg_struct_t */
+    msg_struct_t    *msg_struct_info;  /**< The #msg_struct_t information list */
 }msg_struct_list_s;
 
 
 /**
- *     @brief  Represents a messsage ID.
+ * @brief  The message ID.
  */
 typedef unsigned int msg_message_id_t;
 
 
 /**
- *     @brief  Represents a storage type.
-       See enum _MSG_STORAGE_ID_E
+ * @brief  The storage type.
+ *         See enum _MSG_STORAGE_ID_E.
  */
 typedef unsigned char msg_storage_id_t;
 
 
 /**
- *     @brief  Represents a folder ID.
-       See enum _MSG_FOLDER_ID_E
+ * @brief  The folder ID.
+ *         See enum _MSG_FOLDER_ID_E.
  */
 typedef char msg_folder_id_t;
 
 
 /**
- *     @brief  Represents a request ID, which is unique for each request.
+ * @brief The request ID, which is unique for each request.
  */
 typedef unsigned int msg_request_id_t;
 
 
 /**
- *     @brief  Represents a message priority. \n
- *     The values for this type SHOULD be in _MSG_PRIORITY_TYPE_E.
+ * @brief  The message priority. \n
+ *         The values for this type SHOULD be in _MSG_PRIORITY_TYPE_E.
  */
 typedef unsigned char msg_priority_type_t;
 
 
 /**
- *     @brief  Represents the network status of a message. \n
- *     The values for this type SHOULD be in _MSG_NETWORK_STATUS_E.
+ * @brief  The network status of a message. \n
+ *         The values for this type SHOULD be in _MSG_NETWORK_STATUS_E.
  */
 typedef unsigned char msg_network_status_t;
 
 
 /**
- *     @brief  Represents an address type. \n
- *     The values for this type SHOULD be in _MSG_ADDRESS_TYPE_E.
+ * @brief  The address type. \n
+ *         The values for this type SHOULD be in _MSG_ADDRESS_TYPE_E.
  */
 typedef unsigned char msg_address_type_t;
 
 
 /**
- *     @brief  Represents an recipient type. \n
- *     The values for this type SHOULD be in _MSG_RECIPIENT_TYPE_E.
+ * @brief  The recipient type. \n
+ *         The values for this type SHOULD be in _MSG_RECIPIENT_TYPE_E.
  */
 typedef unsigned char msg_recipient_type_t;
 
 
 /**
- *     @brief  Represents the type of a message direction. \n
- *     The values for this type SHOULD be in _MSG_DIRECTION_TYPE_E.
+ * @brief  The type of a message direction. \n
+ *         The values for this type SHOULD be in _MSG_DIRECTION_TYPE_E.
  */
 typedef unsigned char msg_direction_type_t;
 
 
 /**
- *     @brief  Represents an encoding type. \n
- *     The values for this type SHOULD be in _MSG_ENCODE_TYPE_E.
+ * @brief  The encoding type. \n
+ *         The values for this type SHOULD be in _MSG_ENCODE_TYPE_E.
  */
 typedef unsigned char msg_encode_type_t;
 
 
 /**
- *     @brief  Represents an error code. \n
- *     The values for this type SHOULD be in _MSG_ERROR_E
+ * @brief  The error code. \n
+ *         The values for this type SHOULD be in _MSG_ERROR_E.
  */
 typedef int msg_error_t;
 
 
 /**
-\brief Represents WAP Push App Code.
+* @brief The WAP Push App Code.
 */
 typedef unsigned char msg_push_action_t;
 
 
 /**
-\brief Represents SyncML Message Type.
+* @brief The SyncML Message Type.
 */
 typedef unsigned short msg_syncml_message_type_t;
 
 
 /**
- *     @brief  Represents a Contact ID.
+ * @brief The Contact ID.
  */
 typedef unsigned int msg_contact_id_t;
 
 
 /**
-  *  @brief    Represents a Delivery Report Status.
- *     The values for this type SHOULD be in _MSG_DELIVERY_REPORT_STATUS_E
-  */
+ * @brief  The Report Type. \n
+ *         The values for this type SHOULD be in _MSG_REPORT_TYPE_E.
+ */
+typedef int msg_report_type_t;
+
+
+/**
+ * @brief  The Delivery Report Status. \n
+ *         The values for this type SHOULD be in _MSG_DELIVERY_REPORT_STATUS_E.
+ */
 typedef int msg_delivery_report_status_t;
 
 
 /**
- *     @brief  Represents a Read Report Status.
- *     The values for this type SHOULD be in _MSG_READ_REPORT_STATUS_E
+ * @brief  The Read Report Status.\n
+ *         The values for this type SHOULD be in _MSG_READ_REPORT_STATUS_E
  */
 typedef int msg_read_report_status_t;
 
 
 /**
- *     @brief  Represents a Message Type.
- *     The values for this type SHOULD be in _MSG_MESSAGE_TYPE_E
+ * @brief  The Message Type. \n
+ *         The values for this type SHOULD be in _MSG_MESSAGE_TYPE_E.
 */
 typedef unsigned short msg_message_type_t;
 
+/**
+ * @brief  The Message Backup Type. \n
+ *         The values for this type SHOULD be in _MSG_MESSAGE_BACKUP_TYPE_E.
+*/
+typedef unsigned int msg_message_backup_type_t;
 
 /**
- *     @brief  Represents a thread ID. \n
+ * @brief  The thread ID.
  */
 typedef unsigned int msg_thread_id_t;
 
 // filter
 /**
- *     @brief  Represents a filter ID.
+ * @brief  The filter ID.
  */
 typedef unsigned char msg_filter_id_t;
 
 
 /**
- *     @brief  Represents a filter Type. \n
- *     The filter Type represents a unique filter type. \n
- *     The values for this type SHOULD be in _MSG_FILTER_TYPE_E.
+ * @brief  The filter Type. \n
+ *         The filter type represents a unique filter type. \n
+ *         The values for this type SHOULD be in _MSG_FILTER_TYPE_E.
  */
 typedef unsigned char msg_filter_type_t;
 
@@ -314,392 +454,708 @@ typedef unsigned char msg_filter_type_t;
                                          ENUMS
 ==================================================================================================*/
 
+/**
+ * @brief  Enumeration for the values of a structure type for #msg_sturuct_t. \n
+ */
 enum _MSG_STRUCT_E {
-       MSG_STRUCT_FILTER = 0X0000,                                                             /**< Indicates the MSG_STRUCT_FILTER */
-
-       MSG_STRUCT_MESSAGE_INFO = 0x0200,                               /**< Indicates the MSG_STRUCT_MESSAGE_INFO */
-       MSG_STRUCT_THREAD_INFO = 0x0300,
-
-       MSG_STRUCT_MMS = 0x0500,                                                                /**< Indicates the MSG_STRUCT_MMS */
-       MSG_STRUCT_MMS_PAGE = 0x0600,                                           /**< Indicates the MSG_STRUCT_MMS_PAGE */
-       MSG_STRUCT_MMS_MEDIA = 0x0700,                                  /**< Indicates the MSG_STRUCT_MMS_MEDIA */
-       MSG_STRUCT_MMS_ATTACH = 0x0800,                                 /**< Indicates the MSG_STRUCT_MMS_ATTACH */
-       MSG_STRUCT_MMS_REGION = 0x0900,                                 /**< Indicates the MSG_STRUCT_MMS_REGION */
-       MSG_STRUCT_MMS_TRANSITION = 0x0a00,                     /**< Indicates the MSG_STRUCT_MMS_TRANSITION */
-       MSG_STRUCT_MMS_META = 0x0b00,                                           /**< Indicates the MSG_STRUCT_MMS_META */
-       MSG_STRUCT_MMS_SMIL_TEXT = 0x0c00,                      /**< Indicates the MSG_STRUCT_MMS_SMIL_TEXT */
-       MSG_STRUCT_MMS_SMIL_AVI = 0x0d00,                               /**< Indicates the MSG_STRUCT_MMS_SMIL_AVI */
-
-       MSG_STRUCT_SETTING_SMSC_OPT = 0x2000,
-       MSG_STRUCT_SETTING_SMSC_INFO = 0x2100,                                          /**< Indicates the MSG_STRUCT_SETTING_SMSC_INFO */
-       MSG_STRUCT_SETTING_CB_OPT = 0x2200,                                                     /**< Indicates the MSG_STRUCT_SETTING_CB_OPT */
-       MSG_STRUCT_SETTING_CB_CHANNEL_INFO = 0x2300,                    /**< Indicates the MSG_STRUCT_CB_CHANNEL_INFO */
-       MSG_STRUCT_SETTING_SMS_SEND_OPT = 0x2400,                               /**< Indicates the MSG_STRUCT_SETTING_SMS_SEND_OPT */
-       MSG_STRUCT_SETTING_MMS_SEND_OPT = 0x2500,                               /**< Indicates the MSG_STRUCT_SETTING_MMS_SEND_OPT */
-       MSG_STRUCT_SETTING_MMS_RECV_OPT = 0x2600,                               /**< Indicates the MSG_STRUCT_SETTING_MMS_RECV_OPT */
-       MSG_STRUCT_SETTING_PUSH_MSG_OPT = 0x2700,                               /**< Indicates the MSG_STRUCT_SETTING_PUSH_MSG_OPT */
-       MSG_STRUCT_SETTING_VOICE_MSG_OPT = 0x2800,                              /**< Indicates the MSG_STRUCT_SETTING_VOICE_MSG_OPT */
-       MSG_STRUCT_SETTING_GENERAL_OPT = 0x2900,                                /**< Indicates the MSG_STRUCT_SETTING_GENERAL_OPT */
-       MSG_STRUCT_SETTING_MSGSIZE_OPT = 0x2c00,                                        /**< Indicates the MSG_STRUCT_SETTING_MSGSIZE_OPT */
-
-       MSG_STRUCT_SYNCML_INFO = 0x3100,                                        /**< Indicates the MSG_STRUCT_SYNCML_INFO */
-       MSG_STRUCT_COUNT_INFO = 0x3200,                                 /**< Indicates the MSG_STRUCT_COUNT_INFO */
-       MSG_STRUCT_THREAD_COUNT_INFO = 0x3300,          /**< Indicates the MSG_STRUCT_THREAD_COUNT_INFO */
-       MSG_STRUCT_THREAD_LIST_INDEX = 0x3400,          /**< Indicates the MSG_STRUCT_THREAD_LIST_INDEX */
-       MSG_STRUCT_SORT_RULE = 0x3500,                                          /**< Indicates the MSG_STRUCT_SORT_RULE */
-       MSG_STRUCT_FOLDER_INFO = 0x3600,                                        /**< Indicates the MSG_STRUCT_FOLDER_INFO */
-       MSG_STRUCT_SEARCH_CONDITION = 0x3700,           /**< Indicates the MSG_STRUCT_SEARCH_CONDITION */
-       MSG_STRUCT_REPORT_STATUS_INFO = 0x3800, /**< Indicates the MSG_STRUCT_REPORT_STATUS_INFO */
-
-       MSG_STRUCT_ADDRESS_INFO = 0x4000,                               /**< Indicates the MSG_STRUCT_ADDRESS_INFO */
-       MSG_STRUCT_SENDOPT = 0x4100,                                                    /**< Indicates the MSG_STRUCT_SENDOPT */
-       MSG_STRUCT_MMS_SENDOPT = 0x4200,                                /**< Indicates the MSG_STRUCT_MMS_SENDOPT */
-       MSG_STRUCT_SMS_SENDOPT = 0x4300,                                /**< Indicates the MSG_STRUCT_SMS_SENDOPT */
-       MSG_STRUCT_REJECT_MSG_INFO = 0x4400,                    /**< Indicates the MSG_STRUCT_REJECT_MSG_INFO */
-       MSG_STRUCT_REQUEST_INFO = 0x4500,                               /**< Indicates the MSG_STRUCT_REQUEST_INFO */
-       MSG_STRUCT_SENT_STATUS_INFO = 0x4600,                           /**< Indicates the MSG_STRUCT_SENT_STATUS_INFO */
-};
-
+       MSG_STRUCT_FILTER = 0X0000,                             /**< Indicates the MSG_STRUCT_FILTER */
+
+       MSG_STRUCT_MESSAGE_INFO = 0x0200,                       /**< Indicates the MSG_STRUCT_MESSAGE_INFO */
+       MSG_STRUCT_THREAD_INFO = 0x0300,                        /**< Indicates the MSG_STRUCT_THREAD_INFO*/
+       MSG_STRUCT_CONV_INFO = 0x0400,                          /**< Indicates the MSG_STRUCT_CONV_INFO*/
+       MSG_STRUCT_MMS = 0x0500,                                /**< Indicates the MSG_STRUCT_MMS */
+       MSG_STRUCT_MMS_PAGE = 0x0600,                           /**< Indicates the MSG_STRUCT_MMS_PAGE */
+       MSG_STRUCT_MMS_MEDIA = 0x0700,                          /**< Indicates the MSG_STRUCT_MMS_MEDIA */
+       MSG_STRUCT_MMS_ATTACH = 0x0800,                         /**< Indicates the MSG_STRUCT_MMS_ATTACH */
+       MSG_STRUCT_MMS_REGION = 0x0900,                         /**< Indicates the MSG_STRUCT_MMS_REGION */
+       MSG_STRUCT_MMS_TRANSITION = 0x0a00,                     /**< Indicates the MSG_STRUCT_MMS_TRANSITION */
+       MSG_STRUCT_MMS_META = 0x0b00,                           /**< Indicates the MSG_STRUCT_MMS_META */
+       MSG_STRUCT_MMS_SMIL_TEXT = 0x0c00,                      /**< Indicates the MSG_STRUCT_MMS_SMIL_TEXT */
+       MSG_STRUCT_MMS_SMIL_AVI = 0x0d00,                       /**< Indicates the MSG_STRUCT_MMS_SMIL_AVI */
+
+       MSG_STRUCT_SETTING_SMSC_OPT = 0x2000,                   /**< Indicates the MSG_STRUCT_SETTING_SMSC_OPT */
+       MSG_STRUCT_SETTING_SMSC_INFO = 0x2100,                  /**< Indicates the MSG_STRUCT_SETTING_SMSC_INFO */
+       MSG_STRUCT_SETTING_CB_OPT = 0x2200,                     /**< Indicates the MSG_STRUCT_SETTING_CB_OPT */
+       MSG_STRUCT_SETTING_CB_CHANNEL_INFO = 0x2300,            /**< Indicates the MSG_STRUCT_CB_CHANNEL_INFO */
+       MSG_STRUCT_SETTING_SMS_SEND_OPT = 0x2400,               /**< Indicates the MSG_STRUCT_SETTING_SMS_SEND_OPT */
+       MSG_STRUCT_SETTING_MMS_SEND_OPT = 0x2500,               /**< Indicates the MSG_STRUCT_SETTING_MMS_SEND_OPT */
+       MSG_STRUCT_SETTING_MMS_RECV_OPT = 0x2600,               /**< Indicates the MSG_STRUCT_SETTING_MMS_RECV_OPT */
+       MSG_STRUCT_SETTING_PUSH_MSG_OPT = 0x2700,               /**< Indicates the MSG_STRUCT_SETTING_PUSH_MSG_OPT */
+       MSG_STRUCT_SETTING_VOICE_MSG_OPT = 0x2800,              /**< Indicates the MSG_STRUCT_SETTING_VOICE_MSG_OPT */
+       MSG_STRUCT_SETTING_GENERAL_OPT = 0x2900,                /**< Indicates the MSG_STRUCT_SETTING_GENERAL_OPT */
+
+       MSG_STRUCT_SETTING_MSGSIZE_OPT = 0x2c00,                /**< Indicates the MSG_STRUCT_SETTING_MSGSIZE_OPT */
+
+       MSG_STRUCT_SYNCML_INFO = 0x3100,                        /**< Indicates the MSG_STRUCT_SYNCML_INFO */
+       MSG_STRUCT_COUNT_INFO = 0x3200,                         /**< Indicates the MSG_STRUCT_COUNT_INFO */
+       MSG_STRUCT_THREAD_COUNT_INFO = 0x3300,                  /**< Indicates the MSG_STRUCT_THREAD_COUNT_INFO */
+       MSG_STRUCT_THREAD_LIST_INDEX = 0x3400,                  /**< Indicates the MSG_STRUCT_THREAD_LIST_INDEX */
+       MSG_STRUCT_SORT_RULE = 0x3500,                          /**< Indicates the MSG_STRUCT_SORT_RULE */
+       MSG_STRUCT_FOLDER_INFO = 0x3600,                        /**< Indicates the MSG_STRUCT_FOLDER_INFO */
+       MSG_STRUCT_SEARCH_CONDITION = 0x3700,                   /**< Indicates the MSG_STRUCT_SEARCH_CONDITION */
+       MSG_STRUCT_REPORT_STATUS_INFO = 0x3800,                 /**< Indicates the MSG_STRUCT_REPORT_STATUS_INFO */
+       MSG_STRUCT_MSG_LIST_CONDITION = 0x3900,                 /**< Indicates the MSG_LIST_CONDITION  */
+
+       MSG_STRUCT_ADDRESS_INFO = 0x4000,                       /**< Indicates the MSG_STRUCT_ADDRESS_INFO */
+       MSG_STRUCT_SENDOPT = 0x4100,                            /**< Indicates the MSG_STRUCT_SENDOPT */
+       MSG_STRUCT_MMS_SENDOPT = 0x4200,                        /**< Indicates the MSG_STRUCT_MMS_SENDOPT */
+       MSG_STRUCT_SMS_SENDOPT = 0x4300,                        /**< Indicates the MSG_STRUCT_SMS_SENDOPT */
+       MSG_STRUCT_REJECT_MSG_INFO = 0x4400,                    /**< Indicates the MSG_STRUCT_REJECT_MSG_INFO */
+       MSG_STRUCT_REQUEST_INFO = 0x4500,                       /**< Indicates the MSG_STRUCT_REQUEST_INFO */
+       MSG_STRUCT_SENT_STATUS_INFO = 0x4600,                   /**< Indicates the MSG_STRUCT_SENT_STATUS_INFO */
+       MSG_STRUCT_PUSH_CONFIG_INFO = 0x4700,                   /**< Indicates the MSG_STRUCT_PUSH_CONFIG_INFO */
+       MSG_STRUCT_CB_MSG = 0x4800,                             /**< Indicates the MSG_STRUCT_CB_MSG */
+       MSG_STRUCT_MULTIPART_INFO = 0x4a00,                     /**< Indicates the MSG_STRUCT_MULTIPART_INFO */
+       MSG_STRUCT_MEDIA_INFO = 0x5000,                         /**< Indicates the MSG_STRUCT_MEDIA_INFO*/
+};
+
+/**
+ * @brief  Enumeration for the values of message detail information. \n
+ *         This enum is used as member of #msg_struct_t for MSG_STRUCT_MESSAGE_INFO.
+ */
 enum _MSG_MESSAGE_INFO_E_ {
-       MSG_MESSAGE_ID_INT = MSG_STRUCT_MESSAGE_INFO+1,         /**< Indicates the message ID of this message. */
-       MSG_MESSAGE_THREAD_ID_INT,                              /**< Indicates the thread ID. */
-       MSG_MESSAGE_FOLDER_ID_INT,                              /**< Indicates the folder ID. see enum _MSG_FOLDER_TYPE_E */
-       MSG_MESSAGE_TYPE_INT,                           /**< Indicates the message type. See enum _MSG_MESSAGE_TYPE_E */
-       MSG_MESSAGE_CLASS_TYPE_INT,                             /**< Message class type. See enum _MSG_CLASS_TYPE_E */
-       MSG_MESSAGE_STORAGE_ID_INT,                             /**< Indicates where the message is saved. see enum _MSG_STORAGE_ID_E*/
-       MSG_MESSAGE_ADDR_LIST_STRUCT,                           /**< Indicates the address information list. */
-       MSG_MESSAGE_REPLY_ADDR_STR,                             /**< Indicates the reply address. */
-       MSG_MESSAGE_SUBJECT_STR,                                /**< Indicates the message subject. */
-       MSG_MESSAGE_DISPLAY_TIME_INT,                           /**< Indicates the display time related to the specific operation. */
-       MSG_MESSAGE_NETWORK_STATUS_INT,                         /**< Indicates the network status of the message. See enum _MSG_NETWORK_STATUS_E */
-       MSG_MESSAGE_ENCODE_TYPE_INT,                            /**< Indicates the string encoding type. See enum _MSG_ENCODE_TYPE_E */
-       MSG_MESSAGE_READ_BOOL,                                  /**< Indicates whether the message is read or not. */
-       MSG_MESSAGE_PROTECTED_BOOL,                             /**< Indicates whether the message is protected or not. */
-       MSG_MESSAGE_BACKUP_BOOL,                                /**< Indicates whether the message was restored from PC. */
-       MSG_MESSAGE_PRIORITY_INT,                               /**< Indicates the priority of the message. See enum _MSG_PRIORITY_TYPE_E */
-       MSG_MESSAGE_DIRECTION_INT,                              /**< Indicates whether the message is MO or MT, affecting address. See enum _MSG_DIRECTION_TYPE_E */
-       MSG_MESSAGE_PORT_VALID_BOOL,                            /**< Indicates whether port information is used or not. */
-       MSG_MESSAGE_DEST_PORT_INT,                              /**< Recipient port number, not greater than 16 bit */
-       MSG_MESSAGE_SRC_PORT_INT,                               /**< Sender port number, not greater than 16 bit */
-       MSG_MESSAGE_ATTACH_COUNT_INT,                           /**< Indicates the count of attached files in mms. */
-       MSG_MESSAGE_THUMBNAIL_PATH_STR,                         /**< Indicates the thumbnail path of message. */
-       MSG_MESSAGE_DATA_SIZE_INT,                              /**< Indicates the data size. The unit is byte. */
-       MSG_MESSAGE_SMS_DATA_STR,                               /**< Indicates the message payload information as a body. default character encoding is UTF-8*/
-       MSG_MESSAGE_MMS_TEXT_STR,
-};
-
+       MSG_MESSAGE_ID_INT = MSG_STRUCT_MESSAGE_INFO+1,     /**< Indicates the message ID of this message. */
+       MSG_MESSAGE_THREAD_ID_INT,                          /**< Indicates the thread ID. */
+       MSG_MESSAGE_FOLDER_ID_INT,                          /**< Indicates the folder ID. See enum _MSG_FOLDER_ID_E */
+       MSG_MESSAGE_TYPE_INT,                               /**< Indicates the message type. See enum _MSG_MESSAGE_TYPE_E */
+       MSG_MESSAGE_CLASS_TYPE_INT,                         /**< Indicates the message class type. See enum _MSG_CLASS_TYPE_E */
+       MSG_MESSAGE_STORAGE_ID_INT,                         /**< Indicates where the message is saved. See enum _MSG_STORAGE_ID_E*/
+       MSG_MESSAGE_ADDR_LIST_STRUCT,                       /**< Indicates the address information list. **DEPRECATED** */
+       MSG_MESSAGE_REPLY_ADDR_STR,                         /**< Indicates the reply address. */
+       MSG_MESSAGE_SUBJECT_STR,                            /**< Indicates the message subject. */
+       MSG_MESSAGE_DISPLAY_TIME_INT,                       /**< Indicates the display time related to the specific operation. */
+       MSG_MESSAGE_NETWORK_STATUS_INT,                     /**< Indicates the network status of the message. See enum _MSG_NETWORK_STATUS_E */
+       MSG_MESSAGE_ENCODE_TYPE_INT,                        /**< Indicates the string encoding type. See enum _MSG_ENCODE_TYPE_E */
+       MSG_MESSAGE_READ_BOOL,                              /**< Indicates whether the message is read or not. */
+       MSG_MESSAGE_PROTECTED_BOOL,                         /**< Indicates whether the message is protected or not. */
+       MSG_MESSAGE_BACKUP_BOOL,                            /**< Indicates whether the message was restored from PC. */
+       MSG_MESSAGE_PRIORITY_INT,                           /**< Indicates the priority of the message. See enum _MSG_PRIORITY_TYPE_E */
+       MSG_MESSAGE_DIRECTION_INT,                          /**< Indicates whether the message is MO or MT, affecting address. See enum _MSG_DIRECTION_TYPE_E */
+       MSG_MESSAGE_PORT_VALID_BOOL,                        /**< Indicates whether port information is used or not. */
+       MSG_MESSAGE_DEST_PORT_INT,                          /**< Indicates the recipient port number, not greater than 16 bit */
+       MSG_MESSAGE_SRC_PORT_INT,                           /**< Indicates the sender port number, not greater than 16 bit */
+       MSG_MESSAGE_ATTACH_COUNT_INT,                       /**< Indicates the count of attached files in MMS. */
+       MSG_MESSAGE_THUMBNAIL_PATH_STR,                     /**< Indicates the thumbnail path of message. */
+       MSG_MESSAGE_DATA_SIZE_INT,                          /**< Indicates the data size. The unit is byte. */
+       MSG_MESSAGE_SMS_DATA_STR,                           /**< Indicates the message payload information as a body. default character encoding is UTF-8*/
+       MSG_MESSAGE_MMS_TEXT_STR,                           /**< Indicates the text part of MMS message payload. default character encoding is UTF-8  */
+       MSG_MESSAGE_ADDR_LIST_HND,                          /**< Indicates the address information list. */
+       MSG_MESSAGE_REPLACE_BOOL,                           /**< Indicates whether the message is replace or not */
+       MSG_MESSAGE_SIM_INDEX_INT,                          /**< Indicates the sim index */
+       MSG_MESSAGE_INFO_MAX,                               /**< Placeholder for max value of this enum*/
+};
+
+/**
+ *  @brief  Enumeration for the values of message filter information. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_FILTER.
+ */
 enum MSG_FILTER_INFO_E {
-       MSG_FILTER_ID_INT = MSG_STRUCT_FILTER+1,                /**< Indicates the filter ID. */
-       MSG_FILTER_TYPE_INT,                                    /**< Indicates the filter type. See enum _MSG_FILTER_TYPE_E */
-       MSG_FILTER_VALUE_STR,                                   /**< The value of a filter. */
+       MSG_FILTER_ID_INT = MSG_STRUCT_FILTER+1,        /**< Indicates the filter ID. */
+       MSG_FILTER_TYPE_INT,                            /**< Indicates the filter type. See enum _MSG_FILTER_TYPE_E */
+       MSG_FILTER_VALUE_STR,                           /**< Indicates the value of the filter. */
+       MSG_FILTER_ACTIVE_BOOL,                         /**< Indicates the activation of the filter. */
 };
 
+/**
+ *  @brief  Enumeration for the values of thread information. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_THREAD_INFO.
+ */
 enum MSG_STRUCT_THREAD_INFO_E {
-       MSG_THREAD_ID_INT = MSG_STRUCT_THREAD_INFO+1,           /**< Indicates the message thread ID. */
-       MSG_THREAD_NAME_STR,                                    /**< Indicates the message thread name */
-       MSG_THREAD_MSG_TYPE_INT,                                /**< Indicates the message type. See enum _MSG_MESSAGE_TYPE_E  */
-       MSG_THREAD_MSG_DATA_STR,                                /**< The latest message text. */
-       MSG_THREAD_MSG_TIME_INT,                                /**< The latest message time */
-       MSG_THREAD_DIRECTION_INT,                               /**< The latest message direction See enum _MSG_DIRECTION_TYPE_E */
-       MSG_THREAD_UNREAD_COUNT_INT,                            /**< Indicates unread count of thread */
-       MSG_THREAD_SMS_COUNT_INT,                               /**< Indicates sms message count of thread */
-       MSG_THREAD_MMS_COUNT_INT                                /**< Indicates mms message count of thread */
-};
-
+       MSG_THREAD_ID_INT = MSG_STRUCT_THREAD_INFO+1,       /**< Indicates the message thread ID. */
+       MSG_THREAD_NAME_STR,                                /**< Indicates the message thread name */
+       MSG_THREAD_MSG_TYPE_INT,                            /**< Indicates the message type. See enum _MSG_MESSAGE_TYPE_E  */
+       MSG_THREAD_MSG_DATA_STR,                            /**< The latest message text. */
+       MSG_THREAD_MSG_TIME_INT,                            /**< The latest message time */
+       MSG_THREAD_DIRECTION_INT,                           /**< The latest message direction See enum _MSG_DIRECTION_TYPE_E */
+       MSG_THREAD_UNREAD_COUNT_INT,                        /**< Indicates unread count of thread */
+       MSG_THREAD_SMS_COUNT_INT,                           /**< Indicates SMS message count of thread */
+       MSG_THREAD_MMS_COUNT_INT,                           /**< Indicates MMS message count of thread */
+       MSG_THREAD_PROTECTED_BOOL,                          /**< Indicates whether thread includes protected message. */
+       MSG_THREAD_DRAFT_BOOL,                              /**< Indicates whether thread includes draft message. */
+       MSG_THREAD_SEND_FAILED_BOOL,                        /**< Indicates whether thread includes  send failed message. */
+       MSG_THREAD_SENDING_BOOL,                            /**< Indicates whether thread includes  sending message. */
+
+       MSG_THREAD_INFO_MAX                                 /**< Placeholder for max value of this enum */
+};
+
+/**
+ *  @brief  Enumeration for the values of conversation information. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_CONV_INFO.
+ */
+enum MSG_STRUCT_CONV_INFO_E {
+       MSG_CONV_MSG_ID_INT = MSG_STRUCT_CONV_INFO+1,       /**< Indicates the message ID of this message. */
+       MSG_CONV_MSG_THREAD_ID_INT,                         /**< Indicates the thread ID. */
+       MSG_CONV_MSG_TYPE_INT,                              /**< Indicates the message type. See enum _MSG_MESSAGE_TYPE_E */
+       MSG_CONV_MSG_FOLDER_ID_INT,                         /**< Indicates the folder ID. See enum _MSG_FOLDER_TYPE_E */
+       MSG_CONV_MSG_STORAGE_ID_INT,                        /**< Indicates where the message is saved. See enum _MSG_STORAGE_ID_E*/
+       MSG_CONV_MSG_SUBJECT_STR,                           /**< Indicates the message subject. */
+       MSG_CONV_MSG_DISPLAY_TIME_INT,                      /**< Indicates the display time related to the specific operation. */
+       MSG_CONV_MSG_SCHEDULED_TIME_INT,                    /**< Indicates the time to send scheduled message. */
+       MSG_CONV_MSG_NETWORK_STATUS_INT,                    /**< Indicates the network status of the message. See enum _MSG_NETWORK_STATUS_E */
+       MSG_CONV_MSG_READ_BOOL,                             /**< Indicates whether the message is read or not. */
+       MSG_CONV_MSG_PROTECTED_BOOL,                        /**< Indicates whether the message is protected or not. */
+       MSG_CONV_MSG_DIRECTION_INT,                         /**< Indicates whether the message is MO or MT, affecting address. See enum _MSG_DIRECTION_TYPE_E */
+       MSG_CONV_MSG_PAGE_COUNT_INT,                        /**< Indicates the count of pages in MMS. */
+       MSG_CONV_MSG_ATTACH_COUNT_INT,                      /**< Indicates the count of attached files in MMS. */
+       MSG_CONV_MSG_ATTACH_NAME_STR,                       /**< Indicates the attached file name of message. */
+       MSG_CONV_MSG_AUDIO_NAME_STR,                        /**< Indicates the audio file name of message. */
+       MSG_CONV_MSG_IMAGE_THUMB_PATH_STR,                  /**< Indicates the image thumbnail path of message. */
+       MSG_CONV_MSG_VIDEO_THUMB_PATH_STR,                  /**< Indicates the video thumbnail path of message. */
+       MSG_CONV_MSG_TEXT_SIZE_INT,                         /**< Indicates the data size. The unit is byte. */
+       MSG_CONV_MSG_TEXT_STR,                              /**< Indicates the message payload information as a body. default character encoding is UTF-8*/
+       MSG_CONV_MSG_TCS_BC_LEVEL_INT,                      /**< Indicates the Behavior Level of malware. @c -1 is None*/
+       MSG_CONV_MSG_1ST_MEDIA_PATH_STR,                    /**< Indicates the First Media path of MMS */
+       MSG_CONV_MSG_MULTIPART_HND,
+       MSG_CONV_MSG_SIM_INDEX_INT,                         /**< Indicates the sim index */
+
+       MSG_CONV_INFO_MAX                                   /**< Placeholder for max value of this enum */
+};
+
+/**
+ *  @brief  Enumeration for the values of setting for SMSC options. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SETTING_SMSC_OPT.
+ */
 enum _MSG_STRUCT_SETTING_SMSC_OPT_E {
-       MSG_SMSC_SELECTED_ID_INT = MSG_STRUCT_SETTING_SMSC_OPT+1,
-       MSG_SMSC_LIST_STRUCT
+       MSG_SMSC_SELECTED_ID_INT = MSG_STRUCT_SETTING_SMSC_OPT+1,       /**< Indicates Selected SMSC index option */
+       MSG_SMSC_LIST_STRUCT,                                           /**< Indicates SMSC data information list option*/
+       MSG_SMSC_LIST_INDEX_INT,                                        /**< Indicates SMSC index option for Updating information */
+       MSG_SMSC_LIST_SIM_INDEX_INT                                     /**< Indicates the sim index */
 };
 
+/**
+ *  @brief  Enumeration for the values of setting for SMSC informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SETTING_SMSC_INFO.
+ */
 enum _MSG_STRUCT_SETTING_SMSC_INFO_E {
-       MSG_SMSC_ADDR_TON_INT = MSG_STRUCT_SETTING_SMSC_INFO+1,         /**< Type of number. See enum _MSG_SMS_TON_E */
-       MSG_SMSC_ADDR_NPI_INT,                                  /**< Numbering plan ID. See enum _MSG_SMS_NPI_E */
-       MSG_SMSC_ADDR_STR,                                      /**< SMSC address */
-       MSG_SMSC_NAME_STR,                                      /**< SMSC name */
-       MSG_SMSC_PID_INT,                                       /**< Protocol idendifier See enum _MSG_SMS_PID_E */
-       MSG_SMSC_VAL_PERIOD_INT                                 /**< Validity period value. See enum _MSG_VAL_PERIOD_E*/
+       MSG_SMSC_ADDR_TON_INT = MSG_STRUCT_SETTING_SMSC_INFO+1,     /**< Type of number. See enum _MSG_SMS_TON_E */
+       MSG_SMSC_ADDR_NPI_INT,                                      /**< Numbering plan ID. See enum _MSG_SMS_NPI_E */
+       MSG_SMSC_ADDR_STR,                                          /**< SMSC address */
+       MSG_SMSC_NAME_STR,                                          /**< SMSC name */
+       MSG_SMSC_PID_INT,                                           /**< Protocol idendifier See enum _MSG_SMS_PID_E */
+       MSG_SMSC_VAL_PERIOD_INT                                     /**< Validity period value. See enum _MSG_VAL_PERIOD_E*/
 };
 
+/**
+ *  @brief  Enumeration for the values of setting for CB channel options. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SETTING_CB_OPT.
+ */
 enum _MSG_STRUCT_CB_OPT_E {
-       MSG_CB_RECEIVE_BOOL = MSG_STRUCT_SETTING_CB_OPT+1,              /**< Indicates whether the CB message is received or not. */
-       MSG_CB_RECEIVE_ALL_CHANNEL_BOOL,                        /**< Indicates whether All Channel's CB message is received or not. */
-       MSG_CB_MAX_SIM_COUNT_INT,                               /**< Indicates the number of channels which can be stored in SIM. */
-       MSG_CB_CHANNEL_LIST_STRUCT,                             /**< Indicates the cell broadcasting channel information. */
-       MSG_CB_LANGUAGE_TYPE_ALL_BOOL,
-       MSG_CB_LANGUAGE_TYPE_ENG_BOOL,                  /**< CB message English  */
-       MSG_CB_LANGUAGE_TYPE_GER_BOOL,                  /**< CB message Germany */
-       MSG_CB_LANGUAGE_TYPE_FRE_BOOL,                  /**< CB message France */
-       MSG_CB_LANGUAGE_TYPE_ITA_BOOL,                  /**< CB message Italy */
-       MSG_CB_LANGUAGE_TYPE_NED_BOOL,                  /**< CB message Netherland */
-       MSG_CB_LANGUAGE_TYPE_SPA_BOOL,                  /**< CB message Spain */
-       MSG_CB_LANGUAGE_TYPE_POR_BOOL,                  /**< CB message Portugal */
-       MSG_CB_LANGUAGE_TYPE_SWE_BOOL,                  /**< CB message Sweden */
-       MSG_CB_LANGUAGE_TYPE_TUR_BOOL,                  /**< CB message Turkey */
-};
-
+       MSG_CB_RECEIVE_BOOL = MSG_STRUCT_SETTING_CB_OPT+1,      /**< Indicates whether the CB message is received or not. */
+       MSG_CB_MAX_SIM_COUNT_INT,                               /**< Indicates the number of channels which can be stored in SIM. */
+       MSG_CB_CHANNEL_LIST_STRUCT,                             /**< Indicates the cell broadcasting channel information. */
+       MSG_CB_LANGUAGE_TYPE_ALL_BOOL,                          /**< CB message all languages */
+       MSG_CB_LANGUAGE_TYPE_ENG_BOOL,                          /**< CB message English  */
+       MSG_CB_LANGUAGE_TYPE_GER_BOOL,                          /**< CB message Germany */
+       MSG_CB_LANGUAGE_TYPE_FRE_BOOL,                          /**< CB message France */
+       MSG_CB_LANGUAGE_TYPE_ITA_BOOL,                          /**< CB message Italy */
+       MSG_CB_LANGUAGE_TYPE_NED_BOOL,                          /**< CB message Netherland */
+       MSG_CB_LANGUAGE_TYPE_SPA_BOOL,                          /**< CB message Spain */
+       MSG_CB_LANGUAGE_TYPE_POR_BOOL,                          /**< CB message Portugal */
+       MSG_CB_LANGUAGE_TYPE_SWE_BOOL,                          /**< CB message Sweden */
+       MSG_CB_LANGUAGE_TYPE_TUR_BOOL,                          /**< CB message Turkey */
+       MSG_CB_SIM_INDEX_INT,                                   /**< Indicates the sim index */
+};
+
+/**
+ *  @brief  Enumeration for the values of setting for CB channel informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SETTING_CB_CHANNEL_INFO.
+ */
 enum _MSG_STRUCT_CB_CHANNEL_INFO_E {
-       MSG_CB_CHANNEL_ACTIVATE_BOOL = MSG_STRUCT_SETTING_CB_CHANNEL_INFO+1,    /**< Indicates whether the CB channel is activate or passive. */
-       MSG_CB_CHANNEL_ID_FROM_INT,                                             /**< Indicates the ID of a CB channel. */
-       MSG_CB_CHANNEL_ID_TO_INT,                                               /**< Indicates the ID of a CB channel. */
-       MSG_CB_CHANNEL_NAME_STR                                         /**< Indicates the name of a CB channel. */
+       MSG_CB_CHANNEL_ACTIVATE_BOOL = MSG_STRUCT_SETTING_CB_CHANNEL_INFO+1,    /**< Indicates whether the CB channel is activate or passive. */
+       MSG_CB_CHANNEL_ID_FROM_INT,                                             /**< Indicates the From ID of a CB channel. */
+       MSG_CB_CHANNEL_ID_TO_INT,                                               /**< Indicates the To ID of a CB channel. */
+       MSG_CB_CHANNEL_NAME_STR                                                 /**< Indicates the name of a CB channel. */
 };
 
+/**
+ *  @brief  Enumeration for the values of setting for SMS sending options. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SETTING_SMS_SEND_OPT.
+ */
 enum _MSG_STRUCT_SMS_SEND_OPT_E {
-       MSG_SMS_SENDOPT_ENCODE_TYPE_INT = MSG_STRUCT_SETTING_SMS_SEND_OPT+1,    /**< Indicates the string encoding type.  See enum _MSG_ENCODE_TYPE_E*/
-       MSG_SMS_SENDOPT_NETWORK_MODE_INT,                               /**< Indicates the network mode (CS/PS) to send SMS. See enum _MSG_SMS_NETWORK_MODE_E*/
-       MSG_SMS_SENDOPT_REPLY_PATH_BOOL,                                /**< Indicates whether the SMS reply path is set or not. */
-       MSG_SMS_SENDOPT_DELIVERY_REPORT_BOOL,                           /**< Indicates whether the SMS delivery report will be sent or not. */
-       MSG_SMS_SENDOPT_SAVE_STORAGE_INT                                /**< Indicates the default storage to save SMS. See enum _MSG_SMS_SAVE_STORAGE_E */
+       MSG_SMS_SENDOPT_ENCODE_TYPE_INT = MSG_STRUCT_SETTING_SMS_SEND_OPT+1,  /**< Indicates the string encoding type.  See enum _MSG_ENCODE_TYPE_E*/
+       MSG_SMS_SENDOPT_NETWORK_MODE_INT,                                     /**< Indicates the network mode (CS/PS) to send SMS. See enum _MSG_SMS_NETWORK_MODE_E*/
+       MSG_SMS_SENDOPT_REPLY_PATH_BOOL,                                      /**< Indicates whether the SMS reply path is set or not. */
+       MSG_SMS_SENDOPT_DELIVERY_REPORT_BOOL,                                 /**< Indicates whether the SMS delivery report will be sent or not. */
+       MSG_SMS_SENDOPT_SAVE_STORAGE_INT                                      /**< Indicates the default storage to save SMS. See enum _MSG_SMS_SAVE_STORAGE_E */
 };
 
+/**
+ *  @brief  Enumeration for the values of setting for MMS sending options. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SETTING_MMS_SEND_OPT.
+ */
 enum _MSG_STRUCT_MMS_SEND_OPT_E {
-       MSG_MMS_SENDOPT_CLASS_TYPE_INT = MSG_STRUCT_SETTING_MMS_SEND_OPT+1,             /**< Indicates the class type of message.  See enum _MSG_MMS_MSG_CLASS_TYPE_E */
-       MSG_MMS_SENDOPT_PRIORITY_TYPE_INT,                                      /**< Indicates the priority of the message. See enum _MSG_PRIORITY_TYPE_E */
-       MSG_MMS_SENDOPT_EXPIRY_TIME_INT,                                        /**< Indicates the time when the message is to be removed from the MMSC. See enum _MSG_MMS_EXPIRY_TIME_E */
-       MSG_MMS_SENDOPT_DELIVERY_TIME_INT,                                      /**< Indicates the message transmission time which is set in the MMSC. See enum _MSG_MMS_DELIVERY_TIME_E */
-       MSG_MMS_SENDOPT_CUSTOM_DELIVERY_TIME_INT,                               /**< Indicates the message transmission time which is set in the MMSC. */
-       MSG_MMS_SENDOPT_SENDER_VISIBILITY_BOOL,                                 /**< Indicates whether the address is hidden or not. */
-       MSG_MMS_SENDOPT_DELIVERY_REPORT_BOOL,                                   /**< Indicates whether the delivery report will be sent or not. */
-       MSG_MMS_SENDOPT_READ_REPLY_BOOL,                                        /**< Indicates whether the read report will be sent or not. */
-       MSG_MMS_SENDOPT_KEEP_COPY_BOOL,                                         /**< Indicates whether the message copy is kept or not. */
-       MSG_MMS_SENDOPT_BODY_REPLYING_BOOL,                                     /**< Indicates whether the body is included when replying or not. */
-       MSG_MMS_SENDOPT_HIDE_RECIPIENTS_BOOL,                                   /**< Indicates whether the recipients are hidden or not. */
-       MSG_MMS_SENDOPT_REPLY_CHARGING_INT,                                     /**< Indicates the reply charging type of message. See enum _MSG_MMS_REPLY_CHARGING_TYPE_E */
-       MSG_MMS_SENDOPT_REPLY_CHARGING_DEADLINE_INT,                            /**< Indicates the deadline for replying charging. is set in the MMSC. */
-       MSG_MMS_SENDOPT_REPLY_CHARGING_SIZE_INT,                                /**< Indicates the reply charging size. */
-       MSG_MMS_SENDOPT_CREATION_MODE_INT                                       /**< Indicates the creation mode of MMS. See enum _MSG_MMS_CREATION_MODE_E */
-};
-
+       MSG_MMS_SENDOPT_CLASS_TYPE_INT = MSG_STRUCT_SETTING_MMS_SEND_OPT+1,  /**< Indicates the class type of message.  See enum _MSG_MMS_MSG_CLASS_TYPE_E */
+       MSG_MMS_SENDOPT_PRIORITY_TYPE_INT,                                   /**< Indicates the priority of the message. See enum _MSG_PRIORITY_TYPE_E */
+       MSG_MMS_SENDOPT_EXPIRY_TIME_INT,                                     /**< Indicates the time when the message is to be removed from the MMSC. See enum _MSG_MMS_EXPIRY_TIME_E */
+       MSG_MMS_SENDOPT_DELIVERY_TIME_INT,                                   /**< Indicates the message transmission time which is set in the MMSC. See enum _MSG_MMS_DELIVERY_TIME_E */
+       MSG_MMS_SENDOPT_CUSTOM_DELIVERY_TIME_INT,                            /**< Indicates the message transmission time which is set in the MMSC. */
+       MSG_MMS_SENDOPT_SENDER_VISIBILITY_BOOL,                              /**< Indicates whether the address is hidden or not. */
+       MSG_MMS_SENDOPT_DELIVERY_REPORT_BOOL,                                /**< Indicates whether the delivery report will be sent or not. */
+       MSG_MMS_SENDOPT_READ_REPLY_BOOL,                                     /**< Indicates whether the read report will be sent or not. */
+       MSG_MMS_SENDOPT_KEEP_COPY_BOOL,                                      /**< Indicates whether the message copy is kept or not. */
+       MSG_MMS_SENDOPT_BODY_REPLYING_BOOL,                                  /**< Indicates whether the body is included when replying or not. */
+       MSG_MMS_SENDOPT_HIDE_RECIPIENTS_BOOL,                                /**< Indicates whether the recipients are hidden or not. */
+       MSG_MMS_SENDOPT_REPLY_CHARGING_INT,                                  /**< Indicates the reply charging type of message. See enum _MSG_MMS_REPLY_CHARGING_TYPE_E */
+       MSG_MMS_SENDOPT_REPLY_CHARGING_DEADLINE_INT,                         /**< Indicates the deadline for replying charging. is set in the MMSC. */
+       MSG_MMS_SENDOPT_REPLY_CHARGING_SIZE_INT,                             /**< Indicates the reply charging size. */
+       MSG_MMS_SENDOPT_CREATION_MODE_INT                                    /**< Indicates the creation mode of MMS. See enum _MSG_MMS_CREATION_MODE_E */
+};
+
+/**
+ *  @brief  Enumeration for the values of setting for MMS receiving options. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SETTING_MMS_RECV_OPT.
+ */
 enum _MSG_STRUCT_MMS_RECV_OPT_E {
-       MSG_MMS_RECVOPT_HOME_RETRIEVE_TYPE_INT = MSG_STRUCT_SETTING_MMS_RECV_OPT+1,     /**< Indicates the retrieve type for MMS home network. See enum _MSG_MMS_HOME_RETRIEVE_TYPE_E */
-       MSG_MMS_RECVOPT_ABROAD_RETRIEVE_TYPE_INT,                               /**< Indicates the retrieve type for MMS abroad network. See enum _MSG_MMS_ABROAD_RETRIEVE_TYPE_E */
-       MSG_MMS_RECVOPT_READ_REPORT_BOOL,                                       /**< Indicates whether the read report will be sent or not. */
-       MSG_MMS_RECVOPT_DELIVERY_REPORT_BOOL,                                   /**< Indicates whether the delivery report will be sent or not. */
-       MSG_MMS_RECVOPT_REJECT_UNKNOWN_BOOL,                                    /**< Indicates whether unknown addresses are rejected or not. */
-       MSG_MMS_RECVOPT_REJECT_ADVERTISEMENT_BOOL                               /**< Indicates whether advertisement is rejected or not. */
+       MSG_MMS_RECVOPT_HOME_RETRIEVE_TYPE_INT = MSG_STRUCT_SETTING_MMS_RECV_OPT+1, /**< Indicates the retrieve type for MMS home network. See enum _MSG_MMS_HOME_RETRIEVE_TYPE_E */
+       MSG_MMS_RECVOPT_ABROAD_RETRIEVE_TYPE_INT,                                   /**< Indicates the retrieve type for MMS abroad network. See enum _MSG_MMS_ABROAD_RETRIEVE_TYPE_E */
+       MSG_MMS_RECVOPT_READ_REPORT_BOOL,                                           /**< Indicates whether the read report will be sent or not. */
+       MSG_MMS_RECVOPT_DELIVERY_REPORT_BOOL,                                       /**< Indicates whether the delivery report will be sent or not. */
+       MSG_MMS_RECVOPT_REJECT_UNKNOWN_BOOL,                                        /**< Indicates whether unknown addresses are rejected or not. */
+       MSG_MMS_RECVOPT_REJECT_ADVERTISEMENT_BOOL                                   /**< Indicates whether advertisement is rejected or not. */
 };
 
+/**
+ *  @brief  Enumeration for the values of setting for general options. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SETTING_GENERAL_OPT.
+ */
 enum _MSG_STRUCT_GENERAL_OPT_E {
-       MSG_GENERAL_KEEP_COPY_BOOL = MSG_STRUCT_SETTING_GENERAL_OPT+1,                  /**< Indicates whether the SMS message copy is kept or not. */
-       MSG_GENERAL_ALERT_TONE_INT,                                             /**< Indicates the period of playing alert tone. See enum _MSG_ALERT_TONE_E */
-       MSG_GENERAL_AUTO_ERASE_BOOL                                             /**< Indicates whether the auto-erase option is enabled or not. */
+       MSG_GENERAL_KEEP_COPY_BOOL = MSG_STRUCT_SETTING_GENERAL_OPT+1,  /**< Indicates whether the SMS message copy is kept or not. */
+       MSG_GENERAL_ALERT_TONE_INT,                                     /**< Indicates the period of playing alert tone. See enum _MSG_ALERT_TONE_E */
+       MSG_GENERAL_AUTO_ERASE_BOOL,                                    /**< Indicates whether the auto-erase option is enabled or not. */
+       MSG_GENERAL_BLOCK_UNKNOWN_NUMBER_BOOL,                          /**< Indicates whether unknown sender message is blocked or not. */
+       MSG_GENERAL_SMS_LIMIT_CNT_INT,                                  /**< Indicates the count limitation of SMS messages in one conversation */
+       MSG_GENERAL_MMS_LIMIT_CNT_INT,                                  /**< Indicates the count limitation of MMS messages in one conversation */
+       MSG_GENERAL_MSG_NOTIFICATION_BOOL,                              /**< Indicates whether notification for incoming message is shown or not. */
+       MSG_GENERAL_MSG_VIBRATION_BOOL,                                 /**< Indicates whether vibration for incoming message is run or not. */
+       MSG_GENERAL_MSG_PREVIEW_BOOL,                                   /**< Indicates whether preview for incoming message is shown or not. */
+       MSG_GENERAL_RINGTONE_TYPE_INT,                                  /**< Indicates the message ringtone type. */
+       MSG_GENERAL_RINGTONE_PATH_STR                                   /**< Indicates the message ringtone path */
 };
 
+/**
+ *  @brief  Enumeration for the values of setting for push message options. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SETTING_PUSH_MSG_OPT.
+ */
 enum _MSG_STRUCT_PUSH_MSG_OPT_E {
-       MSG_PUSHMSG_RECEIVE_BOOL = MSG_STRUCT_SETTING_PUSH_MSG_OPT+1,           /**< Indicates whether the push message is received or not. */
-       MSG_PUSHMSG_SERVICE_TYPE_INT                                    /**< Indicates the service type of a push message. See enum _MSG_PUSH_SERVICE_TYPE_E */
+       MSG_PUSHMSG_RECEIVE_BOOL = MSG_STRUCT_SETTING_PUSH_MSG_OPT+1,  /**< Indicates whether the push message is received or not. */
+       MSG_PUSHMSG_SERVICE_TYPE_INT                                   /**< Indicates the service type of a push message. See enum _MSG_PUSH_SERVICE_TYPE_E */
 };
 
+/**
+ *  @brief  Enumeration for the values of setting for voice message options. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SETTING_VOICE_MSG_OPT.
+ */
 enum _MSG_STRUCT_VOICE_MSG_OPT_E {
-       MSG_VOICEMSG_ADDRESS_STR = MSG_STRUCT_SETTING_VOICE_MSG_OPT+1,          /**< Indicates the address for voice message. */
+       MSG_VOICEMSG_ADDRESS_STR = MSG_STRUCT_SETTING_VOICE_MSG_OPT+1,  /**< Indicates the address for voice message. */
+       MSG_VOICEMSG_ALPHA_ID_STR,                                      /**< Indicates the alpha id for voice message address. */
+       MSG_VOICEMSG_SIM_INDEX_INT,                                     /**< Indicates the SIM index for voice message. */
+       MSG_VOICEMSG_VOICE_COUNT_INT,                                   /**< Indicates the count of voice messages. */
 };
 
+
+/**
+ *  @brief  Enumeration for the values of setting for message size option. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SETTING_MSGSIZE_OPT.
+ */
 enum _MSG_STRUCT_MSGSISE_OPT_E {
-       MSG_MESSAGE_SIZE_INT = MSG_STRUCT_SETTING_MSGSIZE_OPT+1,                /**< Indicates the message size */
+       MSG_MESSAGE_SIZE_INT = MSG_STRUCT_SETTING_MSGSIZE_OPT+1,        /**< Indicates the message size */
 };
 
-//MSG_MMS_DATA
+/**
+ *  @brief  Enumeration for the values of MMS detail informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MMS.
+ */
 enum MSG_MMS_INFO_E {
-       MSG_MMS_PAGE_LIST_HND = MSG_STRUCT_MMS+1,                       /**< The pointer to SMIL pages list */
-       MSG_MMS_REGION_LIST_HND,                                        /**< The pointer to SMIL regions list */
-       MSG_MMS_ATTACH_LIST_HND,                                        /**< The pointer to attachment list */
-       MSG_MMS_TRANSITION_LIST_HND,                                    /**< The pointer to SMIL transitions list */
-       MSG_MMS_META_LIST_HND,                                          /**< The pointer to SMIL meta list */
-       MSG_MMS_ROOTLAYOUT_WIDTH_INT,                                   /**< Indicates the width of the root layout */
-       MSG_MMS_ROOTLAYOUT_WIDTH_PERCENT_BOOL,                          /**< Indicates the length is in percentage(%) or not */
-       MSG_MMS_ROOTLAYOUT_HEIGHT_INT,                                  /**< Indicates the height of the root layout */
-       MSG_MMS_ROOTLAYOUT_HEIGHT_PERCENT_BOOL,                         /**< Indicates the length is in percentage(%) or not */
-       MSG_MMS_ROOTLAYOUT_BGCOLOR_INT,                                 /**< Indicates the background color of the root layout */
-};
-
-//MSG_MMS_PAGE
+       MSG_MMS_PAGE_LIST_HND = MSG_STRUCT_MMS+1,       /**< The pointer to SMIL pages list */
+       MSG_MMS_REGION_LIST_HND,                        /**< The pointer to SMIL regions list */
+       MSG_MMS_ATTACH_LIST_HND,                        /**< The pointer to attachment list */
+       MSG_MMS_TRANSITION_LIST_HND,                    /**< The pointer to SMIL transitions list */
+       MSG_MMS_META_LIST_HND,                          /**< The pointer to SMIL meta list */
+       MSG_MMS_ROOTLAYOUT_WIDTH_INT,                   /**< Indicates the width of the root layout */
+       MSG_MMS_ROOTLAYOUT_WIDTH_PERCENT_BOOL,          /**< Indicates the length is in percentage(%) or not */
+       MSG_MMS_ROOTLAYOUT_HEIGHT_INT,                  /**< Indicates the height of the root layout */
+       MSG_MMS_ROOTLAYOUT_HEIGHT_PERCENT_BOOL,         /**< Indicates the length is in percentage(%) or not */
+       MSG_MMS_ROOTLAYOUT_BGCOLOR_INT,                 /**< Indicates the background color of the root layout */
+       MSG_MMS_ROOTLAYOUT_BGCOLOR_BOOL,                /**< Indicates the background color is set in the root layout */
+       MSG_MMS_HEADER_BCC_ADDRESS_LIST_HND,            /**< The pointer to BCC address list */
+       MSG_MMS_HEADER_CC_ADDRESS_LIST_HND,             /**< The pointer to CC address list */
+       MSG_MMS_HEADER_CONTENT_LOCATION_STR,            /**< Indicates contentLocation in MMS header */
+       MSG_MMS_HEADER_CONTENT_TYPE_STR,                /**< Indicates szContentType in MMS header. ex) application/vnd.wap.multipart.related */
+       MSG_MMS_HEADER_DATE_INT,                        /**< Indicates date in MMS header */
+       MSG_MMS_HEADER_DELIVERY_REPORT_INT,             /**< Indicates X-Mms-Delivery-Report */
+       MSG_MMS_HEADER_DELIVERY_TIME_INT,               /**< Indicates X-Mms-Delivery-Time */
+       MSG_MMS_HEADER_EXPIRY_TIME_INT,                 /**< Indicates X-Mms-Expiry-Time */
+       MSG_MMS_HEADER_FROM_STR,                        /**< Indicates FROM address in header */
+       MSG_MMS_HEADER_MESSAGE_CLASS_INT,               /**< Indicates messageClassin in header. ex) Personal | Advertisement | Informational | Auto */
+       MSG_MMS_HEADER_MESSAGE_ID_STR,                  /**< Indicates messageID in header*/
+       MSG_MMS_HEADER_MESSAGE_TYPE_INT,                /**< Indicates MmsMsgTypein header. ex) sendreq */
+       MSG_MMS_HEADER_VERSION_INT,                     /**< Indicates mmsVersion in header. ex) 1.0 1.3 etc */
+       MSG_MMS_HEADER_SIZE_INT,                        /**< Indicates X-Mms-Message-Size */
+       MSG_MMS_HEADER_PRIORITY_INT,                    /**< Indicates _MSG_PRIORITY_TYPE_E in header: Low | Normal | High */
+       MSG_MMS_HEADER_READ_REPORT_INT,                 /**< Indicates X-Mms-Read-Report */
+       MSG_MMS_HEADER_HIDE_ADDRESS_INT,                /**< Indicates X-Mms-Sender-Visibility */
+       MSG_MMS_HEADER_MMS_STATUS_INT,                  /**< Indicates X-Mms-Status */
+       MSG_MMS_HEADER_TO_ADDRESS_LIST_HND,             /**< The pointer to 'TO' address list in header*/
+       MSG_MMS_HEADER_TR_ID_STR,                       /**< Indicates thread ID in header */
+       MSG_MMS_HEADER_CONTENT_CLASS_INT,               /**< Indicates contentClass in header. ex) text | image-basic| image-rich | video-basic | video-rich | megapixel | content-basic | content-rich */
+       MSG_MMS_SMIL_MULTIPART_CONTENT_TYPE_STR,        /**< Indicates multipart content type in header*/
+       MSG_MMS_SMIL_MULTIPART_NAME_STR,                /**<Indicates multipart file name in header*/
+       MSG_MMS_SMIL_MULTIPART_FILEPATH_STR,            /**< Indicates multipart file path in header*/
+       MSG_MMS_SMIL_MULTIPART_CONTENT_ID_STR,          /**< Indicates multipart content id in header*/
+       MSG_MMS_SMIL_MULTIPART_CONTENT_LOCATION_STR,    /**< Indicates multipart content Location in header*/
+       MSG_MMS_MULTIPART_LIST_HND,                     /**< The pointer to MMS multipart list */
+       MSG_MMS_INFO_MAX,                               /**< Placeholder for max value of this enum */
+};
+
+/**
+ *  @brief  Enumeration for the values of MMS multipart informations. \n
+ *          This enum is used as member of #msg_struct_t for MMS_MULTIPART_DATA_S.
+ */
+enum _MSG_STRUCT_MULTIPART_INFO_E {
+       MSG_MMS_MULTIPART_CONTENT_TYPE_STR = MSG_STRUCT_MULTIPART_INFO+1,  /**< Indicates multipart content type */
+       MSG_MMS_MULTIPART_NAME_STR,                                        /**< Indicates multipart file name */
+       MSG_MMS_MULTIPART_FILEPATH_STR,                                    /**< Indicates multipart file path */
+       MSG_MMS_MULTIPART_CONTENT_ID_STR,                                  /**< Indicates mutipart content ID */
+       MSG_MMS_MULTIPART_CONTENT_LOCATION_STR,                            /**< Indicates multipart content Location */
+       MSG_MMS_MULTIPART_TCS_LEVEL_INT,                                   /**< Indicates detection of malware type */
+       MSG_MMS_MULTIPART_MALWARE_ALLOW_INT,                               /**< Indicates malware allowed */
+       MSG_MMS_MULTIPART_THUMBNAIL_FILEPATH_STR,                          /**< Indicates the thumbnail filepath */
+};
+
+/**
+ *  @brief  Enumeration for the values of MMS page informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MMS_PAGE.
+ */
 enum MSG_MMS_PAGE_INFO_E {
-       MSG_MMS_PAGE_MEDIA_LIST_HND = MSG_STRUCT_MMS_PAGE+1,            /**< The pointer to media list */
-       MSG_MMS_PAGE_PAGE_DURATION_INT,                                 /**< Indicates the duration of the page */
-       MSG_MMS_PAGE_BEGIN_TIME_INT,                                    /**< Indicates the begin time of the page */
-       MSG_MMS_PAGE_END_TIME_INT,                                      /**< Indicates the end time of the page */
-       MSG_MMS_PAGE_MIN_INT,                                           /**< Indicates the min attribute of the page */
-       MSG_MMS_PAGE_MAX_INT,                                           /**< Indicates the max attribute of the page */
-       MSG_MMS_PAGE_REPEAT_INT,                                        /**< Indicates the page needs to be displayed repeatedly */
+       MSG_MMS_PAGE_MEDIA_LIST_HND = MSG_STRUCT_MMS_PAGE+1,  /**< The pointer to media list */
+       MSG_MMS_PAGE_PAGE_DURATION_INT,                       /**< Indicates the duration of the page */
+       MSG_MMS_PAGE_BEGIN_TIME_INT,                          /**< Indicates the begin time of the page */
+       MSG_MMS_PAGE_END_TIME_INT,                            /**< Indicates the end time of the page */
+       MSG_MMS_PAGE_MIN_INT,                                 /**< Indicates the min attribute of the page */
+       MSG_MMS_PAGE_MAX_INT,                                 /**< Indicates the max attribute of the page */
+       MSG_MMS_PAGE_REPEAT_INT,                              /**< Indicates the page needs to be displayed repeatedly */
 };
 
+/**
+ *  @brief  Enumeration for the values of MMS media informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MMS_MEDIA.
+ */
 enum MSG_MMS_MEDIA_INFO {
-       MSG_MMS_MEDIA_TYPE_INT = MSG_STRUCT_MMS_MEDIA+1,                /**< Indicates the SMIL media type. see enum MmsSmilMediaType */
-       MSG_MMS_MEDIA_SRC_STR,                                          /**< Indicates the media source name */
-       MSG_MMS_MEDIA_FILENAME_STR,                                     /**< Indicates the file name */
-       MSG_MMS_MEDIA_FILEPATH_STR,                                     /**< Indicates the file path */
-       MSG_MMS_MEDIA_CONTENT_ID_STR,                                   /**< Indicates the content id */
-       MSG_MMS_MEDIA_REGION_ID_STR,                                    /**< Indicates the region id */
-       MSG_MMS_MEDIA_ALTERNATIVE_STR,                                  /**< Indicates the alternative text to be displayed in failure case */
-       MSG_MMS_MEDIA_DRM_TYPE_INT,                                     /**< Indicates the drm type. see enum MsgDrmType */
-       MSG_MMS_MEDIA_DRM_FULLPATH_STR,                                 /**< Indicates the fullpath of the DRM */
-       MSG_MMS_MEDIA_SMIL_TEXT_HND,                                    /**< Indicates the text attributes */
-       MSG_MMS_MEDIA_SMIL_AVI_HND,                                     /**< Indicates the video attributes */
-};
-
-//MSG_MMS_ATTACH
+       MSG_MMS_MEDIA_TYPE_INT = MSG_STRUCT_MMS_MEDIA+1,  /**< Indicates the SMIL media type. See enum MmsSmilMediaType */
+       MSG_MMS_MEDIA_SRC_STR,                            /**< Indicates the media source name */
+       MSG_MMS_MEDIA_FILENAME_STR,                       /**< Indicates the file name */
+       MSG_MMS_MEDIA_FILEPATH_STR,                       /**< Indicates the file path */
+       MSG_MMS_MEDIA_CONTENT_ID_STR,                     /**< Indicates the content ID */
+       MSG_MMS_MEDIA_REGION_ID_STR,                      /**< Indicates the region ID */
+       MSG_MMS_MEDIA_ALTERNATIVE_STR,                    /**< Indicates the alternative text to be displayed in failure case */
+       MSG_MMS_MEDIA_DRM_TYPE_INT,                       /**< Indicates the DRM type. See enum MsgDrmType */
+       MSG_MMS_MEDIA_DRM_FULLPATH_STR,                   /**< Indicates the fullpath of the DRM */
+       MSG_MMS_MEDIA_SMIL_TEXT_HND,                      /**< Indicates the text attributes */
+       MSG_MMS_MEDIA_SMIL_AVI_HND,                       /**< Indicates the video attributes */
+       MSG_MMS_MEDIA_CONTENT_LOCATION_STR,               /**< Indicates the content location */
+       MSG_MMS_MEDIA_CONTENT_TYPE_STR,                   /**< Indicates the content type */
+       MSG_MMS_MEDIA_INFO_MAX,                           /**< Placeholder for max value of this enum*/
+};
+
+/**
+ *  @brief  Enumeration for the values of MMS attachment informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MMS_ATTACH.
+ */
 enum MSG_MMS_ATTACH_INFO_E {
-       MSG_MMS_ATTACH_MIME_TYPE_INT = MSG_STRUCT_MMS_ATTACH+1,         /**< Indicates the file mime type. see enum MimeType */
-       MSG_MMS_ATTACH_FILENAME_STR,                                    /**< Indicates the file name */
-       MSG_MMS_ATTACH_FILEPATH_STR,                                    /**< Indicates the file path */
-       MSG_MMS_ATTACH_FILESIZE_INT,                                    /**< Indicates the size of the file */
-       MSG_MMS_ATTACH_DRM_TYPE_INT,                                    /**< Indicates the drm type. see enum MsgDrmType */
-       MSG_MMS_ATTACH_DRM_FULLPATH_STR,                                /**< Indicates the fullpath of the DRM */
+       MSG_MMS_ATTACH_MIME_TYPE_INT = MSG_STRUCT_MMS_ATTACH+1,     /**< Indicates the file mime type. See enum MimeType */
+       MSG_MMS_ATTACH_FILENAME_STR,                                /**< Indicates the file name */
+       MSG_MMS_ATTACH_FILEPATH_STR,                                /**< Indicates the file path */
+       MSG_MMS_ATTACH_FILESIZE_INT,                                /**< Indicates the size of the file */
+       MSG_MMS_ATTACH_DRM_TYPE_INT,                                /**< Indicates the DRM type. See enum MsgDrmType */
+       MSG_MMS_ATTACH_DRM_FULLPATH_STR,                            /**< Indicates the fullpath of the DRM */
+       MSG_MMS_ATTACH_CONTENT_TYPE_STR,                            /**< Indicates the content type */
+       MSG_MMS_ATTACH_INFO_MAX,                                    /**< Placeholder for max value of this enum*/
 };
 
+/**
+ *  @brief  Enumeration for the values of MMS region informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MMS_REGION.
+ */
 enum MSG_MMS_REGION_INFO_E {
-       MSG_MMS_REGION_ID_STR = MSG_STRUCT_MMS_REGION+1,                /**< Indicates the ID of region information */
-       MSG_MMS_REGION_LENGTH_LEFT_INT,                                 /**< Indicates the left co-ordinate of the region */
-       MSG_MMS_REGION_LENGTH_LEFT_PERCENT_BOOL,                        /**< Indicates the length is in percentage(%) or not */
-       MSG_MMS_REGION_LENGTH_TOP_INT,                                  /**< Indicates the top co-ordinate of the region */
-       MSG_MMS_REGION_LENGTH_TOP_PERCENT_BOOL,                         /**< Indicates the length is in percentage(%) or not */
-       MSG_MMS_REGION_LENGTH_WIDTH_INT,                                /**< Indicates the width of the region */
-       MSG_MMS_REGION_LENGTH_WIDTH_PERCENT_BOOL,                       /**< Indicates the length is in percentage(%) or not */
-       MSG_MMS_REGION_LENGTH_HEIGHT_INT,                               /**< Indicates the width of the region */
-       MSG_MMS_REGION_LENGTH_HEIGHT_PERCENT_BOOL,                      /**< Indicates the length is in percentage(%) or not */
-       MSG_MMS_REGION_BGCOLOR_INT,                                     /**< Indicates the background color of the region */
-       MSG_MMS_REGION_FIT_TYPE_INT,                                    /**< Indicates the fit type. see enum REGION_FIT_TYPE_T */
+       MSG_MMS_REGION_ID_STR = MSG_STRUCT_MMS_REGION+1,      /**< Indicates the ID of region information */
+       MSG_MMS_REGION_LENGTH_LEFT_INT,                       /**< Indicates the left co-ordinate of the region */
+       MSG_MMS_REGION_LENGTH_LEFT_PERCENT_BOOL,              /**< Indicates the length is in percentage(%) or not */
+       MSG_MMS_REGION_LENGTH_TOP_INT,                        /**< Indicates the top co-ordinate of the region */
+       MSG_MMS_REGION_LENGTH_TOP_PERCENT_BOOL,               /**< Indicates the length is in percentage(%) or not */
+       MSG_MMS_REGION_LENGTH_WIDTH_INT,                      /**< Indicates the width of the region */
+       MSG_MMS_REGION_LENGTH_WIDTH_PERCENT_BOOL,             /**< Indicates the length is in percentage(%) or not */
+       MSG_MMS_REGION_LENGTH_HEIGHT_INT,                     /**< Indicates the width of the region */
+       MSG_MMS_REGION_LENGTH_HEIGHT_PERCENT_BOOL,            /**< Indicates the length is in percentage(%) or not */
+       MSG_MMS_REGION_BGCOLOR_INT,                           /**< Indicates the background color of the region */
+       MSG_MMS_REGION_FIT_TYPE_INT,                          /**< Indicates the fit type. See enum REGION_FIT_TYPE_T */
+       MSG_MMS_REGION_BGCOLOR_BOOL,                          /**< Indicates the background color is set in the region */
 };
 
+/**
+ *  @brief  Enumeration for the values of MMS meta data informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MMS_META.
+ */
 enum MSG_MMS_META_INFO_E {
-       MSG_MMS_META_ID_STR = MSG_STRUCT_MMS_META+1,                    /**< Indicates the ID of meta information */
-       MSG_MMS_META_NAME_STR,                                          /**< Indicates the Name */
-       MSG_MMS_META_CONTENT_STR,                                       /**< Indicates the content */
+       MSG_MMS_META_ID_STR = MSG_STRUCT_MMS_META+1,  /**< Indicates the ID of meta information */
+       MSG_MMS_META_NAME_STR,                        /**< Indicates the Name */
+       MSG_MMS_META_CONTENT_STR,                     /**< Indicates the content */
 };
 
-enum MSG_MMS_TRANSION_INFO_E {
-       MSG_MMS_TRANSITION_ID_STR = MSG_STRUCT_MMS_TRANSITION+1,        /**< Indicates the ID of transition information */
-       MSG_MMS_TRANSITION_TYPE_INT,                                    /**< Indicates the transition type. see enum MmsSmilTransType */
-       MSG_MMS_TRANSITION_SUBTYPE_INT,                                 /**< Indicates the transition sub type. see enum MmsSmilTransSubType */
-       MSG_MMS_TRANSITION_DURATION_INT,                                /**< Indicates the transition duration */
+/**
+ *  @brief  Enumeration for the values of MMS transition informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MMS_TRANSITION.
+ */
+enum MSG_MMS_TRANSITION_INFO_E {
+       MSG_MMS_TRANSITION_ID_STR = MSG_STRUCT_MMS_TRANSITION+1,    /**< Indicates the ID of transition information */
+       MSG_MMS_TRANSITION_TYPE_INT,                                /**< Indicates the transition type. See enum MmsSmilTransType */
+       MSG_MMS_TRANSITION_SUBTYPE_INT,                             /**< Indicates the transition sub type. See enum MmsSmilTransSubType */
+       MSG_MMS_TRANSITION_DURATION_INT,                            /**< Indicates the transition duration */
 };
 
+/**
+ *  @brief  Enumeration for the values of MMS SMIL text informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MMS_SMIL_TEXT.
+ */
 enum MSG_MMS_SMIL_TEXT_INFO_E {
-       MSG_MMS_SMIL_TEXT_TRANSITION_IN_ID_STR = MSG_STRUCT_MMS_SMIL_TEXT+1,    /**< Indicates the In SMIL transition id */
-       MSG_MMS_SMIL_TEXT_TRANSITION_OUT_ID_STR,                                /**< Indicates the Out SMIL transition id */
-       MSG_MMS_SMIL_TEXT_REPEAT_INT,                                           /**< Indicates the text needs to be displayed repeatedly */
-       MSG_MMS_SMIL_TEXT_BEGIN_INT,                                            /**< Indicates the begin time */
-       MSG_MMS_SMIL_TEXT_END_INT,                                              /**< Indicates the end time */
-       MSG_MMS_SMIL_TEXT_DURTIME_INT,                                          /**< Indicates the duration */
-       MSG_MMS_SMIL_TEXT_BGCOLOR_INT,                                          /**< Indicates the background color of the text */
-       MSG_MMS_SMIL_TEXT_BOLD_BOOL,                                            /**< Indicates whether the text is bold */
-       MSG_MMS_SMIL_TEXT_UNDERLINE_BOOL,                                       /**< Indicates whether the text is underlined */
-       MSG_MMS_SMIL_TEXT_ITALIC_BOOL,                                          /**< Indicates whether the text is Italic */
-       MSG_MMS_SMIL_TEXT_REVERSE_BOOL,                                         /**< Indicates whether the text is reversed */
-       MSG_MMS_SMIL_TEXT_DIRECTION_TYPE_INT,                                   /**< Indicates the text direction type. see enum MmsTextDirection */
-       MSG_MMS_SMIL_TEXT_SIZE_INT,                                             /**< Indicates the font size */
-       MSG_MMS_SMIL_TEXT_COLOR_INT,                                            /**< Indicates the font color */
-};
-
+       MSG_MMS_SMIL_TEXT_TRANSITION_IN_ID_STR = MSG_STRUCT_MMS_SMIL_TEXT+1,  /**< Indicates the In SMIL transition ID */
+       MSG_MMS_SMIL_TEXT_TRANSITION_OUT_ID_STR,                              /**< Indicates the Out SMIL transition ID */
+       MSG_MMS_SMIL_TEXT_REPEAT_INT,                                         /**< Indicates the text needs to be displayed repeatedly */
+       MSG_MMS_SMIL_TEXT_BEGIN_INT,                                          /**< Indicates the begin time */
+       MSG_MMS_SMIL_TEXT_END_INT,                                            /**< Indicates the end time */
+       MSG_MMS_SMIL_TEXT_DURTIME_INT,                                        /**< Indicates the duration */
+       MSG_MMS_SMIL_TEXT_BGCOLOR_INT,                                        /**< Indicates the background color of the text */
+       MSG_MMS_SMIL_TEXT_BOLD_BOOL,                                          /**< Indicates whether the text is bold */
+       MSG_MMS_SMIL_TEXT_UNDERLINE_BOOL,                                     /**< Indicates whether the text is underlined */
+       MSG_MMS_SMIL_TEXT_ITALIC_BOOL,                                        /**< Indicates whether the text is Italic */
+       MSG_MMS_SMIL_TEXT_REVERSE_BOOL,                                       /**< Indicates whether the text is reversed */
+       MSG_MMS_SMIL_TEXT_DIRECTION_TYPE_INT,                                 /**< Indicates the text direction type. see enum MmsTextDirection */
+       MSG_MMS_SMIL_TEXT_SIZE_INT,                                           /**< Indicates the font size */
+       MSG_MMS_SMIL_TEXT_COLOR_INT,                                          /**< Indicates the font color */
+};
+
+/**
+ *  @brief  Enumeration for the values of MMS SMIL avi informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MMS_SMIL_AVI.
+ */
 enum MSG_MMS_SMIL_AVI_INFO_E {
-       MSG_MMS_SMIL_AVI_TRANSITION_IN_ID_STR = MSG_STRUCT_MMS_SMIL_AVI+1,      /**< Indicates the In SMIL transition id */
-       MSG_MMS_SMIL_AVI_TRANSITION_OUT_ID_STR,                                 /**< Indicates the Out SMIL transition id */
-       MSG_MMS_SMIL_AVI_REPEAT_INT,                                            /**< Indicates the video needs to be displayed repeatedly */
-       MSG_MMS_SMIL_AVI_BEGIN_INT,                                             /**< Indicates the begin time */
-       MSG_MMS_SMIL_AVI_END_INT,                                               /**< Indicates the end time */
-       MSG_MMS_SMIL_AVI_DURTIME_INT,                                           /**< Indicates the duration */
-       MSG_MMS_SMIL_AVI_BGCOLOR_INT,                                           /**< Indicates the background color of the text */
+       MSG_MMS_SMIL_AVI_TRANSITION_IN_ID_STR = MSG_STRUCT_MMS_SMIL_AVI+1,  /**< Indicates the In SMIL transition ID */
+       MSG_MMS_SMIL_AVI_TRANSITION_OUT_ID_STR,                             /**< Indicates the Out SMIL transition ID */
+       MSG_MMS_SMIL_AVI_REPEAT_INT,                                        /**< Indicates the video needs to be displayed repeatedly */
+       MSG_MMS_SMIL_AVI_BEGIN_INT,                                         /**< Indicates the begin time */
+       MSG_MMS_SMIL_AVI_END_INT,                                           /**< Indicates the end time */
+       MSG_MMS_SMIL_AVI_DURTIME_INT,                                       /**< Indicates the duration */
+       MSG_MMS_SMIL_AVI_BGCOLOR_INT,                                       /**< Indicates the background color of the text */
 };
 
+/**
+ *  @brief  Enumeration for the values of message sending options. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SENDOPT.
+ */
 enum MSG_SEND_OPT_E {
-       MSG_SEND_OPT_SETTING_BOOL = MSG_STRUCT_SENDOPT+1,                       /**< Indicates whether the sending option is set ot not for a message */
-       MSG_SEND_OPT_DELIVER_REQ_BOOL,                                          /**< Indicates whether the delivey custom time is used or not */
-       MSG_SEND_OPT_KEEPCOPY_BOOL,                                             /**< Indicates whether the message copy is kept or not */
-       MSG_SEND_OPT_MMS_OPT_HND,                                               /**< The handle of MMS sending option for a message */
-       MSG_SEND_OPT_SMS_OPT_HND,                                               /**< The handle of SMS sending option for a message */
+       MSG_SEND_OPT_SETTING_BOOL = MSG_STRUCT_SENDOPT+1,  /**< Indicates whether the sending option is set or not for a message */
+       MSG_SEND_OPT_DELIVER_REQ_BOOL,                     /**< Indicates whether the delivery custom time is used or not */
+       MSG_SEND_OPT_KEEPCOPY_BOOL,                        /**< Indicates whether the message copy is kept or not */
+       MSG_SEND_OPT_MMS_OPT_HND,                          /**< The handle of MMS sending option for a message */
+       MSG_SEND_OPT_SMS_OPT_HND,                          /**< The handle of SMS sending option for a message */
 };
 
+/**
+ *  @brief  Enumeration for the values of SyncML informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SYNCML_INFO.
+ */
 enum MSG_SYNCML_INFO_E {
-       MSG_SYNCML_INFO_EXTID_INT = MSG_STRUCT_SYNCML_INFO+1,                   /**< Indicates the ext ID */
-       MSG_SYNCML_INFO_PINCODE_INT,                                            /**< Indicates the PIN code */
-       MSG_SYNCML_INFO_MESSAGE_HND,                                            /**< Indicate the handle of a message */
+       MSG_SYNCML_INFO_EXTID_INT = MSG_STRUCT_SYNCML_INFO+1,  /**< Indicates the ext ID */
+       MSG_SYNCML_INFO_PINCODE_INT,                           /**< Indicates the PIN code */
+       MSG_SYNCML_INFO_MESSAGE_HND,                           /**< Indicate the handle of a message */
 };
 
+/**
+ *  @brief  Enumeration for the values of message count status. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_COUNT_INFO.
+ */
 enum MSG_COUNT_INFO_E {
-       MSG_COUNT_INFO_READ_INT = MSG_STRUCT_COUNT_INFO+1,                      /**< The count of read messages */
-       MSG_COUNT_INFO_UNREAD_INT,                                              /**< The count of unread messages */
-       MSG_COUNT_INFO_SMS_INT,                                                 /**< The count of sms type messages */
-       MSG_COUNT_INFO_MMS_INT,                                                 /**< The count of mms type messages */
+       MSG_COUNT_INFO_READ_INT = MSG_STRUCT_COUNT_INFO+1,  /**< The count of read messages */
+       MSG_COUNT_INFO_UNREAD_INT,                          /**< The count of unread messages */
+       MSG_COUNT_INFO_SMS_INT,                             /**< The count of SMS type messages */
+       MSG_COUNT_INFO_MMS_INT,                             /**< The count of MMS type messages */
 };
 
+/**
+ *  @brief  Enumeration for the values of message count in a thread. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_THREAD_COUNT_INFO.
+ */
 enum MSG_THREAD_COUNT_INFO_E {
-       MSG_THREAD_COUNT_TOTAL_INT = MSG_STRUCT_THREAD_COUNT_INFO+1,            /**< Indicates the total number of messages from the Peer. */
-       MSG_THREAD_COUNT_UNREAD_INT,                                            /**< Indicates the unread messages from the Peer. */
-       MSG_THREAD_COUNT_SMS_INT,                                               /**< Indicates the SMS messages from the Peer. */
-       MSG_THREAD_COUNT_MMS_INT,                                               /**< Indicates the MMS messages from the Peer. */
+       MSG_THREAD_COUNT_TOTAL_INT = MSG_STRUCT_THREAD_COUNT_INFO+1,  /**< Indicates the total number of messages from the Peer. */
+       MSG_THREAD_COUNT_UNREAD_INT,                                  /**< Indicates the unread messages from the peer. */
+       MSG_THREAD_COUNT_SMS_INT,                                     /**< Indicates the SMS messages from the peer. */
+       MSG_THREAD_COUNT_MMS_INT,                                     /**< Indicates the MMS messages from the peer. */
 };
 
+/**
+ *  @brief  Enumeration for the values of thread informations for address. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_THREAD_LIST_INDEX.
+ */
 enum MSG_THREAD_LIST_INDEX_E {
-       MSG_THREAD_LIST_INDEX_CONTACTID_INT = MSG_STRUCT_THREAD_LIST_INDEX+1,   /**< The contact id of message common informatioin */
-       MSG_THREAD_LIST_INDEX_ADDR_INFO_HND,                                    /**< The pointer to message common informatioin */
+       MSG_THREAD_LIST_INDEX_CONTACTID_INT = MSG_STRUCT_THREAD_LIST_INDEX+1,   /**< The contact ID of message common informatioin */
+       MSG_THREAD_LIST_INDEX_ADDR_INFO_HND,                                    /**< The pointer to message common informatioin */
 };
 
+/**
+ *  @brief  Enumeration for the values of sort rule for getting message list. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SORT_RULE.
+ */
 enum MSG_SORT_RULE_E {
-       MSG_SORT_RULE_SORT_TYPE_INT = MSG_STRUCT_SORT_RULE+1,           /**< Indicates the sort type. See enum _MSG_SORT_TYPE_E */
-       MSG_SORT_RULE_ACSCEND_BOOL,                                     /**< Indicates the sort order which is ascending or descending */
+       MSG_SORT_RULE_SORT_TYPE_INT = MSG_STRUCT_SORT_RULE+1,  /**< Indicates the sort type. See enum _MSG_SORT_TYPE_E */
+       MSG_SORT_RULE_ACSCEND_BOOL,                            /**< Indicates the sort order which is ascending or descending */
 };
 
+/**
+ *  @brief  Enumeration for the values of message folder information. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_FOLDER_INFO.
+ */
 enum MSG_FOLDER_INFO_E {
-       MSG_FOLDER_INFO_ID_INT = MSG_STRUCT_FOLDER_INFO+1,              /**< Indicates the unique folder ID. */
-       MSG_FOLDER_INFO_NAME_STR,                                       /**< Indicates the name of the folder. */
-       MSG_FOLDER_INFO_TYPE_INT,                                       /**< Indicates the folder type. */
+       MSG_FOLDER_INFO_ID_INT = MSG_STRUCT_FOLDER_INFO+1,  /**< Indicates the unique folder ID. */
+       MSG_FOLDER_INFO_NAME_STR,                           /**< Indicates the name of the folder. */
+       MSG_FOLDER_INFO_TYPE_INT,                           /**< Indicates the folder type. */
 };
 
+/**
+ *  @brief  Enumeration for the values of conditions for searching message. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SEARCH_CONDITION.
+ */
 enum MSG_SEARCH_CONDITION_E {
-       MSG_SEARCH_CONDITION_FOLDERID_INT = MSG_STRUCT_SEARCH_CONDITION+1,              /**< Indicates the folder ID for searching messages. See enum _MSG_FOLDER_ID_E */
-       MSG_SEARCH_CONDITION_MSGTYPE_INT,                                               /**< Indicates the message type for searching messages. See enum _MSG_MESSAGE_TYPE_E */
-       MSG_SEARCH_CONDITION_ADDRESS_VALUE_STR,                                         /**< The address value for searching messages. */
-       MSG_SEARCH_CONDITION_SEARCH_VALUE_STR,                                          /**< The string to search */
-       MSG_SEARCH_CONDITION_RESERVED_INT,
+       MSG_SEARCH_CONDITION_FOLDERID_INT = MSG_STRUCT_SEARCH_CONDITION+1,  /**< The folder ID for searching messages. See enum _MSG_FOLDER_ID_E */
+       MSG_SEARCH_CONDITION_MSGTYPE_INT,                                   /**< The message type for searching messages. See enum _MSG_MESSAGE_TYPE_E */
+       MSG_SEARCH_CONDITION_ADDRESS_VALUE_STR,                             /**< The address value for searching messages. */
+       MSG_SEARCH_CONDITION_SEARCH_VALUE_STR,                              /**< The string to search */
+       MSG_SEARCH_CONDITION_RESERVED_INT,                                  /**< The search condition reserved*/
 };
 
-enum MSG_REPORT_STATUS_E {
-       MSG_REPORT_STATUS_DELIVERY_STATUS_INT = MSG_STRUCT_REPORT_STATUS_INFO+1,        /**< Indicates the message ID of this message. */
-       MSG_REPORT_STATUS_DELIVERY_TIME_INT,                                            /**< Indicates the display time related to the specific operation. */
-       MSG_REPORT_STATUS_READ_STATUS_INT,                                              /**< Indicates the message ID of this message. */
-       MSG_REPORT_STATUS_READ_TIME_INT,                                                /**< Indicates the display time related to the specific operation. */
+/**
+ *  @brief  Enumeration for the values of report message status. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_REPORT_STATUS_INFO.
+ */
+enum MSG_REPORT_E {
+       MSG_REPORT_ADDRESS_STR = MSG_STRUCT_REPORT_STATUS_INFO+1,  /**< Indicates Report address */
+       MSG_REPORT_TYPE_INT,                                       /**< Indicates Report type. See the msg_report_type_t type*/
+       MSG_REPORT_STATUS_INT,                                     /**< Indicates Report status. See the msg_delivery_report_status_t or msg_read_report_status_t type*/
+       MSG_REPORT_TIME_INT,                                       /**< Indicates Report time */
 };
+
+/**
+ *  @brief  Enumeration for the values of conditions for getting message list. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MSG_LIST_CONDITION.
+ */
+enum MSG_LIST_CONDITION_E {
+       MSG_LIST_CONDITION_FOLDER_ID_INT = MSG_STRUCT_MSG_LIST_CONDITION+1,  /**< Indicates the folder ID for searching messages. See enum _MSG_FOLDER_ID_E */
+       MSG_LIST_CONDITION_THREAD_ID_INT,                                    /**< Indicates the thread ID for searching messages. */
+       MSG_LIST_CONDITION_STORAGE_ID_INT,                                   /**< Indicates the storage ID for searching messages. See enum _MSG_STORAGE_ID_E */
+       MSG_LIST_CONDITION_MSGTYPE_INT,                                      /**< Indicates the message type for searching messages. See enum _MSG_MESSAGE_TYPE_E */
+       MSG_LIST_CONDITION_PROTECTED_BOOL,                                   /**< Indicates the protected flag for searching messages*/
+       MSG_LIST_CONDITION_SCHEDULED_BOOL,                                   /**< Indicates the scheduled flag for searching messages*/
+       MSG_LIST_CONDITION_ADDRESS_VALUE_STR,                                /**< The address value for searching messages. */
+       MSG_LIST_CONDITION_TEXT_VALUE_STR,                                   /**< The string to search */
+       MSG_LIST_CONDITION_AND_OPERATER_BOOL,                                /**< Indicates presence of 'AND' operator for searching messages*/
+       MSG_LIST_CONDITION_FROM_TIME_INT,                                    /**< Indicates the 'FROM TIME' for searching messages*/
+       MSG_LIST_CONDITION_TO_TIME_INT,                                      /**< Indicates the 'TO TIME' for searching messages*/
+       MSG_LIST_CONDITION_OFFSET_INT,                                       /**< Indicates Search Result offset*/
+       MSG_LIST_CONDITION_LIMIT_INT,                                        /**< Indicates Search Result limit*/
+       MSG_LIST_CONDITION_SORT_RULE_HND,                                    /**< The pointer to sort rule to apply*/
+       MSG_LIST_CONDITION_SIM_INDEX_INT,
+};
+
+/**
+ *  @brief  Enumeration for the values of address informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_ADDRESS_INFO.
+ */
 enum MSG_ADDRESS_INFO_E {
-       MSG_ADDRESS_INFO_ADDRESS_TYPE_INT = MSG_STRUCT_ADDRESS_INFO+1,                  /**< The type of an address in case of an Email or a mobile phone. See enum _MSG_ADDRESS_TYPE_E */
-       MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT,                                            /**< The type of recipient address in case of To, Cc, and Bcc. See enum _MSG_RECIPIENT_TYPE_E */
-       MSG_ADDRESS_INFO_CONTACT_ID_INT,                                                /**< The contact ID of address */
-       MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,                                             /**< The actual value of an address */
-       MSG_ADDRESS_INFO_DISPLAYNAME_STR,                                               /**< The display name of an address */
+       MSG_ADDRESS_INFO_ADDRESS_TYPE_INT = MSG_STRUCT_ADDRESS_INFO+1,  /**< The type of an address in case of an Email or a mobile phone. See enum _MSG_ADDRESS_TYPE_E */
+       MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT,                            /**< The type of recipient address in case of To, Cc, and Bcc. See enum _MSG_RECIPIENT_TYPE_E */
+       MSG_ADDRESS_INFO_CONTACT_ID_INT,                                /**< The contact ID of address **DEPRECATED** */
+       MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,                             /**< The actual value of an address */
+       MSG_ADDRESS_INFO_DISPLAYNAME_STR,                               /**< The display name of an address **DEPRECATED** */
 };
 
+/**
+ *  @brief  Enumeration for the values of MMS sending options for sent message. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MMS_SENDOPT.
+ */
 enum MSG_MMS_SENDOPT_E {
-       MSG_MMS_SENDOPTION_READ_REQUEST_BOOL = MSG_STRUCT_MMS_SENDOPT+1,                /**< Indicates whether it requests read report or not */
-       MSG_MMS_SENDOPTION_EXPIRY_TIME_INT,                                             /**< Indicates MMS expiry time */
-       MSG_MMS_SENDOPTION_DELIVERY_CUSTOMTIME_BOOL,                                    /**< Indicates whether is use MMS delivery custom time */
-       MSG_MMS_SENDOPTION_DELIVERY_TIME_INT,                                           /**< Indicates MMS delivery time */
-       MSG_MMS_SENDOPTION_PRIORITY_INT,                                                /**< Indicates MMS priority. See enum _MSG_PRIORITY_TYPE_E */
+       MSG_MMS_SENDOPTION_READ_REQUEST_BOOL = MSG_STRUCT_MMS_SENDOPT+1,  /**< Indicates whether it requests read report or not */
+       MSG_MMS_SENDOPTION_EXPIRY_TIME_INT,                               /**< Indicates MMS expiry time */
+       MSG_MMS_SENDOPTION_DELIVERY_CUSTOMTIME_BOOL,                      /**< Indicates whether is use MMS delivery custom time */
+       MSG_MMS_SENDOPTION_DELIVERY_TIME_INT,                             /**< Indicates MMS delivery time */
+       MSG_MMS_SENDOPTION_PRIORITY_INT,                                  /**< Indicates MMS priority. See enum _MSG_PRIORITY_TYPE_E */
 };
 
+/**
+ *  @brief  Enumeration for the values of SMS sending options for sent message. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SMS_SENDOPT.
+ */
 enum MSG_SMS_SENDOPT_E {
-       MSG_SMS_SENDOPT_REPLYPATH_BOOL = MSG_STRUCT_SMS_SENDOPT+1,              /**< Indicates whether reply path is set */
+       MSG_SMS_SENDOPT_REPLYPATH_BOOL = MSG_STRUCT_SMS_SENDOPT+1,  /**< Indicates whether reply path is set */
 };
 
+/**
+ *  @brief  Enumeration for the values of reject message informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_REJECT_MSG_INFO.
+ */
 enum MSG_REJECT_MESSAGE_E {
-       MSG_REJECT_MESSAGE_MSGID_INT = MSG_STRUCT_REJECT_MSG_INFO+1,            /**< Indicates the font type none */
-       MSG_REJECT_MESSAGE_MSGTEXT_STR,                                         /**< Indicates the font type none */
-       MSG_REJECT_MESSAGE_DISPLAY_TIME_INT,                                    /**< Indicates the font type none */
+       MSG_REJECT_MESSAGE_MSGID_INT = MSG_STRUCT_REJECT_MSG_INFO+1,   /**< Indicates the ID of rejected message */
+       MSG_REJECT_MESSAGE_MSGTEXT_STR,                                /**< Indicates the text of rejected message */
+       MSG_REJECT_MESSAGE_DISPLAY_TIME_INT,                           /**< Indicates the display time of rejected message */
 };
 
+/**
+ *  @brief  Enumeration for the values of requested message informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_REQUEST_INFO.
+ */
 enum MSG_REQUEST_INFO_E {
-       MSG_REQUEST_REQUESTID_INT = MSG_STRUCT_REQUEST_INFO+1,  /**< Indicates the request ID, which is unique. When applications submit a request to the framework, this value will be set by the framework. */
-       MSG_REQUEST_MESSAGE_HND,                                /**< Indicates the message structure to be sent by applications. */
-       MSG_REQUEST_SENDOPT_HND,
+       MSG_REQUEST_REQUESTID_INT = MSG_STRUCT_REQUEST_INFO+1,  /**< Indicates the request ID, which is unique. When applications submit a request to the framework, this value will be set by the framework. */
+       MSG_REQUEST_MESSAGE_HND,                                /**< Indicates the message structure to be sent by applications. */
+       MSG_REQUEST_SENDOPT_HND,                                /**< Indicates the send options to be sent by applications*/
 };
 
+/**
+ *  @brief  Enumeration for the values of sent status informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_SENT_STATUS_INFO.
+ */
 enum MSG_SENT_STATUS_INFO_E {
-       MSG_SENT_STATUS_REQUESTID_INT = MSG_STRUCT_SENT_STATUS_INFO+1,  /**< Indicates the corresponding request Id. */
-       MSG_SENT_STATUS_NETWORK_STATUS_INT,                             /**< Indicates the status of the corresponding request. Refer to enum _MSG_NETWORK_STATUS_E*/
+       MSG_SENT_STATUS_REQUESTID_INT = MSG_STRUCT_SENT_STATUS_INFO+1,  /**< Indicates the corresponding request ID. */
+       MSG_SENT_STATUS_NETWORK_STATUS_INT,                             /**< Indicates the status of the corresponding request. See enum _MSG_NETWORK_STATUS_E*/
 };
 
+/**
+ *  @brief  Enumeration for the values of push configurations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_PUSH_CONFIG_INFO.
+ */
+enum MSG_PUSH_CONFIG_INFO_E {
+       MSG_PUSH_CONFIG_CONTENT_TYPE_STR = MSG_STRUCT_PUSH_CONFIG_INFO+1,  /**< Indicates the content type*/
+       MSG_PUSH_CONFIG_APPLICATON_ID_STR,                                 /**< Indicates the application ID*/
+       MSG_PUSH_CONFIG_PACKAGE_NAME_STR,                                  /**< Indicates the package name*/
+       MSG_PUSH_CONFIG_LAUNCH_BOOL,                                       /**< Indicates launch*/
+};
 
 /**
- *     @brief  Represents the values of a message class type. \n
- *     This enum is used as the value of MSG_CLASS_TYPE_T.
+ *  @brief  Enumeration for the values of CB message informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_CB_MSG.
+ */
+enum MSG_CB_MSG_E {
+       MSG_CB_MSG_TYPE_INT     = MSG_STRUCT_CB_MSG+1,      /**<  MSG_TYPE_SMS_CB/ETWS_PRIMARY/ETWS_SECONDARY (see _MSG_MESSAGE_TYPE_E) */
+       MSG_CB_MSG_RECV_TIME_INT,                       /**< Received time*/
+       MSG_CB_MSG_SERIAL_NUM_INT,                      /**< Serial number of CB/ETWS Primary Noti. : 2 bytes binary data */
+       MSG_CB_MSG_MSG_ID_INT,                          /**< Message identifier of CB/ETWS Primary Noti. */
+       MSG_CB_MSG_DCS_INT,                             /**< Data coding scheme of CB MSG. */
+       MSG_CB_MSG_CB_TEXT_LEN_INT,                     /**< Length of CB text (except NULL) */
+       MSG_CB_MSG_CB_TEXT_STR,                         /**< CB text */
+       MSG_CB_MSG_ETWS_WARNING_TYPE_INT,               /**< Warning type of ETWS Primary Noti. : 2 bytes binary data */
+       MSG_CB_MSG_ETWS_WARNING_SECU_INFO_STR,          /**< Warning security information of ETWS Primary Noti. : 50 bytes binary data */
+       MSG_CB_MSG_LANGUAGE_TYPE_STR,                   /**< Language type of CB message data */
+};
+
+/**
+ *  @brief  Enumeration for the values of a message class type. \n
+ *             This enum is used as the value of MSG_CLASS_TYPE_T.
  */
 enum _MSG_CLASS_TYPE_E
 {
@@ -707,123 +1163,151 @@ enum _MSG_CLASS_TYPE_E
        MSG_CLASS_1,                    /**< Stored in the mobile equipment or SIM (depending on memory availability) */
        MSG_CLASS_2,                    /**< Stored in SIM */
        MSG_CLASS_3,                    /**< Transferred to the terminal equipment (such as PDA or PC) which is connected to the mobile equipment */
-       MSG_CLASS_NONE,
+       MSG_CLASS_NONE,                 /**< Message class none*/
 };
 
 /**
- *     @brief  Represents the type of Message. More members maybe added if needed \n
- *     This enum is used as the value of msg_message_type_t.
+ *  @brief  Enumeration for the type of Message. \n
+ *          More members maybe added if needed. \n
+ *             This enum is used as the value of msg_message_type_t.
  */
- enum _MSG_MESSAGE_TYPE_E
+enum _MSG_MESSAGE_TYPE_E
 {
-       MSG_TYPE_INVALID = 0,                   /** < Invalid Type Message */
+       MSG_TYPE_INVALID = 0,               /** < Invalid Type Message */
+
+       MSG_TYPE_SMS,                       /** < Normal SMS Message */
+       MSG_TYPE_SMS_CB,                    /** < Cell Broadcasting SMS Message */
+       MSG_TYPE_SMS_JAVACB,                /** < JAVA Cell Broadcasting SMS Message */
+       MSG_TYPE_SMS_WAPPUSH,               /** < WAP Push SMS Message */
+       MSG_TYPE_SMS_MWI,                   /** < MWI SMS Message */
+       MSG_TYPE_SMS_SYNCML,                /** < SyncML CP SMS Message */
+       MSG_TYPE_SMS_REJECT,                /** < Reject Message */
+
+       MSG_TYPE_MMS,                       /** < Normal MMS Message */
+       MSG_TYPE_MMS_JAVA,                  /** < JAVA MMS Message */
+       MSG_TYPE_MMS_NOTI,                  /** < MMS Notification Message */
 
-       MSG_TYPE_SMS,                                   /** < Normal SMS Message */
-       MSG_TYPE_SMS_CB,                                /** < Cell Broadcasting SMS Message */
-       MSG_TYPE_SMS_JAVACB,                    /** < JAVA Cell Broadcasting SMS Message */
-       MSG_TYPE_SMS_WAPPUSH,           /** < WAP Push SMS Message */
-       MSG_TYPE_SMS_MWI,                               /** < MWI SMS Message */
-       MSG_TYPE_SMS_SYNCML,                    /** < SyncML CP SMS Message */
-       MSG_TYPE_SMS_REJECT,                    /** < Reject Message */
-       MSG_TYPE_MMS,                                   /** < Normal MMS Message */
-       MSG_TYPE_MMS_JAVA,                      /** < JAVA MMS Message */
-       MSG_TYPE_MMS_NOTI,                      /** < MMS Notification Message */
+       MSG_TYPE_SMS_ETWS_PRIMARY,          /** < CB - ETWS Primary Notification */
+       MSG_TYPE_SMS_ETWS_SECONDARY,        /** < CB - ETWS Secondary Notification */
+
+       MSG_TYPE_SMS_CMAS_PRESIDENTIAL,     /** < CB - CMAS Presidential Alerts */
+       MSG_TYPE_SMS_CMAS_EXTREME,          /** < CB - CMAS Extreme Alerts */
+       MSG_TYPE_SMS_CMAS_SEVERE,           /** < CB - CMAS Severe Alerts */
+       MSG_TYPE_SMS_CMAS_AMBER,            /** < CB - CMAS AMBER Alerts (Child Abduction Emergency) */
+       MSG_TYPE_SMS_CMAS_TEST,             /** < CB - CMAS Test */
+       MSG_TYPE_SMS_CMAS_OPERATOR_DEFINED, /** < CB - CMAS Operator defined */
+       MSG_MESSAGE_TYPE_MAX,               /** < Placeholder for max value of this enum */
 };
 
+/**
+ *  @brief  Enumeration for the backup type of Message. More members maybe added if needed \n
+ *             This enum is used as the value of msg_message_backup_type_t.
+ */
+enum _MSG_MESSAGE_BACKUP_TYPE_E
+{
+       MSG_BACKUP_TYPE_ALL = 0,                /**< Backup all*/
+       MSG_BACKUP_TYPE_SMS,                    /**< Backup SMS*/
+       MSG_BACKUP_TYPE_MMS,                    /**< Backup MMS*/
+};
 
 /**
- *     @brief  Represents the values of an error code. \n
- *     Success code is zero, but all error codes SHOULD be negative and smaller than MSG_ERROR_BEGIN. \n
- *     This enum is used as the value of msg_error_t.
+ *  @brief  Enumeration for the values of an error code. \n
+ *             Success code is zero, but all error codes SHOULD be negative and smaller than MSG_SUCCESS. \n
+ *             This enum is used as the value of msg_error_t.
  */
 enum _MSG_ERROR_E
 {
-       MSG_SUCCESS = 0,                                /**< Successful */
-
-       MSG_ERR_NULL_MSGHANDLE = -1,    /**< Message handle is NULL */
-       MSG_ERR_NULL_POINTER = -2,              /**< Pointer is NULL */
-       MSG_ERR_NULL_MESSAGE = -3,              /**< Message is NULL */
-       MSG_ERR_INVALID_STORAGE_ID = -4,        /**< Storage ID is invalid */
-       MSG_ERR_INVALID_MSG_TYPE = -5,          /**< Message type is invalid */
-
-       MSG_ERR_INVALID_STORAGE_REG= -6,        /**< Storage registry is invalid */
-       MSG_ERR_INVALID_MESSAGE_ID = -7,        /**< Message ID is invalid */
-       MSG_ERR_INVALID_MSGHANDLE = -8, /**< Message handle is invalid */
-       MSG_ERR_INVALID_PARAMETER = -9, /**< Parameter is invalid */
-       MSG_ERR_INVALID_MESSAGE = -10,                  /**< Message is invalid */
-
-       MSG_ERR_INVALID_PLUGIN_HANDLE = -11,    /**< Plugin handle is invalid */
-       MSG_ERR_MEMORY_ERROR = -12,                     /**< Memory is error */
-       MSG_ERR_COMMUNICATION_ERROR = -13,      /**< Communication between client and server is error */
-       MSG_ERR_SIM_STORAGE_FULL = -14,         /**< SIM Storage is full */
-       MSG_ERR_TRANSPORT_ERROR = -15,                  /**< Transport event error */
-
-       MSG_ERR_CALLBACK_ERROR = -16,                   /**< Callback event error */
-       MSG_ERR_STORAGE_ERROR = -17,                    /**< Storage event error */
-       MSG_ERR_FILTER_ERROR = -18,                             /**< Filter event error */
-       MSG_ERR_MMS_ERROR = -19,                                /**< MMS event error */
-       MSG_ERR_MMPLAYER_CREATE = -20,                  /**< Multimedia Error*/
-
-       MSG_ERR_MMPLAYER_SET_ATTRS = -21,               /**< Multimedia Error*/
-       MSG_ERR_MMPLAYER_REALIZE = -22,         /**< Multimedia Error*/
-       MSG_ERR_MMPLAYER_PLAY = -23,                    /**< Multimedia Error*/
-       MSG_ERR_MMPLAYER_STOP = -24,                    /**< Multimedia Error*/
-       MSG_ERR_MMPLAYER_DESTROY = -25,         /**< Multimedia Error*/
-
-       MSG_ERR_UNKNOWN = -26,                                  /**< Unknown errors */
+       MSG_SUCCESS = 0,                        /**< Successful */
+
+       MSG_ERR_NULL_MSGHANDLE = -1,            /**< Message handle is NULL */
+       MSG_ERR_NULL_POINTER = -2,              /**< Pointer is NULL */
+       MSG_ERR_NULL_MESSAGE = -3,              /**< Message is NULL */
+       MSG_ERR_INVALID_STORAGE_ID = -4,        /**< Storage ID is invalid */
+       MSG_ERR_INVALID_MSG_TYPE = -5,          /**< Message type is invalid */
+
+       MSG_ERR_INVALID_STORAGE_REG= -6,        /**< Storage registry is invalid */
+       MSG_ERR_INVALID_MESSAGE_ID = -7,        /**< Message ID is invalid */
+       MSG_ERR_INVALID_MSGHANDLE = -8,         /**< Message handle is invalid */
+       MSG_ERR_INVALID_PARAMETER = -9,         /**< Parameter is invalid */
+       MSG_ERR_INVALID_MESSAGE = -10,          /**< Message is invalid */
+
+       MSG_ERR_INVALID_PLUGIN_HANDLE = -11,    /**< Plugin handle is invalid */
+       MSG_ERR_MEMORY_ERROR = -12,             /**< Memory is error */
+       MSG_ERR_COMMUNICATION_ERROR = -13,      /**< Communication between client and server is error */
+       MSG_ERR_SIM_STORAGE_FULL = -14,         /**< SIM Storage is full */
+       MSG_ERR_TRANSPORT_ERROR = -15,          /**< Transport event error */
+
+       MSG_ERR_CALLBACK_ERROR = -16,           /**< Callback event error */
+       MSG_ERR_STORAGE_ERROR = -17,            /**< Storage event error */
+       MSG_ERR_FILTER_ERROR = -18,             /**< Filter event error */
+       MSG_ERR_MMS_ERROR = -19,                /**< MMS event error */
+       MSG_ERR_MMPLAYER_CREATE = -20,          /**< Multimedia Error*/
+
+       MSG_ERR_MMPLAYER_SET_ATTRS = -21,       /**< Multimedia Error*/
+       MSG_ERR_MMPLAYER_REALIZE = -22,         /**< Multimedia Error*/
+       MSG_ERR_MMPLAYER_PLAY = -23,            /**< Multimedia Error*/
+       MSG_ERR_MMPLAYER_STOP = -24,            /**< Multimedia Error*/
+       MSG_ERR_MMPLAYER_DESTROY = -25,         /**< Multimedia Error*/
+
+       MSG_ERR_UNKNOWN = -26,                  /**< Unknown errors */
 
        /* Start Database Errors */
-       MSG_ERR_DB_CONNECT = -27,
-       MSG_ERR_DB_DISCONNECT = -28,
-       MSG_ERR_DB_EXEC = -29,
-       MSG_ERR_DB_GETTABLE = -30,
-
-       MSG_ERR_DB_PREPARE = -31,
-       MSG_ERR_DB_STEP = -32,
-       MSG_ERR_DB_NORECORD= -33,
-       MSG_ERR_DB_STORAGE_INIT = -34,
-       MSG_ERR_DB_MAKE_DIR = -35,
-
-       MSG_ERR_DB_ROW = -36,
-       MSG_ERR_DB_DONE = -37,
-       MSG_ERR_DB_GENERIC= -38,
-       MSG_ERR_DB_END = -39,
+       MSG_ERR_DB_CONNECT = -27,               /**< DB connect error*/
+       MSG_ERR_DB_DISCONNECT = -28,            /**< DB disconnect error*/
+       MSG_ERR_DB_EXEC = -29,                  /**< DB command execute error*/
+       MSG_ERR_DB_GETTABLE = -30,              /**< DB get-table error*/
+
+       MSG_ERR_DB_PREPARE = -31,               /**< DB prepare query error*/
+       MSG_ERR_DB_STEP = -32,                  /**< DB step query error*/
+       MSG_ERR_DB_NORECORD= -33,               /**< DB no-record error*/
+       MSG_ERR_DB_STORAGE_INIT = -34,          /**< DB storage init error*/
+       MSG_ERR_DB_MAKE_DIR = -35,              /**< mkdir error*/
+
+       MSG_ERR_DB_ROW = -36,                   /**< DB step() has another row ready */
+       MSG_ERR_DB_DONE = -37,                  /**< DB step() has finished executing */
+       MSG_ERR_DB_GENERIC= -38,                /**< Generic DB error*/
+       MSG_ERR_DB_END = -39,                   /**< DB end error*/
        /* End Database Errors */
 
        /* Start Setting Errors */
-       MSG_ERR_SET_SETTING = -40,
-       MSG_ERR_SET_SIM_SET = -41,
-       MSG_ERR_SET_READ_ERROR = -42,
-       MSG_ERR_SET_WRITE_ERROR = -43,
-       MSG_ERR_SET_DELETE_ERROR = -44,
+       MSG_ERR_SET_SETTING = -40,              /**< Error setting config data*/
+       MSG_ERR_SET_SIM_SET = -41,              /**< Error setting config data in SIM*/
+       MSG_ERR_SET_READ_ERROR = -42,           /**< Error reading config settings*/
+       MSG_ERR_SET_WRITE_ERROR = -43,          /**< Error in writing config settings*/
+       MSG_ERR_SET_DELETE_ERROR = -44,         /**< Error in deleting config settings*/
        /* End Setting Errors */
 
        /* Start Plugin Errors */
-       MSG_ERR_PLUGIN_TAPIINIT = -45,
-       MSG_ERR_PLUGIN_REGEVENT = -46,
-       MSG_ERR_PLUGIN_TRANSPORT = -47,
-       MSG_ERR_PLUGIN_STORAGE = -48,
-       MSG_ERR_PLUGIN_SETTING = -49,
-
-       MSG_ERR_PLUGIN_WAPDECODE = -50,
-       MSG_ERR_PLUGIN_TAPI_FAILED = -51,
-       MSG_ERR_PLUGIN_SIM_MSG_FULL = -52,
+       MSG_ERR_PLUGIN_TAPIINIT = -45,          /**< Telephony init error*/
+       MSG_ERR_PLUGIN_REGEVENT = -46,          /**< Register even error*/
+       MSG_ERR_PLUGIN_TRANSPORT = -47,         /**< Transport (send/receive) error*/
+       MSG_ERR_PLUGIN_STORAGE = -48,           /**< Storage error*/
+       MSG_ERR_PLUGIN_SETTING = -49,           /**< Error setting config data*/
+
+       MSG_ERR_PLUGIN_WAPDECODE = -50,         /**< WAP decode error*/
+       MSG_ERR_PLUGIN_TAPI_FAILED = -51,       /**< TAPI failure*/
+       MSG_ERR_PLUGIN_SIM_MSG_FULL = -52,      /**< SIM message full error*/
        /* End Plugin Errors */
 
-       MSG_ERR_MESSAGE_COUNT_FULL = -53,
-       MSG_ERR_READREPORT_NOT_REQUESTED = -54,
-       MSG_ERR_READREPORT_ALEADY_SENT = -55,
+       MSG_ERR_MESSAGE_COUNT_FULL = -53,       /**< Message count full*/
+       MSG_ERR_READREPORT_NOT_REQUESTED = -54, /**< Read report  not requested*/
+       MSG_ERR_READREPORT_ALEADY_SENT = -55,   /**< Read report already sent*/
+
+       MSG_ERR_FILTER_DUPLICATED = -56,        /**< Filter duplicate error */
+       MSG_ERR_PERMISSION_DENIED = -57,        /**< Permission denied*/
+       MSG_ERR_NO_SIM = -58,                   /**< No SIM*/
 
-       MSG_ERR_FILTER_DUPLICATED = -56,                                /**< Filter duplicate error */
-       MSG_ERR_SECURITY_ERROR = -57,
-       MSG_ERR_NO_SIM = -58,
-       MSG_ERR_SERVER_NOT_READY= -59,
+       MSG_ERR_SERVER_NOT_READY = -59,         /**< Message server not ready*/
+
+       MSG_ERR_STORE_RESTRICT = -60,           /**< Storage restricted error*/
+       MSG_ERR_DB_BUSY = -61,                  /**< DB file locked*/
+       MSG_ERR_NOT_SUPPORTED = -63,            /**< Not supported */
 };
 
 
 /**
- *     @brief  Represents the values of a message priority. \n
- *     This enum is used as the value of msg_priority_type_t.
+ *  @brief  Enumeration for the values of a message priority. \n
+ *             This enum is used as the value of msg_priority_type_t.
  */
 enum _MSG_PRIORITY_TYPE_E
 {
@@ -834,29 +1318,42 @@ enum _MSG_PRIORITY_TYPE_E
 
 
 /**
- *     @brief  Represents the values of a network status. \n
- *     This enum is used as the value of msg_network_status_t.
+ *  @brief  Enumeration for the values of a network status. \n
+ *             This enum is used as the value of msg_network_status_t.
  */
 enum _MSG_NETWORK_STATUS_E
 {
-       MSG_NETWORK_NOT_SEND = 0,               /**< Message is not sending */
-       MSG_NETWORK_SENDING,                            /**< Message is sending */
-       MSG_NETWORK_SEND_SUCCESS,               /**< Message is sent successfully */
-       MSG_NETWORK_SEND_FAIL,                  /**< Message is failed to send */
-       MSG_NETWORK_DELIVER_SUCCESS,    /**< Message is delivered */
-       MSG_NETWORK_DELIVER_FAIL,               /**< Message is failed to deliver */
-       MSG_NETWORK_RECEIVED,                   /**< Message is received */
-       MSG_NETWORK_REQ_CANCELLED,              /**< Request is cancelled */
-       MSG_NETWORK_RETRIEVING,                         /**< Message is retrieving */
-       MSG_NETWORK_RETRIEVE_SUCCESS,           /**< Message is retrieved successfully */
-       MSG_NETWORK_RETRIEVE_FAIL,                      /**< Message is failed to retrieve */
-       MSG_NETWORK_SEND_TIMEOUT,                       /**< Message is failed to send by timeout */
+       MSG_NETWORK_NOT_SEND = 0,                            /**< Message is not sending */
+       MSG_NETWORK_SENDING,                                 /**< Sending message */
+       MSG_NETWORK_SEND_SUCCESS,                            /**< Message is sent successfully */
+       MSG_NETWORK_SEND_FAIL,                               /**< Failed to send message */
+       MSG_NETWORK_DELIVER_SUCCESS,                         /**< Message is delivered */
+       MSG_NETWORK_DELIVER_FAIL,                            /**< Failed to deliver message */
+       MSG_NETWORK_RECEIVED,                                /**< Message is received */
+       MSG_NETWORK_REQ_CANCELLED,                           /**< Request is cancelled */
+       MSG_NETWORK_RETRIEVING,                              /**< Retrieving message */
+       MSG_NETWORK_RETRIEVE_SUCCESS,                        /**< Message is retrieved successfully */
+       MSG_NETWORK_RETRIEVE_FAIL,                           /**< Failed to retrieve */
+       MSG_NETWORK_SEND_TIMEOUT,                            /**< Send timed-out*/ // WILL BE REMOVED
+       MSG_NETWORK_SEND_FAIL_MANDATORY_INFO_MISSING,        /**< Send failed due to mandatory info missing*/ // WILL BE REMOVED
+       MSG_NETWORK_SEND_FAIL_TEMPORARY,                     /**<Send failed temporarily*/ // WILL BE REMOVED
+       MSG_NETWORK_SEND_FAIL_BY_MO_CONTROL_WITH_MOD,        /**< Send failed by MO control- ALLOWED WITH MOD*/ // WILL BE REMOVED
+       MSG_NETWORK_SEND_FAIL_BY_MO_CONTROL_NOT_ALLOWED,     /**< Send failed by MO control*/ // WILL BE REMOVED
+       MSG_NETWORK_DELIVER_PENDING,                         /**< Delivery pending*/
+       MSG_NETWORK_DELIVER_EXPIRED,                         /**< Delivery expired*/
+       MSG_NETWORK_SEND_PENDING,                            /**< Send is pending*/
+#ifdef FEATURE_SMS_CDMA
+       MSG_NETWORK_SEND_FAIL_UNKNOWN_SUBSCRIBER,                  /**< Unknown subscriber(destination) */
+       MSG_NETWORK_SEND_FAIL_MS_DISABLED,                   /**< Mobile station originated SMS disabled */
+       MSG_NETWORK_SEND_FAIL_NETWORK_NOT_READY,             /**< Network not ready */
+       MSG_NETWORK_RETRIEVE_PENDING,                        /**< Retrieve is pending*/
+#endif
 };
 
 
 /**
- *     @brief  Represents the values of an address type. \n
- *     This enum is used as the value of msg_address_type_t.
+ *  @brief  Enumeration for the values of an address type. \n
+ *             This enum is used as the value of msg_address_type_t.
 */
 enum _MSG_ADDRESS_TYPE_E
 {
@@ -867,21 +1364,21 @@ enum _MSG_ADDRESS_TYPE_E
 
 
 /**
- *     @brief  Represents the values of a recipient type. \n
- *     This enum is used as the value of msg_recipient_type_t.
+ *  @brief  Enumeration for the values of a recipient type. \n
+ *             This enum is used as the value of msg_recipient_type_t.
 */
 enum _MSG_RECIPIENT_TYPE_E
 {
-       MSG_RECIPIENTS_TYPE_UNKNOWN = 0,        /**< The recipient type is unknown. */
-       MSG_RECIPIENTS_TYPE_TO,                 /**< The recipient type is for "To". */
-       MSG_RECIPIENTS_TYPE_CC,                 /**< The recipient type is for "Cc". */
-       MSG_RECIPIENTS_TYPE_BCC,                        /**< The recipient type is for "Bcc". */
+       MSG_RECIPIENTS_TYPE_UNKNOWN = 0,    /**< The recipient type is unknown. */
+       MSG_RECIPIENTS_TYPE_TO,             /**< The recipient type is for "To". */
+       MSG_RECIPIENTS_TYPE_CC,             /**< The recipient type is for "Cc". */
+       MSG_RECIPIENTS_TYPE_BCC,            /**< The recipient type is for "Bcc". */
 };
 
 
 /**
- *     @brief  Represents the values of a direction type. \n
- *     This enum is used as the value of msg_direction_type_t.
+ *  @brief  Enumeration for the values of a direction type. \n
+ *             This enum is used as the value of msg_direction_type_t.
  */
 enum _MSG_DIRECTION_TYPE_E
 {
@@ -891,41 +1388,48 @@ enum _MSG_DIRECTION_TYPE_E
 
 
 /**
- *     @brief  Represents the values of a string encoding type. \n
- *     This enum is used as the value of msg_encode_type_t.
+ *  @brief  Enumeration for the values of a string encoding type. \n
+ *             This enum is used as the value of msg_encode_type_t.
  */
 enum _MSG_ENCODE_TYPE_E
 {
-       MSG_ENCODE_GSM7BIT = 0, /**< The string encoding type is GSM7BIT */
-       MSG_ENCODE_8BIT,                /**< The string encoding type is 8 BIT */
-       MSG_ENCODE_UCS2,                /**< The string encoding type is UCS2 */
-       MSG_ENCODE_AUTO,                /**< The string encoding type is AUTO */
+       MSG_ENCODE_GSM7BIT = 0,      /**< The string encoding type is GSM7BIT */
+       MSG_ENCODE_8BIT,             /**< The string encoding type is 8 BIT */
+       MSG_ENCODE_UCS2,             /**< The string encoding type is UCS2 */
+       MSG_ENCODE_AUTO,             /**< The string encoding type is AUTO */
+
+       MSG_ENCODE_GSM7BIT_ABNORMAL, /**< The string encoding type is GSM7BIT, but abnormal character included */
+#ifdef FEATURE_SMS_CDMA
+       MSG_ENCODE_EUCKR,                               /**< For EUC-KR(Korean) */
+       MSG_ENCODE_SHIFT_JIS,                           /**< For Shift-JIS(Japanese) */
+       MSG_ENCODE_ASCII7BIT,           /**< the string encoding type is ASCII 7 BIT */
+#endif
 };
 
 
 /**
- *     @brief  Represents the action type of Push Message. \n
- *     This enum is used as the value of msg_push_action_t.
+ *  @brief  Enumeration for the action type of Push Message. \n
+ *             This enum is used as the value of msg_push_action_t.
  */
 enum _MSG_PUSH_ACTION_E
 {
        // SI Action
-       MSG_PUSH_SI_ACTION_SIGNAL_NONE = 0x00,
-       MSG_PUSH_SI_ACTION_SIGNAL_LOW,
-       MSG_PUSH_SI_ACTION_SIGNAL_MEDIUM,
-       MSG_PUSH_SI_ACTION_SIGNAL_HIGH,
-       MSG_PUSH_SI_ACTION_DELETE,
+       MSG_PUSH_SI_ACTION_SIGNAL_NONE = 0x00,          /**<  No signal for push message action */
+       MSG_PUSH_SI_ACTION_SIGNAL_LOW,                          /**< Low signal for push message action */
+       MSG_PUSH_SI_ACTION_SIGNAL_MEDIUM,                       /**< Medium signal for push message action */
+       MSG_PUSH_SI_ACTION_SIGNAL_HIGH,                         /**< High signal for push message action */
+       MSG_PUSH_SI_ACTION_DELETE,                                      /**< Delete push message */
 
        // SL Action
-       MSG_PUSH_SL_ACTION_EXECUTE_LOW,
-       MSG_PUSH_SL_ACTION_EXECUTE_HIGH,
-       MSG_PUSH_SL_ACTION_CACHE,
+       MSG_PUSH_SL_ACTION_EXECUTE_LOW,                         /**< Action: execute-low*/
+       MSG_PUSH_SL_ACTION_EXECUTE_HIGH,                        /**< Action: execute-high*/
+       MSG_PUSH_SL_ACTION_CACHE,                                       /**< Action: cache*/
 };
 
 
 /**
- *     @brief  Represents the type of SyncML Message. \n
- *     This enum is used as the value of msg_syncml_message_type_t.
+ *  @brief  Enumeration for the type of SyncML Message. \n
+ *             This enum is used as the value of msg_syncml_message_type_t.
  */
  enum _MSG_SYNCML_MESSAGE_TYPE_E
  {
@@ -944,18 +1448,18 @@ enum _MSG_PUSH_ACTION_E
 
 
 /**
- *     @brief  Represents the values of a Delivery Report Status. \n
- *     This enum is used as the value of msg_delivery_report_status_t.
+ *  @brief  Enumeration for the values of a Delivery Report Status. \n
+ *             This enum is used as the value of msg_delivery_report_status_t.
 */
  enum _MSG_DELIVERY_REPORT_STATUS_E
  {
         MSG_DELIVERY_REPORT_NONE                               =       -1,     /**< Indicates the status unavailable */
         MSG_DELIVERY_REPORT_EXPIRED                    =       0,      /**< Indicates the expired status of message */
-        MSG_DELIVERY_REPORT_SUCCESS                            =       1,      /**< Indicates the success status of message */
+        MSG_DELIVERY_REPORT_SUCCESS                    =       1,      /**< Indicates the success status of message */
         MSG_DELIVERY_REPORT_REJECTED                   =       2,      /**< Indicates the rejected status of message */
         MSG_DELIVERY_REPORT_DEFERRED                   =       3,      /**< Indicates the deferred status of message */
-        MSG_DELIVERY_REPORT_UNRECOGNISED               =       4,      /**< Indicates the unrecongnised status of message */
-        MSG_DELIVERY_REPORT_INDETERMINATE              =       5,      /**< Indicates the unrecongnised status of message */
+        MSG_DELIVERY_REPORT_UNRECOGNISED               =       4,      /**< Indicates the unrecognized status of message */
+        MSG_DELIVERY_REPORT_INDETERMINATE              =       5,      /**< Indicates the intermediate status of message */
         MSG_DELIVERY_REPORT_FORWARDED                  =       6,      /**< Indicates the forwarded status of message */
         MSG_DELIVERY_REPORT_UNREACHABLE                =       7,      /**< Indicates the unreachable status of message */
         MSG_DELIVERY_REPORT_ERROR                              =       8,      /**< Indicates the error status of message */
@@ -963,260 +1467,274 @@ enum _MSG_PUSH_ACTION_E
 
 
 /**
- *     @brief  Represents the values of a Read Report Status. \n
- *     This enum is used as the value of msg_read_report_status_t.
+ *  @brief  Enumeration for the values of a Read Report Status. \n
+ *             This enum is used as the value of msg_read_report_status_t.
 */
 enum _MSG_READ_REPORT_STATUS_E
  {
         MSG_READ_REPORT_NONE                   =       -1,       /**< Indicates the status unavailable */
         MSG_READ_REPORT_IS_READ                =       0,        /**< Indicates the message is read */
-        MSG_READ_REPORT_IS_DELETED     =       1         /**< Indicates the message is deleted */
+        MSG_READ_REPORT_IS_DELETED     =       1,        /**< Indicates the message is deleted */
+        MSG_READ_REPORT_REJECT_BY_USER =       2,        /**< Indicates read report reject by user*/
  };
 
+/**
+ *  @brief  Enumeration for the values of a Report Type. \n
+ *             This enum is used as the value of msg_read_report_status_t.
+*/
+enum _MSG_REPORT_TYPE_E
+ {
+        MSG_REPORT_TYPE_DELIVERY       =       0,      /**< Indicates the type is delivery report*/
+        MSG_REPORT_TYPE_READ   =       1,          /**< Indicates the type is read report*/
+        MSG_REPORT_TYPE_READ_REPORT_SENT = 2,  /**< Indicates the type is read report sent*/
+ };
 
 // filter
 /**
- *     @brief  Represents the values of a filter type. \n
- *     This enum is used as the value of msg_filter_type_t.
+ *  @brief  Enumeration for the values of a filter type. \n
+ *             This enum is used as the value of msg_filter_type_t.
  */
 enum _MSG_FILTER_TYPE_E
 {
-       MSG_FILTER_BY_WORD = 0,                 /**< Filtered by sub string in the text */
-       MSG_FILTER_BY_ADDRESS_SAME,                     /**< Filtered by address exactly same as */
-       MSG_FILTER_BY_ADDRESS_START,                    /**< Filtered by address start with */
-       MSG_FILTER_BY_ADDRESS_INCLUDE,                  /**< Filtered by address include */
+       MSG_FILTER_BY_WORD = 0,             /**< Filtered by sub string in the text */
+       MSG_FILTER_BY_ADDRESS_SAME,         /**< Filtered by address exactly same as */
+       MSG_FILTER_BY_ADDRESS_START,        /**< Filtered by address start with */
+       MSG_FILTER_BY_ADDRESS_INCLUDE,      /**< Filtered by address include */
+       MSG_FILTER_BY_ADDRESS_END,          /**< Filtered by address end with */
 };
 
 
 // mms
 
 /**
- *     @brief  Represents the values of a mime type.
+ *  @brief  Enumeration for the values of a MIME type.
  */
 typedef enum   _MimeType
 {
        // 0
-       MIME_ASTERISK                                                                                   = 0x0000, /**< Indicates the valid default mime type  */
+       MIME_ASTERISK                                       = 0x0000, /**< Indicates the valid default MIME type  */
 
        // 1
-       MIME_APPLICATION_XML                                                                    = 0x1000, /**< Indicates the application xml type */
-       MIME_APPLICATION_WML_XML                                                        = 0x1001,       /**< Indicates the application wml xml type  */
-       MIME_APPLICATION_XHTML_XML                                                      = 0x1002,       /**< Indicates the application xhtml xml type  */
-       MIME_APPLICATION_JAVA_VM                                                                = 0x1003, /**< Indicates the application java vm type */
-       MIME_APPLICATION_SMIL                                                           = 0x1004, /**< Indicates the application smil  type */
-       MIME_APPLICATION_JAVA_ARCHIVE                                           = 0x1005, /**< Indicates the application java archive type */
-       MIME_APPLICATION_JAVA                                                           = 0x1006, /**< Indicates the application java  type */
-       MIME_APPLICATION_OCTET_STREAM                                           = 0x1007, /**< Indicates the application octect stream type */
-       MIME_APPLICATION_STUDIOM                                                        = 0x1008, /**< Indicates the application studiom type */
-       MIME_APPLICATION_FUNMEDIA                                                       = 0x1009, /**< Indicates the application fun media type */
-       MIME_APPLICATION_MSWORD                                                         = 0x100a,       /**< Indicates the application ms word type */
-       MIME_APPLICATION_PDF                                                                    = 0x100b, /**< Indicates the application pdf type */
-       MIME_APPLICATION_SDP                                                                    = 0x100c,  /**< Indicates the application sdp type */
-       MIME_APPLICATION_RAM                                                                    = 0x100d, /**< Indicates the application ram type */
-       MIME_APPLICATION_ASTERIC                                                                = 0x100e, /**< Indicates the application as main type and generic sub type */
+       MIME_APPLICATION_XML                                = 0x1000, /**< Indicates the application XML type */
+       MIME_APPLICATION_WML_XML                            = 0x1001, /**< Indicates the application WML XML type  */
+       MIME_APPLICATION_XHTML_XML                          = 0x1002, /**< Indicates the application XHTML XML type  */
+       MIME_APPLICATION_JAVA_VM                            = 0x1003, /**< Indicates the application Java VM type */
+       MIME_APPLICATION_SMIL                               = 0x1004, /**< Indicates the application SMIL  type */
+       MIME_APPLICATION_JAVA_ARCHIVE                       = 0x1005, /**< Indicates the application Java archive type */
+       MIME_APPLICATION_JAVA                               = 0x1006, /**< Indicates the application Java  type */
+       MIME_APPLICATION_OCTET_STREAM                       = 0x1007, /**< Indicates the application octect stream type */
+       MIME_APPLICATION_STUDIOM                            = 0x1008, /**< Indicates the application studiom type */
+       MIME_APPLICATION_FUNMEDIA                           = 0x1009, /**< Indicates the application fun media type */
+       MIME_APPLICATION_MSWORD                             = 0x100a, /**< Indicates the application MS Word type */
+       MIME_APPLICATION_PDF                                = 0x100b, /**< Indicates the application PDF type */
+       MIME_APPLICATION_SDP                                = 0x100c, /**< Indicates the application SDP type */
+       MIME_APPLICATION_RAM                                = 0x100d, /**< Indicates the application RAM type */
+       MIME_APPLICATION_ASTERIC                            = 0x100e, /**< Indicates the application as main type and generic sub type */
 
        // 16
-       MIME_APPLICATION_VND_WAP_XHTMLXML                                       = 0x1100, /**< Indicates the application wap xhtml xml type */
-       MIME_APPLICATION_VND_WAP_WMLC                                           = 0x1101,  /**< Indicates the application wap wmlc type */
-       MIME_APPLICATION_VND_WAP_WMLSCRIPTC                             = 0x1102,  /**< Indicates the application wap wmlscrpitc type */
-       MIME_APPLICATION_VND_WAP_WTA_EVENTC                             = 0x1103, /**< Indicates the application wap  wta event type */
-       MIME_APPLICATION_VND_WAP_UAPROF                                 = 0x1104, /**< Indicates the application wap uaprof type */
-       MIME_APPLICATION_VND_WAP_SIC                                            = 0x1105,  /**< Indicates the application wap sic type */
-       MIME_APPLICATION_VND_WAP_SLC                                            = 0x1106, /**< Indicates the application wap slc type */
-       MIME_APPLICATION_VND_WAP_COC                                            = 0x1107, /**< Indicates the application wap coc type */
-       MIME_APPLICATION_VND_WAP_SIA                                            = 0x1108, /**< Indicates the application wap sia type */
-       MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML             = 0x1109,  /**< Indicates the application wap connectivity wbxml type */
-       MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA    = 0x110a, /**< Indicates the application wap multipart data type */
-       MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES   = 0x110b, /**< Indicates the application wap multipart byte type */
-       MIME_APPLICATION_VND_WAP_MULTIPART_MIXED                        = 0x110c,  /**< Indicates the application wap multipart mixed type */
-       MIME_APPLICATION_VND_WAP_MULTIPART_RELATED              = 0x110d,  /**< Indicates the application wap multipart related type */
-       MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE  = 0x110e,  /**< Indicates the application wap  multipart alternative type */
-       MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC              = 0x110f, /**< Indicates the application wap mulitpart as main type and generic sub type */
-       MIME_APPLICATION_VND_WAP_WBXML                                  = 0x1110, /**< Indicates the application wap wbxml type */
-       MIME_APPLICATION_VND_OMA_DD_XML                                 = 0x1111, /**< Indicates the application oma dd xml type */
-       MIME_APPLICATION_VND_OMA_DRM_MESSAGE                            = 0x1112,  /**< Indicates the application oma drm message type */
-       MIME_APPLICATION_VND_OMA_DRM_CONTENT                            = 0x1113, /**< Indicates the application oma drm content type */
-       MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML                 = 0x1114, /**< Indicates the application oma drm rights xml type */
-       MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML               = 0x1115,  /**< Indicates the application oma drm rights wbxml type */
-       MIME_APPLICATION_VND_OMA_DRM_RO_XML                             = 0x1116, /**< Indicates the application oma drm ro xml type */
-       MIME_APPLICATION_VND_OMA_DRM_DCF                                        = 0x1117, /**< Indicates the application oma drm dcf type */
-       MIME_APPLICATION_VND_OMA_ROAPPDU_XML                            = 0x1118,  /**< Indicates the application oma roap pdu xml type */
-       MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML                        = 0x1119,       /**< Indicates the application oma roap trigger xml  type */
-       MIME_APPLICATION_VND_SMAF                                                       = 0x111a,  /**< Indicates the application smaf type */
-       MIME_APPLICATION_VND_RN_REALMEDIA                                       = 0x111b,  /**< Indicates the application rn real media type */
-       MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE              = 0x111c,  /**< Indicates the application j2me java archive type */
-       MIME_APPLICATION_VND_EXCEL                                                      = 0x111e,  /**< Indicates the application excel type */
-       MIME_APPLICATION_VND_POWERPOINT                                 = 0x111f,  /**< Indicates the application power point type */
-       MIME_APPLICATION_VND_MSWORD                                             = 0x1120,        /**< Indicates the application ms word type */
+       MIME_APPLICATION_VND_WAP_XHTMLXML                   = 0x1100, /**< Indicates the application wap xhtml xml type */
+       MIME_APPLICATION_VND_WAP_WMLC                       = 0x1101, /**< Indicates the application wap wmlc type */
+       MIME_APPLICATION_VND_WAP_WMLSCRIPTC                 = 0x1102, /**< Indicates the application wap wmlscrpitc type */
+       MIME_APPLICATION_VND_WAP_WTA_EVENTC                 = 0x1103, /**< Indicates the application wap  wta event type */
+       MIME_APPLICATION_VND_WAP_UAPROF                     = 0x1104, /**< Indicates the application wap uaprof type */
+       MIME_APPLICATION_VND_WAP_SIC                        = 0x1105, /**< Indicates the application wap sic type */
+       MIME_APPLICATION_VND_WAP_SLC                        = 0x1106, /**< Indicates the application wap slc type */
+       MIME_APPLICATION_VND_WAP_COC                        = 0x1107, /**< Indicates the application wap coc type */
+       MIME_APPLICATION_VND_WAP_SIA                        = 0x1108, /**< Indicates the application wap sia type */
+       MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML         = 0x1109, /**< Indicates the application wap connectivity wbxml type */
+       MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA        = 0x110a, /**< Indicates the application wap multipart data type */
+       MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES       = 0x110b, /**< Indicates the application wap multipart byte type */
+       MIME_APPLICATION_VND_WAP_MULTIPART_MIXED            = 0x110c, /**< Indicates the application wap multipart mixed type */
+       MIME_APPLICATION_VND_WAP_MULTIPART_RELATED          = 0x110d, /**< Indicates the application wap multipart related type */
+       MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE      = 0x110e, /**< Indicates the application wap  multipart alternative type */
+       MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC          = 0x110f, /**< Indicates the application wap mulitpart as main type and generic sub type */
+       MIME_APPLICATION_VND_WAP_WBXML                      = 0x1110, /**< Indicates the application wap wbxml type */
+       MIME_APPLICATION_VND_OMA_DD_XML                     = 0x1111, /**< Indicates the application oma dd xml type */
+       MIME_APPLICATION_VND_OMA_DRM_MESSAGE                = 0x1112, /**< Indicates the application oma drm message type */
+       MIME_APPLICATION_VND_OMA_DRM_CONTENT                = 0x1113, /**< Indicates the application oma drm content type */
+       MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML             = 0x1114, /**< Indicates the application oma drm rights xml type */
+       MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML           = 0x1115, /**< Indicates the application oma drm rights wbxml type */
+       MIME_APPLICATION_VND_OMA_DRM_RO_XML                 = 0x1116, /**< Indicates the application oma drm ro xml type */
+       MIME_APPLICATION_VND_OMA_DRM_DCF                    = 0x1117, /**< Indicates the application oma drm dcf type */
+       MIME_APPLICATION_VND_OMA_ROAPPDU_XML                = 0x1118, /**< Indicates the application oma roap pdu xml type */
+       MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML            = 0x1119, /**< Indicates the application oma roap trigger xml  type */
+       MIME_APPLICATION_VND_SMAF                           = 0x111a, /**< Indicates the application smaf type */
+       MIME_APPLICATION_VND_RN_REALMEDIA                   = 0x111b, /**< Indicates the application rn real media type */
+       MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE          = 0x111c, /**< Indicates the application J2ME Java archive type */
+       MIME_APPLICATION_VND_SAMSUNG_THEME                  = 0x111d, /**< Indicates the application Samsung theme type */
+       MIME_APPLICATION_VND_EXCEL                          = 0x111e, /**< Indicates the application Excel type */
+       MIME_APPLICATION_VND_POWERPOINT                     = 0x111f, /**< Indicates the application Power point type */
+       MIME_APPLICATION_VND_MSWORD                         = 0x1120, /**< Indicates the application MS Word type */
 
        // 49
-       MIME_APPLICATION_X_HDMLC                                                        = 0x1200, /**< Indicates the application x hdmlc type */
-       MIME_APPLICATION_X_X968_USERCERT                                        = 0x1201, /**< Indicates the application x x968 user certified type */
-       MIME_APPLICATION_X_WWW_FORM_URLENCODED                  = 0x1202, /**< Indicates the application x www form url encoded type */
-       MIME_APPLICATION_X_SMAF                                                         = 0x1203, /**< Indicates the application x smaf type */
-       MIME_APPLICATION_X_FLASH                                                                = 0x1204, /**< Indicates the application x flash type */
-       MIME_APPLICATION_X_EXCEL                                                                = 0x1205, /**< Indicates the application x excel type */
-       MIME_APPLICATION_X_POWERPOINT                                           = 0x1206, /**< Indicates the application x power point type */
+       MIME_APPLICATION_X_HDMLC                            = 0x1200, /**< Indicates the application x hdmlc type */
+       MIME_APPLICATION_X_X968_USERCERT                    = 0x1201, /**< Indicates the application x x968 user certified type */
+       MIME_APPLICATION_X_WWW_FORM_URLENCODED              = 0x1202, /**< Indicates the application x www form url encoded type */
+       MIME_APPLICATION_X_SMAF                             = 0x1203, /**< Indicates the application x smaf type */
+       MIME_APPLICATION_X_FLASH                            = 0x1204, /**< Indicates the application x flash type */
+       MIME_APPLICATION_X_EXCEL                            = 0x1205, /**< Indicates the application x excel type */
+       MIME_APPLICATION_X_POWERPOINT                       = 0x1206, /**< Indicates the application x power point type */
 
        // 56
-       MIME_AUDIO_BASIC                                                                                = 0x2000, /**< Indicates the audio basic type  */
-       MIME_AUDIO_MPEG                                                                         = 0x2001, /**< Indicates the audio mpeg type  */
-       MIME_AUDIO_MP3                                                                          = 0x2002, /**< Indicates the audio mp3 type  */
-       MIME_AUDIO_MPG3                                                                         = 0x2003,  /**< Indicates the audio mpg3 type  */
-       MIME_AUDIO_MPEG3                                                                                = 0x2004, /**< Indicates the audio mpeg3 type  */
-       MIME_AUDIO_MPG                                                                          = 0x2005, /**< Indicates the audio mpg type  */
-       MIME_AUDIO_AAC                                                                          = 0x2006, /**< Indicates the audio aac type  */
-       MIME_AUDIO_G72                                                                          = 0x2007, /**< Indicates the audio g72 type  */
-       MIME_AUDIO_AMR                                                                          = 0x2008, /**< Indicates the audio amr type  */
-       MIME_AUDIO_AMR_WB                                                                       = 0x2009, /**< Indicates the audio amr wb type  */
-       MIME_AUDIO_MMF                                                                          = 0x200a, /**< Indicates the audio mmf type  */
-       MIME_AUDIO_SMAF                                                                         = 0x200b, /**< Indicates the audio smaf type  */
-       MIME_AUDIO_IMELODY                                                                      = 0x200c, /**< Indicates the audio imelody type  */
-       MIME_AUDIO_IMELODY2                                                                     = 0x200d, /**< Indicates the audio imelody2 type  */
-       MIME_AUDIO_MELODY                                                                       = 0x200e, /**< Indicates the audio melody type  */
-       MIME_AUDIO_MID                                                                          = 0x200f, /**< Indicates the audio mid type  */
-       MIME_AUDIO_MIDI                                                                         = 0x2010, /**< Indicates the audio midi type  */
-       MIME_AUDIO_SP_MIDI                                                                      = 0x2011, /**< Indicates the audio sp midi type  */
-       MIME_AUDIO_WAVE                                                                         = 0x2012, /**< Indicates the audio wave type  */
-       MIME_AUDIO_WAV                                                                          = 0x2013, /**< Indicates the audio wav type  */
-       MIME_AUDIO_3GPP                                                                         = 0x2014, /**< Indicates the audio 3gpp type  */
-       MIME_AUDIO_MP4                                                                          = 0x2015, /**< Indicates the audio mp4 type  */
-       MIME_AUDIO_MP4A_LATM                                                            = 0x2016, /**< Indicates the audio mp4 latm type  */
-       MIME_AUDIO_M4A                                                                          = 0x2017, /**< Indicates the audio m4a type  */
-       MIME_AUDIO_MPEG4                                                                                = 0x2018, /**< Indicates the audio mpeg4 type  */
-       MIME_AUDIO_WMA                                                                          = 0x2019, /**< Indicates the audio wma type  */
-       MIME_AUDIO_XMF                                                                          = 0x201a, /**< Indicates the audio xmf type  */
-       MIME_AUDIO_IMY                                                                          = 0x201b, /**< Indicates the audio imy type  */
-       MIME_AUDIO_MOBILE_XMF                                                           = 0x201c, /**< Indicates the audio mobile xmf type  */
+       MIME_AUDIO_BASIC                                    = 0x2000, /**< Indicates the audio basic type  */
+       MIME_AUDIO_MPEG                                     = 0x2001, /**< Indicates the audio mpeg type  */
+       MIME_AUDIO_MP3                                      = 0x2002, /**< Indicates the audio mp3 type  */
+       MIME_AUDIO_MPG3                                     = 0x2003, /**< Indicates the audio mpg3 type  */
+       MIME_AUDIO_MPEG3                                    = 0x2004, /**< Indicates the audio mpeg3 type  */
+       MIME_AUDIO_MPG                                      = 0x2005, /**< Indicates the audio mpg type  */
+       MIME_AUDIO_AAC                                      = 0x2006, /**< Indicates the audio aac type  */
+       MIME_AUDIO_G72                                      = 0x2007, /**< Indicates the audio g72 type  */
+       MIME_AUDIO_AMR                                      = 0x2008, /**< Indicates the audio amr type  */
+       MIME_AUDIO_AMR_WB                                   = 0x2009, /**< Indicates the audio amr wb type  */
+       MIME_AUDIO_MMF                                      = 0x200a, /**< Indicates the audio mmf type  */
+       MIME_AUDIO_SMAF                                     = 0x200b, /**< Indicates the audio smaf type  */
+       MIME_AUDIO_IMELODY                                  = 0x200c, /**< Indicates the audio imelody type  */
+       MIME_AUDIO_IMELODY2                                 = 0x200d, /**< Indicates the audio imelody2 type  */
+       MIME_AUDIO_MELODY                                   = 0x200e, /**< Indicates the audio melody type  */
+       MIME_AUDIO_MID                                      = 0x200f, /**< Indicates the audio mid type  */
+       MIME_AUDIO_MIDI                                     = 0x2010, /**< Indicates the audio midi type  */
+       MIME_AUDIO_SP_MIDI                                  = 0x2011, /**< Indicates the audio sp midi type  */
+       MIME_AUDIO_WAVE                                     = 0x2012, /**< Indicates the audio wave type  */
+       MIME_AUDIO_WAV                                      = 0x2013, /**< Indicates the audio wav type  */
+       MIME_AUDIO_3GPP                                     = 0x2014, /**< Indicates the audio 3gpp type  */
+       MIME_AUDIO_MP4                                      = 0x2015, /**< Indicates the audio mp4 type  */
+       MIME_AUDIO_MP4A_LATM                                = 0x2016, /**< Indicates the audio mp4 latm type  */
+       MIME_AUDIO_M4A                                      = 0x2017, /**< Indicates the audio m4a type  */
+       MIME_AUDIO_MPEG4                                    = 0x2018, /**< Indicates the audio mpeg4 type  */
+       MIME_AUDIO_WMA                                      = 0x2019, /**< Indicates the audio wma type  */
+       MIME_AUDIO_XMF                                      = 0x201a, /**< Indicates the audio xmf type  */
+       MIME_AUDIO_IMY                                      = 0x201b, /**< Indicates the audio imy type  */
+       MIME_AUDIO_MOBILE_XMF                               = 0x201c, /**< Indicates the audio mobile xmf type  */
 
        //85
-       MIME_AUDIO_VND_RN_REALAUDIO                                             = 0x2100, /**< Indicates the audio rn real audio type  */
+       MIME_AUDIO_VND_RN_REALAUDIO                         = 0x2100, /**< Indicates the audio rn real audio type  */
 
        // 86
-       MIME_AUDIO_X_MPEG                                                                       = 0x2200, /**< Indicates the audio x mpeg type  */
-       MIME_AUDIO_X_MP3                                                                                = 0x2201, /**< Indicates the audio x mp3 type  */
-       MIME_AUDIO_X_MPEG3                                                                      = 0x2202,    /**< Indicates the audio x mpeg3 type  */
-       MIME_AUDIO_X_MPG                                                                                = 0x2203, /**< Indicates the audio x mpg type  */
-       MIME_AUDIO_X_AMR                                                                                = 0x2204, /**< Indicates the audio x amr type  */
-       MIME_AUDIO_X_MMF                                                                                = 0x2205, /**< Indicates the audio x mmf type  */
-       MIME_AUDIO_X_SMAF                                                                       = 0x2206, /**< Indicates the audio x smaf type  */
-       MIME_AUDIO_X_IMELODY                                                                    = 0x2207, /**< Indicates the audio x imelody type  */
-       MIME_AUDIO_X_MIDI                                                                               = 0x2208, /**< Indicates the audio x midi type  */
-       MIME_AUDIO_X_MPEGAUDIO                                                          = 0x2209, /**< Indicates the audio x mpeg  type  */
-       MIME_AUDIO_X_PN_REALAUDIO                                                       = 0x220a, /**< Indicates the audio x pn real audio type  */
-       MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO                             = 0x220b, /**< Indicates the audio x pn multirate real audio  type  */
-       MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE                        = 0x220c, /**< Indicates the audio x pn multirate real audio live type  */
-       MIME_AUDIO_X_WAVE                                                                       = 0x220d, /**< Indicates the audio x wave  type  */
-       MIME_AUDIO_X_WAV                                                                                = 0x220e, /**< Indicates the audio x wav  type  */
-       MIME_AUDIO_X_MS_WMA                                                                     = 0x220f, /**< Indicates the audio ms wma type  */
-       MIME_AUDIO_X_MID                                                                                = 0x2210, /**< Indicates the audio mid type  */
-       MIME_AUDIO_X_MS_ASF                                                                     = 0x2211, /**< Indicates the audio ms asf  type  */
-       MIME_AUDIO_X_XMF                                                                                = 0x2212, /**< Indicates the audio x xmf  type  */
+       MIME_AUDIO_X_MPEG                                   = 0x2200, /**< Indicates the audio x mpeg type  */
+       MIME_AUDIO_X_MP3                                    = 0x2201, /**< Indicates the audio x mp3 type  */
+       MIME_AUDIO_X_MPEG3                                  = 0x2202, /**< Indicates the audio x mpeg3 type  */
+       MIME_AUDIO_X_MPG                                    = 0x2203, /**< Indicates the audio x mpg type  */
+       MIME_AUDIO_X_AMR                                    = 0x2204, /**< Indicates the audio x amr type  */
+       MIME_AUDIO_X_MMF                                    = 0x2205, /**< Indicates the audio x mmf type  */
+       MIME_AUDIO_X_SMAF                                   = 0x2206, /**< Indicates the audio x smaf type  */
+       MIME_AUDIO_X_IMELODY                                = 0x2207, /**< Indicates the audio x imelody type  */
+       MIME_AUDIO_X_MIDI                                   = 0x2208, /**< Indicates the audio x midi type  */
+       MIME_AUDIO_X_MPEGAUDIO                              = 0x2209, /**< Indicates the audio x mpeg  type  */
+       MIME_AUDIO_X_PN_REALAUDIO                           = 0x220a, /**< Indicates the audio x pn real audio type  */
+       MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO                 = 0x220b, /**< Indicates the audio x pn multirate real audio  type  */
+       MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE            = 0x220c, /**< Indicates the audio x pn multirate real audio live type  */
+       MIME_AUDIO_X_WAVE                                   = 0x220d, /**< Indicates the audio x wave  type  */
+       MIME_AUDIO_X_WAV                                    = 0x220e, /**< Indicates the audio x wav  type  */
+       MIME_AUDIO_X_MS_WMA                                 = 0x220f, /**< Indicates the audio ms wma type  */
+       MIME_AUDIO_X_MID                                    = 0x2210, /**< Indicates the audio mid type  */
+       MIME_AUDIO_X_MS_ASF                                 = 0x2211, /**< Indicates the audio ms asf  type  */
+       MIME_AUDIO_X_XMF                                    = 0x2212, /**< Indicates the audio x xmf  type  */
 
        // 105
-       MIME_IMAGE_GIF                                                                          = 0x3000, /**< Indicates the image gif type  */
-       MIME_IMAGE_JPEG                                                                         = 0x3001, /**< Indicates the image jpeg type  */
-       MIME_IMAGE_JPG                                                                          = 0x3002, /**< Indicates the image jpg type  */
-       MIME_IMAGE_TIFF                                                                         = 0x3003, /**< Indicates the image tiff type  */
-       MIME_IMAGE_TIF                                                                          = 0x3004, /**< Indicates the image tif type  */
-       MIME_IMAGE_PNG                                                                          = 0x3005, /**< Indicates the image png type  */
-       MIME_IMAGE_WBMP                                                                         = 0x3006, /**< Indicates the image wbmp type  */
-       MIME_IMAGE_PJPEG                                                                                = 0x3007, /**< Indicates the image pjpeg type  */
-       MIME_IMAGE_BMP                                                                          = 0x3008, /**< Indicates the image bmp type  */
-       MIME_IMAGE_SVG                                                                          = 0x3009, /**< Indicates the image svg type  */
-       MIME_IMAGE_SVG1                                                                         = 0x300a, /**< Indicates the image svg1 type  */
+       MIME_IMAGE_GIF                                      = 0x3000, /**< Indicates the image gif type  */
+       MIME_IMAGE_JPEG                                     = 0x3001, /**< Indicates the image jpeg type  */
+       MIME_IMAGE_JPG                                      = 0x3002, /**< Indicates the image jpg type  */
+       MIME_IMAGE_TIFF                                     = 0x3003, /**< Indicates the image tiff type  */
+       MIME_IMAGE_TIF                                      = 0x3004, /**< Indicates the image tif type  */
+       MIME_IMAGE_PNG                                      = 0x3005, /**< Indicates the image png type  */
+       MIME_IMAGE_WBMP                                     = 0x3006, /**< Indicates the image wbmp type  */
+       MIME_IMAGE_PJPEG                                    = 0x3007, /**< Indicates the image pjpeg type  */
+       MIME_IMAGE_BMP                                      = 0x3008, /**< Indicates the image bmp type  */
+       MIME_IMAGE_SVG                                      = 0x3009, /**< Indicates the image svg type  */
+       MIME_IMAGE_SVG1                                     = 0x300a, /**< Indicates the image svg1 type  */
 
        // 116
-       MIME_IMAGE_VND_WAP_WBMP                                                 = 0x3100,  /**< Indicates the image vnd wap wbmp type  */
-       MIME_IMAGE_VND_TMO_GIF                                                          = 0x3101,  /**< Indicates the image vnd tmo gif type  */
-       MIME_IMAGE_VND_TMO_JPG                                                          = 0x3102,  /**< Indicates the image vnd tmo jpg type  */
+       MIME_IMAGE_VND_WAP_WBMP                             = 0x3100, /**< Indicates the image vnd wap wbmp type  */
+       MIME_IMAGE_VND_TMO_GIF                              = 0x3101, /**< Indicates the image vnd tmo gif type  */
+       MIME_IMAGE_VND_TMO_JPG                              = 0x3102, /**< Indicates the image vnd tmo jpg type  */
 
        // 119
-       MIME_IMAGE_X_BMP                                                                                = 0x3200, /**< Indicates the image x bmp type  */
+       MIME_IMAGE_X_BMP                                    = 0x3200, /**< Indicates the image x bmp type  */
 
        // 120
-       MIME_MESSAGE_RFC822                                                                     = 0x4000,  /**< Indicates the message rfc822 type  */
+       MIME_MESSAGE_RFC822                                 = 0x4000, /**< Indicates the message rfc822 type  */
 
        // 121
-       MIME_MULTIPART_MIXED                                                                    = 0x5000,  /**< Indicates the multipart mixed type  */
-       MIME_MULTIPART_RELATED                                                          = 0x5001, /**< Indicates the multipart related type  */
-       MIME_MULTIPART_ALTERNATIVE                                                      = 0x5002, /**< Indicates the multipart alternative type  */
-       MIME_MULTIPART_FORM_DATA                                                        = 0x5003, /**< Indicates the multipart form data type  */
-       MIME_MULTIPART_BYTERANGE                                                        = 0x5004, /**< Indicates the multipart byte range type  */
-       MIME_MULTIPART_REPORT                                                           = 0x5005, /**< Indicates the multipart report type  */
-       MIME_MULTIPART_VOICE_MESSAGE                                            = 0x5006, /**< Indicates the multipart voice message type  */
+       MIME_MULTIPART_MIXED                                = 0x5000, /**< Indicates the multipart mixed type  */
+       MIME_MULTIPART_RELATED                              = 0x5001, /**< Indicates the multipart related type  */
+       MIME_MULTIPART_ALTERNATIVE                          = 0x5002, /**< Indicates the multipart alternative type  */
+       MIME_MULTIPART_FORM_DATA                            = 0x5003, /**< Indicates the multipart form data type  */
+       MIME_MULTIPART_BYTERANGE                            = 0x5004, /**< Indicates the multipart byte range type  */
+       MIME_MULTIPART_REPORT                               = 0x5005, /**< Indicates the multipart report type  */
+       MIME_MULTIPART_VOICE_MESSAGE                        = 0x5006, /**< Indicates the multipart voice message type  */
 
        // 128
-       MIME_TEXT_TXT                                                                                   = 0x6000, /**< Indicates the text txt type  */
-       MIME_TEXT_HTML                                                                          = 0x6001, /**< Indicates the text html type  */
-       MIME_TEXT_PLAIN                                                                         = 0x6002,  /**< Indicates the text plain type  */
-       MIME_TEXT_CSS                                                                                   = 0x6003,  /**< Indicates the text css type  */
-       MIME_TEXT_XML                                                                                   = 0x6004,  /**< Indicates the text xml type  */
-       MIME_TEXT_IMELODY                                                                               = 0x6005,  /**< Indicates the text imelody type  */
+       MIME_TEXT_TXT                                       = 0x6000, /**< Indicates the text txt type  */
+       MIME_TEXT_HTML                                      = 0x6001, /**< Indicates the text html type  */
+       MIME_TEXT_PLAIN                                     = 0x6002, /**< Indicates the text plain type  */
+       MIME_TEXT_CSS                                       = 0x6003, /**< Indicates the text css type  */
+       MIME_TEXT_XML                                       = 0x6004, /**< Indicates the text xml type  */
+       MIME_TEXT_IMELODY                                   = 0x6005, /**< Indicates the text imelody type  */
+       MIME_TEXT_CALENDAR                                  = 0x6006, /**< Indicates the text calendar type */
 
        // 134
-       MIME_TEXT_VND_WAP_WMLSCRIPT                                             = 0x6100, /**< Indicates the text wap wmlscript  type  */
-       MIME_TEXT_VND_WAP_WML                                                           = 0x6101, /**< Indicates the text wap wml  type  */
-       MIME_TEXT_VND_WAP_WTA_EVENT                                             = 0x6102, /**< Indicates the text wap wta event  type  */
-       MIME_TEXT_VND_WAP_CONNECTIVITY_XML                              = 0x6103, /**< Indicates the text wap connectivity xml  type  */
-       MIME_TEXT_VND_WAP_SI                                                                    = 0x6104,  /**< Indicates the text wap si  type  */
-       MIME_TEXT_VND_WAP_SL                                                            = 0x6105, /**< Indicates the text wap sl  type  */
-       MIME_TEXT_VND_WAP_CO                                                            = 0x6106, /**< Indicates the text wap co  type  */
-       MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR                           = 0x6107, /**< Indicates the text sun j2me type  */
+       MIME_TEXT_VND_WAP_WMLSCRIPT                         = 0x6100, /**< Indicates the text wap wmlscript  type  */
+       MIME_TEXT_VND_WAP_WML                               = 0x6101, /**< Indicates the text wap wml  type  */
+       MIME_TEXT_VND_WAP_WTA_EVENT                         = 0x6102, /**< Indicates the text wap wta event  type  */
+       MIME_TEXT_VND_WAP_CONNECTIVITY_XML                  = 0x6103, /**< Indicates the text wap connectivity xml  type  */
+       MIME_TEXT_VND_WAP_SI                                = 0x6104, /**< Indicates the text wap si  type  */
+       MIME_TEXT_VND_WAP_SL                                = 0x6105, /**< Indicates the text wap sl  type  */
+       MIME_TEXT_VND_WAP_CO                                = 0x6106, /**< Indicates the text wap co  type  */
+       MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR               = 0x6107, /**< Indicates the text sun j2me type  */
 
        // 142
-       MIME_TEXT_X_HDML                                                                                = 0x6200, /**< Indicates the x html  type  */
-       MIME_TEXT_X_VCALENDAR                                                           = 0x6201,  /**< Indicates the x calendar  type  */
-       MIME_TEXT_X_VCARD                                                                       = 0x6202, /**< Indicates the x vcard  type  */
-       MIME_TEXT_X_IMELODY                                                                     = 0x6203, /**< Indicates the x imelody  type  */
-       MIME_TEXT_X_IMELODY2                                                                    = 0x6204, /**< Indicates the x imelody2  type  */
-       MIME_TEXT_X_VNOTE                                                                       = 0x6205,  /**< Indicates the x vnote  type  */
-
-       // 148
-       MIME_VIDEO_MPEG4                                                                                = 0x7000, /**< Indicates the mpeg4  type  */
-       MIME_VIDEO_MP4                                                                          = 0x7001, /**< Indicates the mp4  type  */
-       MIME_VIDEO_H263                                                                         = 0x7002, /**< Indicates the h263  type  */
-       MIME_VIDEO_3GPP                                                                         = 0x7003, /**< Indicates the 3gpp  type  */
-       MIME_VIDEO_3GP                                                                          = 0x7004, /**< Indicates the 3gp  type  */
-       MIME_VIDEO_AVI                                                                          = 0x7005, /**< Indicates the avi  type  */
-       MIME_VIDEO_SDP                                                                          = 0x7006, /**< Indicates the sdp  type  */
-       MIME_VIDEO_MP4_ES                                                                       = 0x7007, /**< Indicates the mp4 es  type  */
-       MIME_VIDEO_MPEG                                                                         = 0x7008, /**< Indicates the mpeg  type  */
-
-       // 157
-       MIME_VIDEO_VND_RN_REALVIDEO                                                     = 0x7100, /**< Indicates the pn real video type  */
-       MIME_VIDEO_VND_RN_REALMEDIA                                                     = 0x7101, /**< Indicates the pn multi rate real media type  */
-
-       // 159
-       MIME_VIDEO_X_MP4                                                                                = 0x7200, /**< Indicates the video x mp4 type  */
-       MIME_VIDEO_X_PV_MP4                                                                     = 0x7201, /**< Indicates the video x pv mp4 type  */
-       MIME_VIDEO_X_PN_REALVIDEO                                                       = 0x7202, /**< Indicates the x pn real video type  */
-       MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO                             = 0x7203, /**< Indicates the x pn multi rate real video type  */
-       MIME_VIDEO_X_MS_WMV                                                                     = 0x7204, /**< Indicates the x ms wmv type  */
-       MIME_VIDEO_X_MS_ASF                                                                     = 0x7205, /**< Indicates the x ms asf type  */
-       MIME_VIDEO_X_PV_PVX                                                                     = 0x7206, /**< Indicates the x pv pvx type  */
-
-       MIME_TYPE_VALUE_MAX                                                                     = 0x7207,               /**< Indicates the maximum mime type  */
-       MIME_UNKNOWN                                                                                    = 0xffff        /**< Indicates the unknown mime type  */
+       MIME_TEXT_X_HDML                                    = 0x6200, /**< Indicates the x html  type  */
+       MIME_TEXT_X_VCALENDAR                               = 0x6201, /**< Indicates the x calendar  type  */
+       MIME_TEXT_X_VCARD                                   = 0x6202, /**< Indicates the x vcard  type  */
+       MIME_TEXT_X_IMELODY                                 = 0x6203, /**< Indicates the x imelody  type  */
+       MIME_TEXT_X_IMELODY2                                = 0x6204, /**< Indicates the x imelody2  type  */
+       MIME_TEXT_X_VNOTE                                   = 0x6205, /**< Indicates the x vnote  type  */
+       MIME_TEXT_X_VTODO                                   = 0x6206, /**< Indicates the x todo  type  */
+
+       // 149
+       MIME_VIDEO_MPEG4                                    = 0x7000, /**< Indicates the mpeg4  type  */
+       MIME_VIDEO_MP4                                      = 0x7001, /**< Indicates the mp4  type  */
+       MIME_VIDEO_H263                                     = 0x7002, /**< Indicates the h263  type  */
+       MIME_VIDEO_3GPP                                     = 0x7003, /**< Indicates the 3gpp  type  */
+       MIME_VIDEO_3GP                                      = 0x7004, /**< Indicates the 3gp  type  */
+       MIME_VIDEO_AVI                                      = 0x7005, /**< Indicates the avi  type  */
+       MIME_VIDEO_SDP                                      = 0x7006, /**< Indicates the sdp  type  */
+       MIME_VIDEO_MP4_ES                                   = 0x7007, /**< Indicates the mp4 es  type  */
+       MIME_VIDEO_MPEG                                     = 0x7008, /**< Indicates the mpeg  type  */
+       MIME_VIDEO_MOV                                      = 0x7009, /**< Indicates the mov  type  */
+
+       // 158
+       MIME_VIDEO_VND_RN_REALVIDEO                         = 0x7100, /**< Indicates the pn real video type  */
+       MIME_VIDEO_VND_RN_REALMEDIA                         = 0x7101, /**< Indicates the pn multi rate real media type  */
+
+       // 160
+       MIME_VIDEO_X_MP4                                    = 0x7200, /**< Indicates the video x mp4 type  */
+       MIME_VIDEO_X_PV_MP4                                 = 0x7201, /**< Indicates the video x pv mp4 type  */
+       MIME_VIDEO_X_PN_REALVIDEO                           = 0x7202, /**< Indicates the x pn real video type  */
+       MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO                 = 0x7203, /**< Indicates the x pn multi rate real video type  */
+       MIME_VIDEO_X_MS_WMV                                 = 0x7204, /**< Indicates the x ms wmv type  */
+       MIME_VIDEO_X_MS_ASF                                 = 0x7205, /**< Indicates the x ms asf type  */
+       MIME_VIDEO_X_PV_PVX                                 = 0x7206, /**< Indicates the x pv pvx type  */
+
+       MIME_TYPE_VALUE_MAX                                 = 0x7207, /**< Indicates the maximum MIME type  */
+       MIME_UNKNOWN                                        = 0xffff  /**< Indicates the unknown MIME type  */
 
 } MimeType;
 
 /**
- *     @brief  Represents the values of a DRM type.
+ *  @brief  Enumeration for the values of a DRM type.
  */
-//#ifdef __SUPPORT_DRM__
 typedef enum
 {
-       MSG_DRM_TYPE_NONE       = 0, /**< Indicates the drm type none */
+       MSG_DRM_TYPE_NONE       = 0, /**< Indicates the DRM type none */
        MSG_DRM_TYPE_FL         = 1, /**< Indicates the forward lock */         /* 2004-07-09: forwardLock type */
        MSG_DRM_TYPE_CD         = 2, /**< Indicates the combined delivery */    /* 2004-07-09: combined delivery type */
        MSG_DRM_TYPE_SD         = 3, /**< Indicates the separate delivery */    /* 2004-07-09: seperate delivery type */
-       MSG_DRM_TYPE_SSD        = 4     /**< Indicates the special separate delivery */ // 2005-02-28: add Special Sperate Delivery
+       MSG_DRM_TYPE_SSD        = 4      /**< Indicates the special separate delivery */        // 2005-02-28: add Special Sperate Delivery
 }MsgDrmType;
-//#endif
 
 /**
- *     @brief  Represents the values of a SMIL region type.
+ *  @brief  Enumeration for the values of a SMIL region type.
  */
 typedef enum _REGION_FIT_TYPE_T
 {
@@ -1226,344 +1744,412 @@ typedef enum _REGION_FIT_TYPE_T
 
 
 /**
- *     @brief  Represents the values of a SMIL media type.
+ *  @brief  Enumeration for the values of a SMIL media type.
  */
 typedef enum
 {
-       MMS_SMIL_MEDIA_INVALID = 0, /**< Indicates the invalid media type */
-       MMS_SMIL_MEDIA_IMG,                     /**< Indicates the image media */
-       MMS_SMIL_MEDIA_AUDIO,           /**< Indicates the audio media */
-       MMS_SMIL_MEDIA_VIDEO,           /**< Indicates the video media */
-       MMS_SMIL_MEDIA_TEXT,            /**< Indicates the text media */
-       MMS_SMIL_MEDIA_ANIMATE,         /**< Indicates the animation media */
-       MMS_SMIL_MEDIA_IMG_OR_VIDEO     , /**< Indicates the image or video media */
-       MMS_SMIL_MEDIA_MAX = 0xffffffff,        /**< Indicates the maximum media type */
+       MMS_SMIL_MEDIA_INVALID = 0,       /**< Indicates the invalid media type */
+       MMS_SMIL_MEDIA_IMG,               /**< Indicates the image media */
+       MMS_SMIL_MEDIA_AUDIO,             /**< Indicates the audio media */
+       MMS_SMIL_MEDIA_VIDEO,             /**< Indicates the video media */
+       MMS_SMIL_MEDIA_TEXT,              /**< Indicates the text media */
+       MMS_SMIL_MEDIA_ANIMATE,           /**< Indicates the animation media */
+       MMS_SMIL_MEDIA_IMG_OR_VIDEO     ,     /**< Indicates the image or video media */
+       MMS_SMIL_MEDIA_MAX = 0xffffffff,  /**< Indicates the maximum media type */
 }MmsSmilMediaType;
 
 /**
- *     @brief  Represents the values of a SMIL transition type.
+ *  @brief  Enumeration for the values of a SMIL transition type.
  */
 typedef enum
 {
-       MMS_SMIL_TRANS_NONE = 0,                /**< Indicates the transition type none */                      /* default */
-       MMS_SMIL_TRANS_SLIDEWIPE = 1,   /**< Indicates the slide wipe transition */
-       MMS_SMIL_TRANS_BARWIPE = 2,             /**< Indicates the bar wipe transition */
+       MMS_SMIL_TRANS_NONE = 0,         /**< Indicates the transition type none */                     /* default */
+       MMS_SMIL_TRANS_SLIDEWIPE = 1,    /**< Indicates the slide wipe transition */
+       MMS_SMIL_TRANS_BARWIPE = 2,      /**< Indicates the bar wipe transition */
        MMS_SMIL_TRANS_BARNDOORWIPE = 3, /**< Indicates the bar and door wipe transition */
-       MMS_SMIL_TRANS_FADE = 4,                /**< Indicates the fade transition */
-       MMS_SMIL_TRANS_RANDOMBLOCK = 5, /**< Indicates the random block transition */
-       MMS_SMIL_TRANS_ZOOMIN = 6,              /**< Indicates the zoom in transition */
-       MMS_SMIL_TRANS_IRISWIPE = 7,    /**< Indicates the iris wipe transition */
-       MMS_SMIL_TRANS_BOXWIPE = 8,             /**< Indicates the box wipe transition */
-       MMS_SMIL_TRANS_FOURBOXWIPE = 9, /**< Indicates the four box wipe transition */
-       MMS_SMIL_TRANS_PUSHWIPE  =10,   /**< Indicates the push wipe transition */
+       MMS_SMIL_TRANS_FADE = 4,         /**< Indicates the fade transition */
+       MMS_SMIL_TRANS_RANDOMBLOCK = 5,  /**< Indicates the random block transition */
+       MMS_SMIL_TRANS_ZOOMIN = 6,       /**< Indicates the zoom in transition */
+       MMS_SMIL_TRANS_IRISWIPE = 7,     /**< Indicates the iris wipe transition */
+       MMS_SMIL_TRANS_BOXWIPE = 8,      /**< Indicates the box wipe transition */
+       MMS_SMIL_TRANS_FOURBOXWIPE = 9,  /**< Indicates the four box wipe transition */
+       MMS_SMIL_TRANS_PUSHWIPE  =10,    /**< Indicates the push wipe transition */
        MMS_SMIL_TRANS_ELLIPSEWIPE  = 11 /**< Indicates the ellipse wipe transition */
 }MmsSmilTransType;
 
 /**
- *     @brief  Represents the values of a SMIL transition sub type.
+ *  @brief  Enumeration for the values of a SMIL transition sub type.
  */
 typedef enum
 {
-       MMS_SMIL_TRANS_SUB_NONE = 0,    /**< Indicates the transition sub type none */
-       MMS_SMIL_TRANS_SUB_FROM_LEFT = 1,       /**< Indicates the from left transition */      /* slideWipe's default */
-       MMS_SMIL_TRANS_SUB_FROM_TOP = 2,        /**< Indicates the from top transition */
-       MMS_SMIL_TRANS_SUB_FROM_BOTTOM = 3,     /**< Indicates the from bottom transition */
+       MMS_SMIL_TRANS_SUB_NONE = 0,          /**< Indicates the transition sub type none */
+       MMS_SMIL_TRANS_SUB_FROM_LEFT = 1,     /**< Indicates the from left transition */        /* slideWipe's default */
+       MMS_SMIL_TRANS_SUB_FROM_TOP = 2,      /**< Indicates the from top transition */
+       MMS_SMIL_TRANS_SUB_FROM_BOTTOM = 3,   /**< Indicates the from bottom transition */
        MMS_SMIL_TRANS_SUB_TOP_TO_BOTTOM = 4, /**< Indicates the from top to bottom transition */                       /* barWipe's default */
        MMS_SMIL_TRANS_SUB_BOTTOM_TO_TOP = 5, /**< Indicates the from bottom to top transition */
-       MMS_SMIL_TRANS_SUB_HORIZONTAL = 6,      /**< Indicates the horizontal transition */             /* barDoorWipe's default */
-    MMS_SMIL_TRANS_SUB_FROM_RIGHT = 7, /**< Indicates the from right transition */
-    MMS_SMIL_TRANS_SUB_VERTICAL = 8 /**< Indicates the vertical transition */
+       MMS_SMIL_TRANS_SUB_HORIZONTAL = 6,    /**< Indicates the horizontal transition */               /* barDoorWipe's default */
+       MMS_SMIL_TRANS_SUB_FROM_RIGHT = 7,    /**< Indicates the from right transition */
+       MMS_SMIL_TRANS_SUB_VERTICAL = 8       /**< Indicates the vertical transition */
 }MmsSmilTransSubType;
 
 /**
- *     @brief  Represents the values of a text font type.
+ *  @brief  Enumeration for the values of a text font type.
  */
 typedef enum
 {
-       MMS_SMIL_FONT_TYPE_NONE = 0, /**< Indicates the font type none */
-       MMS_SMIL_FONT_TYPE_NORMAL = 1, /**< Indicates the font type normal */
-       MMS_SMIL_FONT_TYPE_ITALIC = 2, /**< Indicates the font type italic */
-       MMS_SMIL_FONT_TYPE_BOLD = 3, /**< Indicates the font type bold */
+       MMS_SMIL_FONT_TYPE_NONE = 0,     /**< Indicates the font type none */
+       MMS_SMIL_FONT_TYPE_NORMAL = 1,   /**< Indicates the font type normal */
+       MMS_SMIL_FONT_TYPE_ITALIC = 2,   /**< Indicates the font type italic */
+       MMS_SMIL_FONT_TYPE_BOLD = 3,     /**< Indicates the font type bold */
        MMS_SMIL_FONT_TYPE_UNDERLINE = 4 /**< Indicates the font type underline */
 }MmsSmilFontType;
 
 /**
- *     @brief  Represents the values of a MMS text direction.
+ *  @brief  Enumeration for the values of a MMS text direction.
  */
 typedef enum   _MmsTextDir{
        MMS_TEXT_DIRECTION_INVALID = -1, /**< Indicates the invalid direction */
-       MMS_TEXT_DIRECTION_RIGHT = 0,   /**< Indicates the right direction */
-       MMS_TEXT_DIRECTION_DOWN,                /**< Indicates the down direction */            // supported to GC
+       MMS_TEXT_DIRECTION_RIGHT = 0,    /**< Indicates the right direction */
+       MMS_TEXT_DIRECTION_DOWN,         /**< Indicates the down direction */           // supported to GC
 } MmsTextDirection;
 
 /**
- *     @brief  Represents the values of MMS Read Report Sent Status.
+ *  @brief  Enumeration for the values of MMS Read Report Sent Status.
  */
 typedef enum
 {
-       MMS_RECEIVE_READ_REPORT_NO_SEND,        // didn't send yet
-       MMS_RECEIVE_READ_REPORT_MUST_SEND,      // didn't send yet but will send
-       MMS_RECEIVE_READ_REPORT_SENT,           // sent
-       MMS_RECEIVE_READ_REPORT_NO_SENT,        // required but, didn't send by user's choice
+       MMS_RECEIVE_READ_REPORT_NO_SEND,    /**< Not sent yet */
+       MMS_RECEIVE_READ_REPORT_MUST_SEND,  /**< Not sent yet, but will be sent */
+       MMS_RECEIVE_READ_REPORT_SENT,       /**< Sent */
+       MMS_RECEIVE_READ_REPORT_NO_SENT,    /**< Must be sent, but did not send by user's choice */
 } MmsRecvReadReportSendStatus ;
 
 
 // setting
 
 /**
- *     @brief  Represents the values of an option type. \n
- *     This enum is used as the value of MSG_OPTION_TYPE_T.
+ *  @brief  Enumeration for the values of an option type. \n
+ *             This enum is used as the value of MSG_OPTION_TYPE_T.
  */
 enum _MSG_OPTION_TYPE_E
 {
-       MSG_GENERAL_OPT,                        /**< General option */
-       MSG_SMS_SENDOPT,                        /**< SMS send option */
-       MSG_SMSC_LIST,                          /**< SMSC list option */
-       MSG_MMS_SENDOPT,                        /**< MMS send option */
-       MSG_MMS_RECVOPT,                        /**< MMS receive option */
-       MSG_MMS_CLASSOPT,                       /**< MMS class option such as personal, advertisement, and informational */
-       MSG_MMS_STYLEOPT,                       /**< MMS style option */
-       MSG_PUSHMSG_OPT,                        /**< Push message option */
-       MSG_CBMSG_OPT,                  /**< Cell broadcasting message option */
-       MSG_VOICEMAIL_OPT,                      /**< Voice mail option */
-       MSG_MSGSIZE_OPT,                        /**< Message size option */
+       MSG_GENERAL_OPT,            /**< General option */
+       MSG_SMS_SENDOPT,            /**< SMS send option */
+       MSG_SMSC_LIST,              /**< SMSC list option */
+       MSG_MMS_SENDOPT,            /**< MMS send option */
+       MSG_MMS_RECVOPT,            /**< MMS receive option */
+       MSG_MMS_CLASSOPT,           /**< MMS class option such as personal, advertisement, and informational */
+       MSG_MMS_STYLEOPT,           /**< MMS style option */
+       MSG_PUSHMSG_OPT,            /**< Push message option */
+       MSG_CBMSG_OPT,              /**< Cell broadcasting message option */
+       MSG_VOICEMAIL_OPT,          /**< Voice mail option */
+       MSG_MSGSIZE_OPT,            /**< Message size option */
+       MSG_OPTION_TYPE_MAX,        /**< Placeholder for max value of this enum*/
 };
 
 
 /**
- *     @brief  Represents the values of an SMS network mode. \n
- *     This enum is used as the value of MSG_SMS_NETWORK_MODE_T.
+ *  @brief  Enumeration for the values of an SMS network mode. \n
+ *             This enum is used as the value of MSG_SMS_NETWORK_MODE_T.
  */
 enum _MSG_SMS_NETWORK_MODE_E
 {
-       MSG_SMS_NETWORK_PS_ONLY = 0x01,         /**< Packet switched */
-       MSG_SMS_NETWORK_CS_ONLY = 0x02,         /**< Circuit switched */
-       MSG_SMS_NETWORK_PS_FIRST = 0x03,                /**< Packet switching preferred */
+       MSG_SMS_NETWORK_PS_ONLY = 0x01,     /**< Packet switched */
+       MSG_SMS_NETWORK_CS_ONLY = 0x02,     /**< Circuit switched */
+       MSG_SMS_NETWORK_PS_FIRST = 0x03,    /**< Packet switching preferred */
 };
 
 
 /**
- *     @brief  Represents the value of period of playing alert tone. \n
- *     The values for this type SHOULD be in MSG_ALERT_TONE_T.
+ *  @brief  Enumeration for the value of period of playing alert tone. \n
+ *             The values for this type SHOULD be in MSG_ALERT_TONE_T.
  */
 enum _MSG_ALERT_TONE_E
 {
-       MSG_ALERT_TONE_ONCE,
-       MSG_ALERT_TONE_2MINS,
-       MSG_ALERT_TONE_5MINS,
-       MSG_ALERT_TONE_10MINS,
+       MSG_ALERT_TONE_ONCE,        /**< Play alert tone once*/
+       MSG_ALERT_TONE_2MINS,       /**< Repeat alarm in 2 mins*/
+       MSG_ALERT_TONE_5MINS,       /**< Repeat alarm in 5 mins*/
+       MSG_ALERT_TONE_10MINS,      /**< Repeat alarm in 10 mins*/
 };
 
 
 /**
- *     @brief  Represents the value of a default storage to save SMS. \n
- *     The values for this type SHOULD be in MSG_SMS_SAVE_STORAGE_T.
+ *  @brief  Enumeration for the value of a default storage to save SMS. \n
+ *             The values for this type SHOULD be in MSG_SMS_SAVE_STORAGE_T.
  */
 enum _MSG_SMS_SAVE_STORAGE_E
 {
-       MSG_SMS_SAVE_STORAGE_SIM,
-       MSG_SMS_SAVE_STORAGE_PHONE,
+       MSG_SMS_SAVE_STORAGE_SIM,           /**< Save SMS to SIM*/
+       MSG_SMS_SAVE_STORAGE_PHONE,         /**< Save SMS to phone*/
 };
 
 
 /**
- *     @brief  Represents the values of the type of number for SMS center address. \n
- *     This enum is used as the value of MSG_SMS_TON_T.
+ *  @brief  Enumeration for the values of the type of number for SMS center address. \n
+ *             This enum is used as the value of MSG_SMS_TON_T.
  */
 enum _MSG_SMS_TON_E
 {
-       MSG_TON_UNKNOWN = 0,                    /**< Unknown */
-       MSG_TON_INTERNATIONAL,          /**< International */
-       MSG_TON_NATIONAL,                               /**< National */
-       MSG_TON_NETWORK,                                /**< Network */
-       MSG_TON_SUBSCRIBER,                     /**< Subscriber */
-       MSG_TON_ALPHANUMERIC,           /**< Alpha numeric */
-       MSG_TON_ABBREVIATED,                    /**< Abbreviated */
-       MSG_TON_RESERVE,                                /**< Reserve */
+       MSG_TON_UNKNOWN = 0,            /**< Unknown */
+       MSG_TON_INTERNATIONAL,          /**< International */
+       MSG_TON_NATIONAL,               /**< National */
+       MSG_TON_NETWORK,                /**< Network */
+       MSG_TON_SUBSCRIBER,             /**< Subscriber */
+       MSG_TON_ALPHANUMERIC,           /**< Alpha numeric */
+       MSG_TON_ABBREVIATED,            /**< Abbreviated */
+       MSG_TON_RESERVE,                /**< Reserve */
 };
 
 
 /**
- *     @brief  Represents the values of the numbering plan ID for SMS center address. \n
- *     This enum is used as the value of MSG_SMS_NPI_T.
+ *  @brief  Enumeration for the values of the numbering plan ID for SMS center address. \n
+ *             This enum is used as the value of MSG_SMS_NPI_T.
  */
 enum _MSG_SMS_NPI_E
 {
-       MSG_NPI_UNKNOWN = 0,                    /**< Unknown */
-       MSG_NPI_ISDN = 1,                               /**< ISDN */
-       MSG_NPI_DATA = 3,                               /**< Data */
-       MSG_NPI_TELEX = 4,                              /**< Telex */
-       MSG_NPI_SMSC = 5,                               /**< SMSC */
-       MSG_NPI_NATIONAL = 8,                   /**< National */
-       MSG_NPI_PRIVATE = 9,                    /**< Private */
-       MSG_NPI_IDENTIFICATION_ERMES = 10,              /**< Identification ermes */
-       MSG_NPI_IDENTIFICATION_RESERVED = 0xF           /**< Identification reserved */
+       MSG_NPI_UNKNOWN = 0,                        /**< Unknown */
+       MSG_NPI_ISDN = 1,                           /**< ISDN */
+       MSG_NPI_DATA = 3,                           /**< Data */
+       MSG_NPI_TELEX = 4,                          /**< Telex */
+       MSG_NPI_SMSC = 5,                           /**< SMSC */
+       MSG_NPI_NATIONAL = 8,                       /**< National */
+       MSG_NPI_PRIVATE = 9,                        /**< Private */
+       MSG_NPI_IDENTIFICATION_ERMES = 10,          /**< Identification ermes */
+       MSG_NPI_IDENTIFICATION_RESERVED = 0xF       /**< Identification reserved */
 };
 
 
 /**
- *     @brief  Represents the values of the protocol ID for SMS center address. \n
- *     This enum is used as the value of MSG_SMS_PID_T.
+ *  @brief  Enumeration for the values of the protocol ID for SMS center address. \n
+ *             This enum is used as the value of MSG_SMS_PID_T.
  */
 enum  _MSG_SMS_PID_E
 {
-       MSG_PID_NONE,           /**< None */
-       MSG_PID_TEXT,           /**< Text */
-       MSG_PID_VOICE,          /**< Voice */
-       MSG_PID_FAX,            /**< Fax */
-       MSG_PID_X400,           /**< X400 */
-       MSG_PID_ERMES,          /**< Ermes */
-       MSG_PID_EMAIL,          /**< Email */
-       MSG_PID_MAX             /**< Default */
+       MSG_PID_NONE,       /**< None */
+       MSG_PID_TEXT,       /**< Text */
+       MSG_PID_VOICE,      /**< Voice */
+       MSG_PID_FAX,        /**< Fax */
+       MSG_PID_X400,       /**< X400 */
+       MSG_PID_ERMES,      /**< Ermes */
+       MSG_PID_EMAIL,      /**< Email */
+       MSG_PID_MAX         /**< Default */
 };
 
 
 /**
- *     @brief  Represents the values of the Validity Period for SMS center. \n
- *     This enum is used as the value of MSG_VAL_PERIOD_T.
+ *  @brief  Enumeration for the values of the Validity Period for SMS center. \n
+ *             This enum is used as the value of MSG_VAL_PERIOD_T.
+ *
+ *     0 to 143 : (TP-VP + 1) x 5 minutes (i.e. 5 minutes intervals up to 12 hours)
+ *     144 to 167 : 12 hours + ((TP-VP -143) x 30 minutes)
+ *     168 to 196 : (TP-VP - 166) x 1 day
+ *     197 to 255 : (TP-VP - 192) x 1 week
+ *
  */
 enum  _MSG_VAL_PERIOD_E
 {
-       MSG_VAL_1DAY = 167,
-       MSG_VAL_2DAYS = 168,
-       MSG_VAL_1WEEK = 173,
-       MSG_VAL_2WEEKS = 180,
-       MSG_VAL_MAXIMUM = 255,
+       MSG_VAL_ZERO = 0,               /**< Validity period is zero */
+       MSG_VAL_1DAY = 167,             /**< Validity period is 1 day */
+       MSG_VAL_2DAYS = 168,            /**< Validity period is 2 days */
+       MSG_VAL_3DAYS = 169,            /**< Validity period is 3 days */
+       MSG_VAL_4DAYS = 170,            /**< Validity period is 4 days */
+       MSG_VAL_5DAYS = 171,            /**< Validity period is 5 days */
+       MSG_VAL_6DAYS = 172,            /**< Validity period is 6 days */
+       MSG_VAL_1WEEK = 173,            /**< Validity period is 1 week */
+       MSG_VAL_2WEEKS = 180,           /**< Validity period is 2 weeks */
+       MSG_VAL_3WEEKS = 187,           /**< Validity period is 3 weeks */
+       MSG_VAL_MAXIMUM = 255,          /**< Validity period is maximum */
 };
 
 
+/**
+ *  @brief  Enumeration for the values of the MMS expiry time. \n
+ *             This enum is used as the value of MSG_MMS_EXPIRY_TIME_T.
+ */
 enum  _MSG_MMS_EXPIRY_TIME_E
 {
-       MSG_EXPIRY_TIME_MAXIMUM = 0,
-       MSG_EXPIRY_TIME_1DAY = 86400,
-       MSG_EXPIRY_TIME_2DAYS = 2*86400,
-       MSG_EXPIRY_TIME_1WEEK = 604800,
-       MSG_EXPIRY_TIME_2WEEKS = 2*604800,
+       MSG_EXPIRY_TIME_MAXIMUM = 0,            /**< Expiry time is zero */
+       MSG_EXPIRY_TIME_1DAY = 86400,           /**< Expiry time is 1 day */
+       MSG_EXPIRY_TIME_2DAYS = 2*86400,        /**< Expiry time is 2 days */
+       MSG_EXPIRY_TIME_1WEEK = 604800,         /**< Expiry time is 1 week */
+       MSG_EXPIRY_TIME_2WEEKS = 2*604800,      /**< Expiry time is 2 weeks */
 };
 
 
+/**
+ *  @brief  Enumeration for the values of the MMS delivery time. \n
+ *             This enum is used as the value of MSG_MMS_DELIVERY_TIME_T.
+ */
 enum  _MSG_MMS_DELIVERY_TIME_E
 {
-       MSG_DELIVERY_TIME_IMMEDIATLY = 0,
-       MSG_DELIVERY_TIME_1HOUR = 3600,
-       MSG_DELIVERY_TIME_1DAY = 86400,
-       MSG_DELIVERY_TIME_1WEEK = 604800,
-       MSG_DELIVERY_TIME_CUSTOM
+       MSG_DELIVERY_TIME_IMMEDIATLY = 0,           /**< Immediate MMS delivery */
+       MSG_DELIVERY_TIME_1HOUR = 3600,             /**< MMS delivery in 1 hour */
+       MSG_DELIVERY_TIME_1DAY = 86400,             /**< MMS delivery in 1 day */
+       MSG_DELIVERY_TIME_1WEEK = 604800,           /**< MMS delivery in 1 week */
+       MSG_DELIVERY_TIME_CUSTOM                    /**< MMS delivery in custom time */
 };
 
 
+/**
+ *  @brief  Enumeration for the values of the MMS class type. \n
+ *             This enum is used as the value of MSG_MMS_MSG_CLASS_TYPE_T.
+ */
 enum _MSG_MMS_MSG_CLASS_TYPE_E
 {
-       MSG_CLASS_PERSONAL,                     /**<Personal message class*/
-       MSG_CLASS_ADVERTISEMENT,                /**<Advertisement message class*/
-       MSG_CLASS_INFORMATIONAL,                /**<Informational message class */
-       MSG_CLASS_AUTO,                         /**<Automatic */
-       MSG_CLASS_MAX                                   /**< */
+       MSG_CLASS_PERSONAL,             /**<Personal message class*/
+       MSG_CLASS_ADVERTISEMENT,        /**<Advertisement message class*/
+       MSG_CLASS_INFORMATIONAL,        /**<Informational message class */
+       MSG_CLASS_AUTO,                 /**<Automatic */
+       MSG_CLASS_MAX                   /**< Place-holder to indicate max number of MMS class types*/
 };
 
 
+/**
+ *  @brief  Enumeration for the values of the MMS reply charging type. \n
+ *             This enum is used as the value of MSG_MMS_REPLY_CHARGING_TYPE_T.
+ */
 enum _MSG_MMS_REPLY_CHARGING_TYPE_E
 {
-       MSG_REPLY_CHARGING_NONE,                                        /**<Reply-Charging none */
-       MSG_REPLY_CHARGING_REQUESTED,                           /**<Reply-Charging requested */
-       MSG_REPLY_CHARGING_REQUESTED_TEXT_ONLY, /**<Reply-Charging requested text-only */
-       MSG_REPLY_CHARGING_ACCEPTED,                            /**<Reply-Charging accepted */
-       MSG_REPLY_CHARGING_ACCEPTED_TEXT_ONLY,  /**<Reply-Charging accepted text-only */
-       MSG_REPLY_CHARGING_MAX
+       MSG_REPLY_CHARGING_NONE,                    /**<Reply-Charging none */
+       MSG_REPLY_CHARGING_REQUESTED,               /**<Reply-Charging requested */
+       MSG_REPLY_CHARGING_REQUESTED_TEXT_ONLY,     /**<Reply-Charging requested text-only */
+       MSG_REPLY_CHARGING_ACCEPTED,                /**<Reply-Charging accepted */
+       MSG_REPLY_CHARGING_ACCEPTED_TEXT_ONLY,      /**<Reply-Charging accepted text-only */
+       MSG_REPLY_CHARGING_MAX                      /**< Place-holder to indicate max number of MMS reply charging types*/
 };
 
 
+/**
+ *  @brief  Enumeration for the values of the MMS creation mode. \n
+ *             This enum is used as the value of MSG_MMS_CREATION_MODE_T.
+ */
 enum _MSG_MMS_CREATION_MODE_E
 {
-       MSG_CREATION_MODE_RESTRICTED,
-       MSG_CREATION_MODE_WARNING,
-       MSG_CREATION_MODE_FREE
+       MSG_CREATION_MODE_RESTRICTED,           /**< MMS created in restricted mode */
+       MSG_CREATION_MODE_WARNING,              /**< MMS created in warning mode */
+       MSG_CREATION_MODE_FREE                  /**< MMS created in free mode */
 };
 
 
 /**
- *     @brief  Represents the values of the retrieve type for MMS home network. \n
- *     This enum is used as the value of MSG_MMS_HOME_RETRIEVE_TYPE_T.
+ *  @brief  Enumeration for the values of the retrieve type for MMS home network. \n
+ *             This enum is used as the value of MSG_MMS_HOME_RETRIEVE_TYPE_T.
  */
 enum _MSG_MMS_HOME_RETRIEVE_TYPE_E
 {
-       MSG_HOME_AUTO_DOWNLOAD,         /**< Home auto download */
-       MSG_HOME_MANUAL,                                        /**< Home manual */
-       MSG_HOME_RESTRICTED,                            /**< Home restricted */
-       MSG_HOME_REJECT,                                        /**< Home reject */
-       MSG_HOME_MAX                                            /**< Default */
+       MSG_HOME_AUTO_DOWNLOAD,             /**< Home auto download */
+       MSG_HOME_MANUAL,                    /**< Home manual */
+       MSG_HOME_RESTRICTED,                /**< Home restricted */
+       MSG_HOME_REJECT,                    /**< Home reject */
+       MSG_HOME_MAX                        /**< Default */
 };
 
 
 /**
- *     @brief  Represents the values of the retrieve type for MMS abroad network. \n
- *     This enum is used as the value of MSG_MMS_ABROAD_RETRIEVE_TYPE_T.
+ *  @brief  Enumeration for the values of the retrieve type for MMS abroad network. \n
+ *             This enum is used as the value of MSG_MMS_ABROAD_RETRIEVE_TYPE_T.
  */
 enum _MSG_MMS_ABROAD_RETRIEVE_TYPE_E
 {
-       MSG_ABROAD_AUTO_DOWNLOAD,       /**< Abroad auto download */
-       MSG_ABROAD_MANUAL,                      /**< Abroad manual */
-       MSG_ABROAD_RESTRICTED,          /**< Abroad restricted */
-       MSG_ABROAD_REJECT,                      /**< Abroad reject */
-       MSG_ABROAD_MAX                          /**< Default */
+       MSG_ABROAD_AUTO_DOWNLOAD,   /**< Abroad auto download */
+       MSG_ABROAD_MANUAL,          /**< Abroad manual */
+       MSG_ABROAD_RESTRICTED,      /**< Abroad restricted */
+       MSG_ABROAD_REJECT,          /**< Abroad reject */
+       MSG_ABROAD_MAX              /**< Default */
 };
 
 
 /**
- *     @brief  Represents the values of the frequency of sending MMS read report. \n
- *     This enum is used as the value of MSG_MMS_SEND_READ_REPORT_T.
+ *  @brief  Enumeration for the values of the frequency of sending MMS read report. \n
+ *             This enum is used as the value of MSG_MMS_SEND_READ_REPORT_T.
  */
 enum _MSG_MMS_SEND_READ_REPORT_E
 {
-       MSG_SEND_READ_REPORT_ALWAYS,    /**< Read report always */
-       MSG_SEND_READ_REPORT_NEVER,             /**< Read report never */
-       MSG_SEND_READ_REPORT_REQUEST,   /**< Read report request */
-       MSG_SEND_READ_REPORT_MAX                /**< Default */
+       MSG_SEND_READ_REPORT_ALWAYS,    /**< Read report always */
+       MSG_SEND_READ_REPORT_NEVER,     /**< Read report never */
+       MSG_SEND_READ_REPORT_REQUEST,   /**< Read report request */
+       MSG_SEND_READ_REPORT_MAX        /**< Default */
 };
 
 
 /**
- *     @brief  Represents the values of the service type for a push message. \n
- *     This enum is used as the value of MSG_PUSH_SERVICE_TYPE_T.
+ *  @brief  Enumeration for the values of the service type for a push message. \n
+ *             This enum is used as the value of MSG_PUSH_SERVICE_TYPE_T.
  */
 enum _MSG_PUSH_SERVICE_TYPE_E
 {
-       MSG_PUSH_SERVICE_ALWAYS,        /**< Push message service always */
-       MSG_PUSH_SERVICE_PROMPT,                /**< Push message service prompt */
-       MSG_PUSH_SERVICE_NEVER,         /**< Push message service never */
+       MSG_PUSH_SERVICE_ALWAYS,    /**< Push message service always */
+       MSG_PUSH_SERVICE_PROMPT,    /**< Push message service prompt */
+       MSG_PUSH_SERVICE_NEVER,     /**< Push message service never */
 };
 
 
 /**
- *     @brief  Represents the values of the language type for a cell broadcasting message. \n
- *     This enum is used as the value of MSG_CB_LANGUAGE_TYPE_T.
+ *  @brief  Enumeration for the values of the language type for a cell broadcasting message. \n
+ *             This enum is used as the value of MSG_CB_LANGUAGE_TYPE_T.
  */
 enum _MSG_CB_LANGUAGE_TYPE_E
 {
-       MSG_CBLANG_TYPE_ALL,                    /**< CB check all */
-       MSG_CBLANG_TYPE_ENG,                    /**< CB message English  */
-       MSG_CBLANG_TYPE_GER,                    /**< CB message Germany */
-       MSG_CBLANG_TYPE_FRE,                    /**< CB message France */
-       MSG_CBLANG_TYPE_ITA,                    /**< CB message Italy */
-       MSG_CBLANG_TYPE_NED,                    /**< CB message Netherland */
-       MSG_CBLANG_TYPE_SPA,                    /**< CB message Spain */
-       MSG_CBLANG_TYPE_POR,                    /**< CB message Portugal */
-       MSG_CBLANG_TYPE_SWE,                    /**< CB message Sweden */
-       MSG_CBLANG_TYPE_TUR,                    /**< CB message Turkey */
-       MSG_CBLANG_TYPE_MAX                     /**< Default */
+       MSG_CBLANG_TYPE_ALL,            /**< CB check all */
+       MSG_CBLANG_TYPE_ENG,            /**< CB message English  */
+       MSG_CBLANG_TYPE_GER,            /**< CB message Germany */
+       MSG_CBLANG_TYPE_FRE,            /**< CB message France */
+       MSG_CBLANG_TYPE_ITA,            /**< CB message Italy */
+       MSG_CBLANG_TYPE_NED,            /**< CB message Netherland */
+       MSG_CBLANG_TYPE_SPA,            /**< CB message Spain */
+       MSG_CBLANG_TYPE_POR,            /**< CB message Portugal */
+       MSG_CBLANG_TYPE_SWE,            /**< CB message Sweden */
+       MSG_CBLANG_TYPE_TUR,            /**< CB message Turkey */
+       MSG_CBLANG_TYPE_MAX             /**< Default */
 };
 
-
 /**
- *     @brief  Represents the values of SIM status. \n
- *     This enum is used as the value of MSG_SIM_STATUS_T.
+ *  @brief  Enumeration for the values of SIM status. \n
+ *             This enum is used as the value of MSG_SIM_STATUS_T.
  */
 enum _MSG_SIM_STATUS_E
 {
-       MSG_SIM_STATUS_NORMAL = 0,
-       MSG_SIM_STATUS_CHANGED,
-       MSG_SIM_STATUS_NOT_FOUND,
+       MSG_SIM_STATUS_NORMAL = 0,          /**< SIM normal */
+       MSG_SIM_STATUS_CHANGED,             /**< SIM changed */
+       MSG_SIM_STATUS_NOT_FOUND,           /**< SIM not found */
+};
+
+/**
+ *  @brief  Enumeration for the values of a message ringtone type. \n
+ *             This enum is used as the value of MSG_RINGTONE_TYPE_T.
+ */
+enum _MSG_RINGTONE_TYPE_E
+{
+       MSG_RINGTONE_TYPE_DEFAULT = 0,  /**< Default ringtone type */
+       MSG_RINGTONE_TYPE_USER,         /**< User defined ringtone type */
+       MSG_RINGTONE_TYPE_SILENT        /**< Silent type */
+};
+
+/**
+ *  @brief  Enumeration for the values of a SIM index(SIM slot number). \n
+ *             This enum is used as the value of msg_sim_slot_id_t.
+ */
+enum _MSG_SIM_SLOT_ID_E
+{
+       MSG_SIM_SLOT_ID_1 = 1,  /**SIM Slot #1 */
+       MSG_SIM_SLOT_ID_2,      /**SIM Slot #2 */
 };
 
 
+/**
+ *  @brief  Enumeration for the values of media informations. \n
+ *          This enum is used as member of #msg_struct_t for MSG_STRUCT_MEDIA_INFO.
+ */
+enum MSG_MEDIA_INFO_E {
+       MSG_MEDIA_ITEM_STR = MSG_STRUCT_MEDIA_INFO+1,    /**< Indicates the local path, sticker Id of a media file */
+       MSG_MEDIA_MIME_TYPE_STR,                         /**< Indicates the mimetype of a media file */
+       MSG_MEDIA_THUMB_PATH_STR,                        /**< Indicates the thumbnail path of a media file */
+       MSG_MEDIA_MESSAGE_ID_INT,                        /**< Indicates the message id */
+};
+
+/**
+ * @}
+ */
+
 #endif /* MSG_TYPES_H_ */
diff --git a/include/msg_helper/MsgHelper.h b/include/msg_helper/MsgHelper.h
deleted file mode 100755 (executable)
index 0bfef12..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#ifndef MSG_HELPER_H
-#define MSG_HELPER_H
-
-
-#include "MsgTypes.h"
-
-/*==================================================================================================
-                                       DEFINES
-==================================================================================================*/
-
-#define MSG_SOUND_START        "SOUND_START"
-#define MSG_SOUND_STOP         "SOUND_STOP"
-
-#define MAX_SOUND_FILE_LEN 1024
-
-#define DEFAULT_FILE           "/usr/share/media/Sherbet.wav"
-#define ALERT_ON_CALL_TONE     "/opt/etc/msg-service/alert_on_call.mp3"
-
-#define HAPTIC_TEST_ITERATION 1
-#define MSG_VIBRATION_INTERVAL 3000
-
-typedef void (*msg_sensor_cb)();
-
-/*==================================================================================================
-                                       FUNCTION PROTOTYPES
-==================================================================================================*/
-
-// SoundPlayer
-msg_error_t MsgSoundPlayUninit();
-void MsgSoundPlayStart();
-void MsgSoundPlayStop();
-int MsgSoundPlayMelody(char *pMsgToneFilePath, bool bIncreasing);
-void MsgSoundPlayVibration();
-
-//Sensor FW wrapper.
-msg_error_t MsgSensorConnect();
-void MsgSensorDisconnect();
-msg_error_t MsgRegSensorCB(msg_sensor_cb cb);
-
-#endif // MSG_HELPER_H
\ No newline at end of file
index ff1d0fb..3f90d85 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_HANDLE_H
@@ -43,20 +43,21 @@ class MsgHandle
                virtual ~MsgHandle();
 
                // Control
-               void openHandle();
-               void closeHandle(MsgHandle* pHandle);
+               void openHandle();
+               void closeHandle(MsgHandle* pHandle);
 
                // Transport
                msg_error_t submitReq(MSG_REQUEST_S* pReq);
-               msg_error_t cancelReq(msg_request_id_t reqId);
 
                msg_error_t regSentStatusCallback(msg_sent_status_cb onStatusChanged,  void *pUserParam);
                msg_error_t regSmsMessageCallback(msg_sms_incoming_cb onMsgIncoming, unsigned short port, void *pUserParam);
                msg_error_t regMmsConfMessageCallback(msg_mms_conf_msg_incoming_cb onMMSConfMsgIncoming, const char *pAppId, void *pUserParam);
                msg_error_t regSyncMLMessageCallback(msg_syncml_msg_incoming_cb onSyncMLMsgIncoming, void *pUserParam);
                msg_error_t regLBSMessageCallback(msg_lbs_msg_incoming_cb onLBSMsgIncoming, void *pUserParam);
-
+               msg_error_t regPushMessageCallback(msg_push_msg_incoming_cb onPushMsgIncoming, const char *pAppId, void *pUserParam);
+               msg_error_t regCBMessageCallback(msg_cb_incoming_cb onCBIncoming, bool bSave, void *pUserParam);
                msg_error_t regSyncMLMessageOperationCallback(msg_syncml_msg_operation_cb onSyncMLMsgOperation, void *pUserParam);
+               msg_error_t regReportMessageCallback(msg_report_msg_incoming_cb onReportMsgCB, void *pUserParam);
 
                msg_error_t operateSyncMLMessage(msg_message_id_t msgId);
 
@@ -65,15 +66,18 @@ class MsgHandle
                msg_error_t addSyncMLMessage(const MSG_SYNCML_MESSAGE_S *pSyncMLMsg);
                msg_error_t updateMessage(const MSG_MESSAGE_HIDDEN_S *pMsg, const MSG_SENDINGOPT_S *pSendOpt);
                msg_error_t updateReadStatus(msg_message_id_t MsgId, bool bRead);
+               msg_error_t setConversationToRead(msg_thread_id_t ThreadId);
                msg_error_t updateProtectedStatus(msg_message_id_t MsgId, bool bProtected);
                msg_error_t deleteMessage(msg_message_id_t MsgId);
                msg_error_t deleteAllMessagesInFolder(msg_folder_id_t FolderId, bool bOnlyDB);
+               msg_error_t deleteMessagesByList(msg_id_list_s *pMsgIdList);
                msg_error_t moveMessageToFolder(msg_message_id_t MsgId, msg_folder_id_t DestFolderId);
                msg_error_t moveMessageToStorage(msg_message_id_t MsgId, msg_storage_id_t DestStorageId);
                msg_error_t countMessage(msg_folder_id_t FolderId, MSG_COUNT_INFO_S *pCountInfo);
                msg_error_t countMsgByType(const MSG_MESSAGE_TYPE_S *pMsgType, int *pMsgCount);
                msg_error_t countMsgByContact(const MSG_THREAD_LIST_INDEX_INFO_S *pAddrInfo, MSG_THREAD_COUNT_INFO_S *pMsgThreadCountList);
                msg_error_t getMessage(msg_message_id_t MsgId, MSG_MESSAGE_HIDDEN_S *pMsg, MSG_SENDINGOPT_S *pSendOpt);
+               msg_error_t getConversationViewItem(msg_message_id_t MsgId, MSG_CONVERSATION_VIEW_S *pConv);
                msg_error_t getFolderViewList(msg_folder_id_t FolderId, const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pMsgFolderViewList);
                msg_error_t addFolder(const MSG_FOLDER_INFO_S *pFolderInfo);
                msg_error_t updateFolder(const MSG_FOLDER_INFO_S *pFolderInfo);
@@ -82,7 +86,7 @@ class MsgHandle
 
                msg_error_t getThreadViewList(const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pThreadViewList);
                msg_error_t getConversationViewList(msg_thread_id_t ThreadId, msg_struct_list_s *pConvViewList);
-               msg_error_t deleteThreadMessageList(msg_thread_id_t thread_id);
+               msg_error_t deleteThreadMessageList(msg_thread_id_t thread_id, bool include_protected_msg);
                msg_error_t getQuickPanelData(msg_quickpanel_type_t Type, MSG_MESSAGE_HIDDEN_S *pMsg);
                msg_error_t resetDatabase();
                msg_error_t getMemSize(unsigned int* memsize);
@@ -96,6 +100,7 @@ class MsgHandle
                msg_error_t getFilterList(msg_struct_list_s *pFilterList);
                msg_error_t setFilterOperation(bool bSetFlag);
                msg_error_t getFilterOperation(bool *pSetFlag);
+               msg_error_t setFilterActivation(msg_filter_id_t filter_id, bool active);
 
                //setting
                msg_error_t getSMSCOption(msg_struct_t msg_struct);
@@ -107,7 +112,7 @@ class MsgHandle
                msg_error_t getMmsSendOpt(msg_struct_t msg_struct);
                msg_error_t setMmsSendOpt(msg_struct_t msg_struct);
                msg_error_t getMmsRecvOpt(msg_struct_t msg_struct);
-               msg_error_t setMmsRecvOpt(msg_struct_t msg_struct);;
+               msg_error_t setMmsRecvOpt(msg_struct_t msg_struct);
                msg_error_t getPushMsgOpt(msg_struct_t msg_struct);
                msg_error_t setPushMsgOpt(msg_struct_t msg_struct);
                msg_error_t getVoiceMsgOpt(msg_struct_t msg_struct);
@@ -118,18 +123,25 @@ class MsgHandle
                msg_error_t setMsgSizeOpt(msg_struct_t msg_struct);
 
                //Backup & Restore
-               msg_error_t backupMessage();
-               msg_error_t restoreMessage();
-
+               msg_error_t backupMessage(msg_message_backup_type_t type, const char *backup_filepath);
+               msg_error_t restoreMessage(const char *backup_filepath);
+               msg_error_t getVobject(msg_message_id_t MsgId, void** encodedData);
                // ETC
                msg_error_t searchMessage(const char *pSearchString, msg_struct_list_s *pThreadViewList);
-               msg_error_t searchMessage(const MSG_SEARCH_CONDITION_S *pSearchCon, int offset, int limit, msg_struct_list_s *pMsgList);
+
                msg_error_t getRejectMsgList(const char *pNumber, msg_struct_list_s *pRejectMsgList);
                msg_error_t regStorageChangeCallback(msg_storage_change_cb onStorageChange, void *pUserParam);
-               msg_error_t getReportStatus(msg_message_id_t msg_id, MSG_REPORT_STATUS_INFO_S *pReport_status);
+               msg_error_t getReportStatus(msg_message_id_t msg_id, msg_struct_list_s *report_list);
                msg_error_t getThreadIdByAddress(msg_struct_list_s *pAddrList, msg_thread_id_t *pThreadId);
+               msg_error_t getThreadIdByAddress(msg_list_handle_t msg_address_list, msg_thread_id_t *pThreadId);
                msg_error_t getThread(msg_thread_id_t threadId, MSG_THREAD_VIEW_S* pThreadInfo);
-               msg_error_t getMessageList(msg_folder_id_t folderId, msg_thread_id_t threadId, msg_message_type_t msgType, msg_storage_id_t storageId, msg_struct_list_s *pMsgList);
+               msg_error_t getMessageList(const MSG_LIST_CONDITION_S *pListCond, msg_struct_list_s *pMsgList);
+               msg_error_t getMediaList(const msg_thread_id_t thread_id, msg_list_handle_t *pMediaList);
+
+               // Push Event
+               msg_error_t addPushEvent(MSG_PUSH_EVENT_INFO_S *push_event);
+               msg_error_t deletePushEvent(MSG_PUSH_EVENT_INFO_S *push_event);
+               msg_error_t updatePushEvent(MSG_PUSH_EVENT_INFO_S *pSrc, MSG_PUSH_EVENT_INFO_S *pDst);
 
                void convertMsgStruct(const MSG_MESSAGE_INFO_S *pSource, MSG_MESSAGE_HIDDEN_S *pDest);
                void convertSendOptStruct(const MSG_SENDINGOPT_INFO_S* pSrc, MSG_SENDINGOPT_S* pDest, MSG_MESSAGE_TYPE_S msgType);
@@ -137,19 +149,20 @@ class MsgHandle
        private:
                void connectSocket();
                void    disconnectSocket();
-               void write(const char *pCmd, int CmdSize, char **ppEvent);
+               void write(const char *pCmd, int CmdSize, char **ppEvent);
                void read(char **ppEvent);
-               void generateConnectionId(char *ConnectionId);
+               void generateConnectionId(char *ConnectionId);
                void convertMsgStruct(const MSG_MESSAGE_HIDDEN_S *pSource, MSG_MESSAGE_INFO_S *pDest);
                void convertSendOptStruct(const MSG_SENDINGOPT_S* pSrc, MSG_SENDINGOPT_INFO_S* pDest, MSG_MESSAGE_TYPE_S msgType);
                int getSettingCmdSize(MSG_OPTION_TYPE_T optionType);
+               bool CheckEventData(char *pEventData);
 
-               char            mConnectionId[20];
-               short   mCounter;
+               char mConnectionId[20];
+               short mCounter;
 
-               char                            mCookie[MAX_COOKIE_LEN];
+               char mCookie[MAX_COOKIE_LEN];
 
-               MsgIpcClientSocket      mClientSock;
+               MsgIpcClientSocket mClientSock;
 };
 
 #endif // MSG_HANDLE_H
index 53002cf..7b4fc39 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef __MSG_PROXY_LISTENER_H__
@@ -26,7 +26,7 @@
 #include "MsgMutex.h"
 #include "MsgHandle.h"
 
-#include <map>
+#include <set>
 #include <list>
 #include <glib.h>
 
@@ -60,6 +60,22 @@ typedef struct
 typedef struct
 {
        MsgHandle* hAddr;
+       msg_push_msg_incoming_cb pfPushIncomingCB;
+       char appId[MAX_WAPPUSH_ID_LEN+1];
+       void* userParam;
+} MSG_PUSH_INCOMING_CB_ITEM_S;
+
+typedef struct
+{
+       MsgHandle* hAddr;
+       msg_cb_incoming_cb pfCBIncomingCB;
+       bool bsave;
+       void* userParam;
+} MSG_CB_INCOMING_CB_ITEM_S;
+
+typedef struct
+{
+       MsgHandle* hAddr;
        msg_syncml_msg_incoming_cb pfSyncMLIncomingCB;
        void* userParam;
 } MSG_SYNCML_INCOMING_CB_ITEM_S;
@@ -86,14 +102,25 @@ typedef struct
 } MSG_STORAGE_CHANGE_CB_ITEM_S;
 
 
+typedef struct
+{
+       MsgHandle* hAddr;
+       msg_report_msg_incoming_cb pfReportMsgIncomingCB;
+       void* userParam;
+} MSG_REPORT_INCOMING_CB_ITEM_S;
+
+
 typedef std::list<MSG_SENT_STATUS_CB_ITEM_S> MsgSentStatusCBList;
 typedef std::list<MSG_INCOMING_CB_ITEM_S> MsgNewMessageCBList;
 typedef std::list<MSG_MMS_CONF_INCOMING_CB_ITEM_S> MsgNewMMSConfMessageCBList;
+typedef std::list<MSG_PUSH_INCOMING_CB_ITEM_S> MsgNewPushMessageCBList;
+typedef std::list<MSG_CB_INCOMING_CB_ITEM_S> MsgNewCBMessageCBList;
 typedef std::list<MSG_SYNCML_INCOMING_CB_ITEM_S> MsgNewSyncMLMessageCBList;
 typedef std::list<MSG_LBS_INCOMING_CB_ITEM_S> MsgNewLBSMessageCBList;
 typedef std::list<MSG_SYNCML_OPERATION_CB_ITEM_S> MsgOperationSyncMLMessageCBList;
 typedef std::list<MSG_STORAGE_CHANGE_CB_ITEM_S> MsgStorageChangeCBList;
-
+typedef std::list<MSG_REPORT_INCOMING_CB_ITEM_S> MsgReportMessageCBList;
+typedef std::set<MsgHandle*> handle_set;
 
 /*==================================================================================================
                                      CLASS DEFINITIONS
@@ -103,23 +130,30 @@ class MsgProxyListener
 public:
        static MsgProxyListener* instance();
 
-       void start();
+       void start(MsgHandle* pMsgHandle);
        void stop();
 
        bool regSentStatusEventCB(MsgHandle* pMsgHandle, msg_sent_status_cb pfSentStatus, void *pUserParam);
        bool regMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_sms_incoming_cb pfNewMessage, int port, void *pUserParam);
        bool regMMSConfMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_mms_conf_msg_incoming_cb pfNewMMSConfMessage, const char *pAppId, void *pUserParam);
+       bool regPushMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_push_msg_incoming_cb pfNewPushMessage, const char *pAppId, void *pUserParam);
+       bool regCBMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_cb_incoming_cb pfNewCBMessage, bool bSave, void *pUserParam);
        bool regSyncMLMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_syncml_msg_incoming_cb pfNewSyncMLMessage, void *pUserParam);
        bool regLBSMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_lbs_msg_incoming_cb pfNewLBSMsgIncoming, void *pUserParam);
        bool regSyncMLMessageOperationEventCB(MsgHandle* pMsgHandle, msg_syncml_msg_operation_cb pfSyncMLMessageOperation, void *pUserParam);
        bool regStorageChangeEventCB(MsgHandle* pMsgHandle, msg_storage_change_cb pfStorageChangeOperation, void *pUserParam);
+       bool regReportMsgIncomingCB(MsgHandle* pMsgHandle, msg_report_msg_incoming_cb pfReportMessage, void *pUserParam);
 
        void clearListOfClosedHandle(MsgHandle* pMsgHandle);
 
        void handleEvent(const MSG_EVENT_S* ptr);
 
        int getRemoteFd();
-       int readFromSocket(char** buf, int* len);
+       int readFromSocket(char** buf, unsigned int* len);
+       void resetProxyListener();
+#ifdef CHECK_SENT_STATUS_CALLBACK
+       int getSentStatusCbCnt();
+#endif
 
 private:
        MsgProxyListener();
@@ -129,6 +163,8 @@ private:
 
        unsigned int running;
 
+       handle_set      openHandleSet;
+
        MsgIpcClientSocket cliSock;
 
        Mutex mx;
@@ -137,10 +173,13 @@ private:
        MsgSentStatusCBList sentStatusCBList;
        MsgNewMessageCBList newMessageCBList;
        MsgNewMMSConfMessageCBList newMMSConfMessageCBList;
+       MsgNewPushMessageCBList newPushMessageCBList;
+       MsgNewCBMessageCBList newCBMessageCBList;
        MsgNewSyncMLMessageCBList newSyncMLMessageCBList;
        MsgNewLBSMessageCBList newLBSMessageCBList;
        MsgOperationSyncMLMessageCBList operationSyncMLMessageCBList;
        MsgStorageChangeCBList storageChangeCBList;
+       MsgReportMessageCBList reportMessageCBList;
 
        GIOChannel *channel;
        guint eventSourceId;
index 49c7a0b..e12e1fb 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_CONTACT_H
@@ -35,7 +35,9 @@ msg_error_t MsgCloseContactSvc();
 msg_error_t MsgInitContactSvc(MsgContactChangeCB cb);
 
 msg_error_t MsgGetContactInfo(const MSG_ADDRESS_INFO_S *pAddrInfo, MSG_CONTACT_INFO_S *pContactInfo);
+msg_error_t MsgGetContactSearchList(const char *pSearchVal, MSG_ADDRESS_INFO_S **pAddrInfo, int *count);
 
+void MsgSyncAddressbook();
 void MsgSyncContact();
 
 bool MsgInsertContact(MSG_CONTACT_INFO_S *pContactInfo, const char *pNumber);
@@ -43,13 +45,18 @@ bool MsgUpdateContact(int index, int type);
 bool MsgDeleteContact(int index);
 
 int MsgGetContactNameOrder();
+msg_error_t MsgGetContactStyleDisplayName(const char *first, const char *last, const char *middle, const char *prefix, const char *suffix, int contactNameOrder, char *displayName, unsigned int size);
 
-msg_error_t MsgAddPhoneLog(const MSG_MESSAGE_INFO_S *pMsgInfo);
-msg_error_t MsgDeletePhoneLog(msg_message_id_t msgId);
+void MsgAddPhoneLog(const MSG_MESSAGE_INFO_S *pMsgInfo);
+void MsgDeletePhoneLog(msg_message_id_t msgId);
 
 int MsgContactSVCBeginTrans();
 int MsgContactSVCEndTrans(bool bSuccess);
 
+bool checkBlockingMode(char *address, bool *pisFavorites);
 
+int MsgContactGetMinMatchDigit();
+void MsgConvertNumber(const char* pSrcNum, char* pDestNum, int destSize);
+bool MsgIsNumber(const char* pSrc);
 #endif //MSG_CONTACT_H
 
index 952805c..8cb07d5 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef __MSG_DEBUG_H__
 #include <string.h>
 #include <sys/time.h>
 #include <time.h>
+#include <dlog.h>
 
-#include "MsgTypes.h"
 #include "MsgCmdTypes.h"
-#include "MsgFilterTypes.h"
-
-extern "C"{
-       #include <dlog.h>
-};
-
 
 /*==================================================================================================
                                     DEFINES
 ==================================================================================================*/
 #define USER_TAG "MSG_FW"
+#undef LOG_TAG
+#define LOG_TAG "MSG_SERVICE"
+#define MSG_SMS_VALID_TAG "VLD_SMS"
+#define MSG_MMS_VALID_TAG "VLD_MMS"
 
 #define DLOG_ENABLE
-//#define LOG_ENABLE
 
+#if defined(DLOG_ENABLE)
 
-/*==================================================================================================
-                                     FUNCTION PROTOTYPES
-==================================================================================================*/
-int get_tid();
+/*log macros*/
+#define MSG_BEGIN()\
+       do\
+       {\
+               SLOGD(" BEGIN >>>> \n");\
+       } while(0)
 
+#define MSG_END()\
+       do\
+       {\
+               SLOGD(" END   <<<<  \n");\
+       } while(0)
 
-#if defined(DLOG_ENABLE)
+#define MSG_DEBUG(fmt, ...)\
+       do\
+       {\
+               SLOGD(fmt"\n", ##__VA_ARGS__);\
+       } while(0)
 
-#define MSG_FATAL(fmt, ...) \
-       do \
+#define MSG_INFO(fmt, ...)\
+       do\
        {\
-               SLOG(LOG_ERROR, USER_TAG, "[%s: %s(): %d] ERROR << " fmt " >>\n\n", rindex(__FILE__, '/')+1,  __FUNCTION__, __LINE__, ##__VA_ARGS__);\
+               SLOGI("* Info * " fmt "\n", ##__VA_ARGS__);\
+       } while(0)
+
+#define MSG_WARN(fmt, ...)\
+       do\
+       {\
+               SLOGW("* Warning * " fmt "\n", ##__VA_ARGS__);\
+       } while(0)
+
+#define MSG_ERR(fmt, ...)\
+       do\
+       {\
+               SLOGE("* Error * " fmt "\n", ##__VA_ARGS__);\
+       } while(0)
+
+#define MSG_FATAL(fmt, ...)\
+       do\
+       {\
+               SLOGE(" ERROR << " fmt " >>\n", ##__VA_ARGS__);\
+       } while(0)
+
+/*secure log macros*/
+#define MSG_SEC_DEBUG(fmt, ...)\
+       do\
+       {\
+               SECURE_SLOGD(fmt"\n", ##__VA_ARGS__);\
        } while (0)
 
-#define MSG_DEBUG(fmt, ...)\
+#define MSG_SEC_INFO(fmt, ...)\
        do\
        {\
-               SLOG(LOG_DEBUG, USER_TAG, "[%s: %s(): %d] " fmt"\n\n", rindex(__FILE__, '/')+1,  __FUNCTION__, __LINE__, ##__VA_ARGS__);\
+               SECURE_SLOGI("* Info * " fmt"\n", ##__VA_ARGS__);\
        } while (0)
 
-#define MSG_BEGIN() \
+/*valid data log macros*/
+#define MSG_SMS_VLD_INFO(fmt, ...)\
        do\
-    {\
-               SLOG(LOG_DEBUG, USER_TAG, "[%s: %s(): %d] BEGIN >>>> \n\n", rindex(__FILE__, '/')+1,  __FUNCTION__, __LINE__ );\
-    } while( 0 )
+       {\
+               SLOG(LOG_DEBUG, MSG_SMS_VALID_TAG, "[SMS INFO]%s, "fmt"\n", __TIMESTAMP__, ##__VA_ARGS__);\
+       } while (0)
 
-#define MSG_END() \
+#define MSG_SMS_VLD_TXT(fmt, ...)\
        do\
-    {\
-               SLOG(LOG_DEBUG, USER_TAG, "[%s: %s(): %d] END   <<<<  \n\n", rindex(__FILE__, '/')+1,  __FUNCTION__, __LINE__ );\
-    } \
-    while( 0 )
+       {\
+               SLOG(LOG_DEBUG, MSG_SMS_VALID_TAG, "[SMS_TEXT]%s, "fmt"\n", __TIMESTAMP__, ##__VA_ARGS__);\
+       } while (0)
 
+#define MSG_MMS_VLD_INFO(fmt, ...)\
+       do\
+       {\
+               SLOG(LOG_DEBUG, MSG_MMS_VALID_TAG, "[MMS INFO]%s, "fmt"\n", __TIMESTAMP__, ##__VA_ARGS__);\
+       } while (0)
+
+#define MSG_MMS_VLD_TXT(fmt, ...)\
+       do\
+       {\
+               SLOG(LOG_DEBUG, MSG_MMS_VALID_TAG, "[MMS TEXT]%s, "fmt"\n", __TIMESTAMP__, ##__VA_ARGS__);\
+       } while (0)
+
+#define MSG_MMS_VLD_FILE(fmt, ...)\
+       do\
+       {\
+               SLOG(LOG_DEBUG, MSG_MMS_VALID_TAG, "[MMS FILE]%s, "fmt"\n", __TIMESTAMP__, ##__VA_ARGS__);\
+       } while (0)
+
+/*err & warn return message log macros*/
+#define MSG_ERR_RET_VM(expr, val, fmt, ...)\
+       do\
+       {\
+               if (expr) {\
+                       MSG_ERR(fmt, ##__VA_ARGS__);\
+                       return (val);\
+               }\
+       } while(0)
+
+#define MSG_ERR_RET_M(expr, fmt, ...)\
+       do\
+       {\
+               if (expr) {\
+                       MSG_ERR(fmt, ##__VA_ARGS__);\
+                       return;\
+               }\
+       } while(0)
+
+#define MSG_WARN_M(expr, fmt, ...)\
+       do\
+       {\
+               if (expr) {\
+                       MSG_WARN(fmt, ##__VA_ARGS__);\
+               }\
+       } while(0)
+
+/*profile log macros*/
 #define MSG_PROFILE_BEGIN(pfid) \
-       unsigned int __prf_l1_##pfid = __LINE__;    \
-       struct timeval __prf_1_##pfid;              \
-       struct timeval __prf_2_##pfid;              \
-       do {                                        \
-               gettimeofday(&__prf_1_##pfid, 0);       \
+       unsigned int __prf_l1_##pfid = __LINE__;\
+       struct timeval __prf_1_##pfid;\
+       struct timeval __prf_2_##pfid;\
+       do {\
+               gettimeofday(&__prf_1_##pfid, 0);\
        } while (0)
 
 #define MSG_PROFILE_END(pfid) \
@@ -92,18 +172,19 @@ int get_tid();
                long __ds = __prf_2_##pfid.tv_sec - __prf_1_##pfid.tv_sec;\
                long __dm = __prf_2_##pfid.tv_usec - __prf_1_##pfid.tv_usec;\
                if ( __dm < 0 ) { __ds--; __dm = 1000000 + __dm; } \
-               SLOG(LOG_DEBUG, USER_TAG, "**PROFILE** [MSGFW: %s: %s() %u ~ %u] " #pfid                            \
-               " -> Elapsed Time: %u.%06u seconds\n",                    \
-               rindex(__FILE__, '/')+1,                \
+               SLOGD("**PROFILE** [MSGFW: %s: %s() %u ~ %u] " #pfid " -> Elapsed Time: %u.%06u seconds\n",\
+               rindex(__FILE__, '/')+1,\
                __FUNCTION__, \
-               __prf_l1_##pfid,                                         \
-               __prf_l2_##pfid,                                         \
-               (unsigned int)(__ds),                                    \
-               (unsigned int)(__dm));                                   \
+               __prf_l1_##pfid,\
+               __prf_l2_##pfid,\
+               (unsigned int)(__ds),\
+               (unsigned int)(__dm));\
        } while (0)
 
 #elif defined(LOG_ENABLE)
 
+int get_tid();
+
 #define MSG_FATAL(fmt, ...) \
        do \
        {\
@@ -188,6 +269,19 @@ int get_tid();
 
 #endif
 
+
+#define MSG_FREE(x) \
+       ({\
+               if (x != NULL){\
+               free(x);\
+               x = NULL;}\
+       })
+
+
+/*==================================================================================================
+                                                                        FUNCTION PROTOTYPES
+==================================================================================================*/
+
 const char * MsgDbgCmdStr(MSG_CMD_TYPE_T cmdType);
 const char * MsgDbgEvtStr(MSG_EVENT_TYPE_T evtType);
 
index 09d83ef..b1a8779 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef __MSG_DRM_WRAPPER_H_
@@ -41,6 +41,7 @@ bool MsgDrmGetMimeTypeEx(const char *szFileName, char *szMimeType, int nMimeType
 bool MsgDrmGetContentID(const char *szFileName, char *szContentID, int nContentIDLen);
 bool MsgDrmGetDrmType(const char *szFileName, MSG_DRM_TYPE *eDRMType);
 bool MsgDrmConvertDmtoDcfType(char *inputFile, char *outputFile);
+bool MsgDrmCheckRingtone(const char *ringtonePath);
 
 #ifdef __cplusplus
 }
index 50ce5b7..5d4c73f 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_EXCEPTION_H
@@ -69,6 +69,7 @@ public:
                SECURITY_ERROR,
                SERVER_READY_ERROR = 13,
 
+               REQ_EXIST_ERROR,
                // dont erase NUM_ERRORS. place a new error code in ahead of NUM_ERRORS
                NUM_ERRORS
        };
index 6aee579..9ff1c8b 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_GCONF_WRAPPER_H
@@ -57,11 +57,13 @@ int                                 MsgSettingGetBool(const char *pKey, bool *pVal);
 msg_error_t    MsgSettingHandleNewMsg(int SmsCnt, int MmsCnt);
 msg_error_t    MsgSettingSetIndicator(int SmsCnt, int MmsCnt);
 
-bool   MsgSettingGetAutoReject();
+int    MsgSettingGetAutoReject();
 bool   MsgSettingGetUnknownAutoReject();
 
 void   MsgSettingRegVconfCB();
 void   MsgSettingRemoveVconfCB();
+
 void MsgSettingRegVconfCBCommon(const char *pKey, _vconf_change_cb pCb);
+void MsgSettingRemoveVconfCBCommon(const char *pKey, _vconf_change_cb pCb);
 
 #endif // MSG_GCONF_WRAPPER_H
index 683f26e..8795d48 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef __IPCSocket_H__
@@ -65,14 +65,15 @@ public:
        msg_error_t connect(const char *path);
        msg_error_t close();
        /* write msg to ipc server */
-       int     write(const char* buf, int len);
+       int     write(const char* buf, unsigned int len);
        /* read msg from ipc server */
-       int     read(char** buf, int* len);
+       int     read(char** buf, unsigned int* len);
        void    addfd(int fd);
        int             getRemoteFd() {return remotefd; }
 private:
-       int readn(char *buf, int len );
-       int writen (const char *buf, int len);
+       int readn(char *buf, unsigned int len );
+       int writen (const char *buf, unsigned int len);
+       bool wait_for_reply();
 
        int sockfd, remotefd, maxfd;
        fd_set fds;
@@ -95,13 +96,13 @@ public:
        /* read msg from client of fd */
        int     read(int fd, char** buf, int* len );
        /* write msg to ipc client */
-       int     write(int fd, const char* buf, int len);
+       int     write(int fd, const char* buf, unsigned int len);
        void    addfd(int fd);
        void    setSockfd(int fd) { sockfd = fd; }
 
 private:
-       int readn(int fd, char *buf, int len );
-       int writen (int fd, const char *buf, int len);
+       int readn(int fd, char *buf, unsigned int len );
+       int writen (int fd, const char *buf, unsigned int len);
 
        /* server socket fd */
        int sockfd;
diff --git a/include/utils/MsgJsonParser.h b/include/utils/MsgJsonParser.h
new file mode 100755 (executable)
index 0000000..9cebec0
--- /dev/null
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef __MSG_JSON_PARSER_H__
+#define __MSG_JSON_PARSER_H__
+
+#include <stdio.h>
+#include "MsgDebug.h"
+
+#define MSG_JSON_OBJ_SET_STR(json_obj, key, val)\
+       if(json_obj && key && val){\
+               json_object_set_string_member(json_obj, key, val);\
+       } else {\
+               MSG_DEBUG("Error : json_obj = %p, key = %s, val = %s", json_obj, key, val);\
+       }
+
+#define MSG_JSON_OBJ_SET_INT(json_obj, key, val)\
+       if(json_obj && key){\
+               json_object_set_int_member(json_obj, key, val);\
+       } else {\
+               MSG_DEBUG("Error : json_obj = %p, key = %s, val = %d", json_obj, key, val);\
+       }
+
+#define MSG_JSON_OBJ_SET_OBJ(json_obj, key, val)\
+       if(json_obj && key){\
+               json_object_set_object_member(json_obj, key, val);\
+       } else {\
+               MSG_DEBUG("Error : json_obj = %p, key = %s, val = %p", json_obj, key, val);\
+       }
+
+#define MSG_JSON_OBJ_SET_ARRAY(json_obj, key, json_array)\
+       if(json_obj && key && json_array){\
+               json_object_set_array_member(json_obj, key, json_array);\
+       } else {\
+               MSG_DEBUG("Error : json_obj = %p, key = %s, json_array = %p", json_obj, key, json_array);\
+       }
+
+#define MSG_JSON_ARRAY_ADD_OBJECT(json_array, json_obj)\
+       if(json_array && json_obj){\
+               json_array_add_object_element(json_array, json_obj);\
+       } else {\
+               MSG_DEBUG("Error : json_array = %p, json_obj = %p", json_array, json_obj);\
+       }
+
+#define MSG_PRINT_PARSER_OBJECT(index, obj) {\
+       switch(obj.type) {\
+       case MSG_JSON_PARSER_NULL:\
+               MSG_DEBUG("parse obj : idx = %d, key =[%s], type = [%d], value = [%p], value num = [%f]", index, obj.key, obj.type, obj.value, obj.number_value);\
+               break;\
+       case MSG_JSON_PARSER_INT:\
+               MSG_DEBUG("parse obj : idx = [%d], key = [%s], type = [%s], value = [%d]", index, obj.key, "MSG_JSON_PARSER_INT", (int)obj.number_value);\
+               break;\
+       case MSG_JSON_PARSER_UINT:\
+               MSG_DEBUG("parse obj : idx = [%d], key = [%s], type = [%s], value = [%u]", index, obj.key, "MSG_JSON_PARSER_UINT", (unsigned int)obj.number_value);\
+               break;\
+       case MSG_JSON_PARSER_REAL:\
+               MSG_DEBUG("parse obj : idx = [%d], key = [%s], type = [%s], value = [%f]", index, obj.key, "MSG_JSON_PARSER_REAL", obj.number_value);\
+               break;\
+       case MSG_JSON_PARSER_STRING:\
+               MSG_DEBUG("parse obj : idx = [%d], key = [%s], type = [%s], value = [%s]", index, obj.key, "MSG_JSON_PARSER_STRING", (char *)obj.value);\
+               break;\
+       case MSG_JSON_PARSER_BOOLEAN:\
+               MSG_DEBUG("parse obj : idx = [%d], key = [%s], type = [%s], value = [%s]", index, obj.key, "MSG_JSON_PARSER_BOOLEAN", obj.number_value == 0 ? "TRUE" : "FALSE");\
+               break;\
+       case MSG_JSON_PARSER_ARRAY:\
+               MSG_DEBUG("parse obj : idx = [%d], key = [%s], type = [%s]", index, obj.key, "MSG_JSON_PARSER_ARRAY");\
+               break;\
+       case MSG_JSON_PARSER_OBJECT:\
+               MSG_DEBUG("parse obj : idx = [%d], key = [%s], type = [%s]", index, obj.key, "MSG_JSON_PARSER_OBJECT");\
+               break;\
+       default:\
+               MSG_DEBUG("parse obj : idx = %d, key =[%s], type = [%d], value = [%p], value num = [%f]", index, obj.key, obj.type, obj.value, obj.number_value);\
+               break;\
+       }\
+}
+/**
+*@enum msg_json_parser_value_type
+* This enumerates json-node types.
+*/
+typedef enum {
+        MSG_JSON_PARSER_NULL = 0,      /** 0 <null value */
+        MSG_JSON_PARSER_INT,           /** 1 < signed integer value */
+        MSG_JSON_PARSER_UINT,          /** 2 < unsigned integer value */
+        MSG_JSON_PARSER_REAL,          /** 3 < double value */
+        MSG_JSON_PARSER_STRING,        /** 4 < UTF-8 string value */
+        MSG_JSON_PARSER_BOOLEAN,       /** 5 < bool value */
+        MSG_JSON_PARSER_ARRAY,         /** 6 < array value (ordered list) */
+        MSG_JSON_PARSER_OBJECT,        /** 7 < object value */
+} msg_json_parser_value_type;
+
+typedef void *msg_json_parser_handle;
+
+typedef struct msg_json_parser_object_t {
+        msg_json_parser_value_type type;
+        char *key;
+        void *value;    /** Value of the node. VALID
+                                        only if type is
+                                        MSG_JSON_PARSER_NULL,
+                                        MSG_JSON_PARSER_STRING,
+                                        MSG_JSON_PARSER_ARRAY,
+                                        MSG_JSON_PARSER_OBJECT */
+        double number_value; /** Value of the node. VALID
+                                        only if type is
+                                        MSG_JSON_PARSER_UINT,
+                                        MSG_JSON_PARSER_INT,
+                                        MSG_JSON_PARSER_REAL,
+                                        MSG_JSON_PARSER_BOOLEAN */
+} msg_json_parser_object;
+
+msg_json_parser_handle msg_json_parser_handle_create(void);
+void msg_json_parser_handle_destory(msg_json_parser_handle *handle);
+int msg_json_parser_get_value(msg_json_parser_object *json_obj);
+int msg_json_parser_object_get_value(msg_json_parser_object *json_obj);
+int msg_json_parser_get_next_child(const msg_json_parser_object *parent, msg_json_parser_object *child, int index);
+void msg_json_parser_parse_buffer(msg_json_parser_handle handle, const char* value, int value_len, msg_json_parser_object *json_obj);
+int msg_json_parser_get_child_by_name(const msg_json_parser_object *parent, msg_json_parser_object *child, const char *name);
+
+#endif /*__MSG_JSON_PARSER_H__*/
+
index 4900312..7fa9522 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef __MSG_MEMORY_H__
index a91f81a..e08e2bd 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_MMS_MESSAGE_H
 #include "MsgTypes.h"
 #include "MsgMmsTypes.h"
 
-int msg_verify_number(const char *raw, char *trimmed);
-int msg_verify_email(const char *raw);
 msg_error_t _MsgMmsAddPage(MMS_MESSAGE_DATA_S *pMsgData, MMS_PAGE_S *pPage);
 msg_error_t _MsgMmsAddMedia(MMS_PAGE_S *pPage, MMS_MEDIA_S *pMedia);
-msg_error_t _MsgMmsAddSmilDoc(char *pSmil, MMS_MESSAGE_DATA_S *pMsgData);
 msg_error_t _MsgMmsAddAttachment(MMS_MESSAGE_DATA_S *pMsgData, MMS_ATTACH_S *pMedia);
 msg_error_t _MsgMmsAddRegion(MMS_MESSAGE_DATA_S *pMsgData, MMS_SMIL_REGION * pRegion);
 msg_error_t _MsgMmsAddTransition(MMS_MESSAGE_DATA_S *pMsgData, MMS_SMIL_TRANSITION *pTransition);
 msg_error_t _MsgMmsAddMeta(MMS_MESSAGE_DATA_S *pMsgData, MMS_SMIL_META *pMeta);
 
-bool _MsgMmsFindMatchedMedia(MMS_MESSAGE_DATA_S *pMsgData, char *pszFilePath);
-
 MMS_PAGE_S *_MsgMmsGetPage(MMS_MESSAGE_DATA_S *pMsgData, int pageIdx);
 MMS_SMIL_REGION *_MsgMmsGetSmilRegion(MMS_MESSAGE_DATA_S *pMsgData, int regionIdx);
 MMS_MEDIA_S *_MsgMmsGetMedia(MMS_PAGE_S *pPage, int mediaIdx);
 MMS_ATTACH_S *_MsgMmsGetAttachment(MMS_MESSAGE_DATA_S *pMsgData, int attachIdx);
 MMS_SMIL_TRANSITION *_MsgMmsGetTransition(MMS_MESSAGE_DATA_S *pMsgData, int transitionIdx);
 MMS_SMIL_META *_MsgMmsGetMeta(MMS_MESSAGE_DATA_S *pMsgData, int metaIdx);
+
 int    _MsgMmsGetPageCount(MMS_MESSAGE_DATA_S *pMsgData);
 int _MsgMmsGetAttachCount(MMS_MESSAGE_DATA_S *pMsgData);
 int _MsgMmsGetTransitionCount(MMS_MESSAGE_DATA_S *pMsgData);
 int _MsgMmsGetMetaCount(MMS_MESSAGE_DATA_S *pMsgData);
 
-msg_error_t _MsgMmsReleasePageList(MMS_MESSAGE_DATA_S *pMsgData);
-msg_error_t _MsgMmsReleaseRegionList(MMS_MESSAGE_DATA_S *pMsgData);
-msg_error_t    _MsgMmsReleaseAttachList(MMS_MESSAGE_DATA_S *pMsgData);
-msg_error_t _MsgMmsReleaseMetaList(MMS_MESSAGE_DATA_S *pMsgData);
-msg_error_t _MsgMmsReleaseTransitionList(MMS_MESSAGE_DATA_S *pMsgData);
+void MsgMmsReleaseMmsLists(MMS_MESSAGE_DATA_S *pMsgData);
 
 char *_MsgMmsSerializeMessageData(const MMS_MESSAGE_DATA_S *pMsgData, unsigned int *pSize);
-bool _MsgMmsDeserializeMessageData(MMS_MESSAGE_DATA_S *pBody, char *pFileData);
-bool _MsgMmsSetRootLayout(MMS_MESSAGE_DATA_S *pMmsMsg, MMS_SMIL_ROOTLAYOUT *pRootlayout);
+bool _MsgMmsDeserializeMessageData(MMS_MESSAGE_DATA_S *pMsgData, const char *pData);
+
+bool _MsgMmsSetRootLayout(MMS_MESSAGE_DATA_S *pMsgData, MMS_SMIL_ROOTLAYOUT *pRootlayout);
+
+void _MsgMmsPrint(MMS_MESSAGE_DATA_S *pMsgData);
+void _MsgMmsAttachPrint(MMS_ATTACH_S *attach);
+void _MsgMmsMediaPrint(MMS_MEDIA_S *media);
+void _MsgMmsPagePrint(MMS_PAGE_S *page);
+
+MMS_HEADER_DATA_S *MsgMmsCreateHeader();
+void MsgMmsInitHeader(MMS_HEADER_DATA_S *pMmsHeaderData);
+void MsgMmsReleaseHeader(MMS_HEADER_DATA_S **ppMmHeadersData);
+
+MMS_MULTIPART_DATA_S *MsgMmsCreateMultipart();
+void MsgMmsInitMultipart(MMS_MULTIPART_DATA_S *pMmsMultipart);
+void MsgMmsReleaseMultipart(MMS_MULTIPART_DATA_S **ppMmsMultipart);
+
+MMS_DATA_S *MsgMmsCreate();
+
+void MsgMmsRelease(MMS_DATA_S **ppMmsData);
+
+int MsgMmsReleaseMultipartList(MMSList **ppMultipartList);
+
+int MsgMmsGetSmilMultipart(MMSList *pMultipartList, MMS_MULTIPART_DATA_S **smil_multipart);//TODO : delete
+
+int MsgMmsConvertMmsDataToMmsMessageData(MMS_DATA_S *pSrc, MMS_MESSAGE_DATA_S *pDst);
+
+int MsgMmsConvertMmsMessageDataToMmsData(MMS_MESSAGE_DATA_S *pSrc, MMS_DATA_S *pDst);
+
+MMS_ADDRESS_DATA_S *MsgMmsCreateAddress(int addressType, const char *addressVal);
+void MsgMmsReleaseAddress(MMS_ADDRESS_DATA_S **ppMmsAddressData);
+int MsgMmsReleaseAddressList(MMSList **ppAddressList);
+
+int MsgMmsSetMultipartData(MMS_MULTIPART_DATA_S *pMultipart);
+int MsgMmsSetMultipartFilePath(const char *dirPath, MMS_MULTIPART_DATA_S *pMultipart);
+
+int MsgMmsSetMultipartListData(MMS_DATA_S *pMmsData);
+int MsgMmsSetMultipartListFilePath(const char *dirPath, MMS_DATA_S *pMmsData);
+
+int printMultipart(MMS_MULTIPART_DATA_S *multipart);
+int printMultipartList(MMSList *pMultipartList);//for debug
+
+void _MsgMmsMultipartPrint(MMS_MULTIPART_DATA_S *multipart);
 
+bool  _MsgMmsRemoveEmptyObject(MMS_MESSAGE_DATA_S *pMmsMsg);
 
 #endif // MSG_MMS_MESSAGE_H
index 44aae6a..c3b1cc6 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef __MSG_MUTEX_H__
@@ -33,8 +33,23 @@ void WaitMsgReady(int sec);
 class Mutex
 {
 public:
-       Mutex(){ pthread_mutex_init(&m, 0); }
+       Mutex(){
+               pthread_mutexattr_t mattr;
+               pthread_mutexattr_init(&mattr);
+               pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_RECURSIVE);
+               pthread_mutex_init(&m, &mattr);
+               pthread_mutexattr_destroy(&mattr);
+       }
+       ~Mutex(){ pthread_mutex_destroy(&m); }
        void lock(){ pthread_mutex_lock(&m); }
+
+       int timedlock(){
+               struct timespec abs_time;
+               clock_gettime(CLOCK_REALTIME, &abs_time);
+               abs_time.tv_sec += 1;
+               return pthread_mutex_timedlock(&m, &abs_time);
+       }
+
        void unlock(){ pthread_mutex_unlock(&m); }
        pthread_mutex_t* pMutex() { return &m; }
 
diff --git a/include/utils/MsgNotificationWrapper.h b/include/utils/MsgNotificationWrapper.h
deleted file mode 100755 (executable)
index 8eb6173..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#ifndef MSG_QUICKPANEL_WRAPPER_H
-#define MSG_QUICKPANEL_WRAPPER_H
-
-/*==================================================================================================
-                                         INCLUDE FILES
-==================================================================================================*/
-#include "MsgInternalTypes.h"
-#include "MsgSqliteWrapper.h"
-
-
-/*==================================================================================================
-                                         DEFINES
-==================================================================================================*/
-#define NORMAL_MSG_ICON_PATH   "/opt/apps/org.tizen.message/res/icons/default/small/org.tizen.message.noti.png"
-#define VOICE_MSG_ICON_PATH            "/opt/apps/org.tizen.message/res/icons/default/small/org.tizen.message.voice.png"
-#define CB_MSG_ICON_PATH                       "/opt/apps/org.tizen.message/res/icons/default/small/org.tizen.message.noti.png"
-#define NOTI_MSG_ICON_PATH             "/opt/apps/org.tizen.message/res/icons/default/small/org.tizen.message.noti.png"
-
-#define MSG_APP_PACKAGE_NAME   "message"
-#define MSG_APP_LOCALEDIR                      "/opt/apps/org.tizen.message/res/locale"
-
-#define SENDING_MULTIMEDIA_MESSAGE_FAILED      "Sending multimedia message failed"
-#define MULTIMEDIA_MESSAGE_SENT                                        "Multimedia message sent"
-#define RETRIEVING_MESSAGE_FAILED                                      "Retrieving message failed"
-#define MESSAGE_RETRIEVED                                                              "Message retrieved"
-
-
-/*==================================================================================================
-                                     FUNCTION PROTOTYPES
-==================================================================================================*/
-
-msg_error_t MsgInsertNoti(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S* pMsg);
-
-msg_error_t MsgInsertSmsReportToNoti(MsgDbHandler *pDbHandle, msg_message_id_t MsgId, msg_delivery_report_status_t Status);
-
-msg_error_t MsgInsertMmsReportToNoti(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S* pMsg);
-
-msg_error_t MsgDeleteNotiByMsgId(msg_message_id_t msgId);
-
-msg_error_t MsgDeleteNotiByThreadId(msg_thread_id_t ThreadId);
-
-msg_error_t MsgInsertTicker(const char* pTickerMsg, const char* pLocaleTickerMsg);
-
-#endif // MSG_QUICKPANEL_WRAPPER_H
diff --git a/include/utils/MsgSerialize.h b/include/utils/MsgSerialize.h
new file mode 100755 (executable)
index 0000000..9a8dc5f
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MSG_MMS_SERIALIZE_H
+#define MSG_MMS_SERIALIZE_H
+
+#include "MsgMmsTypes.h"
+
+int MsgSerializeMmsJsonData(const MMS_DATA_S *pMsgData, char **pValue);
+int MsgDeserializeMmsJsonData(char* value, int value_len, MMS_DATA_S **ppMmsData);
+
+int MsgSerializeMms(const MMS_DATA_S *pMsgData, char **pValue);
+int MsgDeserializeMmsData(char* value, int value_len, MMS_DATA_S **ppMmsData);
+
+#endif //MSG_MMS_SERIALIZE_H
+
diff --git a/include/utils/MsgSoundPlayer.h b/include/utils/MsgSoundPlayer.h
deleted file mode 100755 (executable)
index ce690e8..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#ifndef MSG_SOUND_PLAYER_H
-#define MSG_SOUND_PLAYER_H
-
-
-/*==================================================================================================
-                                    DEFINES
-==================================================================================================*/
-
-/*==================================================================================================
-                                    INCLUDE FILES
-==================================================================================================*/
-
-
-/*==================================================================================================
-                                     FUNCTION PROTOTYPES
-==================================================================================================*/
-void MsgSoundPlayStart();
-void MsgSoundPlayStop();
-
-bool MsgSoundSetRepeatAlarm();
-bool MsgSoundCreateRepeatAlarm(int RepeatTime);
-int MsgSoundRepeatAlarmCB(int TimerId, void *pUserParam);
-int MsgSoundGetUnreadMsgCnt();
-void MsgSoundInitRepeatAlarm();
-
-#endif // MSG_SOUND_PLAYER_H
index e219b7a..1703146 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_SQLITE_WRAPPER_H
                                     INCLUDE FILES
 ==================================================================================================*/
 #include "MsgTypes.h"
-
+#include <db-util.h>
+#include "MsgMutex.h"
 
 /*==================================================================================================
                                     DEFINES
 ==================================================================================================*/
-#define MSGFW_DB_NAME                  "/opt/dbspace/.msg_service.db"
+#define MSGFW_DB_NAME                  "/opt/usr/dbspace/.msg_service.db"
 
 #define MSGFW_MESSAGE_TABLE_NAME                               "MSG_MESSAGE_TABLE"
 #define MSGFW_FOLDER_TABLE_NAME                                        "MSG_FOLDER_TABLE"
 #define MSGFW_CB_MSG_TABLE_NAME                                "MSG_CBMSG_TABLE"
 #define MMS_PLUGIN_MESSAGE_TABLE_NAME          "MSG_MMS_MESSAGE_TABLE"
 #define MSGFW_SYNCML_MSG_TABLE_NAME            "MSG_SYNCML_TABLE"
+
+#if 0
+#define MSGFW_RECEIVED_CB_MSG_TABLE_NAME       "MSG_CB_MESSAGE_TABLE"
+#endif
+
+#define MSGFW_CB_CHANNEL_INFO_TABLE_NAME       "MSG_CB_CHANNEL_INFO_TABLE"
+#ifdef FEATURE_SMS_CDMA
+#define MSGFW_CDMA_CB_CHANNEL_INFO_TABLE_NAME          "MSG_CDMA_CB_CHANNEL_INFO_TABLE"
+#endif
+
 #define MSGFW_SMS_SENDOPT_TABLE_NAME           "MSG_SMS_SENDOPT_TABLE"
+#define MSGFW_SMS_REPORT_TABLE_NAME            "MSG_SMS_REPORT_TABLE"
+#define MSGFW_REPORT_TABLE_NAME                                        "MSG_REPORT_TABLE"
+#define MSGFW_PUSH_CONFIG_TABLE_NAME           "MSG_PUSHCFG_TABLE"
+#define MSGFW_MMS_PREVIEW_TABLE_NAME           "MSG_MMS_PREVIEW_INFO_TABLE"
+#define MSGFW_MMS_MULTIPART_TABLE_NAME         "MSG_MULTIPART_TABLE"
+
+#ifdef FEATURE_SMS_CDMA
+#define MSGFW_UNIQUENESS_INFO_TABLE_NAME       "MSG_UNIQUENESS_INFO_TABLE"
+#endif
+
+#define MSGFW_TMP_MSGID_TABLE_NAME                     "MSG_TMP_MSGID_TABLE"
+
+#define MSGFW_ADDRESS_TEMP_TABLE_NAME          "MSG_ADDRESS_TEMP_TABLE"
 
 #define MAX_QUERY_LEN                                  3072
 #define MAX_FOLDER_NAME_LEN            20
 #define MAX_ACCOUNT_NAME_LEN   51
 
+#define MSGFW_DB_ESCAPE_CHAR           '\\'
+
+#define SHM_FILE_FOR_DB_LOCK                "/.msg_shm_db_lock"
 
 /*==================================================================================================
                                      FUNCTION PROTOTYPES
 ==================================================================================================*/
 void   MsgReleaseMemoryDB();
+msg_error_t MsgConvertStrWithEscape(const char *input, char **output);
 
 
 /*==================================================================================================
@@ -65,12 +93,14 @@ public:
 
        bool checkTableExist(const char *pTableName);
        msg_error_t execQuery(const char *pQuery);
-       msg_error_t getTable(const char *pQuery, int *pRowCnt);
+       msg_error_t getTable(const char *pQuery, int *pRowCnt, int *pColumnCnt);
        void freeTable();
        msg_error_t bindText(const char *pBindStr, int index);
+       msg_error_t bindInt(const int pBindint, int index);
        msg_error_t bindBlob(const void * pBindBlob, int size, int index);
        msg_error_t prepareQuery(const char *pQuery);
        msg_error_t stepQuery();
+       void resetQuery();
        void finalizeQuery();
        int columnInt(int ColumnIndex);
        const unsigned char* columnText(int ColumnIndex);
@@ -79,14 +109,25 @@ public:
        msg_error_t endTrans(bool Success);
        int getColumnToInt(int RowIndex);
        char getColumnToChar(int RowIndex);
+       char* getColumnToString(int RowIndex);
        void getColumnToString(int RowIndex, int Length, char *pString);
        msg_error_t getRowId(const char *pTableName, unsigned int *pRowId);
+       void getMmapMutex(const char *shm_file_name);
+       void freeMmapMutex();
+       void shm_mutex_timedlock (int sec);
+       void shm_mutex_unlock();
 
 private:
-
        char **result;
-
+       sqlite3 *handle;
+       sqlite3_stmt *stmt;
+       pthread_mutex_t *mmapMx;
+       int shm_fd;
+       static Mutex mx;
 };
 
+
+MsgDbHandler *getDbHandle();
+void removeDbHandle();
 #endif // MSG_SQLITE_WRAPPER_H
 
similarity index 82%
rename from plugin/sms_plugin/include/SmsPluginTextConvert.h
rename to include/utils/MsgTextConvert.h
index 08cee2b..3401874 100755 (executable)
@@ -1,21 +1,21 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#ifndef SMS_PLUGIN_TEXT_CONVERT_H
-#define SMS_PLUGIN_TEXT_CONVERT_H
+#ifndef MSG_TEXT_CONVERT_H
+#define MSG_TEXT_CONVERT_H
 
 
 /*==================================================================================================
@@ -23,7 +23,7 @@
 ==================================================================================================*/
 #include <map>
 
-#include "SmsPluginTypes.h"
+//#include "SmsPluginTypes.h"
 
 
 /*==================================================================================================
 
 #define MAX_DUMP_COLUMN        16
 
-typedef unsigned short WCHAR;
+typedef unsigned long WCHAR;
 
-typedef unsigned char SMS_CHAR_TYPE_T;
+typedef unsigned char MSG_CHAR_TYPE_T;
+
+typedef unsigned char MSG_LANGUAGE_ID_T;
 
 
 /*==================================================================================================
                                 ENUMS
 ==================================================================================================*/
-enum _SMS_CHAR_TYPE_E
+enum _MSG_CHAR_TYPE_E
 {
-       SMS_CHAR_DEFAULT = 0,
-       SMS_CHAR_GSM7EXT,
-       SMS_CHAR_TURKISH,
-       SMS_CHAR_SPANISH,
-       SMS_CHAR_PORTUGUESE
+       MSG_CHAR_DEFAULT = 0,
+       MSG_CHAR_GSM7EXT,
+       MSG_CHAR_TURKISH,
+       MSG_CHAR_SPANISH,
+       MSG_CHAR_PORTUGUESE
 };
 
+enum _MSG_LANGUAGE_ID_E
+{
+       MSG_LANG_ID_RESERVED = 0,
+       MSG_LANG_ID_TURKISH,
+       MSG_LANG_ID_SPANISH,
+       MSG_LANG_ID_PORTUGUESE,
+       MSG_LANG_ID_BENGALI,
+       MSG_LANG_ID_GUJARATI,
+       MSG_LANG_ID_HINDI,
+       MSG_LANG_ID_KANNADA,
+       MSG_LANG_ID_MALAYALAM,
+       MSG_LANG_ID_ORIYA,
+       MSG_LANG_ID_PUNJABI,
+       MSG_LANG_ID_TAMIL,
+       MSG_LANG_ID_TELUGU,
+       MSG_LANG_ID_URDU,
+};
 
 /*==================================================================================================
                                      STRUCTURES
 ==================================================================================================*/
+
+typedef struct _MSG_LANG_INFO_S
+{
+       bool                                                    bSingleShift;
+       bool                                                    bLockingShift;
+
+       MSG_LANGUAGE_ID_T                       singleLang;
+       MSG_LANGUAGE_ID_T                       lockingLang;
+} MSG_LANG_INFO_S;
+
+
+typedef struct _MSG_SINGLE_SHIFT_S
+{
+       MSG_LANGUAGE_ID_T       langId;
+} MSG_SINGLE_SHIFT_S;
+
+
+typedef struct _MSG_LOCKING_SHIFT_S
+{
+       MSG_LANGUAGE_ID_T       langId;
+} MSG_LOCKING_SHIFT_S;
+
+
 // ETSI GSM 03.38 GSM 7 bit Default Alphabet Table -> UCS2
 static const WCHAR g_GSM7BitToUCS2[] =
 {
@@ -209,39 +251,47 @@ static const WCHAR g_PortuLockingToUCS2[] =
 /*==================================================================================================
                                 CLASS DEFINITIONS
 ==================================================================================================*/
-class SmsPluginTextConvert
+class MsgTextConvert
 {
 public:
-       static SmsPluginTextConvert* instance();
+       static MsgTextConvert* instance();
 
-       int convertUTF8ToGSM7bit(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, OUT SMS_LANGUAGE_ID_T *pLangId);
+       int convertUTF8ToGSM7bit(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, OUT MSG_LANGUAGE_ID_T *pLangId, OUT bool *bIncludeAbnormalChar);
        int convertUTF8ToUCS2(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen);
+#ifndef FEATURE_SMS_CDMA
+       int convertUTF8ToAuto(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, OUT MSG_LANGUAGE_ID_T *pLangId, OUT msg_encode_type_t *pCharType);
+#else
        int convertUTF8ToAuto(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, OUT msg_encode_type_t *pCharType);
+#endif
 
-       int convertGSM7bitToUTF8(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, IN SMS_LANG_INFO_S *pLangInfo);
+       int convertGSM7bitToUTF8(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, IN MSG_LANG_INFO_S *pLangInfo);
        int convertUCS2ToUTF8(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN  int srcTextLen);
        int convertEUCKRToUTF8(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN  int srcTextLen);
+       int convertSHIFTJISToUTF8(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN  int srcTextLen);
 
 private:
-       SmsPluginTextConvert();
-       virtual ~SmsPluginTextConvert();
+       MsgTextConvert();
+       ~MsgTextConvert();
 
-       static SmsPluginTextConvert* pInstance;
+       int convertUCS2ToGSM7bit(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, OUT MSG_LANGUAGE_ID_T *pLangId, OUT bool *bIncludeAbnormalChar);
+       int convertUCS2ToASCII(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, OUT bool *pUnknown);
 
-       int convertUCS2ToGSM7bit(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, OUT SMS_LANGUAGE_ID_T *pLangId);
-       int convertUCS2ToGSM7bitAuto(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, OUT bool *pUnknown);
-
-       int convertGSM7bitToUCS2(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, IN SMS_LANG_INFO_S *pLangInfo);
+       int convertGSM7bitToUCS2(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, IN MSG_LANG_INFO_S *pLangInfo);
 
        void convertDumpTextToHex(const unsigned char *pText, int length);
 
+       static MsgTextConvert* pInstance;
+
        std::map<unsigned short, unsigned char> extCharList;
        std::map<unsigned short, unsigned char> ucs2toGSM7DefList;
        std::map<unsigned short, unsigned char> ucs2toGSM7ExtList;
        std::map<unsigned short, unsigned char> ucs2toTurkishList;
        std::map<unsigned short, unsigned char> ucs2toSpanishList;
        std::map<unsigned short, unsigned char> ucs2toPortuList;
+
+       std::map<unsigned short, unsigned char> replaceCharList;
+
 };
 
-#endif //SMS_PLUGIN_TEXT_CONVERT_H
+#endif //MSG_TEXT_CONVERT_H
 
index 9d36330..8600b2a 100755 (executable)
@@ -1,31 +1,28 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_UTIL_FILE_H
 #define MSG_UTIL_FILE_H
 
-
+#include <stdio.h>
 /*==================================================================================================
                                        DEFINES
 ==================================================================================================*/
 #define FM_READ_WRITE_BUFFER_MAX (1024*1024*3)
 
-#define TPDU_LOG_FILE "/opt/etc/msg-service/tpduLog.txt"
-
-
 /*==================================================================================================
                                        FUNCTION PROTOTYPES
 ==================================================================================================*/
@@ -57,7 +54,12 @@ int MsgRmRf(char *pDirPath);
 unsigned int MsgDu(const char *pDirPath);
 bool MsgAppendFile(const char *pFilePath, const char *pData, int DataSize);
 void MsgMmsInitDir();
-
+bool MsgAccessFile(const char *filepath, int mode);
+bool MsgChmod(const char *filepath, int mode);
+bool MsgChown(const char *filepath, int uid, int gid);
+bool MsgCreateFile(const char *pFilePath,char *pData, int DataSize);
+char *MsgGetDirName(char *file_path);
+char *MsgGetFileName(char *file_path);
 
 #endif // MSG_UTIL_FILE_H
 
index 0d11260..5595a01 100755 (executable)
@@ -1,22 +1,23 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_UTIL_FUNCTION_H
 #define MSG_UTIL_FUNCTION_H
 
+#define        MSG_UTIL_CH_EMAIL_AT    '@'
 
 /*==================================================================================================
                                          INCLUDE FILES
@@ -31,6 +32,8 @@
                                        FUNCTION PROTOTYPES
 ==================================================================================================*/
 
+bool MsgCheckFeatureSupport(const char *feature_name);
+
 // Encoders
 int MsgEncodeCountInfo(MSG_COUNT_INFO_S *pCountInfo, char **ppDest);
 
@@ -40,7 +43,7 @@ int MsgEncodeRecipientList(MSG_RECIPIENTS_LIST_S *pRecipientList, char **ppDest)
 
 int MsgEncodeMsgId(msg_message_id_t *pMsgId, char **ppDest);
 
-int MsgEncodeMsgInfo(MSG_MESSAGE_INFO_S *pMsgInfo, char **ppDest);
+int MsgEncodeMsgInfo(const MSG_MESSAGE_INFO_S *pMsgInfo, char **ppDest);
 
 int MsgEncodeMsgInfo(MSG_MESSAGE_INFO_S *pMsgInfo,  MSG_SENDINGOPT_INFO_S* pSendOptInfo, char **ppDest);
 
@@ -68,7 +71,9 @@ int MsgEncodeSyncMLOperationData(int msgId, int extId, char **ppDest);
 
 int MsgEncodeStorageChangeData(const msg_storage_change_type_t storageChangeType, const msg_id_list_s *pMsgIdList, char **ppDest);
 
-int MsgEncodeReportStatus(MSG_REPORT_STATUS_INFO_S* pReportStatus, char **ppDest);
+int MsgEncodeReportMsgData(const msg_report_type_t msgReportType, const MSG_MESSAGE_INFO_S *pMsgInfo, char **ppDest);
+
+int MsgEncodeReportStatus(MSG_REPORT_STATUS_INFO_S* pReportStatus, int count, char **ppDest);
 
 int MsgEncodeThreadId(msg_thread_id_t *pThreadId, char **ppDest);
 
@@ -80,6 +85,8 @@ void MsgDecodeMsgId(char *pSrc, msg_message_id_t *pMsgId);
 
 void MsgDecodeCountInfo(char *pSrc, MSG_COUNT_INFO_S *pCountInfo);
 
+void MsgDecodeMsgInfo(char *pSrc, MSG_MESSAGE_INFO_S *pMsgInfo);
+
 void MsgDecodeMsgInfo(char *pSrc, MSG_MESSAGE_INFO_S *pMsgInfo,  MSG_SENDINGOPT_INFO_S* pSendOptInfo);
 
 void MsgDecodeFolderViewList(char *pSrc, msg_struct_list_s *pFolderViewList);
@@ -96,11 +103,11 @@ void MsgDecodeFilterFlag(char *pSrc, bool *pSetFlag);
 
 void MsgDecodeMsgType(char *pSrc, MSG_MESSAGE_TYPE_S* pMsgType);
 
-void   MsgDecodeContactCount(char *pSrc,  MSG_THREAD_COUNT_INFO_S *pMsgThreadCountList);
+void MsgDecodeContactCount(char *pSrc,  MSG_THREAD_COUNT_INFO_S *pMsgThreadCountList);
 
 void MsgDecodeMemSize(char *pSrc, unsigned int *memsize);
 
-void   MsgDecodeReportStatus(char *pSrc,  MSG_REPORT_STATUS_INFO_S *pReportStatus);
+void MsgDecodeReportStatus(char *pSrc,  msg_struct_list_s *report_list);
 
 void MsgDecodeThreadId(char *pSrc, msg_thread_id_t *pThreadId);
 
@@ -111,8 +118,16 @@ void MsgDecodeThreadInfo(char *pSrc, MSG_THREAD_VIEW_S *pThreadInfo);
 int MsgMakeEvent(const void *pData, int DataSize, MSG_EVENT_TYPE_T MsgEvent, msg_error_t MsgError, void **ppEvent);
 
 
+// Utin functions
 int msg_verify_number(const char *raw, char *trimmed);
 
 int msg_verify_email(const char *raw);
 
+char* msg_clean_country_code(char *src);
+
+char* msg_normalize_number(char *src);
+
+msg_error_t MsgMakeSortRule(const MSG_SORT_RULE_S *pSortRule, char *pSqlSort);
+
+bool msg_is_valid_email(char *pAddress);
 #endif // MSG_UTIL_FUNCTION_H
index d0ab5d9..56bce45 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MSG_UTIL_STORAGE_H
 #include "MsgInternalTypes.h"
 #include "MsgStorageTypes.h"
 #include "MsgSqliteWrapper.h"
-
+#include "MsgSettingTypes.h"
 
 /*==================================================================================================
                                        FUNCTION PROTOTYPES
 ==================================================================================================*/
 // Common Function
+
 unsigned int MsgStoAddMessageTable(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsgInfo);
 msg_error_t MsgStoSetReadStatus(MsgDbHandler *pDbHandle, msg_message_id_t MsgId, bool bRead);
 msg_error_t MsgStoGetOldestMessage(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsgInfo, msg_message_id_t *pMsgId);
 msg_error_t MsgStoCheckMsgCntFull(MsgDbHandler *pDbHandle, const MSG_MESSAGE_TYPE_S* pMsgType, msg_folder_id_t FolderId);
 msg_error_t MsgStoCountMsgByLimitCategory(MsgDbHandler *pDbHandle, const MSG_MESSAGE_TYPE_S *pMsgType, int *pMsgCount, msg_folder_id_t folderId );
+msg_error_t MsgStocheckMemoryStatus();
 int MsgStoCheckMsgCntLimit(const MSG_MESSAGE_TYPE_S* pMsgType, msg_folder_id_t FolderId);
 
 msg_error_t MsgStoAddAddress(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsg, msg_thread_id_t *pConvId);
-msg_error_t MsgStoGetAddressByMsgId(MsgDbHandler *pDbHandle, msg_message_id_t msgId, int contactNameOrder, int *nAddressCnt, MSG_ADDRESS_INFO_S *pAddress);
+msg_error_t MsgStoGetAddressByMsgId(MsgDbHandler *pDbHandle, msg_message_id_t msgId, int contactNameOrder, int *nAddressCnt, MSG_ADDRESS_INFO_S **pAddress);
 msg_error_t MsgStoGetAddressByMsgId(MsgDbHandler *pDbHandle, msg_message_id_t msgId, int contactNameOrder, msg_struct_list_s *pAddress);
 msg_error_t MsgStoGetAddressByConvId(MsgDbHandler *pDbHandle, msg_thread_id_t convId, int contactNameOrder, msg_struct_list_s *pAddrlist);
+void MsgStoUpdateAddress(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsg, msg_thread_id_t convId);
 msg_error_t MsgStoAddConversation(MsgDbHandler *pDbHandle, msg_thread_id_t *pConvId);
 msg_error_t MsgStoUpdateConversation(MsgDbHandler *pDbHandle, msg_thread_id_t convId);
 msg_error_t MsgStoSetConversationDisplayName(MsgDbHandler *pDbHandle, int contactId);
 msg_error_t MsgStoSetConversationDisplayName(MsgDbHandler *pDbHandle, msg_thread_id_t convId);
 msg_error_t MsgStoClearConversationTable(MsgDbHandler *pDbHandle);
+
+#ifdef FEATURE_SMS_CDMA
+msg_error_t MsgStoAddCBChannelInfo(MsgDbHandler *pDbHandle, MSG_CB_CHANNEL_S *pCBChannel);
+msg_error_t MsgStoGetCBChannelInfo(MsgDbHandler *pDbHandle, MSG_CB_CHANNEL_S *pCBChannel);
+#else
+msg_error_t MsgStoAddCBChannelInfo(MsgDbHandler *pDbHandle, MSG_CB_CHANNEL_S *pCBChannel, msg_sim_slot_id_t simIndex);
+msg_error_t MsgStoGetCBChannelInfo(MsgDbHandler *pDbHandle, MSG_CB_CHANNEL_S *pCBChannel, msg_sim_slot_id_t simIndex);
+#endif
+
 bool MsgExistAddress(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsg, msg_thread_id_t *pConvId);
+bool MsgExistAddress(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S *pMsg,  msg_thread_id_t convId, int index);
+bool MsgExistConversation(MsgDbHandler *pDbHandle, msg_thread_id_t convId);
+bool MsgExistMessage(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S *pMsg);
 
 int MsgStoGetUnreadCnt(MsgDbHandler *pDbHandle, MSG_MAIN_TYPE_T MsgType);
 msg_error_t MsgStoAddContactInfo(MsgDbHandler *pDbHandle, MSG_CONTACT_INFO_S *pContactInfo, const char *pNumber);
+msg_error_t MsgStoClearContactInfoByAddrbookIdList(MsgDbHandler *pDbHandle, int* addrbookList, int addrbookCnt);
 msg_error_t MsgStoClearContactInfo(MsgDbHandler *pDbHandle, int ContactId);
-msg_error_t MsgStoClearContactInfo(MsgDbHandler *pDbHandle, int ContactId, const char *pNumber);
+msg_error_t MsgStoResetContactInfo(MsgDbHandler *pDbHandle, int contactId);
 msg_error_t MsgStoGetMmsRawFilePath(MsgDbHandler *pDbHandle, msg_message_id_t msgId, char *pFilePath);
 bool MsgStoCheckReadReportRequested(MsgDbHandler *pDbHandle, msg_message_id_t MsgId);
 bool MsgStoCheckReadReportIsSent(MsgDbHandler *pDbHandle, msg_message_id_t MsgId);
-char *MsgStoReplaceString(const char *org_str, const char *old_str, const char *new_str);
+msg_error_t MsgStoUpdateNetworkStatus(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S *pMsgInfo, msg_network_status_t status);
+
+// Lists
+msg_error_t MsgStoGetFolderViewList(msg_folder_id_t FolderId, const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pMsgFolderViewList);
+msg_error_t MsgStoGetThreadViewList(const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pThreadViewList);
+msg_error_t MsgStoGetConversationViewItem(msg_message_id_t msgId, MSG_CONVERSATION_VIEW_S *pConv);
+msg_error_t MsgStoGetConversationViewList(msg_thread_id_t ThreadId, msg_struct_list_s *pConvViewList);
+msg_error_t MsgStoSearchMessage(const char *pSearchString, msg_struct_list_s *pThreadViewList);
+
+msg_error_t MsgStoGetRejectMsgList(const char *pNumber, msg_struct_list_s *pRejectMsgList);
+msg_error_t MsgStoGetAddressList(const msg_thread_id_t threadId, msg_struct_list_s *pAddrList);
+msg_error_t MsgStoGetMessageList(const MSG_LIST_CONDITION_S *pListCond, msg_struct_list_s *pMsgList);
+msg_error_t MsgStoGetMediaList(const msg_thread_id_t threadId, msg_list_handle_t *pMediaList);
+
+#ifdef FEATURE_SMS_CDMA
+msg_error_t MsgStoClearUniquenessTable();
+#endif
 
 #endif // MSG_UTIL_STORAGE_H
 
diff --git a/include/utils/MsgVMessage.h b/include/utils/MsgVMessage.h
new file mode 100755 (executable)
index 0000000..ad9f3e3
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MSG_VMESSAGE_H
+#define MSG_VMESSAGE_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgStorageTypes.h"
+#include "MsgInternalTypes.h"
+#include "MsgUtilStorage.h"
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+char* MsgVMessageAddRecord(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S* pMsg);
+char* MsgVMessageEncode(MSG_MESSAGE_INFO_S *pMsg);
+char* _convert_tm_to_vdata_str(const struct tm * tm);
+bool _convert_vdata_str_to_tm(const char* szText, struct tm * tm);
+
+#endif //MSG_VMESSAGE_H
+
index 6af422f..3f56ff7 100755 (executable)
@@ -10,7 +10,7 @@ IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
 ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "") 
 MESSAGE("Build type: ${CMAKE_BUILD_TYPE}")
 
-SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
+SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
 
 ##########################################################
 # Define MAPI   
@@ -29,20 +29,19 @@ SET(MAPI-SRCS
 
 INCLUDE_DIRECTORIES(
        ${CMAKE_SOURCE_DIR}/include/common
-       ${CMAKE_SOURCE_DIR}/include/framework
        ${CMAKE_SOURCE_DIR}/include/proxy
        ${CMAKE_SOURCE_DIR}/include/utils
        ${CMAKE_SOURCE_DIR}/include/mapi
 )
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(mapi_pkgs REQUIRED glib-2.0 dlog)
+pkg_check_modules(mapi_pkgs REQUIRED glib-2.0 dlog privacy-manager-client vconf)
 
 FOREACH(flag ${mapi_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
 ENDFOREACH(flag)
 
-SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
 
 ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
 
index cf24235..8116e05 100755 (executable)
@@ -1,20 +1,21 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
+#include <privacy_checker_client.h>
 
 #include "MsgHandle.h"
 #include "MsgDebug.h"
 ==================================================================================================*/
 EXPORT_API int msg_open_msg_handle(msg_handle_t *handle)
 {
-       MsgHandle* pHandle = new MsgHandle();
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
 
        if (handle == NULL)
        {
                MSG_FATAL("Input Paramter is NULL");
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
+       MsgHandle* pHandle = new MsgHandle();
 
        // Create MsgHandle
        *handle = (msg_handle_t)pHandle;
 
        if (*handle == NULL)
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
 
        try
        {
@@ -51,8 +60,14 @@ EXPORT_API int msg_open_msg_handle(msg_handle_t *handle)
        {
                MSG_FATAL("%s", e.what());
 
+               // Destroy MsgHandle
+               delete (MsgHandle*)(*handle);
+               (*handle) = NULL;
+
                if (e.errorCode() == MsgException::SERVER_READY_ERROR)
                        return MSG_ERR_SERVER_NOT_READY;
+               else if(e.errorCode() == MsgException::SECURITY_ERROR)
+                       return MSG_ERR_PERMISSION_DENIED;
                else
                        return MSG_ERR_COMMUNICATION_ERROR;
        }
@@ -63,10 +78,19 @@ EXPORT_API int msg_open_msg_handle(msg_handle_t *handle)
 
 EXPORT_API int msg_close_msg_handle(msg_handle_t *handle)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || *handle == NULL)
        {
                MSG_FATAL("Input Paramter is NULL");
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)(*handle);
index cf862e0..4871163 100755 (executable)
@@ -1,24 +1,26 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
+#include <privacy_checker_client.h>
 
 #include "MsgException.h"
 #include "MsgDebug.h"
 #include "MsgHandle.h"
+#include "msg_private.h"
 #include "msg.h"
 
 /*==================================================================================================
 ==================================================================================================*/
 EXPORT_API int msg_add_filter(msg_handle_t handle, const msg_struct_t msg_struct_handle)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        // TODO : check NULL in msg_struct_handle
        msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
 
        if (handle == NULL || msg_struct == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        if(msg_struct->type != MSG_STRUCT_FILTER)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -59,20 +70,29 @@ EXPORT_API int msg_add_filter(msg_handle_t handle, const msg_struct_t msg_struct
 
 EXPORT_API int msg_update_filter(msg_handle_t handle, const msg_struct_t msg_struct_handle)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        // TODO : check NULL in msg_struct_handle
        msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
 
        if (handle == NULL || msg_struct == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
 
        if(msg_struct->type != MSG_STRUCT_FILTER)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -93,11 +113,20 @@ EXPORT_API int msg_update_filter(msg_handle_t handle, const msg_struct_t msg_str
 
 EXPORT_API int msg_delete_filter(msg_handle_t handle, msg_filter_id_t filter_id)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -118,11 +147,20 @@ EXPORT_API int msg_delete_filter(msg_handle_t handle, msg_filter_id_t filter_id)
 
 EXPORT_API int msg_get_filter_list(msg_handle_t handle, msg_struct_list_s *filter_list)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || filter_list == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -143,11 +181,20 @@ EXPORT_API int msg_get_filter_list(msg_handle_t handle, msg_struct_list_s *filte
 
 EXPORT_API int msg_set_filter_operation(msg_handle_t handle, bool set_flag)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -168,11 +215,20 @@ EXPORT_API int msg_set_filter_operation(msg_handle_t handle, bool set_flag)
 
 EXPORT_API int msg_get_filter_operation(msg_handle_t handle, bool *set_flag)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -191,6 +247,60 @@ EXPORT_API int msg_get_filter_operation(msg_handle_t handle, bool *set_flag)
 }
 
 
+EXPORT_API int msg_set_filter_active(msg_handle_t handle, msg_filter_id_t filter_id, bool active)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
+
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setFilterActivation(filter_id, active);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_FILTER_ERROR;
+       }
+
+       return err;
+}
+
+
+bool msg_get_filter_info_bool(void *filter, int field)
+{
+       if (!filter)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = 0;
+
+       MSG_FILTER_S *filter_data = (MSG_FILTER_S *)filter;
+
+       switch (field)
+       {
+       case MSG_FILTER_ACTIVE_BOOL :
+               ret = filter_data->bActive;
+               break;
+       default :
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       return ret;
+}
 
 
 int msg_get_filter_info_int(void *filter, int field)
@@ -239,6 +349,26 @@ char *msg_get_filter_info_str(void *filter, int field)
        return ret_str;
 }
 
+int msg_set_filter_info_bool(void *filter, int field, bool value)
+{
+       if (!filter)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_error_t err =  MSG_SUCCESS;
+       MSG_FILTER_S *filter_data = (MSG_FILTER_S *)filter;
+
+       switch (field)
+       {
+       case MSG_FILTER_ACTIVE_BOOL :
+               filter_data->bActive = value;
+               break;
+       default :
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       return err;
+}
+
 int msg_set_filter_info_int(void *filter, int field, int value)
 {
        if (!filter)
@@ -273,8 +403,11 @@ int msg_set_filter_info_str(void *filter, int field, char *value, int size)
        switch (field)
        {
        case MSG_FILTER_VALUE_STR :
-               strncpy(filter_data->filterValue, value, size);
+       {
+               int len = (size > MAX_FILTER_VALUE_LEN)?MAX_FILTER_VALUE_LEN:size;
+               strncpy(filter_data->filterValue, value, len);
                break;
+       }
        default :
                return MSG_ERR_INVALID_PARAMETER;
        }
index 23fabc4..0a73738 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <string.h>
 #include "MsgStorageTypes.h"
 #include "MsgInternalTypes.h"
 #include "MsgMmsMessage.h"
-
+#include "MsgSerialize.h"
 #include "msg.h"
 #include "msg_private.h"
 
+msg_struct_s *__msg_message_create_address_struct()
+{
+       msg_struct_s *msg_struct = new msg_struct_s;
+       bzero(msg_struct, sizeof(msg_struct_s));
+
+       msg_struct->type = MSG_STRUCT_ADDRESS_INFO;
+       msg_struct->data = new MSG_ADDRESS_INFO_S;
+       memset(msg_struct->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+       return msg_struct;
+}
+
+void __msg_message_release_address_struct(gpointer data)
+{
+       if (data == NULL)
+               return;
+
+       msg_struct_s *addr_struct = (msg_struct_s *)data;
+       MSG_ADDRESS_INFO_S *addrInfo = (MSG_ADDRESS_INFO_S *)addr_struct->data;
+
+       delete (MSG_ADDRESS_INFO_S *)addrInfo;
+
+       addr_struct->data = NULL;
+
+       delete addr_struct;
+}
+
+
 void msg_message_create_struct(msg_struct_s *msg_struct)
 {
        MSG_MESSAGE_HIDDEN_S *msg = (MSG_MESSAGE_HIDDEN_S *)new MSG_MESSAGE_HIDDEN_S;
@@ -50,27 +78,32 @@ void msg_message_create_struct(msg_struct_s *msg_struct)
        msg->dataSize = 0;
        msg->pData = NULL;
        msg->pMmsData = NULL;
+       msg->mmsDataSize = 0;
+       msg->simIndex = MSG_SIM_SLOT_ID_1;
 
        /* Allocate memory for address list of message */
        msg_struct_list_s *addr_list = (msg_struct_list_s *)new msg_struct_list_s;
 
        addr_list->nCount = 0;
-       addr_list->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_ADDRESS_INFO_S *)*MAX_TO_ADDRESS_CNT];
-
-       msg_struct_s *pTmp = NULL;
-
-       for (int i = 0; i < MAX_TO_ADDRESS_CNT; i++) {
-               addr_list->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];
-               pTmp = (msg_struct_s *)addr_list->msg_struct_info[i];
-               pTmp->type = MSG_STRUCT_ADDRESS_INFO;
-               pTmp->data = new MSG_ADDRESS_INFO_S;
-               memset(pTmp->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
-
-               addr_list->msg_struct_info[i] = (msg_struct_t)pTmp;
+       addr_list->msg_struct_info = (msg_struct_t *)calloc(MAX_TO_ADDRESS_CNT, sizeof(msg_struct_s *));
+
+       if (addr_list->msg_struct_info != NULL) {
+               msg_struct_s *pTmp = NULL;
+
+               for (int i = 0; i < MAX_TO_ADDRESS_CNT; i++) {
+                       addr_list->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
+                       pTmp = (msg_struct_s *)addr_list->msg_struct_info[i];
+                       memset(pTmp, 0x00, sizeof(msg_struct_s));
+                       pTmp->type = MSG_STRUCT_ADDRESS_INFO;
+                       pTmp->data = new MSG_ADDRESS_INFO_S;
+                       memset(pTmp->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+               }
        }
 
        msg->addr_list = addr_list;
 
+       msg->addressList = NULL;
+
        msg_struct->data = (int *)msg;
 }
 
@@ -86,10 +119,11 @@ int msg_message_release(msg_struct_s **msg_struct)
        if (msg->pMmsData) {
                delete [] static_cast<char*>(msg->pMmsData);
                msg->pMmsData = NULL;
+               msg->mmsDataSize = 0;
        }
 
        // Memory Free
-       if (msg->addr_list!= NULL)
+       if (msg->addr_list != NULL)
        {
                for(int i=0; i<MAX_TO_ADDRESS_CNT; i++) {
                        msg_struct_s * addrInfo = (msg_struct_s *)msg->addr_list->msg_struct_info[i];
@@ -99,12 +133,18 @@ int msg_message_release(msg_struct_s **msg_struct)
                        msg->addr_list->msg_struct_info[i] = NULL;
                }
 
-               delete [] msg->addr_list->msg_struct_info;
+               g_free(msg->addr_list->msg_struct_info);
 
                delete msg->addr_list;
                msg->addr_list = NULL;
        }
 
+       // Free GList *addressList
+       if (msg->addressList) {
+               g_list_free_full(msg->addressList, __msg_message_release_address_struct);
+               msg->addressList = NULL;
+       }
+
        delete msg;
        (*msg_struct)->data = NULL;
 
@@ -138,35 +178,67 @@ int msg_message_get_int_value(void *data, int field, int *value)
        {
         if (msg_data->mainType == MSG_SMS_TYPE)
         {
-                       if (msg_data->subType == MSG_CB_SMS)
-                               *value = MSG_TYPE_SMS_CB;
-                       else if (msg_data->subType == MSG_JAVACB_SMS)
-                               *value = MSG_TYPE_SMS_JAVACB;
-                       else if (msg_data->subType == MSG_WAP_SI_SMS || msg_data->subType == MSG_WAP_SL_SMS)
-                               *value = MSG_TYPE_SMS_WAPPUSH;
-                       else if (msg_data->subType == MSG_MWI_VOICE_SMS || msg_data->subType == MSG_MWI_FAX_SMS
-                                       || msg_data->subType == MSG_MWI_EMAIL_SMS || msg_data->subType == MSG_MWI_OTHER_SMS)
-                               *value = MSG_TYPE_SMS_MWI;
-                       else if (msg_data->subType == MSG_SYNCML_CP)
-                               *value = MSG_TYPE_SMS_SYNCML;
-                       else if (msg_data->subType == MSG_REJECT_SMS)
-                               *value = MSG_TYPE_SMS_REJECT;
-                       else
-                               *value = MSG_TYPE_SMS;
-        }
-        else if (msg_data->mainType == MSG_MMS_TYPE)
-        {
+                       switch (msg_data->subType) {
+                               case MSG_CB_SMS :
+                                       *value = MSG_TYPE_SMS_CB;
+                                       break;
+                               case MSG_JAVACB_SMS :
+                                       *value = MSG_TYPE_SMS_JAVACB;
+                                       break;
+                               case MSG_WAP_SI_SMS :
+                               case MSG_WAP_SL_SMS :
+                                       *value = MSG_TYPE_SMS_WAPPUSH;
+                                       break;
+                               case MSG_MWI_VOICE_SMS :
+                               case MSG_MWI_FAX_SMS :
+                               case MSG_MWI_EMAIL_SMS :
+                               case MSG_MWI_OTHER_SMS :
+                                       *value = MSG_TYPE_SMS_MWI;
+                                       break;
+                               case MSG_SYNCML_CP :
+                                       *value = MSG_TYPE_SMS_SYNCML;
+                                       break;
+                               case MSG_REJECT_SMS :
+                                       *value = MSG_TYPE_SMS_REJECT;
+                                       break;
+                               case MSG_ETWS_SMS :
+                                       *value = MSG_TYPE_SMS_ETWS_PRIMARY;
+                                       break;
+                               case MSG_CMAS_PRESIDENTIAL :
+                                       *value = MSG_TYPE_SMS_CMAS_PRESIDENTIAL;
+                                       break;
+                               case MSG_CMAS_EXTREME :
+                                       *value = MSG_TYPE_SMS_CMAS_EXTREME;
+                                       break;
+                               case MSG_CMAS_SEVERE :
+                                       *value = MSG_TYPE_SMS_CMAS_SEVERE;
+                                       break;
+                               case MSG_CMAS_AMBER :
+                                       *value = MSG_TYPE_SMS_CMAS_AMBER;
+                                       break;
+                               case MSG_CMAS_TEST :
+                                       *value = MSG_TYPE_SMS_CMAS_TEST;
+                                       break;
+                               case MSG_CMAS_OPERATOR_DEFINED :
+                                       *value = MSG_TYPE_SMS_CMAS_OPERATOR_DEFINED;
+                                       break;
+                               default :
+                                       *value = MSG_TYPE_SMS;
+                       }
+               }
+               else if (msg_data->mainType == MSG_MMS_TYPE)
+               {
                        if (msg_data->subType == MSG_NOTIFICATIONIND_MMS)
                                *value = MSG_TYPE_MMS_NOTI;
                        else if (msg_data->subType == MSG_SENDREQ_JAVA_MMS)
                                *value = MSG_TYPE_MMS_JAVA;
                        else
                                *value = MSG_TYPE_MMS;
-        }
-        else
-               *value = MSG_TYPE_INVALID;
+               }
+               else
+                       *value = MSG_TYPE_INVALID;
 
-       break;
+               break;
        }
        case MSG_MESSAGE_CLASS_TYPE_INT :
                *value = msg_data->classType;
@@ -201,6 +273,9 @@ int msg_message_get_int_value(void *data, int field, int *value)
        case MSG_MESSAGE_DATA_SIZE_INT :
                *value = msg_data->dataSize;
                break;
+       case MSG_MESSAGE_SIM_INDEX_INT :
+               *value = msg_data->simIndex;
+               break;
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -231,6 +306,14 @@ int msg_message_get_bool_value(void *data, int field, bool *value)
        case MSG_MESSAGE_PORT_VALID_BOOL :
                *value = msg_data->bPortValid;
                break;
+       case MSG_MESSAGE_REPLACE_BOOL :
+       {
+               if (msg_data->subType >= MSG_REPLACE_TYPE1_SMS && msg_data->subType <= MSG_REPLACE_TYPE7_SMS)
+                       *value = true;
+               else
+                       *value = false;
+               break;
+       }
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -260,9 +343,20 @@ int msg_message_get_str_value(void *data, int field, char *value, int size)
                break;
        case MSG_MESSAGE_SMS_DATA_STR :
        case MSG_MESSAGE_MMS_TEXT_STR :
-               if (msg_data->pData != NULL)
-                       strncpy(value, (char *)msg_data->pData, size);
+               if (msg_data->pData)
+               {
+                       if (msg_data->mainType == MSG_SMS_TYPE) {
+                               int data_len = 0;
+                               ((size_t)size >= msg_data->dataSize)? (data_len = msg_data->dataSize) : data_len = size;
+                               memset(value, 0, size);
+                               memcpy(value, msg_data->pData, data_len);
+                       } else if (msg_data->mainType == MSG_MMS_TYPE) {
+                               memset(value, 0, size);
+                               strncpy(value, (char *)msg_data->pData, size);
+                       }
+               }
                break;
+
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -278,8 +372,6 @@ int msg_message_get_struct_hnd(void *data, int field, void **value)
 
        int ret = MSG_SUCCESS;
 
-       MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)data;
-
        switch (field) {
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
@@ -302,6 +394,9 @@ int msg_message_get_list_hnd(void *data, int field, void **value)
        case MSG_MESSAGE_ADDR_LIST_STRUCT :
                *value = (void *)msg_data->addr_list;
                break;
+       case MSG_MESSAGE_ADDR_LIST_HND :
+               *value = (msg_list_handle_t)msg_data->addressList;
+               break;
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -332,22 +427,30 @@ int msg_message_set_int_value(void *data, int field, int value)
                break;
        case MSG_MESSAGE_TYPE_INT :
        {
-        if (value == MSG_TYPE_SMS) {
-               msg_data->mainType = MSG_SMS_TYPE;
-               msg_data->subType = MSG_NORMAL_SMS;
-        } else if (value == MSG_TYPE_MMS) {
-               msg_data->mainType = MSG_MMS_TYPE;
-               msg_data->subType = MSG_SENDREQ_MMS;
-        } else if (value == MSG_TYPE_MMS_JAVA) {
-               msg_data->mainType = MSG_MMS_TYPE;
+               if (value == MSG_TYPE_SMS) {
+                       msg_data->mainType = MSG_SMS_TYPE;
+                       msg_data->subType = MSG_NORMAL_SMS;
+               }
+               else if (value == MSG_TYPE_MMS) {
+                       msg_data->mainType = MSG_MMS_TYPE;
+                       msg_data->subType = MSG_SENDREQ_MMS;
+               }
+               else if (value == MSG_TYPE_MMS_JAVA) {
+                       msg_data->mainType = MSG_MMS_TYPE;
                        msg_data->subType = MSG_SENDREQ_JAVA_MMS;
-        } else if (value == MSG_TYPE_SMS_SYNCML) {
-               msg_data->mainType = MSG_SMS_TYPE;
-               msg_data->subType = MSG_SYNCML_CP;
-        } else if (value == MSG_TYPE_SMS_REJECT) {
-               msg_data->mainType = MSG_SMS_TYPE;
-               msg_data->subType = MSG_REJECT_SMS;
-        }
+               }
+               else if (value == MSG_TYPE_SMS_SYNCML) {
+                       msg_data->mainType = MSG_SMS_TYPE;
+                       msg_data->subType = MSG_SYNCML_CP;
+               }
+               else if (value == MSG_TYPE_SMS_REJECT) {
+                       msg_data->mainType = MSG_SMS_TYPE;
+                       msg_data->subType = MSG_REJECT_SMS;
+               }
+               else if (value == MSG_TYPE_SMS_ETWS_PRIMARY) {
+                       msg_data->mainType = MSG_SMS_TYPE;
+                       msg_data->subType = MSG_ETWS_SMS;
+               }
         break;
        }
        case MSG_MESSAGE_CLASS_TYPE_INT :
@@ -383,6 +486,9 @@ int msg_message_set_int_value(void *data, int field, int value)
        case MSG_MESSAGE_DATA_SIZE_INT :
                msg_data->dataSize = value;
                break;
+       case MSG_MESSAGE_SIM_INDEX_INT :
+               msg_data->simIndex = value;
+               break;
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -442,16 +548,13 @@ int msg_message_set_str_value(void *data, int field, char *value, int size)
                break;
        case MSG_MESSAGE_SMS_DATA_STR :
        {
-                if (msg_data->pData)
-                        delete [] static_cast<char*>(msg_data->pData);
-
-                msg_data->dataSize = size;
-
-                msg_data->pData = (void*)new char[msg_data->dataSize+1];
-
-                memcpy((char *)msg_data->pData, value, msg_data->dataSize);
+               if (msg_data->pData)
+                       delete [] static_cast<char*>(msg_data->pData);
 
-                ((char*) msg_data->pData)[msg_data->dataSize] = '\0';
+               msg_data->dataSize = size;
+               msg_data->pData = (void*)new char[msg_data->dataSize+1];
+               memcpy((char *)msg_data->pData, value, msg_data->dataSize);
+               ((char*) msg_data->pData)[msg_data->dataSize] = '\0';
        }
                break;
        default :
@@ -469,8 +572,6 @@ int msg_message_set_struct_hnd(void *data, int field, void *value)
 
        int ret = MSG_SUCCESS;
 
-       MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)data;
-
        switch (field) {
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
@@ -500,21 +601,24 @@ void msg_message_copy_message(MSG_MESSAGE_HIDDEN_S *pSrc, MSG_MESSAGE_HIDDEN_S *
        pDst->direction = pSrc->direction;
        pDst->bPortValid = pSrc->bPortValid;
        pDst->dataSize = pSrc->dataSize;
+       pDst->mmsDataSize = pSrc->mmsDataSize;
+       pDst->simIndex = pSrc->simIndex;
        memcpy(pDst->subject, pSrc->subject, sizeof(pDst->subject));
-       if(pSrc->dataSize)
+
+       if(pSrc->pMmsData && pSrc->mmsDataSize)
        {
-               if(pSrc->pMmsData)
-               {
-                       pDst->pMmsData = new char[pSrc->dataSize + 1];
-                       memcpy(pDst->pMmsData, pSrc->pMmsData, pSrc->dataSize);
-               }
-               if(pSrc->pData)
-               {
-                       int data_len = strlen((const char *)pSrc->pData);
-                       pDst->pData = new char[data_len + 1];
-                       strncpy((char *)pDst->pData, (const char *)pSrc->pData, data_len);
-               }
+               pDst->pMmsData = new char[pSrc->mmsDataSize];
+               memcpy(pDst->pMmsData, pSrc->pMmsData, pSrc->mmsDataSize);
        }
+
+       if(pSrc->dataSize && pSrc->pData)
+       {
+               int data_len = strlen((const char *)pSrc->pData);
+               pDst->pData = new char[data_len + 1];
+               memset(pDst->pData, 0x00, data_len + 1);
+               strncpy((char *)pDst->pData, (const char *)pSrc->pData, data_len);
+       }
+
        msg_struct_list_s *src_addrlist = pSrc->addr_list;
        msg_struct_list_s *dst_addrlist = pDst->addr_list;
        dst_addrlist->nCount = src_addrlist->nCount;
@@ -525,10 +629,149 @@ void msg_message_copy_message(MSG_MESSAGE_HIDDEN_S *pSrc, MSG_MESSAGE_HIDDEN_S *
                msg_struct_s *dst_addr = (msg_struct_s *)dst_addrlist->msg_struct_info[i];
                memcpy(dst_addr->data, src_addr->data, sizeof(MSG_ADDRESS_INFO_S));
        }
+
+       if (strlen(pSrc->thumbPath) > 0) {
+               memset(pDst->thumbPath, 0x00, sizeof(pDst->thumbPath));
+               memcpy(pDst->thumbPath, pSrc->thumbPath, sizeof(pDst->thumbPath));
+       }
+
+       for (unsigned int i=0; i < g_list_length(pSrc->addressList); i++) {
+               msg_struct_s *addr_struct = __msg_message_create_address_struct();
+               MSG_ADDRESS_INFO_S *addrInfo = (MSG_ADDRESS_INFO_S *)addr_struct->data;
+
+               msg_struct_s *addr_info = (msg_struct_s *)g_list_nth_data(pSrc->addressList,(guint)i);
+               MSG_ADDRESS_INFO_S *address = (MSG_ADDRESS_INFO_S *)addr_info->data;
+
+               addrInfo->addressType = address->addressType;
+               addrInfo->recipientType = address->recipientType;
+               addrInfo->contactId = address->contactId;
+               strncpy(addrInfo->addressVal, address->addressVal, MAX_ADDRESS_VAL_LEN);
+               strncpy(addrInfo->displayName, address->displayName, MAX_DISPLAY_NAME_LEN);
+               addrInfo->displayName[MAX_DISPLAY_NAME_LEN] = '\0';
+
+               pDst->addressList = g_list_append(pDst->addressList, addr_struct);
+       }
 }
 
+int msg_cb_message_get_int_value(void *data, int field, int *value)
+{
+       if (!data)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_CB_MSG_S *cb_msg = (MSG_CB_MSG_S *)data;
+
+       *value = 0;
+
+       switch (field)
+       {
+               case MSG_CB_MSG_TYPE_INT :
+                       {
+                               switch (cb_msg->type) {
+                                       case MSG_ETWS_SMS :
+                                               *value = MSG_TYPE_SMS_ETWS_PRIMARY;
+                                               break;
+                                       case MSG_CB_SMS:
+                                               *value = ((cb_msg->messageId & 0xFFF8) == 0x1100 ) ? MSG_TYPE_SMS_ETWS_SECONDARY : MSG_TYPE_SMS_CB;
+                                               break;
+                                       case MSG_CMAS_PRESIDENTIAL :
+                                               *value = MSG_TYPE_SMS_CMAS_PRESIDENTIAL;
+                                               break;
+                                       case MSG_CMAS_EXTREME :
+                                               *value = MSG_TYPE_SMS_CMAS_EXTREME;
+                                               break;
+                                       case MSG_CMAS_SEVERE :
+                                               *value = MSG_TYPE_SMS_CMAS_SEVERE;
+                                               break;
+                                       case MSG_CMAS_AMBER :
+                                               *value = MSG_TYPE_SMS_CMAS_AMBER;
+                                               break;
+                                       case MSG_CMAS_TEST :
+                                               *value = MSG_TYPE_SMS_CMAS_TEST;
+                                               break;
+                                       case MSG_CMAS_OPERATOR_DEFINED :
+                                               *value = MSG_TYPE_SMS_CMAS_OPERATOR_DEFINED;
+                                               break;
+                                       default :
+                                               ret = MSG_ERR_UNKNOWN;
+                               }
+                       }
+                       break;
+               case MSG_CB_MSG_RECV_TIME_INT :
+                       *value = cb_msg->receivedTime;
+                       break;
+               case MSG_CB_MSG_SERIAL_NUM_INT :
+                       *value = cb_msg->serialNum;
+                       break;
+               case MSG_CB_MSG_MSG_ID_INT :
+                       *value = cb_msg->messageId;
+                       break;
+               case MSG_CB_MSG_DCS_INT :
+                       *value = (int)cb_msg->dcs;
+                       break;
+               case MSG_CB_MSG_CB_TEXT_LEN_INT :
+                       *value = cb_msg->cbTextLen;
+                       break;
+               case MSG_CB_MSG_ETWS_WARNING_TYPE_INT :
+                       *value = cb_msg->etwsWarningType;
+                       break;
+               default :
+                       ret = MSG_ERR_INVALID_PARAMETER;
+                       break;
+       }
+
+       return ret;
+}
+
+int msg_cb_message_get_str_value(void *data, int field, char *value, int size)
+{
+       if (!data || !value)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_CB_MSG_S *cb_msg = (MSG_CB_MSG_S *)data;
+
+       switch (field) {
+               case MSG_CB_MSG_CB_TEXT_STR:
+                       {
+                               int     copylen = 0;
+                               copylen = (size > cb_msg->cbTextLen) ? cb_msg->cbTextLen : size - 1;
+                               memcpy (value, cb_msg->cbText, copylen);
+                               value[copylen] = '\0';
+                       }
+                       break;
+               case MSG_CB_MSG_LANGUAGE_TYPE_STR:
+                       {
+                               int     copylen = 0;
+                               copylen = ((size_t)size > strlen((const char*)cb_msg->language_type)) ? strlen((const char*)cb_msg->language_type) : size - 1;
+                               memcpy (value, cb_msg->language_type, copylen);
+                               value[copylen] = '\0';
+                       }
+                       break;
+               case MSG_CB_MSG_ETWS_WARNING_SECU_INFO_STR:
+                       {
+                               if ((size_t)size < sizeof(cb_msg->etwsWarningSecurityInfo))
+                                       ret = MSG_ERR_INVALID_PARAMETER;
+                               else
+                                       memcpy (value, cb_msg->etwsWarningSecurityInfo, sizeof(cb_msg->etwsWarningSecurityInfo));
+                       }
+                       break;
+
+               default :
+                       ret = MSG_ERR_INVALID_PARAMETER;
+                       break;
+       }
+
+       return ret;
+}
+
+
+
 EXPORT_API int msg_get_mms_struct(msg_struct_t msg_struct_handle, msg_struct_t mms_struct_handle)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
        //TODO :: check message type is MMS
        int ret = MSG_SUCCESS;
        msg_struct_s *msg_struct = (msg_struct_s *)msg_struct_handle;
@@ -548,24 +791,28 @@ EXPORT_API int msg_get_mms_struct(msg_struct_t msg_struct_handle, msg_struct_t m
 
        MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)msg_struct->data;
 
-       MMS_MESSAGE_DATA_S *tmp_mms_data  = (MMS_MESSAGE_DATA_S *)calloc(1, sizeof(MMS_MESSAGE_DATA_S));
+       if (msg_data->pMmsData == NULL) {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
 
-       _MsgMmsDeserializeMessageData(tmp_mms_data, (char*)msg_data->pMmsData);
+       MMS_DATA_S *mms_data = NULL;
 
-       convert_from_mmsdata(tmp_mms_data, mms_struct);
+       MsgDeserializeMmsData((char*)msg_data->pMmsData, msg_data->mmsDataSize, &mms_data);
 
-       _MsgMmsReleasePageList(tmp_mms_data);
-       _MsgMmsReleaseRegionList(tmp_mms_data);
-       _MsgMmsReleaseAttachList(tmp_mms_data);
-       _MsgMmsReleaseTransitionList(tmp_mms_data);
-       _MsgMmsReleaseMetaList(tmp_mms_data);
-       free(tmp_mms_data);
+       if (mms_data) {
+               convert_to_hidden_mmsdata(mms_data, mms_struct);
+
+               MsgMmsRelease(&mms_data);
+       } else {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
 
        return ret;
 }
 
 EXPORT_API int msg_set_mms_struct(msg_struct_t msg_struct_handle, msg_struct_t mms_struct_handle)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
        //TODO :: check message type is MMS
        int ret = MSG_SUCCESS;
        msg_struct_s *msg_struct = (msg_struct_s *)msg_struct_handle;
@@ -585,18 +832,91 @@ EXPORT_API int msg_set_mms_struct(msg_struct_t msg_struct_handle, msg_struct_t m
 
        MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)msg_struct->data;
 
-       MMS_MESSAGE_DATA_S *tmp_mms_data = (MMS_MESSAGE_DATA_S *)calloc(1,sizeof(MMS_MESSAGE_DATA_S));
+       MMS_DATA_S *mms_data = MsgMmsCreate();
+       if (mms_data == NULL)
+               return MSG_ERR_MEMORY_ERROR;
+
+       convert_from_hidden_mmsdata(mms_struct, mms_data);
+
+       int mmsDataSize = MsgSerializeMms(mms_data, (char **)&msg_data->pMmsData);
 
-       convert_to_mmsdata(mms_struct, tmp_mms_data);
+       if (mmsDataSize > 0)
+               msg_data->mmsDataSize = mmsDataSize;
 
-       msg_data->pMmsData = _MsgMmsSerializeMessageData(tmp_mms_data, &(msg_data->dataSize));
+       //TODO:: set subtype
+
+       MsgMmsRelease(&mms_data);
+
+       return ret;
+}
+
+
+int msg_message_list_append(msg_struct_t msg_struct_handle, int field, msg_struct_t *item)
+{
+       msg_error_t err = MSG_SUCCESS;
+       msg_struct_s *msg_struct = (msg_struct_s *)msg_struct_handle;
+       MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)msg_struct->data;
+
+       msg_struct_s *msg_struct_item = NULL;
+       switch(field) {
+       case MSG_MESSAGE_ADDR_LIST_HND:
+       {
+               msg_struct_item = __msg_message_create_address_struct();
+               msg_data->addressList = g_list_append(msg_data->addressList, msg_struct_item);
+               *item = (msg_struct_t)msg_struct_item;
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+
+int msg_message_list_clear(msg_struct_t msg_struct_handle, int field)
+{
+       msg_error_t err = MSG_SUCCESS;
+       msg_struct_s *msg_struct = (msg_struct_s *)msg_struct_handle;
+       MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)msg_struct->data;
+
+       switch(field) {
+       case MSG_MESSAGE_ADDR_LIST_HND:
+       {
+               // Free GList *addressList
+               if (msg_data->addressList) {
+                       g_list_free_full(msg_data->addressList, __msg_message_release_address_struct);
+                       msg_data->addressList = NULL;
+               }
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+int msg_conversation_get_list_hnd(void *data, int field, void **value)
+{
+       if (!data)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_CONVERSATION_VIEW_S *msg_data = (MSG_CONVERSATION_VIEW_S *)data;
+
+       switch (field) {
+       case MSG_CONV_MSG_MULTIPART_HND :
+               *value = (void *)msg_data->multipart_list;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
 
-       _MsgMmsReleasePageList(tmp_mms_data);
-       _MsgMmsReleaseRegionList(tmp_mms_data);
-       _MsgMmsReleaseAttachList(tmp_mms_data);
-       _MsgMmsReleaseTransitionList(tmp_mms_data);
-       _MsgMmsReleaseMetaList(tmp_mms_data);
-       free(tmp_mms_data);
        return ret;
 }
 
index 218f643..e4f157c 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
 #include "MsgTypes.h"
 #include "MsgMmsTypes.h"
 #include "MsgMmsMessage.h"
-#include "MsgDebug.h"\r
+#include "MsgDebug.h"
 
 #include "msg.h"
 #include "msg_private.h"
 
 //Internel Struct
-typedef struct _MMS_DATA_S
+typedef struct
 {
        GList                   *pagelist;
        GList                   *regionlist;
@@ -37,24 +37,30 @@ typedef struct _MMS_DATA_S
        GList                   *metalist;
        MMS_SMIL_ROOTLAYOUT     rootlayout;
        MMS_APPID_INFO_S        msgAppId;
+       MMS_HEADER_DATA_S header;
+       MMS_MULTIPART_DATA_S smil;
+       GList *multipartlist;//MMS_MULTIPART_DATA_S
 } MMS_DATA_HIDDEN_S;
 
 typedef struct
 {
        MmsSmilMediaType        mediatype; /**< Indicates the SMIL media type. see enum MmsSmilMediaType */
 
-       char                    szSrc[MSG_FILEPATH_LEN_MAX];/**< Indicates the media source name */
-       char                    szFileName[MSG_FILENAME_LEN_MAX]; /**< Indicates the file name */
-       char                    szFilePath[MSG_FILEPATH_LEN_MAX]; /**< Indicates the file path */
-       char                    szContentID[MSG_MSG_ID_LEN+1]; /**< Indicates the content id */
-       char                    regionId[MAX_SMIL_REGION_ID]; /**< Indicates the region id */
-       char                    szAlt[MAX_SMIL_ALT_LEN]; /**< Indicates the alternative text to be displayed in failure case */
+       char                    szSrc[MSG_FILEPATH_LEN_MAX + 1];/**< Indicates the media source name */
+       char                    szFileName[MSG_FILENAME_LEN_MAX + 1]; /**< Indicates the file name */
+       char                    szFilePath[MSG_FILEPATH_LEN_MAX + 1]; /**< Indicates the file path */
+       char                    szContentID[MSG_MSG_ID_LEN + 1]; /**< Indicates the content id */
+       char                    regionId[MAX_SMIL_REGION_ID + 1]; /**< Indicates the region id */
+       char                    szAlt[MAX_SMIL_ALT_LEN + 1]; /**< Indicates the alternative text to be displayed in failure case */
        MsgDrmType              drmType; /**< Indicates the drm type. see enum MsgDrmType */
-       char                    szDrm2FullPath[MSG_FILEPATH_LEN_MAX];  /**< Indicates the fullpath of the DRM */
+       char                    szDrm2FullPath[MSG_FILEPATH_LEN_MAX + 1];  /**< Indicates the fullpath of the DRM */
        msg_struct_s *pText;
        msg_struct_s *pAVI;
+       char szContentType[MSG_MSG_ID_LEN + 1];
+       char szContentLocation[MSG_MSG_ID_LEN + 1];
 } MMS_MEDIA_HIDDEN_S;
 
+static void __msg_mms_data_struct_init(MMS_DATA_HIDDEN_S *pMmsDataHidden);
 static void __msg_mms_release_mms(msg_struct_s *mms_struct);
 static void __msg_mms_release_page(msg_struct_s *page_struct);
 static void __msg_mms_release_media(msg_struct_s *media_struct);
@@ -62,10 +68,32 @@ static void __msg_mms_release_region(msg_struct_s *region_struct);
 static void __msg_mms_release_attach(msg_struct_s *attach_struct);
 static void __msg_mms_release_transition(msg_struct_s *transition_struct);
 static void __msg_mms_release_meta(msg_struct_s *meta_struct);
-
+static void __msg_mms_release_multipart(msg_struct_s *multipart_struct);
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
+static void __removeLessGreaterMark(const char *szSrcID, char *szDest, int destSize)
+{
+       char szBuf[MSG_MSG_ID_LEN + 1] = {0, };
+       int cLen = strlen(szSrcID);
+
+       if (cLen == 0)
+               return;
+
+       if (cLen > 1 && szSrcID[0] == '<' && szSrcID[cLen - 1] == '>') {
+               strncpy(szBuf, &szSrcID[1], cLen - 2);
+               szBuf[cLen - 2] = '\0';
+       } else if (cLen > 1 && szSrcID[0] == '"' && szSrcID[cLen-1] == '"') {
+               strncpy(szBuf, &szSrcID[1], cLen - 2);
+               szBuf[cLen - 2] = '\0';
+       } else {
+               strncpy(szBuf, szSrcID, cLen);
+               szBuf[cLen] = '\0';
+       }
+
+       snprintf(szDest, destSize, "%s", szBuf);
+}
+
 static inline void *get_msg_struct_data(msg_struct_s *msg_struct)
 {
        if (msg_struct == NULL)
@@ -94,6 +122,7 @@ void *msg_mms_create_struct_data(int field)
        case MSG_STRUCT_MMS:
                data = (void *)new MMS_DATA_HIDDEN_S;
                bzero(data, sizeof(MMS_DATA_HIDDEN_S));
+               __msg_mms_data_struct_init((MMS_DATA_HIDDEN_S *)data);
                break;
        case MSG_STRUCT_MMS_PAGE:
                data = (void *)new MMS_PAGE_S;
@@ -134,6 +163,11 @@ void *msg_mms_create_struct_data(int field)
                data = (void *)new MmsSmilAVI;
                bzero(data, sizeof(MmsSmilAVI));
                break;
+       case MSG_STRUCT_MULTIPART_INFO:
+               data = new MMS_MULTIPART_DATA_S;
+               bzero(data, sizeof(MMS_MULTIPART_DATA_S));
+               MsgMmsInitMultipart((MMS_MULTIPART_DATA_S *)data);
+               break;
        }
 
        return data;
@@ -154,81 +188,120 @@ void msg_mms_list_item_free_func(gpointer data)
                __msg_mms_release_transition(msg_struct);
        } else if (msg_struct->type == MSG_STRUCT_MMS_META) {
                __msg_mms_release_meta(msg_struct);
+       } else if (msg_struct->type == MSG_STRUCT_MULTIPART_INFO) {
+               __msg_mms_release_multipart(msg_struct);
        }
 }
 
 void __msg_mms_release_page(msg_struct_s *page_struct)
 {
-       MMS_PAGE_S *page = (MMS_PAGE_S *)page_struct->data;
-       if (page->medialist) {
-                g_list_free_full(page->medialist, msg_mms_list_item_free_func);
-       }
+       if (page_struct) {
+               MMS_PAGE_S *page = (MMS_PAGE_S *)page_struct->data;
+
+               if (page) {
+                       if (page->medialist) {
+                                g_list_free_full(page->medialist, msg_mms_list_item_free_func);
+                       }
 
-       delete (MMS_PAGE_S *)page;
-       page_struct->data = NULL;
+                       delete (MMS_PAGE_S *)page;
+                       page_struct->data = NULL;
+               }
 
-       delete page_struct;
+               delete page_struct;
+       }
 }
 
 void __msg_mms_release_media(msg_struct_s *media_struct)
 {
-       MMS_MEDIA_HIDDEN_S *media = (MMS_MEDIA_HIDDEN_S *)media_struct->data;
+       if (media_struct) {
+               MMS_MEDIA_HIDDEN_S *media = (MMS_MEDIA_HIDDEN_S *)media_struct->data;
 
-       if (media->pText)
-               msg_mms_release_struct(&media->pText);
+               if (media) {
+                       if (media->pText)
+                               msg_mms_release_struct(&media->pText);
 
-       if (media->pAVI)
-               msg_mms_release_struct(&media->pAVI);
+                       if (media->pAVI)
+                               msg_mms_release_struct(&media->pAVI);
 
-       delete (MMS_MEDIA_HIDDEN_S *)media;
+                       delete (MMS_MEDIA_HIDDEN_S *)media;
 
-       media_struct->data = NULL;
+                       media_struct->data = NULL;
+               }
 
-       delete media_struct;
+               delete media_struct;
+       }
 }
 
 void __msg_mms_release_attach(msg_struct_s *attach_struct)
 {
-       MMS_ATTACH_S *attach = (MMS_ATTACH_S *)attach_struct->data;
+       if (attach_struct) {
+               MMS_ATTACH_S *attach = (MMS_ATTACH_S *)attach_struct->data;
 
-       delete (MMS_ATTACH_S *)attach;
+               if (attach)
+                       delete (MMS_ATTACH_S *)attach;
 
-       attach_struct->data = NULL;
+               attach_struct->data = NULL;
 
-       delete attach_struct;
+               delete attach_struct;
+       }
 }
 
 void __msg_mms_release_region(msg_struct_s *region_struct)
 {
-       MMS_SMIL_REGION *region = (MMS_SMIL_REGION *)region_struct->data;
+       if (region_struct) {
+               MMS_SMIL_REGION *region = (MMS_SMIL_REGION *)region_struct->data;
 
-       delete (MMS_SMIL_REGION *)region;
+               if (region)
+                       delete (MMS_SMIL_REGION *)region;
 
-       region_struct->data = NULL;
+               region_struct->data = NULL;
 
-       delete region_struct;
+               delete region_struct;
+       }
 }
 
 void __msg_mms_release_transition(msg_struct_s *transition_struct)
 {
-       MMS_SMIL_TRANSITION *transition = (MMS_SMIL_TRANSITION *)transition_struct->data;
+       if (transition_struct) {
+               MMS_SMIL_TRANSITION *transition = (MMS_SMIL_TRANSITION *)transition_struct->data;
 
-       delete (MMS_SMIL_TRANSITION *)transition;
+               if (transition)
+                       delete (MMS_SMIL_TRANSITION *)transition;
 
-       transition_struct->data = NULL;
+               transition_struct->data = NULL;
 
-       delete transition_struct;
+               delete transition_struct;
+       }
 }
 
 void __msg_mms_release_meta(msg_struct_s *meta_struct)
 {
-       MMS_SMIL_META *meta = (MMS_SMIL_META *)meta_struct->data;
+       if (meta_struct) {
+               MMS_SMIL_META *meta = (MMS_SMIL_META *)meta_struct->data;
 
-       delete (MMS_SMIL_META *)meta;
+               if (meta)
+                       delete (MMS_SMIL_META *)meta;
 
-       meta_struct->data = NULL;
+               meta_struct->data = NULL;
 
-       delete meta_struct;
+               delete meta_struct;
+       }
+}
+
+void __msg_mms_release_multipart(msg_struct_s *multipart_struct)
+{
+       if (multipart_struct) {
+               MMS_MULTIPART_DATA_S *multipart = (MMS_MULTIPART_DATA_S *)multipart_struct->data;
+
+               if (multipart) {
+                       g_free(multipart->pMultipartData); multipart->pMultipartData = NULL;
+                       delete (MMS_MULTIPART_DATA_S *)multipart;
+               }
+
+               multipart_struct->data = NULL;
+
+               delete multipart_struct;
+       }
 }
 
 void __msg_mms_release_mms(msg_struct_s *mms_struct)
@@ -260,6 +333,16 @@ void __msg_mms_release_mms(msg_struct_s *mms_struct)
                mms->metalist = NULL;
        }
 
+       if (mms->multipartlist) {
+               g_list_free_full(mms->multipartlist, msg_mms_list_item_free_func);
+               mms->multipartlist = NULL;
+       }
+
+       if (mms->smil.pMultipartData) {
+               g_free(mms->smil.pMultipartData);
+               mms->smil.pMultipartData = NULL;
+       }
+
        delete (MMS_DATA_HIDDEN_S *)mms;
 
        mms_struct->data = NULL;
@@ -303,16 +386,32 @@ int msg_mms_release_struct(msg_struct_s **msg_struct_data)
                *msg_struct_data = NULL;
                break;
        case MSG_STRUCT_MMS_SMIL_TEXT:
-               delete (MmsSmilText*)msg_struct->data;
+               if (msg_struct->data) {
+                       delete (MmsSmilText*)msg_struct->data;
+                       msg_struct->data = NULL;
+               }
                delete msg_struct;
                *msg_struct_data = NULL;
                break;
        case MSG_STRUCT_MMS_SMIL_AVI:
-               delete (MmsSmilAVI*)msg_struct->data;
+               if (msg_struct->data) {
+                       delete (MmsSmilAVI*)msg_struct->data;
+                       msg_struct->data = NULL;
+               }
+               delete msg_struct;
+               *msg_struct_data = NULL;
+               break;
+       case MSG_STRUCT_MULTIPART_INFO:
+       {
+               if (msg_struct->data) {
+                       delete (MMS_MULTIPART_DATA_S *)(msg_struct->data);
+                       msg_struct->data = NULL;
+               }
                delete msg_struct;
                *msg_struct_data = NULL;
                break;
        }
+       }
 
        return 0;
 }
@@ -325,12 +424,39 @@ int msg_mms_get_int_value(msg_struct_s *msg_struct, int field, int *value)
        case MSG_STRUCT_MMS:
        {
                MMS_DATA_HIDDEN_S *mms_data = (MMS_DATA_HIDDEN_S *)msg_struct->data;
-               if (field == MSG_MMS_ROOTLAYOUT_WIDTH_INT)
+               if (field == MSG_MMS_ROOTLAYOUT_WIDTH_INT) {
                        *value = mms_data->rootlayout.width.value;
-               else if (field == MSG_MMS_ROOTLAYOUT_HEIGHT_INT)
+               } else if (field == MSG_MMS_ROOTLAYOUT_HEIGHT_INT) {
                        *value = mms_data->rootlayout.height.value;
-               else if (field == MSG_MMS_ROOTLAYOUT_BGCOLOR_INT)
+               } else if (field == MSG_MMS_ROOTLAYOUT_BGCOLOR_INT) {
                        *value = mms_data->rootlayout.bgColor;
+               } else if (field == MSG_MMS_HEADER_DATE_INT) {
+                       *value = mms_data->header.date;
+               } else if (field == MSG_MMS_HEADER_DELIVERY_REPORT_INT) {
+                       *value = mms_data->header.bDeliveryReport;
+               } else if (field == MSG_MMS_HEADER_DELIVERY_TIME_INT) {
+                       *value = mms_data->header.delivery.time;
+               } else if (field == MSG_MMS_HEADER_EXPIRY_TIME_INT) {
+                       *value = mms_data->header.expiry.time;
+               } else if (field == MSG_MMS_HEADER_MESSAGE_CLASS_INT) {
+                       *value = mms_data->header.messageClass;
+               } else if (field == MSG_MMS_HEADER_MESSAGE_TYPE_INT) {
+                       *value = mms_data->header.messageType;
+               } else if (field == MSG_MMS_HEADER_VERSION_INT) {
+                       *value = mms_data->header.mmsVersion;
+               } else if (field == MSG_MMS_HEADER_SIZE_INT) {
+                       *value = mms_data->header.messageSize;
+               } else if (field == MSG_MMS_HEADER_PRIORITY_INT) {
+                       *value = mms_data->header.mmsPriority;
+               } else if (field == MSG_MMS_HEADER_READ_REPORT_INT) {
+                       *value = mms_data->header.bReadReport;
+               } else if (field == MSG_MMS_HEADER_HIDE_ADDRESS_INT) {
+                       *value = mms_data->header.bHideAddress;
+               } else if (field == MSG_MMS_HEADER_MMS_STATUS_INT) {
+                       *value = mms_data->header.mmsStatus;
+               } else if (field == MSG_MMS_HEADER_CONTENT_CLASS_INT) {
+                       *value = mms_data->header.contentClass;
+               }
                else
                        err = MSG_ERR_INVALID_PARAMETER;
        }
@@ -356,7 +482,7 @@ int msg_mms_get_int_value(msg_struct_s *msg_struct, int field, int *value)
        break;
        case MSG_STRUCT_MMS_MEDIA:
        {
-               MMS_MEDIA_S *mms_media_data = (MMS_MEDIA_S *)msg_struct->data;
+               MMS_MEDIA_HIDDEN_S *mms_media_data = (MMS_MEDIA_HIDDEN_S *)msg_struct->data;
                if (field == MSG_MMS_MEDIA_TYPE_INT)
                        *value = mms_media_data->mediatype;
                else if (field == MSG_MMS_MEDIA_DRM_TYPE_INT)
@@ -450,11 +576,15 @@ int msg_mms_get_int_value(msg_struct_s *msg_struct, int field, int *value)
                        err = MSG_ERR_INVALID_PARAMETER;
        }
        break;
+       case MSG_STRUCT_MULTIPART_INFO:
+               err = msg_multipart_get_int_value(msg_struct->data, field, value);
+       break;
+
        default :
                err = MSG_ERR_INVALID_PARAMETER;
                break;
        }
-       return MSG_SUCCESS;
+       return err;
 }
 
 int msg_mms_get_str_value(msg_struct_s *msg_struct, int field, char *value, int size)
@@ -462,23 +592,57 @@ int msg_mms_get_str_value(msg_struct_s *msg_struct, int field, char *value, int
        msg_error_t err = MSG_SUCCESS;
 
        switch(msg_struct->type) {
+       case MSG_STRUCT_MMS:
+       {
+               MMS_DATA_HIDDEN_S *mms_data = (MMS_DATA_HIDDEN_S *)msg_struct->data;
+               if (field == MSG_MMS_HEADER_CONTENT_LOCATION_STR) {// mms header
+                       strncpy(value, mms_data->header.contentLocation, size);
+               } else if (field == MSG_MMS_HEADER_CONTENT_TYPE_STR) {
+                       strncpy(value, mms_data->header.szContentType, size);
+               } else if (field == MSG_MMS_HEADER_FROM_STR) {
+                       strncpy(value, mms_data->header.szFrom, size);
+               } else if (field == MSG_MMS_HEADER_MESSAGE_ID_STR) {
+                       strncpy(value, mms_data->header.messageID, size);
+               } else if (field == MSG_MMS_HEADER_TR_ID_STR) {
+                       strncpy(value, mms_data->header.trID, size);
+
+               } else if (field == MSG_MMS_SMIL_MULTIPART_CONTENT_TYPE_STR) { // smil
+                       strncpy(value, mms_data->smil.szContentType, size);
+               } else if (field == MSG_MMS_SMIL_MULTIPART_NAME_STR) {
+                       strncpy(value, mms_data->smil.szFileName, size);
+               } else if (field == MSG_MMS_SMIL_MULTIPART_FILEPATH_STR) {
+                       strncpy(value, mms_data->smil.szFilePath, size);
+               } else if (field == MSG_MMS_SMIL_MULTIPART_CONTENT_ID_STR) {
+                       strncpy(value, mms_data->smil.szContentID, size);
+               } else if (field == MSG_MMS_SMIL_MULTIPART_CONTENT_LOCATION_STR) {
+                       strncpy(value, mms_data->smil.szContentLocation, size);
+               }
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
        case MSG_STRUCT_MMS_MEDIA:
        {
-               MMS_MEDIA_S *mms_media_data = (MMS_MEDIA_S *)msg_struct->data;
+               MMS_MEDIA_HIDDEN_S *mms_media_data = (MMS_MEDIA_HIDDEN_S *)msg_struct->data;
                if (field == MSG_MMS_MEDIA_SRC_STR)
                        strncpy(value, mms_media_data->szSrc, size);
                else if (field == MSG_MMS_MEDIA_FILENAME_STR)
                        strncpy(value, mms_media_data->szFileName, size);
                else if (field == MSG_MMS_MEDIA_FILEPATH_STR)
                        strncpy(value, mms_media_data->szFilePath, size);
-               else if (field == MSG_MMS_MEDIA_CONTENT_ID_STR)
-                       strncpy(value, mms_media_data->szContentID, size);
-               else if (field == MSG_MMS_MEDIA_REGION_ID_STR)
+               else if (field == MSG_MMS_MEDIA_CONTENT_ID_STR) {
+                       if (strlen(mms_media_data->szContentID) > 0)
+                               snprintf(value, size, "<%s>", mms_media_data->szContentID);
+               }else if (field == MSG_MMS_MEDIA_REGION_ID_STR)
                        strncpy(value, mms_media_data->regionId, size);
                else if (field == MSG_MMS_MEDIA_ALTERNATIVE_STR)
                        strncpy(value, mms_media_data->szAlt, size);
                else if (field == MSG_MMS_MEDIA_DRM_FULLPATH_STR)
                        strncpy(value, mms_media_data->szDrm2FullPath, size);
+               else if (field == MSG_MMS_MEDIA_CONTENT_LOCATION_STR)
+                       strncpy(value, mms_media_data->szContentLocation, size);
+               else if (field == MSG_MMS_MEDIA_CONTENT_TYPE_STR)
+                       strncpy(value, mms_media_data->szContentType, size);
                else
                        err = MSG_ERR_INVALID_PARAMETER;
        }
@@ -492,6 +656,8 @@ int msg_mms_get_str_value(msg_struct_s *msg_struct, int field, char *value, int
                        strncpy(value, mms_attach_data->szFilePath, size);
                else if (field == MSG_MMS_ATTACH_DRM_FULLPATH_STR)
                        strncpy(value, mms_attach_data->szDrm2FullPath, size);
+               else if (field == MSG_MMS_ATTACH_CONTENT_TYPE_STR)
+                       strncpy(value, mms_attach_data->szContentType, size);
                else
                        err = MSG_ERR_INVALID_PARAMETER;
        }
@@ -549,11 +715,15 @@ int msg_mms_get_str_value(msg_struct_s *msg_struct, int field, char *value, int
                        err = MSG_ERR_INVALID_PARAMETER;
        }
        break;
+       case MSG_STRUCT_MULTIPART_INFO:
+               err = msg_multipart_get_str_value(msg_struct->data, field, value, size);
+       break;
+
        default :
                        err = MSG_ERR_INVALID_PARAMETER;
                break;
        }
-       return MSG_SUCCESS;
+       return err;
 }
 
 int msg_mms_get_bool_value(msg_struct_s *msg_struct, int field, bool *value)
@@ -568,6 +738,8 @@ int msg_mms_get_bool_value(msg_struct_s *msg_struct, int field, bool *value)
                        *value = mms_data->rootlayout.width.bUnitPercent;
                else if (field == MSG_MMS_ROOTLAYOUT_HEIGHT_PERCENT_BOOL)
                        *value = mms_data->rootlayout.height.bUnitPercent;
+               else if (field == MSG_MMS_ROOTLAYOUT_BGCOLOR_BOOL)
+                       *value = mms_data->rootlayout.bBgColor;
                else
                        err = MSG_ERR_INVALID_PARAMETER;
        }
@@ -583,6 +755,8 @@ int msg_mms_get_bool_value(msg_struct_s *msg_struct, int field, bool *value)
                        *value = mms_region_data->width.bUnitPercent;
                else if (field == MSG_MMS_REGION_LENGTH_HEIGHT_PERCENT_BOOL)
                        *value = mms_region_data->height.bUnitPercent;
+               else if (field == MSG_MMS_REGION_BGCOLOR_BOOL)
+                       *value = mms_region_data->bBgColor;
                else
                        err = MSG_ERR_INVALID_PARAMETER;
        }
@@ -606,7 +780,7 @@ int msg_mms_get_bool_value(msg_struct_s *msg_struct, int field, bool *value)
                err = MSG_ERR_INVALID_PARAMETER;
                break;
        }
-       return MSG_SUCCESS;
+       return err;
 }
 
 int msg_mms_get_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s **value)
@@ -629,7 +803,7 @@ int msg_mms_get_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s
                err = MSG_ERR_INVALID_PARAMETER;
                break;
        }
-       return MSG_SUCCESS;
+       return err;
 }
 
 int msg_mms_get_list_handle(msg_struct_s *msg_struct, int field, msg_list_handle_t *value)
@@ -650,6 +824,8 @@ int msg_mms_get_list_handle(msg_struct_s *msg_struct, int field, msg_list_handle
                        *value = (msg_list_handle_t)mms_data->transitionlist;
                else if (field == MSG_MMS_META_LIST_HND)
                        *value = (msg_list_handle_t)mms_data->metalist;
+               else if (field == MSG_MMS_MULTIPART_LIST_HND)
+                       *value = (msg_list_handle_t)mms_data->multipartlist;
                else
                        err = MSG_ERR_INVALID_PARAMETER;
        }
@@ -667,7 +843,7 @@ int msg_mms_get_list_handle(msg_struct_s *msg_struct, int field, msg_list_handle
                err = MSG_ERR_INVALID_PARAMETER;
                break;
        }
-       return MSG_SUCCESS;
+       return err;
 }
 /*SET*/
 int msg_mms_set_int_value(msg_struct_s *msg_struct, int field, int value)
@@ -682,8 +858,36 @@ int msg_mms_set_int_value(msg_struct_s *msg_struct, int field, int value)
                        mms_data->rootlayout.width.value = value;
                else if (field == MSG_MMS_ROOTLAYOUT_HEIGHT_INT)
                        mms_data->rootlayout.height.value = value;
-               else if (field == MSG_MMS_ROOTLAYOUT_BGCOLOR_INT)
+               else if (field == MSG_MMS_ROOTLAYOUT_BGCOLOR_INT) {
+                       mms_data->rootlayout.bBgColor = true;
                        mms_data->rootlayout.bgColor = value;
+               } else if (field == MSG_MMS_HEADER_DATE_INT) {
+                       mms_data->header.date = value;
+               } else if (field == MSG_MMS_HEADER_DELIVERY_REPORT_INT) {
+                       mms_data->header.bDeliveryReport = (bool)value;
+               } else if (field == MSG_MMS_HEADER_DELIVERY_TIME_INT) {
+                       mms_data->header.delivery.time = value;
+               } else if (field == MSG_MMS_HEADER_EXPIRY_TIME_INT) {
+                       mms_data->header.expiry.time = value;
+               } else if (field == MSG_MMS_HEADER_MESSAGE_CLASS_INT) {
+                       mms_data->header.messageClass = value;
+               } else if (field == MSG_MMS_HEADER_MESSAGE_TYPE_INT) {
+                       mms_data->header.messageType = value;
+               } else if (field == MSG_MMS_HEADER_VERSION_INT) {
+                       mms_data->header.mmsVersion = value;
+               } else if (field == MSG_MMS_HEADER_SIZE_INT) {
+                       mms_data->header.messageSize = value;
+               } else if (field == MSG_MMS_HEADER_PRIORITY_INT) {
+                       mms_data->header.mmsPriority = value;
+               } else if (field == MSG_MMS_HEADER_READ_REPORT_INT) {
+                       mms_data->header.bReadReport = (bool)value;
+               } else if (field == MSG_MMS_HEADER_HIDE_ADDRESS_INT) {
+                       mms_data->header.bHideAddress = value;
+               } else if (field == MSG_MMS_HEADER_MMS_STATUS_INT) {
+                       mms_data->header.mmsStatus = value;
+               } else if (field == MSG_MMS_HEADER_CONTENT_CLASS_INT) {
+                       mms_data->header.contentClass = value;
+               }
                else
                        err = MSG_ERR_INVALID_PARAMETER;
        }
@@ -709,7 +913,7 @@ int msg_mms_set_int_value(msg_struct_s *msg_struct, int field, int value)
        break;
        case MSG_STRUCT_MMS_MEDIA:
        {
-               MMS_MEDIA_S *mms_media_data = (MMS_MEDIA_S *)msg_struct->data;
+               MMS_MEDIA_HIDDEN_S *mms_media_data = (MMS_MEDIA_HIDDEN_S *)msg_struct->data;
                if (field == MSG_MMS_MEDIA_TYPE_INT)
                        mms_media_data->mediatype = (MmsSmilMediaType)value;
                else if (field == MSG_MMS_MEDIA_DRM_TYPE_INT)
@@ -742,9 +946,10 @@ int msg_mms_set_int_value(msg_struct_s *msg_struct, int field, int value)
                        mms_region_data->width.value = value;
                else if (field == MSG_MMS_REGION_LENGTH_HEIGHT_INT)
                        mms_region_data->height.value = value;
-               else if (field == MSG_MMS_REGION_BGCOLOR_INT)
+               else if (field == MSG_MMS_REGION_BGCOLOR_INT) {
+                       mms_region_data->bBgColor = true;
                        mms_region_data->bgColor = value;
-               else if (field == MSG_MMS_REGION_FIT_TYPE_INT)
+               else if (field == MSG_MMS_REGION_FIT_TYPE_INT)
                        mms_region_data->fit = (REGION_FIT_TYPE_T)value;
                else
                        err = MSG_ERR_INVALID_PARAMETER;
@@ -807,7 +1012,7 @@ int msg_mms_set_int_value(msg_struct_s *msg_struct, int field, int value)
                err = MSG_ERR_INVALID_PARAMETER;
                break;
        }
-       return MSG_SUCCESS;
+       return err;
 }
 
 int msg_mms_set_str_value(msg_struct_s *msg_struct, int field, char *value, int size)
@@ -817,36 +1022,40 @@ int msg_mms_set_str_value(msg_struct_s *msg_struct, int field, char *value, int
        switch(msg_struct->type) {
        case MSG_STRUCT_MMS_MEDIA:
        {
-               MMS_MEDIA_S *mms_media_data = (MMS_MEDIA_S *)msg_struct->data;
+               MMS_MEDIA_HIDDEN_S *mms_media_data = (MMS_MEDIA_HIDDEN_S *)msg_struct->data;
                if (field == MSG_MMS_MEDIA_SRC_STR)
                        strncpy(mms_media_data->szSrc, value, MSG_FILEPATH_LEN_MAX);
                else if (field == MSG_MMS_MEDIA_FILENAME_STR) {
                        strncpy(mms_media_data->szFileName, value, MSG_FILEPATH_LEN_MAX);
                } else if (field == MSG_MMS_MEDIA_FILEPATH_STR) {
                        char *filename = NULL;
-                       if (value != NULL) {\r
-                               MSG_DEBUG("media file path = %s", value);\r
-                               strncpy(mms_media_data->szFilePath, value, MSG_FILEPATH_LEN_MAX);\r
-                               filename = strrchr(value, '/');\r
-                               if (filename != NULL) {\r
-                                       strncpy(mms_media_data->szFileName, filename + 1, MSG_FILENAME_LEN_MAX-1);\r
-                                       strncpy(mms_media_data->szContentID, filename + 1, MSG_MSG_ID_LEN);\r
-                               } else {\r
-                                       strncpy(mms_media_data->szFileName, value + 1, MSG_FILENAME_LEN_MAX-1);\r
-                                       strncpy(mms_media_data->szContentID, value + 1, MSG_MSG_ID_LEN);\r
-                               }\r
-                       } else {\r
-                               MSG_DEBUG("media file path is NULL");\r
-                               err = MSG_ERR_INVALID_PARAMETER;\r
-                       }\r
+                       if (value != NULL) {
+                               MSG_SEC_DEBUG("media file path = %s", value);
+                               strncpy(mms_media_data->szFilePath, value, MSG_FILEPATH_LEN_MAX);
+                               filename = strrchr(value, '/');
+                               if (filename != NULL) {
+                                       strncpy(mms_media_data->szFileName, filename + 1, MSG_FILENAME_LEN_MAX);
+                                       strncpy(mms_media_data->szContentID, filename + 1, MSG_MSG_ID_LEN);
+                               } else {
+                                       strncpy(mms_media_data->szFileName, value + 1, MSG_FILENAME_LEN_MAX);
+                                       strncpy(mms_media_data->szContentID, value + 1, MSG_MSG_ID_LEN);
+                               }
+                       } else {
+                               MSG_DEBUG("media file path is NULL");
+                               err = MSG_ERR_INVALID_PARAMETER;
+                       }
                } else if (field == MSG_MMS_MEDIA_CONTENT_ID_STR)
-                       strncpy(mms_media_data->szContentID, value, MSG_MSG_ID_LEN);
-               else if (field == MSG_MMS_MEDIA_REGION_ID_STR)
+                       __removeLessGreaterMark(value, mms_media_data->szContentID, MSG_MSG_ID_LEN);
+                else if (field == MSG_MMS_MEDIA_REGION_ID_STR)
                        strncpy(mms_media_data->regionId, value, MAX_SMIL_REGION_ID);
                else if (field == MSG_MMS_MEDIA_ALTERNATIVE_STR)
                        strncpy(mms_media_data->szAlt, value, MAX_SMIL_ALT_LEN);
                else if (field == MSG_MMS_MEDIA_DRM_FULLPATH_STR)
                        strncpy(mms_media_data->szDrm2FullPath, value, MSG_FILEPATH_LEN_MAX);
+               else if (field == MSG_MMS_MEDIA_CONTENT_LOCATION_STR)
+                       strncpy(mms_media_data->szContentLocation, value, MSG_FILEPATH_LEN_MAX);
+               else if (field == MSG_MMS_MEDIA_CONTENT_TYPE_STR)
+                       strncpy(mms_media_data->szContentType, value, MSG_FILEPATH_LEN_MAX);
                else
                        err = MSG_ERR_INVALID_PARAMETER;
        }
@@ -854,34 +1063,37 @@ int msg_mms_set_str_value(msg_struct_s *msg_struct, int field, char *value, int
        case MSG_STRUCT_MMS_ATTACH:
        {
                MMS_ATTACH_S *mms_attach_data = (MMS_ATTACH_S *)msg_struct->data;
-               if (field == MSG_MMS_ATTACH_FILENAME_STR)
+               if (field == MSG_MMS_ATTACH_FILENAME_STR) {
                        strncpy(mms_attach_data->szFileName, value, MSG_FILENAME_LEN_MAX);
-               else if (field == MSG_MMS_ATTACH_FILEPATH_STR) {
+               else if (field == MSG_MMS_ATTACH_FILEPATH_STR) {
                        char *filename = NULL;
                        char *filepath = value;
 
-                       if (filepath != NULL) {\r
-                               MSG_DEBUG("attach file path = %s", filepath);\r
-                               mms_attach_data->mediatype = MIME_UNKNOWN;\r
-                               mms_attach_data->fileSize = -1;\r
-
-                               strncpy(mms_attach_data->szFilePath, filepath, MSG_FILEPATH_LEN_MAX-1);\r
-\r
-                               filename = strrchr(filepath, '/');\r
-                               if (filename != NULL) {\r
-                                       strncpy(mms_attach_data->szFileName, filename + 1, MSG_FILENAME_LEN_MAX-1);\r
-                               } else {\r
-                                       strncpy(mms_attach_data->szFileName, filepath, MSG_FILENAME_LEN_MAX-1);\r
-                               }\r
-\r
-                       } else {\r
-                               MSG_DEBUG("attach file path is NULL");\r
-                               err = MSG_ERR_INVALID_PARAMETER;\r
-                       }\r
-               } else if (field == MSG_MMS_ATTACH_DRM_FULLPATH_STR)
+                       if (filepath != NULL) {
+                               MSG_SEC_DEBUG("attach file path = %s", filepath);
+                               mms_attach_data->mediatype = MIME_UNKNOWN;
+                               mms_attach_data->fileSize = -1;
+
+                               strncpy(mms_attach_data->szFilePath, filepath, MSG_FILEPATH_LEN_MAX);
+
+                               filename = strrchr(filepath, '/');
+                               if (filename != NULL) {
+                                       strncpy(mms_attach_data->szFileName, filename + 1, MSG_FILENAME_LEN_MAX);
+                               } else {
+                                       strncpy(mms_attach_data->szFileName, filepath, MSG_FILENAME_LEN_MAX);
+                               }
+
+                       } else {
+                               MSG_DEBUG("attach file path is NULL");
+                               err = MSG_ERR_INVALID_PARAMETER;
+                       }
+               } else if (field == MSG_MMS_ATTACH_DRM_FULLPATH_STR) {
                        strncpy(mms_attach_data->szDrm2FullPath, value, MSG_FILEPATH_LEN_MAX);
-               else
+               } else if (field == MSG_MMS_ATTACH_CONTENT_TYPE_STR) {
+                       strncpy(mms_attach_data->szContentType, value, MSG_FILEPATH_LEN_MAX);
+               } else {
                        err = MSG_ERR_INVALID_PARAMETER;
+               }
        }
        break;
        case MSG_STRUCT_MMS_REGION:
@@ -908,9 +1120,9 @@ int msg_mms_set_str_value(msg_struct_s *msg_struct, int field, char *value, int
                if (field == MSG_MMS_META_ID_STR)
                        strncpy(mms_meta_data->szID, value, MAX_SMIL_META_ID);
                else if (field == MSG_MMS_META_NAME_STR)
-                       strncpy(mms_meta_data->szID, value, MAX_SMIL_META_NAME);
+                       strncpy(mms_meta_data->szName, value, MAX_SMIL_META_NAME);
                else if (field == MSG_MMS_META_CONTENT_STR)
-                       strncpy(mms_meta_data->szID, value, MAX_SMIL_META_CONTENT);
+                       strncpy(mms_meta_data->szContent, value, MAX_SMIL_META_CONTENT);
                else
                        err = MSG_ERR_INVALID_PARAMETER;
        }
@@ -937,11 +1149,44 @@ int msg_mms_set_str_value(msg_struct_s *msg_struct, int field, char *value, int
                        err = MSG_ERR_INVALID_PARAMETER;
        }
        break;
+       case MSG_STRUCT_MMS:
+       {
+               MMS_DATA_HIDDEN_S *mms_data = (MMS_DATA_HIDDEN_S *)msg_struct->data;
+               if (field == MSG_MMS_HEADER_CONTENT_LOCATION_STR) {// mms header
+                       strncpy(mms_data->header.contentLocation, value, sizeof(mms_data->header.contentLocation) - 1 );
+               } else if (field == MSG_MMS_HEADER_CONTENT_TYPE_STR) {
+                       strncpy(mms_data->header.szContentType, value, sizeof(mms_data->header.szContentType) - 1 );
+               } else if (field == MSG_MMS_HEADER_FROM_STR) {
+                       strncpy(mms_data->header.szFrom, value, sizeof(mms_data->header.szFrom) - 1 );
+               } else if (field == MSG_MMS_HEADER_MESSAGE_ID_STR) {
+                       strncpy(mms_data->header.messageID, value, sizeof(mms_data->header.messageID) - 1 );
+               } else if (field == MSG_MMS_HEADER_TR_ID_STR) {
+                       strncpy(mms_data->header.trID, value, sizeof(mms_data->header.trID) - 1 );
+
+               } else if (field == MSG_MMS_SMIL_MULTIPART_CONTENT_TYPE_STR) { // smil
+                       strncpy(mms_data->smil.szContentType, value, sizeof(mms_data->smil.szContentType) - 1 );
+               } else if (field == MSG_MMS_SMIL_MULTIPART_NAME_STR) {
+                       strncpy(mms_data->smil.szFileName, value, sizeof(mms_data->smil.szFileName) - 1 );
+               } else if (field == MSG_MMS_SMIL_MULTIPART_FILEPATH_STR) {
+                       strncpy(mms_data->smil.szFilePath, value, sizeof(mms_data->smil.szFilePath) - 1 );
+               } else if (field == MSG_MMS_SMIL_MULTIPART_CONTENT_ID_STR) {
+                       strncpy(mms_data->smil.szContentID, value, sizeof(mms_data->smil.szContentID) - 1 );
+               } else if (field == MSG_MMS_SMIL_MULTIPART_CONTENT_LOCATION_STR) {
+                       strncpy(mms_data->smil.szContentLocation, value, sizeof(mms_data->smil.szContentLocation) - 1 );
+               }
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MULTIPART_INFO:
+               err = msg_multipart_set_str_value(msg_struct->data, field, value, size);
+       break;
+
        default :
                        err = MSG_ERR_INVALID_PARAMETER;
                break;
        }
-       return MSG_SUCCESS;
+       return err;
 }
 
 int msg_mms_set_bool_value(msg_struct_s *msg_struct, int field, bool value)
@@ -994,7 +1239,7 @@ int msg_mms_set_bool_value(msg_struct_s *msg_struct, int field, bool value)
                err = MSG_ERR_INVALID_PARAMETER;
                break;
        }
-       return MSG_SUCCESS;
+       return err;
 }
 
 int msg_mms_set_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s *value)
@@ -1018,7 +1263,7 @@ int msg_mms_set_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s
                err = MSG_ERR_INVALID_PARAMETER;
                break;
        }
-       return MSG_SUCCESS;
+       return err;
 }
 
 int msg_mms_set_list_handle(msg_struct_s *msg_struct, int field, msg_list_handle_t value)
@@ -1056,16 +1301,15 @@ int msg_mms_set_list_handle(msg_struct_s *msg_struct, int field, msg_list_handle
                err = MSG_ERR_INVALID_PARAMETER;
                break;
        }
-       return MSG_SUCCESS;
+       return err;
 }
 
-EXPORT_API int msg_mms_add_item(msg_struct_t msg_struct_handle, int field, msg_struct_t *item)
+int msg_mms_list_append(msg_struct_t msg_struct_handle, int field, msg_struct_t *item)
 {
        msg_error_t err = MSG_SUCCESS;
        msg_struct_s *msg_struct = (msg_struct_s *)msg_struct_handle;
 
        msg_struct_s *msg_struct_item = NULL;
-       void *data = NULL;
        switch(msg_struct->type) {
        case MSG_STRUCT_MMS:
        {
@@ -1073,25 +1317,29 @@ EXPORT_API int msg_mms_add_item(msg_struct_t msg_struct_handle, int field, msg_s
                MMS_DATA_HIDDEN_S *mms_data = (MMS_DATA_HIDDEN_S *)msg_struct->data;
 
                if (field == MSG_STRUCT_MMS_PAGE) {
-                       msg_struct_item = msg_mms_create_struct(field);
+                       msg_struct_item = msg_mms_create_struct(MSG_STRUCT_MMS_PAGE);
                        mms_data->pagelist = g_list_append(mms_data->pagelist, msg_struct_item);
                        *item = (msg_struct_t)msg_struct_item;
                } else if (field == MSG_STRUCT_MMS_REGION) {
-                       msg_struct_item = msg_mms_create_struct(field);
+                       msg_struct_item = msg_mms_create_struct(MSG_STRUCT_MMS_REGION);
                        mms_data->regionlist = g_list_append(mms_data->regionlist, msg_struct_item);
                        *item = (msg_struct_t)msg_struct_item;
                } else if (field == MSG_STRUCT_MMS_ATTACH) {
-                       msg_struct_item = msg_mms_create_struct(field);
+                       msg_struct_item = msg_mms_create_struct(MSG_STRUCT_MMS_ATTACH);
                        mms_data->attachlist = g_list_append(mms_data->attachlist, msg_struct_item);
                        *item = (msg_struct_t)msg_struct_item;
                } else if (field == MSG_STRUCT_MMS_TRANSITION) {
-                       msg_struct_item = msg_mms_create_struct(field);
+                       msg_struct_item = msg_mms_create_struct(MSG_STRUCT_MMS_TRANSITION);
                        mms_data->transitionlist = g_list_append(mms_data->transitionlist, msg_struct_item);
                        *item = (msg_struct_t)msg_struct_item;
                } else if (field == MSG_STRUCT_MMS_META) {
-                       msg_struct_item = msg_mms_create_struct(field);
+                       msg_struct_item = msg_mms_create_struct(MSG_STRUCT_MMS_META);
                        mms_data->metalist = g_list_append(mms_data->metalist, msg_struct_item);
                        *item = (msg_struct_t)msg_struct_item;
+               } else if (field == MSG_MMS_MULTIPART_LIST_HND) {
+                       msg_struct_item = (msg_struct_s *)msg_create_struct(MSG_STRUCT_MULTIPART_INFO);
+                       mms_data->multipartlist = g_list_append(mms_data->multipartlist, msg_struct_item);
+                       *item = (msg_struct_t)msg_struct_item;
                } else {
                        err = MSG_ERR_INVALID_PARAMETER;
                }
@@ -1128,11 +1376,12 @@ void convert_to_media_data(const msg_struct_s *pSrc, MMS_MEDIA_S *pDest)
        memcpy(dst_media->szSrc, src_media->szSrc, MSG_FILEPATH_LEN_MAX);
        memcpy(dst_media->szFileName, src_media->szFileName, MSG_FILEPATH_LEN_MAX);
        memcpy(dst_media->szFilePath, src_media->szFilePath, MSG_FILEPATH_LEN_MAX);
-       memcpy(dst_media->szContentID, src_media->szContentID, MSG_MSG_ID_LEN+1);
+       memcpy(dst_media->szContentID, src_media->szContentID, MSG_MSG_ID_LEN);
        memcpy(dst_media->regionId, src_media->regionId, MAX_SMIL_REGION_ID);
        memcpy(dst_media->szAlt, src_media->szAlt, MAX_SMIL_ALT_LEN);
-
        memcpy(dst_media->szDrm2FullPath, src_media->szDrm2FullPath, MSG_FILEPATH_LEN_MAX);
+       memcpy(dst_media->szContentType, src_media->szContentType, MSG_MSG_ID_LEN);
+       memcpy(dst_media->szContentLocation, src_media->szContentLocation, MSG_MSG_ID_LEN);
        dst_media->drmType = src_media->drmType;
 
        if (src_media->mediatype == MMS_SMIL_MEDIA_TEXT) {
@@ -1155,11 +1404,12 @@ void convert_from_media_data(const MMS_MEDIA_S *pSrc, msg_struct_s *pDest)
        memcpy(dst_media->szSrc, src_media->szSrc, MSG_FILEPATH_LEN_MAX);
        memcpy(dst_media->szFileName, src_media->szFileName, MSG_FILEPATH_LEN_MAX);
        memcpy(dst_media->szFilePath, src_media->szFilePath, MSG_FILEPATH_LEN_MAX);
-       memcpy(dst_media->szContentID, src_media->szContentID, MSG_MSG_ID_LEN+1);
+       memcpy(dst_media->szContentID, src_media->szContentID, MSG_MSG_ID_LEN);
        memcpy(dst_media->regionId, src_media->regionId, MAX_SMIL_REGION_ID);
        memcpy(dst_media->szAlt, src_media->szAlt, MAX_SMIL_ALT_LEN);
-
        memcpy(dst_media->szDrm2FullPath, src_media->szDrm2FullPath, MSG_FILEPATH_LEN_MAX);
+       memcpy(dst_media->szContentType, src_media->szContentType, MSG_MSG_ID_LEN);
+       memcpy(dst_media->szContentLocation, src_media->szContentLocation, MSG_MSG_ID_LEN);
        dst_media->drmType = src_media->drmType;
 
        if (src_media->mediatype == MMS_SMIL_MEDIA_TEXT) {
@@ -1182,17 +1432,104 @@ void convert_to_mmsdata(const msg_struct_s *pSrc, MMS_MESSAGE_DATA_S *pDest)
 
        for (i = 0; i < pDest->pageCnt; i++) {
                MMS_PAGE_S *page = (MMS_PAGE_S *)calloc(1, sizeof(MMS_PAGE_S));
-               MMS_PAGE_S *src_page = (MMS_PAGE_S *)get_msg_struct_data((msg_struct_s *)g_list_nth_data(pSrcMms->pagelist, i));
+               if (page) {
+                       MMS_PAGE_S *src_page = (MMS_PAGE_S *)get_msg_struct_data((msg_struct_s *)g_list_nth_data(pSrcMms->pagelist, i));
+                       page->mediaCnt = g_list_length(src_page->medialist);
+
+                       for (j = 0; j < page->mediaCnt; j++)
+                       {
+                               MMS_MEDIA_S *dst_media = (MMS_MEDIA_S *)calloc(1, sizeof(MMS_MEDIA_S));
+                               msg_struct_s *src_media_s = (msg_struct_s *)g_list_nth_data(src_page->medialist, j);
+
+                               if (dst_media)
+                                       convert_to_media_data(src_media_s, dst_media);
+
+                               page->medialist = g_list_append(page->medialist, dst_media);
+                       }
+
+                       page->nDur = src_page->nDur;
+                       page->nBegin = src_page->nBegin;
+                       page->nEnd = src_page->nEnd;
+                       page->nMin = src_page->nMin;
+                       page->nMax = src_page->nMax;
+                       page->nRepeat = src_page->nRepeat;
+
+                       pDest->pagelist = g_list_append(pDest->pagelist, page);
+               }
+       }
+
+       pDest->regionCnt = g_list_length(pSrcMms->regionlist);
+
+       for (i = 0; i < pDest->regionCnt; i++) {
+               MMS_SMIL_REGION *region = (MMS_SMIL_REGION *)calloc(1, sizeof(MMS_SMIL_REGION));
+               if (region) {
+                       MMS_SMIL_REGION *src_region = (MMS_SMIL_REGION *)get_msg_struct_data((msg_struct_s *)g_list_nth_data(pSrcMms->regionlist, i));
+                       memcpy(region, src_region, sizeof(MMS_SMIL_REGION));
+                       pDest->regionlist = g_list_append(pDest->regionlist, region);
+               }
+       }
+
+       pDest->attachCnt = g_list_length(pSrcMms->attachlist);
+
+       for (i = 0; i < pDest->attachCnt; i++) {
+               MMS_ATTACH_S *attach = (MMS_ATTACH_S *)calloc(1, sizeof(MMS_ATTACH_S));
+               if (attach) {
+                       MMS_ATTACH_S *src_attach = (MMS_ATTACH_S *)get_msg_struct_data((msg_struct_s *)g_list_nth_data(pSrcMms->attachlist, i));
+                       memcpy(attach, src_attach, sizeof(MMS_ATTACH_S));
+                       pDest->attachlist = g_list_append(pDest->attachlist, attach);
+               }
+       }
+
+       pDest->transitionCnt = g_list_length(pSrcMms->transitionlist);
+
+       for (i = 0; i < pDest->transitionCnt; i++) {
+               MMS_SMIL_TRANSITION *transition = (MMS_SMIL_TRANSITION *)calloc(1, sizeof(MMS_SMIL_TRANSITION));
+               if (transition) {
+                       MMS_SMIL_TRANSITION *src_transition = (MMS_SMIL_TRANSITION *)get_msg_struct_data((msg_struct_s *)g_list_nth_data(pSrcMms->transitionlist, i));
+                       memcpy(transition, src_transition, sizeof(MMS_SMIL_TRANSITION));
+                       pDest->transitionlist = g_list_append(pDest->transitionlist, transition);
+               }
+       }
+
+       pDest->metaCnt = g_list_length(pSrcMms->metalist);
+
+       for (i = 0; i < pDest->metaCnt; i++) {
+               MMS_SMIL_META *meta = (MMS_SMIL_META *)calloc(1, sizeof(MMS_SMIL_META));
+               if (meta) {
+                       MMS_SMIL_META *src_meta = (MMS_SMIL_META *)get_msg_struct_data((msg_struct_s *)g_list_nth_data(pSrcMms->metalist, i));
+                       memcpy(meta, src_meta, sizeof(MMS_SMIL_META));
+                       pDest->metalist = g_list_append(pDest->metalist, meta);
+               }
+       }
+
+       memcpy(&pDest->rootlayout, &pSrcMms->rootlayout, sizeof(MMS_SMIL_ROOTLAYOUT));
+
+       memcpy(&pDest->msgAppId, &pSrcMms->msgAppId, sizeof(MMS_APPID_INFO_S));
+       memcpy(&pDest->header, &pSrcMms->header, sizeof(MMS_HEADER_DATA_S));
+       memcpy(&pDest->smil, &pSrcMms->smil, sizeof(MMS_MULTIPART_DATA_S));
+}
+
+void convert_from_mmsdata(const MMS_MESSAGE_DATA_S *pSrc, msg_struct_s *pDest)
+{
+       int i, j;
+       MMS_DATA_HIDDEN_S *pDestMms = (MMS_DATA_HIDDEN_S *)pDest->data;
+
+       for (i = 0; i < pSrc->pageCnt; i++) {
+               msg_struct_s *page_struct = msg_mms_create_struct(MSG_STRUCT_MMS_PAGE);
+               MMS_PAGE_S *page = (MMS_PAGE_S *)page_struct->data;
+
+               MMS_PAGE_S *src_page = (MMS_PAGE_S *)g_list_nth_data(pSrc->pagelist, i);
                page->mediaCnt = g_list_length(src_page->medialist);
 
                for (j = 0; j < page->mediaCnt; j++)
                {
-                       MMS_MEDIA_S *dst_media = (MMS_MEDIA_S *)calloc(1, sizeof(MMS_MEDIA_S));
-                       msg_struct_s *src_media_s = (msg_struct_s *)g_list_nth_data(src_page->medialist, j);
+                       msg_struct_s *dst_media_s = msg_mms_create_struct(MSG_STRUCT_MMS_MEDIA);
 
-                       convert_to_media_data(src_media_s, dst_media);
+                       MMS_MEDIA_S *src_media = (MMS_MEDIA_S *)g_list_nth_data(src_page->medialist, j);
 
-                       page->medialist = g_list_append(page->medialist, dst_media);
+                       convert_from_media_data(src_media, dst_media_s);
+
+                       page->medialist = g_list_append(page->medialist, dst_media_s);
                }
 
                page->nDur = src_page->nDur;
@@ -1202,7 +1539,85 @@ void convert_to_mmsdata(const msg_struct_s *pSrc, MMS_MESSAGE_DATA_S *pDest)
                page->nMax = src_page->nMax;
                page->nRepeat = src_page->nRepeat;
 
-               pDest->pagelist = g_list_append(pDest->pagelist, page);
+               pDestMms->pagelist = g_list_append(pDestMms->pagelist, page_struct);
+       }
+
+       for (i = 0; i < pSrc->regionCnt; i++) {
+               msg_struct_s *region_struct = msg_mms_create_struct(MSG_STRUCT_MMS_REGION);
+               MMS_SMIL_REGION *region = (MMS_SMIL_REGION *)region_struct->data;
+               MMS_SMIL_REGION *src_region = (MMS_SMIL_REGION *)g_list_nth_data(pSrc->regionlist, i);
+               memcpy(region, src_region, sizeof(MMS_SMIL_REGION));
+               pDestMms->regionlist = g_list_append(pDestMms->regionlist, region_struct);
+       }
+
+       for (i = 0; i < pSrc->attachCnt; i++) {
+               msg_struct_s *attach_struct = msg_mms_create_struct(MSG_STRUCT_MMS_ATTACH);
+               MMS_ATTACH_S *attach = (MMS_ATTACH_S *)attach_struct->data;
+               MMS_ATTACH_S *src_attach = (MMS_ATTACH_S *)g_list_nth_data(pSrc->attachlist, i);
+               memcpy(attach, src_attach, sizeof(MMS_ATTACH_S));
+               pDestMms->attachlist = g_list_append(pDestMms->attachlist, attach_struct);
+       }
+
+       for (i = 0; i < pSrc->transitionCnt; i++) {
+               msg_struct_s *transition_struct = msg_mms_create_struct(MSG_STRUCT_MMS_TRANSITION);
+               MMS_SMIL_TRANSITION *transition = (MMS_SMIL_TRANSITION *)transition_struct->data;
+               MMS_SMIL_TRANSITION *src_transition = (MMS_SMIL_TRANSITION *)g_list_nth_data(pSrc->transitionlist, i);
+               memcpy(transition, src_transition, sizeof(MMS_SMIL_TRANSITION));
+               pDestMms->transitionlist = g_list_append(pDestMms->transitionlist, transition_struct);
+       }
+
+       for (i = 0; i < pSrc->metaCnt; i++) {
+               msg_struct_s *meta_struct = msg_mms_create_struct(MSG_STRUCT_MMS_META);
+               MMS_SMIL_META *meta = (MMS_SMIL_META *)meta_struct->data;
+               MMS_SMIL_META *src_meta = (MMS_SMIL_META *)g_list_nth_data(pSrc->metalist, i);
+
+               memcpy(meta, src_meta, sizeof(MMS_SMIL_META));
+               pDestMms->metalist = g_list_append(pDestMms->metalist, meta_struct);
+       }
+
+       memcpy(&pDestMms->rootlayout, &pSrc->rootlayout, sizeof(MMS_SMIL_ROOTLAYOUT));
+
+       memcpy(&pDestMms->msgAppId, &pSrc->msgAppId, sizeof(MMS_APPID_INFO_S));
+
+       memcpy(&pDestMms->header, &pSrc->header, sizeof(MMS_HEADER_DATA_S));
+       memcpy(&pDestMms->smil, &pSrc->smil, sizeof(MMS_MULTIPART_DATA_S));
+
+}
+
+void convert_to_mmsdata2(MMS_DATA_HIDDEN_S *pSrcMms, MMS_MESSAGE_DATA_S *pDest)
+{
+       int i, j;
+       //MMS_DATA_HIDDEN_S *pSrcMms = (MMS_DATA_HIDDEN_S *)pSrc->data;
+
+       pDest->pageCnt = g_list_length(pSrcMms->pagelist);
+
+       for (i = 0; i < pDest->pageCnt; i++) {
+               MMS_PAGE_S *page = (MMS_PAGE_S *)calloc(1, sizeof(MMS_PAGE_S));
+               MMS_PAGE_S *src_page = (MMS_PAGE_S *)get_msg_struct_data((msg_struct_s *)g_list_nth_data(pSrcMms->pagelist, i));
+               if (page) {
+                       page->mediaCnt = g_list_length(src_page->medialist);
+
+                       for (j = 0; j < page->mediaCnt; j++)
+                       {
+                               MMS_MEDIA_S *dst_media = (MMS_MEDIA_S *)calloc(1, sizeof(MMS_MEDIA_S));
+                               msg_struct_s *src_media_s = (msg_struct_s *)g_list_nth_data(src_page->medialist, j);
+
+                               if (dst_media) {
+                                       convert_to_media_data(src_media_s, dst_media);
+
+                                       page->medialist = g_list_append(page->medialist, dst_media);
+                               }
+                       }
+
+                       page->nDur = src_page->nDur;
+                       page->nBegin = src_page->nBegin;
+                       page->nEnd = src_page->nEnd;
+                       page->nMin = src_page->nMin;
+                       page->nMax = src_page->nMax;
+                       page->nRepeat = src_page->nRepeat;
+
+                       pDest->pagelist = g_list_append(pDest->pagelist, page);
+               }
        }
 
        pDest->regionCnt = g_list_length(pSrcMms->regionlist);
@@ -1210,8 +1625,10 @@ void convert_to_mmsdata(const msg_struct_s *pSrc, MMS_MESSAGE_DATA_S *pDest)
        for (i = 0; i < pDest->regionCnt; i++) {
                MMS_SMIL_REGION *region = (MMS_SMIL_REGION *)calloc(1, sizeof(MMS_SMIL_REGION));
                MMS_SMIL_REGION *src_region = (MMS_SMIL_REGION *)get_msg_struct_data((msg_struct_s *)g_list_nth_data(pSrcMms->regionlist, i));
-               memcpy(region, src_region, sizeof(MMS_SMIL_REGION));
-               pDest->regionlist = g_list_append(pDest->regionlist, region);
+               if (region) {
+                       memcpy(region, src_region, sizeof(MMS_SMIL_REGION));
+                       pDest->regionlist = g_list_append(pDest->regionlist, region);
+               }
        }
 
        pDest->attachCnt = g_list_length(pSrcMms->attachlist);
@@ -1219,8 +1636,10 @@ void convert_to_mmsdata(const msg_struct_s *pSrc, MMS_MESSAGE_DATA_S *pDest)
        for (i = 0; i < pDest->attachCnt; i++) {
                MMS_ATTACH_S *attach = (MMS_ATTACH_S *)calloc(1, sizeof(MMS_ATTACH_S));
                MMS_ATTACH_S *src_attach = (MMS_ATTACH_S *)get_msg_struct_data((msg_struct_s *)g_list_nth_data(pSrcMms->attachlist, i));
-               memcpy(attach, src_attach, sizeof(MMS_ATTACH_S));
-               pDest->attachlist = g_list_append(pDest->attachlist, attach);
+               if (attach) {
+                       memcpy(attach, src_attach, sizeof(MMS_ATTACH_S));
+                       pDest->attachlist = g_list_append(pDest->attachlist, attach);
+               }
        }
 
        pDest->transitionCnt = g_list_length(pSrcMms->transitionlist);
@@ -1228,8 +1647,10 @@ void convert_to_mmsdata(const msg_struct_s *pSrc, MMS_MESSAGE_DATA_S *pDest)
        for (i = 0; i < pDest->transitionCnt; i++) {
                MMS_SMIL_TRANSITION *transition = (MMS_SMIL_TRANSITION *)calloc(1, sizeof(MMS_SMIL_TRANSITION));
                MMS_SMIL_TRANSITION *src_transition = (MMS_SMIL_TRANSITION *)get_msg_struct_data((msg_struct_s *)g_list_nth_data(pSrcMms->transitionlist, i));
-               memcpy(transition, src_transition, sizeof(MMS_SMIL_TRANSITION));
-               pDest->transitionlist = g_list_append(pDest->transitionlist, transition);
+               if (transition) {
+                       memcpy(transition, src_transition, sizeof(MMS_SMIL_TRANSITION));
+                       pDest->transitionlist = g_list_append(pDest->transitionlist, transition);
+               }
        }
 
        pDest->metaCnt = g_list_length(pSrcMms->metalist);
@@ -1237,19 +1658,23 @@ void convert_to_mmsdata(const msg_struct_s *pSrc, MMS_MESSAGE_DATA_S *pDest)
        for (i = 0; i < pDest->metaCnt; i++) {
                MMS_SMIL_META *meta = (MMS_SMIL_META *)calloc(1, sizeof(MMS_SMIL_META));
                MMS_SMIL_META *src_meta = (MMS_SMIL_META *)get_msg_struct_data((msg_struct_s *)g_list_nth_data(pSrcMms->metalist, i));
-               memcpy(meta, src_meta, sizeof(MMS_SMIL_META));
-               pDest->metalist = g_list_append(pDest->metalist, meta);
+               if (meta) {
+                       memcpy(meta, src_meta, sizeof(MMS_SMIL_META));
+                       pDest->metalist = g_list_append(pDest->metalist, meta);
+               }
        }
 
        memcpy(&pDest->rootlayout, &pSrcMms->rootlayout, sizeof(MMS_SMIL_ROOTLAYOUT));
 
        memcpy(&pDest->msgAppId, &pSrcMms->msgAppId, sizeof(MMS_APPID_INFO_S));
+       memcpy(&pDest->header, &pSrcMms->header, sizeof(MMS_HEADER_DATA_S));
+       memcpy(&pDest->smil, &pSrcMms->smil, sizeof(MMS_MULTIPART_DATA_S));
 }
 
-void convert_from_mmsdata(const MMS_MESSAGE_DATA_S *pSrc, msg_struct_s *pDest)
+void convert_from_mmsdata2(const MMS_MESSAGE_DATA_S *pSrc, MMS_DATA_HIDDEN_S *pDestMms)
 {
        int i, j;
-       MMS_DATA_HIDDEN_S *pDestMms = (MMS_DATA_HIDDEN_S *)pDest->data;
+       //MMS_DATA_HIDDEN_S *pDestMms = (MMS_DATA_HIDDEN_S *)pDest->data;
 
        for (i = 0; i < pSrc->pageCnt; i++) {
                msg_struct_s *page_struct = msg_mms_create_struct(MSG_STRUCT_MMS_PAGE);
@@ -1315,4 +1740,186 @@ void convert_from_mmsdata(const MMS_MESSAGE_DATA_S *pSrc, msg_struct_s *pDest)
        memcpy(&pDestMms->rootlayout, &pSrc->rootlayout, sizeof(MMS_SMIL_ROOTLAYOUT));
 
        memcpy(&pDestMms->msgAppId, &pSrc->msgAppId, sizeof(MMS_APPID_INFO_S));
+
+       memcpy(&pDestMms->header, &pSrc->header, sizeof(MMS_HEADER_DATA_S));
+       memcpy(&pDestMms->smil, &pSrc->smil, sizeof(MMS_MULTIPART_DATA_S));
+
+}
+
+
+int msg_multipart_get_str_value(void *data, int field, char *value, int size)
+{
+       if (!data || !value)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MMS_MULTIPART_DATA_S *msg_data = (MMS_MULTIPART_DATA_S *)data;
+
+       switch (field) {
+       case MSG_MMS_MULTIPART_CONTENT_TYPE_STR:
+               strncpy(value, msg_data->szContentType, size);
+               break;
+       case MSG_MMS_MULTIPART_NAME_STR:
+               strncpy(value, msg_data->szFileName, size);
+               break;
+       case MSG_MMS_MULTIPART_FILEPATH_STR:
+               strncpy(value, msg_data->szFilePath, size);
+               break;
+       case MSG_MMS_MULTIPART_THUMBNAIL_FILEPATH_STR:
+               strncpy(value, msg_data->szThumbFilePath, size);
+               break;
+       case MSG_MMS_MULTIPART_CONTENT_ID_STR:
+               strncpy(value, msg_data->szContentID, size);
+               break;
+       case MSG_MMS_MULTIPART_CONTENT_LOCATION_STR:
+               strncpy(value, msg_data->szContentLocation, size);
+               break;
+
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+int msg_multipart_get_int_value(void *data, int field, int *value)
+{
+       if (!data || !value)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MMS_MULTIPART_DATA_S *msg_data = (MMS_MULTIPART_DATA_S *)data;
+
+       switch (field) {
+               case MSG_MMS_MULTIPART_TCS_LEVEL_INT:
+                       *value = msg_data->tcs_bc_level;
+                       break;
+               case MSG_MMS_MULTIPART_MALWARE_ALLOW_INT:
+                       *value = msg_data->malware_allow;
+                       break;
+               default :
+                       ret = MSG_ERR_INVALID_PARAMETER;
+                       break;
+       }
+
+       return ret;
+}
+
+int msg_multipart_set_str_value(void *data, int field, char *value, int size)
+{
+       if (!data || !value)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MMS_MULTIPART_DATA_S *msg_data = (MMS_MULTIPART_DATA_S *)data;
+
+       //CID 41980: Reducing the size argument to strncpy calls to accomodate string termination '\0' in case source string is larger than size
+       switch (field) {
+       case MSG_MMS_MULTIPART_CONTENT_TYPE_STR:
+               strncpy(msg_data->szContentType, value, MSG_MSG_ID_LEN);
+               break;
+       case MSG_MMS_MULTIPART_NAME_STR:
+               strncpy(msg_data->szFileName, value, MSG_FILENAME_LEN_MAX);
+               break;
+       case MSG_MMS_MULTIPART_FILEPATH_STR:
+               strncpy(msg_data->szFilePath, value, MSG_FILEPATH_LEN_MAX);
+               break;
+       case MSG_MMS_MULTIPART_THUMBNAIL_FILEPATH_STR:
+               break;
+       case MSG_MMS_MULTIPART_CONTENT_ID_STR:
+               strncpy(msg_data->szContentID, value, MSG_MSG_ID_LEN);
+               break;
+       case MSG_MMS_MULTIPART_CONTENT_LOCATION_STR:
+               strncpy(msg_data->szContentLocation, value, MSG_MSG_ID_LEN);
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+void convert_to_hidden_mmsdata(MMS_DATA_S *pSrc, msg_struct_s *pDest)
+{
+       MMS_DATA_HIDDEN_S *pDestMms = (MMS_DATA_HIDDEN_S *)pDest->data;
+
+       MMS_MESSAGE_DATA_S *MmsMessageData = NULL;
+       unique_ptr<MMS_MESSAGE_DATA_S*, void(*)(MMS_MESSAGE_DATA_S**)> buf(&MmsMessageData, unique_ptr_deleter);
+       MmsMessageData = (MMS_MESSAGE_DATA_S *)new char[sizeof(MMS_MESSAGE_DATA_S)];
+       memset(MmsMessageData, 0x00, sizeof(MMS_MESSAGE_DATA_S));
+
+       MsgMmsConvertMmsDataToMmsMessageData(pSrc, MmsMessageData);
+
+       convert_from_mmsdata2(MmsMessageData, pDestMms);
+
+       MsgMmsReleaseMmsLists(MmsMessageData);
+
+       if (pSrc->header) {
+               memcpy(&pDestMms->header, pSrc->header, sizeof(MMS_HEADER_DATA_S));
+       }
+
+       if (pSrc->smil) {
+               memcpy(&pDestMms->smil, pSrc->smil, sizeof(MMS_MULTIPART_DATA_S));
+               pDestMms->smil.type = MIME_APPLICATION_SMIL;
+               pDestMms->smil.pMultipartData = (char *)calloc(1,  pDestMms->smil.nMultipartDataLen+1);
+               if (pDestMms->smil.pMultipartData)
+                       memcpy(pDestMms->smil.pMultipartData, pSrc->smil->pMultipartData,pDestMms->smil.nMultipartDataLen);
+       }
+
+       if (pSrc->multipartlist) {
+
+               int list_cnt = g_list_length(pSrc->multipartlist);
+
+               for (int i = 0; i < list_cnt; i++) {
+                       MMS_MULTIPART_DATA_S *src_multipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(pSrc->multipartlist, i);
+
+                       if (src_multipart) {
+                               msg_struct_s *multipart_struct = (msg_struct_s *)msg_create_struct(MSG_STRUCT_MULTIPART_INFO);
+
+                               MMS_MULTIPART_DATA_S *dst_multipart = (MMS_MULTIPART_DATA_S*)multipart_struct->data;
+
+                               memcpy(dst_multipart, src_multipart, sizeof(MMS_MULTIPART_DATA_S));
+
+                               pDestMms->multipartlist = g_list_append(pDestMms->multipartlist, multipart_struct);
+                       }
+               }
+       }
+
+}
+
+void convert_from_hidden_mmsdata(msg_struct_s *pSrc, MMS_DATA_S *pDest)
+{
+
+       MMS_DATA_HIDDEN_S *pSrcMms = (MMS_DATA_HIDDEN_S *)pSrc->data;
+
+       MMS_MESSAGE_DATA_S *MmsMessageData = NULL;
+       unique_ptr<MMS_MESSAGE_DATA_S*, void(*)(MMS_MESSAGE_DATA_S**)> buf(&MmsMessageData, unique_ptr_deleter);
+       MmsMessageData = (MMS_MESSAGE_DATA_S *)new char[sizeof(MMS_MESSAGE_DATA_S)];
+       memset(MmsMessageData, 0x00, sizeof(MMS_MESSAGE_DATA_S));
+
+       convert_to_mmsdata2(pSrcMms, MmsMessageData);
+
+       MsgMmsConvertMmsMessageDataToMmsData(MmsMessageData, pDest);
+
+       MsgMmsReleaseMmsLists(MmsMessageData);
+}
+
+void __msg_mms_data_struct_init(MMS_DATA_HIDDEN_S *pMmsDataHidden)
+{
+       if (pMmsDataHidden) {
+               pMmsDataHidden->pagelist = NULL;
+               pMmsDataHidden->regionlist = NULL;
+               pMmsDataHidden->attachlist = NULL;
+               pMmsDataHidden->transitionlist = NULL;
+               pMmsDataHidden->metalist = NULL;
+
+               MsgMmsInitHeader(&pMmsDataHidden->header);
+               MsgMmsInitMultipart(&pMmsDataHidden->smil);
+               pMmsDataHidden->smil.type = MIME_APPLICATION_SMIL;
+               snprintf(pMmsDataHidden->smil.szContentType, sizeof(pMmsDataHidden->smil.szContentType), "%s", "application/smil");
+       }
 }
index 6240ef5..4538163 100755 (executable)
@@ -1,20 +1,21 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
+#include <privacy_checker_client.h>
 #include <MsgException.h>
 #include "MsgHandle.h"
 #include "MsgDebug.h"
@@ -61,6 +62,9 @@ int msg_setting_get_int_value(msg_struct_s *msg_struct, int field, int *value)
        case MSG_STRUCT_SETTING_MSGSIZE_OPT :
                *value = msg_get_msgsize_opt_int(msg_struct->data, field);
                break;
+       case MSG_STRUCT_SETTING_VOICE_MSG_OPT :
+               *value = msg_get_voice_msg_opt_int(msg_struct->data, field);
+               break;
        default :
                err = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -192,6 +196,9 @@ int msg_setting_set_int_value(msg_struct_s *msg_struct, int field, int value)
        case MSG_STRUCT_SETTING_MSGSIZE_OPT :
                err = msg_set_msgsize_opt_int(msg_struct->data, field, value);
                break;
+       case MSG_STRUCT_SETTING_VOICE_MSG_OPT :
+               err = msg_set_voice_msg_opt_int(msg_struct->data, field, value);
+               break;
        default :
                err = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -260,12 +267,21 @@ int msg_setting_set_bool_value(msg_struct_s *msg_struct, int field, bool value)
 
 EXPORT_API int msg_get_smsc_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
 
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -285,12 +301,21 @@ EXPORT_API int msg_get_smsc_opt(msg_handle_t handle, msg_struct_t msg_struct)
 
 EXPORT_API int msg_set_smsc_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
 
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || msg_struct == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -343,6 +368,9 @@ int msg_get_smsc_opt_int(void *smsc_opt, int field)
        case MSG_SMSC_SELECTED_ID_INT :
                ret = smsc_opt_data->selected;
                break;
+       case MSG_SMSC_LIST_SIM_INDEX_INT :
+               ret = smsc_opt_data->simIndex;
+               break;
        default :
                return MSG_ERR_INVALID_PARAMETER;
        }
@@ -362,7 +390,13 @@ int msg_set_smsc_opt_int(void *smsc_opt, int field, int value)
        switch (field)
        {
        case MSG_SMSC_SELECTED_ID_INT :
-               ret = smsc_opt_data->selected;
+               smsc_opt_data->selected = value;
+               break;
+       case MSG_SMSC_LIST_INDEX_INT :
+               smsc_opt_data->index = value;
+               break;
+       case MSG_SMSC_LIST_SIM_INDEX_INT :
+               smsc_opt_data->simIndex = value;
                break;
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
@@ -486,12 +520,21 @@ int msg_set_smsc_info_str(void *smsc_info, int field, char *val, int size)
 
 EXPORT_API int msg_get_cb_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
 
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -511,12 +554,21 @@ EXPORT_API int msg_get_cb_opt(msg_handle_t handle, msg_struct_t msg_struct)
 
 EXPORT_API int msg_set_cb_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
 
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || msg_struct == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -548,6 +600,9 @@ int msg_get_cb_option_int(void *cb_opt, int field)
        case MSG_CB_MAX_SIM_COUNT_INT :
                ret = cb_opt_data->maxSimCnt;
                break;
+       case MSG_CB_SIM_INDEX_INT :
+               ret = cb_opt_data->simIndex;
+               break;
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -570,6 +625,9 @@ int msg_set_cb_option_int(void *cb_opt, int field, int value)
        case MSG_CB_MAX_SIM_COUNT_INT :
                cb_opt_data->maxSimCnt = value;
                break;
+       case MSG_CB_SIM_INDEX_INT :
+               cb_opt_data->simIndex = value;
+               break;
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -841,12 +899,21 @@ int msg_set_cb_channel_info_str(void *cb_ch_info, int field, char *val, int size
 
 EXPORT_API int msg_get_sms_send_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
 
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -866,12 +933,21 @@ EXPORT_API int msg_get_sms_send_opt(msg_handle_t handle, msg_struct_t msg_struct
 
 EXPORT_API int msg_set_sms_send_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
 
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || msg_struct == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -995,12 +1071,21 @@ int msg_set_sms_send_opt_bool(void *sms_send_opt, int field, bool value)
 
 EXPORT_API int msg_get_mms_send_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
 
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -1020,12 +1105,21 @@ EXPORT_API int msg_get_mms_send_opt(msg_handle_t handle, msg_struct_t msg_struct
 
 EXPORT_API int msg_set_mms_send_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
 
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || msg_struct == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -1210,12 +1304,21 @@ int msg_set_mms_send_opt_bool(void *mms_send_opt, int field, bool value)
 
 EXPORT_API int msg_get_mms_recv_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
 
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -1235,12 +1338,21 @@ EXPORT_API int msg_get_mms_recv_opt(msg_handle_t handle, msg_struct_t msg_struct
 
 EXPORT_API int msg_set_mms_recv_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
 
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || msg_struct == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -1370,11 +1482,20 @@ int msg_set_mms_recv_opt_bool(void *mms_recv_opt, int field, bool value)
 
 EXPORT_API int msg_get_push_msg_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -1394,11 +1515,20 @@ EXPORT_API int msg_get_push_msg_opt(msg_handle_t handle, msg_struct_t msg_struct
 
 EXPORT_API int msg_set_push_msg_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || msg_struct == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -1504,11 +1634,20 @@ int msg_set_push_msg_opt_bool(void *push_msg_opt, int field, bool value)
 
 EXPORT_API int msg_get_voice_msg_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -1528,11 +1667,20 @@ EXPORT_API int msg_get_voice_msg_opt(msg_handle_t handle, msg_struct_t msg_struc
 
 EXPORT_API int msg_set_voice_msg_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || msg_struct == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -1550,6 +1698,52 @@ EXPORT_API int msg_set_voice_msg_opt(msg_handle_t handle, msg_struct_t msg_struc
        return err;
 }
 
+int msg_get_voice_msg_opt_int(void *voice_msg_opt, int field)
+{
+       if (!voice_msg_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_ERR_INVALID_PARAMETER;
+
+       MSG_VOICEMAIL_OPT_S *voice_opt = (MSG_VOICEMAIL_OPT_S *)voice_msg_opt;
+
+       switch (field)
+       {
+       case MSG_VOICEMSG_SIM_INDEX_INT :
+               ret = voice_opt->simIndex;
+               break;
+       case MSG_VOICEMSG_VOICE_COUNT_INT :
+               ret = voice_opt->voiceCnt;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_voice_msg_opt_int(void *voice_msg_opt, int field, int value)
+{
+       if (!voice_msg_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_VOICEMAIL_OPT_S *voice_opt = (MSG_VOICEMAIL_OPT_S *)voice_msg_opt;
+
+       switch (field)
+       {
+       case MSG_VOICEMSG_SIM_INDEX_INT :
+               voice_opt->simIndex = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
 char *msg_get_voice_msg_opt_str(void *voice_msg_opt, int field)
 {
        if (!voice_msg_opt)
@@ -1564,6 +1758,9 @@ char *msg_get_voice_msg_opt_str(void *voice_msg_opt, int field)
        case MSG_VOICEMSG_ADDRESS_STR :
                ret_str = voice_opt->mailNumber;
                break;
+       case MSG_VOICEMSG_ALPHA_ID_STR :
+               ret_str = voice_opt->alpahId;
+               break;
        default :
                break;
        }
@@ -1596,11 +1793,20 @@ int msg_set_voice_msg_opt_str(void *voice_msg_opt, int field, char *val, int siz
 
 EXPORT_API int msg_get_general_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -1620,11 +1826,20 @@ EXPORT_API int msg_get_general_opt(msg_handle_t handle, msg_struct_t msg_struct)
 
 EXPORT_API int msg_set_general_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || msg_struct == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -1656,6 +1871,15 @@ int msg_get_general_opt_int(void *general_opt, int field)
        case MSG_GENERAL_ALERT_TONE_INT :
                ret = opt->alertTone;
                break;
+       case MSG_GENERAL_SMS_LIMIT_CNT_INT :
+               ret = opt->smsLimitCnt;
+               break;
+       case MSG_GENERAL_MMS_LIMIT_CNT_INT :
+               ret = opt->mmsLimitCnt;
+               break;
+       case MSG_GENERAL_RINGTONE_TYPE_INT :
+               ret = opt->ringtoneType;
+               break;
        default :
                break;
        }
@@ -1677,6 +1901,15 @@ int msg_set_general_opt_int(void *general_opt, int field, int value)
        case MSG_GENERAL_ALERT_TONE_INT :
                opt->alertTone = value;
                break;
+       case MSG_GENERAL_SMS_LIMIT_CNT_INT :
+               opt->smsLimitCnt = value;
+               break;
+       case MSG_GENERAL_MMS_LIMIT_CNT_INT :
+               opt->mmsLimitCnt = value;
+               break;
+       case MSG_GENERAL_RINGTONE_TYPE_INT :
+               opt->ringtoneType = value;
+               break;
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -1702,6 +1935,18 @@ bool msg_get_general_opt_bool(void *general_opt, int field)
        case MSG_GENERAL_AUTO_ERASE_BOOL :
                ret = opt->bAutoErase;
                break;
+       case MSG_GENERAL_BLOCK_UNKNOWN_NUMBER_BOOL :
+               ret = opt->bBlockUnknownMsg;
+               break;
+       case MSG_GENERAL_MSG_NOTIFICATION_BOOL :
+               ret = opt->bNotification;
+               break;
+       case MSG_GENERAL_MSG_VIBRATION_BOOL :
+               ret = opt->bVibration;
+               break;
+       case MSG_GENERAL_MSG_PREVIEW_BOOL :
+               ret = opt->bPreview;
+               break;
        default :
                break;
        }
@@ -1726,6 +1971,62 @@ int msg_set_general_opt_bool(void *general_opt, int field, bool value)
        case MSG_GENERAL_AUTO_ERASE_BOOL :
                opt->bAutoErase = value;
                break;
+       case MSG_GENERAL_BLOCK_UNKNOWN_NUMBER_BOOL :
+               opt->bBlockUnknownMsg = value;
+               break;
+       case MSG_GENERAL_MSG_NOTIFICATION_BOOL :
+               opt->bNotification = value;
+               break;
+       case MSG_GENERAL_MSG_VIBRATION_BOOL :
+               opt->bVibration = value;
+               break;
+       case MSG_GENERAL_MSG_PREVIEW_BOOL :
+               opt->bPreview = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+char *msg_get_general_opt_str(void *general_opt, int field)
+{
+       if (!general_opt)
+               return NULL;
+
+       char *ret_str = NULL;
+
+       MSG_GENERAL_OPT_S *opt = (MSG_GENERAL_OPT_S *)general_opt;
+
+       switch (field)
+       {
+       case MSG_GENERAL_RINGTONE_PATH_STR :
+               ret_str = opt->ringtonePath;
+               break;
+       default :
+               break;
+       }
+
+       return ret_str;
+}
+
+int msg_set_general_opt_str(void *general_opt, int field, char *val, int size)
+{
+       if (!general_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_GENERAL_OPT_S *opt = (MSG_GENERAL_OPT_S *)general_opt;
+
+       switch (field)
+       {
+       case MSG_GENERAL_RINGTONE_PATH_STR :
+               bzero(opt->ringtonePath, sizeof(opt->ringtonePath));
+               snprintf(opt->ringtonePath, sizeof(opt->ringtonePath), "%s", val);
+               break;
        default :
                ret = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -1734,13 +2035,23 @@ int msg_set_general_opt_bool(void *general_opt, int field, bool value)
        return ret;
 }
 
+
 EXPORT_API int msg_get_msgsize_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -1760,11 +2071,20 @@ EXPORT_API int msg_get_msgsize_opt(msg_handle_t handle, msg_struct_t msg_struct)
 
 EXPORT_API int msg_set_msgsize_opt(msg_handle_t handle, msg_struct_t msg_struct)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || msg_struct == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
index c729773..2a90a66 100755 (executable)
@@ -1,20 +1,21 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
+#include <privacy_checker_client.h>
 
 #include "MsgHandle.h"
 #include "MsgDebug.h"
 #include "msg_storage.h"
 
 
-static int msg_thread_get_msg_type(int mainType, int subType);
+static int msg_get_msg_type(int mainType, int subType);
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
 EXPORT_API int msg_add_message(msg_handle_t handle, msg_struct_t opq_msg, const msg_struct_t send_opt)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || opq_msg == NULL || send_opt == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -59,11 +69,20 @@ EXPORT_API int msg_add_message(msg_handle_t handle, msg_struct_t opq_msg, const
 
 EXPORT_API int msg_add_syncml_message(msg_handle_t handle, const msg_struct_t syncml_msg)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || syncml_msg == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -85,11 +104,20 @@ EXPORT_API int msg_add_syncml_message(msg_handle_t handle, const msg_struct_t sy
 
 EXPORT_API int msg_update_message(msg_handle_t handle, const msg_struct_t opq_msg, const msg_struct_t send_opt)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || opq_msg == NULL || send_opt == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -98,12 +126,6 @@ EXPORT_API int msg_update_message(msg_handle_t handle, const msg_struct_t opq_ms
 
        MSG_MESSAGE_HIDDEN_S *msg = (MSG_MESSAGE_HIDDEN_S *)pMsgStruct->data;
 
-       if (msg->addr_list->nCount > 1)
-       {
-               MSG_DEBUG("Multiple Address cannot be updated [%d]", msg->addr_list->nCount);
-               return -EINVAL;
-       }
-
        try
        {
                err = pHandle->updateMessage(msg, (MSG_SENDINGOPT_S *)pStruct->data);
@@ -120,11 +142,20 @@ EXPORT_API int msg_update_message(msg_handle_t handle, const msg_struct_t opq_ms
 
 EXPORT_API int msg_update_read_status(msg_handle_t handle, msg_message_id_t msg_id, bool read)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -143,13 +174,56 @@ EXPORT_API int msg_update_read_status(msg_handle_t handle, msg_message_id_t msg_
 }
 
 
+EXPORT_API int msg_set_conversation_to_read(msg_handle_t handle,  msg_thread_id_t thread_id)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
+
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setConversationToRead(thread_id);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
 EXPORT_API int msg_update_protected_status(msg_handle_t handle, msg_message_id_t msg_id, bool is_protected)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -167,14 +241,22 @@ EXPORT_API int msg_update_protected_status(msg_handle_t handle, msg_message_id_t
        return err;
 }
 
-
 EXPORT_API int msg_delete_message(msg_handle_t handle, msg_message_id_t msg_id)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -195,11 +277,20 @@ EXPORT_API int msg_delete_message(msg_handle_t handle, msg_message_id_t msg_id)
 
 EXPORT_API int msg_delete_all_msgs_in_folder(msg_handle_t handle, msg_folder_id_t folder_id, bool bOnlyDB)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -218,13 +309,56 @@ EXPORT_API int msg_delete_all_msgs_in_folder(msg_handle_t handle, msg_folder_id_
 }
 
 
+EXPORT_API int msg_delete_msgs_by_list(msg_handle_t handle, msg_id_list_s *msg_id_list)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
+
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->deleteMessagesByList(msg_id_list);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
 EXPORT_API int msg_move_msg_to_folder(msg_handle_t handle, msg_message_id_t msg_id, msg_folder_id_t dest_folder_id)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -245,14 +379,23 @@ EXPORT_API int msg_move_msg_to_folder(msg_handle_t handle, msg_message_id_t msg_
 
 EXPORT_API int msg_move_msg_to_storage(msg_handle_t handle, msg_message_id_t msg_id, msg_storage_id_t storage_id)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
-       if (storage_id != MSG_STORAGE_PHONE && storage_id != MSG_STORAGE_SIM)
+       if (storage_id < MSG_STORAGE_PHONE || storage_id > MSG_STORAGE_SIM2)
        {
                MSG_FATAL("unsupported storage [%d]", storage_id);
                return MSG_ERR_INVALID_PARAMETER;
@@ -276,11 +419,20 @@ EXPORT_API int msg_move_msg_to_storage(msg_handle_t handle, msg_message_id_t msg
 
 EXPORT_API int msg_count_message(msg_handle_t handle, msg_folder_id_t folder_id, msg_struct_t count_info)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -301,11 +453,20 @@ EXPORT_API int msg_count_message(msg_handle_t handle, msg_folder_id_t folder_id,
 
 EXPORT_API int msg_count_msg_by_type(msg_handle_t handle, msg_message_type_t msg_type, int *msg_count)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -344,11 +505,20 @@ EXPORT_API int msg_count_msg_by_type(msg_handle_t handle, msg_message_type_t msg
 
 EXPORT_API int msg_count_msg_by_contact(msg_handle_t handle, const msg_struct_t addr_info, msg_struct_t msg_thread_count_list)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || addr_info == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -371,12 +541,21 @@ EXPORT_API int msg_count_msg_by_contact(msg_handle_t handle, const msg_struct_t
 
 EXPORT_API int msg_get_message(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_t opq_msg, msg_struct_t send_opt)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || !opq_msg)
        {
                MSG_FATAL("handle or opq_msg is NULL");
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -397,34 +576,65 @@ EXPORT_API int msg_get_message(msg_handle_t handle, msg_message_id_t msg_id, msg
        return err;
 }
 
-
-EXPORT_API int msg_get_folder_view_list(msg_handle_t handle, msg_folder_id_t folder_id, const msg_struct_t sort_rule, msg_struct_list_s *msg_folder_view_list)
+EXPORT_API int msg_get_vobject_data(msg_handle_t handle, msg_message_id_t msg_id, void** result_data)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
-       if (handle == NULL)
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || result_data == NULL)
        {
-               return -EINVAL;
+               MSG_FATAL("handle or result_data is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
-       msg_struct_s *pStruct = (msg_struct_s *)sort_rule;
 
        try
        {
-               if (sort_rule == NULL)
-               {
-                       MSG_SORT_RULE_S sortRule = {0};
+               err = pHandle->getVobject(msg_id, result_data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
 
-                       sortRule.sortType = MSG_SORT_BY_READ_STATUS;
-                       sortRule.bAscending = true;
+       return err;
+}
 
-                       err = pHandle->getFolderViewList(folder_id, &sortRule, msg_folder_view_list);
-               }
-               else
-               {
-               err = pHandle->getFolderViewList(folder_id, (MSG_SORT_RULE_S *)pStruct->data, msg_folder_view_list);
+EXPORT_API int msg_get_conversation(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_t conv)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
+
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || !conv)
+       {
+               MSG_FATAL("handle or opq_msg is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
        }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       msg_struct_s *pMsgStruct = (msg_struct_s *)conv;
+       try
+       {
+               err = pHandle->getConversationViewItem(msg_id, (MSG_CONVERSATION_VIEW_S *)pMsgStruct->data);
        }
        catch (MsgException& e)
        {
@@ -435,14 +645,22 @@ EXPORT_API int msg_get_folder_view_list(msg_handle_t handle, msg_folder_id_t fol
        return err;
 }
 
-
 EXPORT_API int msg_get_thread_view_list(msg_handle_t handle, const msg_struct_t sort_rule, msg_struct_list_s *msg_thread_view_list)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -476,11 +694,20 @@ EXPORT_API int msg_get_thread_view_list(msg_handle_t handle, const msg_struct_t
 
 EXPORT_API int msg_get_conversation_view_list(msg_handle_t handle, msg_thread_id_t thread_id, msg_struct_list_s *msg_conv_view_list)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -499,20 +726,29 @@ EXPORT_API int msg_get_conversation_view_list(msg_handle_t handle, msg_thread_id
 }
 
 
-EXPORT_API int msg_delete_thread_message_list(msg_handle_t handle, msg_thread_id_t thread_id)
+EXPORT_API int msg_delete_thread_message_list(msg_handle_t handle, msg_thread_id_t thread_id, bool include_protected_msg)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
 
        try
        {
-               err = pHandle->deleteThreadMessageList(thread_id);
+               err = pHandle->deleteThreadMessageList(thread_id, include_protected_msg);
        }
        catch (MsgException& e)
        {
@@ -526,11 +762,20 @@ EXPORT_API int msg_delete_thread_message_list(msg_handle_t handle, msg_thread_id
 
 EXPORT_API int msg_add_folder(msg_handle_t handle, const msg_struct_t folder_info)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || folder_info == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -552,11 +797,20 @@ EXPORT_API int msg_add_folder(msg_handle_t handle, const msg_struct_t folder_inf
 
 EXPORT_API int msg_update_folder(msg_handle_t handle, const msg_struct_t folder_info)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || folder_info == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -578,11 +832,20 @@ EXPORT_API int msg_update_folder(msg_handle_t handle, const msg_struct_t folder_
 
 EXPORT_API int msg_delete_folder(msg_handle_t handle, msg_folder_id_t folder_id)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -603,11 +866,20 @@ EXPORT_API int msg_delete_folder(msg_handle_t handle, msg_folder_id_t folder_id)
 
 EXPORT_API int msg_get_folder_list(msg_handle_t handle, msg_struct_list_s *folder_list)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -628,16 +900,25 @@ EXPORT_API int msg_get_folder_list(msg_handle_t handle, msg_struct_list_s *folde
 
 EXPORT_API int msg_generate_message(msg_handle_t handle, msg_message_type_t msg_type, msg_folder_id_t folder_id, unsigned int num_msg)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
                MSG_DEBUG("Handle is NULL");
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        if (folder_id >= MSG_MAX_FOLDER_ID)
        {
                MSG_DEBUG("folderId is invalid [%d]", folder_id);
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MSG_DEBUG("type : %d, folder : %d, num_msg : %d", msg_type, folder_id, num_msg);
@@ -661,6 +942,9 @@ EXPORT_API int msg_generate_message(msg_handle_t handle, msg_message_type_t msg_
        for (unsigned int i = 0; i < num_msg; i++)
        {
                msg_s = (msg_struct_s *)msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
+               if (msg_s == NULL)
+                       return MSG_ERR_NOT_SUPPORTED;
+
                msgInfo = (MSG_MESSAGE_HIDDEN_S *)msg_s->data;
 
                msgInfo->folderId = folder_id;
@@ -691,7 +975,7 @@ EXPORT_API int msg_generate_message(msg_handle_t handle, msg_message_type_t msg_
                addrInfo = (MSG_ADDRESS_INFO_S *)addr_s->data;
 
                addrInfo->addressType = MSG_ADDRESS_TYPE_PLMN;
-               postfix = rand()%10000;
+               postfix = random()%10000;
                snprintf(addrInfo->addressVal, MAX_ADDRESS_VAL_LEN+1, "%s%04d", prefix, postfix);
 
                addrInfo->recipientType = MSG_RECIPIENTS_TYPE_TO;
@@ -758,134 +1042,119 @@ EXPORT_API int msg_generate_message(msg_handle_t handle, msg_message_type_t msg_
                catch (MsgException& e)
                {
                        MSG_FATAL("%s", e.what());
+                       msg_release_struct((msg_struct_t *)&msg_s);
                        return MSG_ERR_STORAGE_ERROR;
                }
 
                if (msg_type == MSG_TYPE_MMS && msgInfo->pMmsData) //free pMmsData directly. It is added to enhance performance
                        delete [] static_cast<char*>(msgInfo->pMmsData);
 
+               msg_release_struct((msg_struct_t *)&msg_s);
+
                if (err < 0)
                {
                        MSG_DEBUG("err [%d]", err);
                        return err;
                }
-
-               msg_release_struct((msg_struct_t *)&msg_s);
        }
 
        return MSG_SUCCESS;
 }
 
 
-EXPORT_API int msg_generate_sms(msg_handle_t handle, msg_folder_id_t folder_id, unsigned int num_msg)
+EXPORT_API int msg_get_quick_panel_data(msg_handle_t handle, msg_quickpanel_type_t type, msg_struct_t opq_msg)
 {
-       MSG_DEBUG("folder %d, num_msg %d", folder_id, num_msg);
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
 
-       if (handle == NULL)
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
        {
-               MSG_DEBUG("Handle is NULL");
-               return -EINVAL;
+               return MSG_ERR_PERMISSION_DENIED;
        }
 
-       if (folder_id >= MSG_MAX_FOLDER_ID)
+       if (handle == NULL || !opq_msg )
        {
-               MSG_DEBUG("folderId is invalid");
-               return -EINVAL;
+               MSG_FATAL("handle or opq_msg is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
-       int err = 0;
-       char strMsg[20] = {0};
-       char prefix[10] ="0103001";
-       int postfix = 0;
+       MsgHandle* pHandle = (MsgHandle*)handle;
+       msg_struct_s *pMsg = (msg_struct_s *)opq_msg;
 
-       MSG_SENDINGOPT_S sendingOpt = {0};
-       sendingOpt.bSetting = false;
+       try
+       {
+               err = pHandle->getQuickPanelData(type, (MSG_MESSAGE_HIDDEN_S *)pMsg->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
 
-       srand(getpid());
+       return err;
+}
 
-       msg_struct_s *msg_s = NULL;
-       msg_struct_s *addr_s = NULL;
-       MSG_MESSAGE_HIDDEN_S *msgInfo = NULL;
-       MSG_ADDRESS_INFO_S *addrInfo = NULL;
 
-       for (unsigned int i = 0; i < num_msg; i++)
+EXPORT_API int msg_reset_database(msg_handle_t handle)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
+
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
        {
-               msg_s = (msg_struct_s *)msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
-               msgInfo = (MSG_MESSAGE_HIDDEN_S *)msg_s->data;
+               return MSG_ERR_PERMISSION_DENIED;
+       }
 
-               msgInfo->msgId  = 0; // It should be set 0
-               msgInfo->folderId = folder_id;
+       if (handle == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
 
-               msgInfo->mainType = MSG_SMS_TYPE;
-               msgInfo->subType = 0;
+       MsgHandle* pHandle = (MsgHandle*)handle;
 
-               msgInfo->storageId = MSG_STORAGE_PHONE;
+       try
+       {
+               err = pHandle->resetDatabase();
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
 
-               snprintf(strMsg, sizeof(strMsg), "test %d", i);
-               msgInfo->dataSize = strlen(strMsg);
-               msgInfo->pData = strMsg;
+       return err;
+}
 
-               msgInfo->addr_list->nCount = 1;
 
-               addr_s = (msg_struct_s *)msgInfo->addr_list->msg_struct_info[0];
+EXPORT_API int msg_get_mem_size(msg_handle_t handle, unsigned int* memsize)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
 
-               addrInfo = (MSG_ADDRESS_INFO_S *)addr_s->data;
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
 
-               addrInfo->addressType = MSG_ADDRESS_TYPE_PLMN;
-               postfix = rand()%10000;
-               snprintf(addrInfo->addressVal, MAX_ADDRESS_VAL_LEN+1, "%s%04d", prefix, postfix);
+       if (handle == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
 
-               addrInfo->recipientType = MSG_RECIPIENTS_TYPE_TO;
-
-               time(&(msgInfo->displayTime));
-
-               msgInfo->networkStatus = MSG_NETWORK_NOT_SEND;
-               msgInfo->bRead = false;
-               msgInfo->bProtected = false;
-               msgInfo->priority = MSG_MESSAGE_PRIORITY_NORMAL;
-               msgInfo->direction = MSG_DIRECTION_TYPE_MO;
-
-//             err = msg_add_message(handle, (msg_message_t) &msgInfo, &sendingOpt);
-               try
-               {
-                       MsgHandle* pHandle = (MsgHandle*)handle;
-                       err = pHandle->addMessage(msgInfo, &sendingOpt);
-               }
-               catch (MsgException& e)
-               {
-                       MSG_FATAL("%s", e.what());
-                       return MSG_ERR_STORAGE_ERROR;
-               }
-
-               if (err < 0)
-               {
-                       MSG_DEBUG("err [%d]", err);
-                       return err;
-               }
-
-               msg_release_struct((msg_struct_t *)&msg_s);
-       }
-
-       return MSG_SUCCESS;
-}
-
-
-EXPORT_API int msg_get_quick_panel_data(msg_handle_t handle, msg_quickpanel_type_t type, msg_struct_t opq_msg)
-{
-       msg_error_t err =  MSG_SUCCESS;
-
-       if (handle == NULL || !opq_msg )
-       {
-               MSG_FATAL("handle or opq_msg is NULL");
-               return -EINVAL;
-       }
-
-       MsgHandle* pHandle = (MsgHandle*)handle;
-       msg_struct_s *pMsg = (msg_struct_s *)opq_msg;
+       MsgHandle* pHandle = (MsgHandle*)handle;
 
        try
        {
-               err = pHandle->getQuickPanelData(type, (MSG_MESSAGE_HIDDEN_S *)pMsg->data);
+               err = pHandle->getMemSize(memsize);
        }
        catch (MsgException& e)
        {
@@ -894,23 +1163,32 @@ EXPORT_API int msg_get_quick_panel_data(msg_handle_t handle, msg_quickpanel_type
        }
 
        return err;
-}
 
+}
 
-EXPORT_API int msg_reset_database(msg_handle_t handle)
+EXPORT_API int msg_backup_message(msg_handle_t handle, msg_message_backup_type_t type, const char *backup_filepath)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
-       if (handle == NULL)
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
        {
-               return -EINVAL;
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || backup_filepath == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
 
        try
        {
-               err = pHandle->resetDatabase();
+               err = pHandle->backupMessage(type, backup_filepath);
        }
        catch (MsgException& e)
        {
@@ -922,20 +1200,29 @@ EXPORT_API int msg_reset_database(msg_handle_t handle)
 }
 
 
-EXPORT_API int msg_get_mem_size(msg_handle_t handle, unsigned int* memsize)
+EXPORT_API int msg_restore_message(msg_handle_t handle, const char *backup_filepath)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
-       if (handle == NULL)
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || backup_filepath == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
 
        try
        {
-               err = pHandle->getMemSize(memsize);
+               err = pHandle->restoreMessage(backup_filepath);
        }
        catch (MsgException& e)
        {
@@ -944,23 +1231,37 @@ EXPORT_API int msg_get_mem_size(msg_handle_t handle, unsigned int* memsize)
        }
 
        return err;
-
 }
 
-EXPORT_API int msg_backup_message(msg_handle_t handle)
+
+EXPORT_API int msg_search_message_for_thread_view(msg_handle_t handle, const char *search_string, msg_struct_list_s *msg_thread_view_list)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
-       if (handle == NULL)
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
        {
-               return -EINVAL;
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || search_string == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (strlen(search_string) <= 0 || strlen(search_string) > MAX_MSG_TEXT_LEN)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
 
        try
        {
-               err = pHandle->backupMessage();
+               err = pHandle->searchMessage(search_string, msg_thread_view_list);
        }
        catch (MsgException& e)
        {
@@ -971,21 +1272,29 @@ EXPORT_API int msg_backup_message(msg_handle_t handle)
        return err;
 }
 
-
-EXPORT_API int msg_restore_message(msg_handle_t handle)
+EXPORT_API int msg_get_reject_msg_list(msg_handle_t handle, const char *phone_num, msg_struct_list_s *msg_reject_msg_list)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
 
        try
        {
-               err = pHandle->restoreMessage();
+               err = pHandle->getRejectMsgList(phone_num, msg_reject_msg_list);
        }
        catch (MsgException& e)
        {
@@ -997,51 +1306,65 @@ EXPORT_API int msg_restore_message(msg_handle_t handle)
 }
 
 
-EXPORT_API int msg_search_message_for_thread_view(msg_handle_t handle, const char *search_string, msg_struct_list_s *msg_thread_view_list)
+EXPORT_API int msg_reg_storage_change_callback(msg_handle_t handle, msg_storage_change_cb cb, void *user_param)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
-       if (handle == NULL || search_string == NULL)
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
        {
-               return -EINVAL;
+               return MSG_ERR_PERMISSION_DENIED;
        }
 
-       if (strlen(search_string) <= 0 || strlen(search_string) > MAX_MSG_TEXT_LEN)
+       if (handle == NULL || cb == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
 
        try
        {
-               err = pHandle->searchMessage(search_string, msg_thread_view_list);
+               err = pHandle->regStorageChangeCallback(cb, user_param);
        }
        catch (MsgException& e)
        {
                MSG_FATAL("%s", e.what());
-               return MSG_ERR_STORAGE_ERROR;
+               if (e.errorCode() == MsgException::SERVER_READY_ERROR)
+                       return MSG_ERR_PERMISSION_DENIED;
+               else
+                       return MSG_ERR_CALLBACK_ERROR;
        }
 
        return err;
 }
 
-
-EXPORT_API int msg_search_message(msg_handle_t handle, const msg_struct_t msg_search_conditions, int offset, int limit, msg_struct_list_s *msg_list)
+EXPORT_API int msg_get_report_status(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_list_s *report_list)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
-       if (handle == NULL || msg_search_conditions == NULL)
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || msg_id < 1 || report_list == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
-       msg_struct_s *pStruct = (msg_struct_s *)msg_search_conditions;
 
        try
        {
-               err = pHandle->searchMessage((MSG_SEARCH_CONDITION_S *)pStruct->data, offset, limit, msg_list);
+               err = pHandle->getReportStatus(msg_id, report_list);
        }
        catch (MsgException& e)
        {
@@ -1052,20 +1375,29 @@ EXPORT_API int msg_search_message(msg_handle_t handle, const msg_struct_t msg_se
        return err;
 }
 
-EXPORT_API int msg_get_reject_msg_list(msg_handle_t handle, const char *phone_num, msg_struct_list_s *msg_reject_msg_list)
+EXPORT_API int msg_get_address_list(msg_handle_t handle, msg_thread_id_t thread_id, msg_struct_list_s *msg_address_list)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
 
        try
        {
-               err = pHandle->getRejectMsgList(phone_num, msg_reject_msg_list);
+               err = pHandle->getAddressList(thread_id, msg_address_list);
        }
        catch (MsgException& e)
        {
@@ -1077,46 +1409,32 @@ EXPORT_API int msg_get_reject_msg_list(msg_handle_t handle, const char *phone_nu
 }
 
 
-EXPORT_API int msg_reg_storage_change_callback(msg_handle_t handle, msg_storage_change_cb cb, void *user_param)
+EXPORT_API int msg_get_thread_id_by_address(msg_handle_t handle, msg_struct_list_s *msg_address_list, msg_thread_id_t *thread_id)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
-       if (handle == NULL || cb == NULL)
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
        {
-               return -EINVAL;
+               return MSG_ERR_PERMISSION_DENIED;
        }
 
-       MsgHandle* pHandle = (MsgHandle*)handle;
-
-       try
-       {
-               err = pHandle->regStorageChangeCallback(cb, user_param);
-       }
-       catch (MsgException& e)
-       {
-               MSG_FATAL("%s", e.what());
-               return MSG_ERR_CALLBACK_ERROR;
+       if (handle == NULL || msg_address_list == NULL || thread_id == NULL) {
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
-       return err;
-}
-
-
-EXPORT_API int msg_get_report_status(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_t report_status)
-{
-       msg_error_t err =  MSG_SUCCESS;
-
-       if (handle == NULL || msg_id < 1)
-       {
-               return -EINVAL;
+       if (msg_address_list->nCount < 1 ) {
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
-       msg_struct_s *pStruct = (msg_struct_s *)report_status;
 
        try
        {
-               err = pHandle->getReportStatus(msg_id, (MSG_REPORT_STATUS_INFO_S *)pStruct->data);
+               err = pHandle->getThreadIdByAddress(msg_address_list, thread_id);
        }
        catch (MsgException& e)
        {
@@ -1127,20 +1445,30 @@ EXPORT_API int msg_get_report_status(msg_handle_t handle, msg_message_id_t msg_i
        return err;
 }
 
-EXPORT_API int msg_get_address_list(msg_handle_t handle, msg_thread_id_t thread_id, msg_struct_list_s *msg_address_list)
+
+EXPORT_API int msg_get_thread_id_by_address2(msg_handle_t handle, msg_list_handle_t msg_address_list, msg_thread_id_t *thread_id)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
-       if (handle == NULL)
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || msg_address_list == NULL || thread_id == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
 
        try
        {
-               err = pHandle->getAddressList(thread_id, msg_address_list);
+               err = pHandle->getThreadIdByAddress(msg_address_list, thread_id);
        }
        catch (MsgException& e)
        {
@@ -1152,20 +1480,36 @@ EXPORT_API int msg_get_address_list(msg_handle_t handle, msg_thread_id_t thread_
 }
 
 
-EXPORT_API int msg_get_thread_id_by_address(msg_handle_t handle, msg_struct_list_s *msg_address_list, msg_thread_id_t *thread_id)
+EXPORT_API int msg_get_thread(msg_handle_t handle, msg_thread_id_t thread_id, msg_struct_t msg_thread)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
-       if (handle == NULL || msg_address_list->nCount < 1)
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
        {
-               return -EINVAL;
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || msg_thread == NULL ) {
+               MSG_FATAL("handle or msg_thread is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
+       msg_struct_s *msgThread = (msg_struct_s *)msg_thread;
+       if (msgThread->type != MSG_STRUCT_THREAD_INFO) {
+               MSG_FATAL("Invaild type. type [%d]", msgThread->type);
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MSG_THREAD_VIEW_S* pThreadInfo = (MSG_THREAD_VIEW_S *)msgThread->data;
 
        try
        {
-               err = pHandle->getThreadIdByAddress(msg_address_list, thread_id);
+               err = pHandle->getThread(thread_id, pThreadInfo);
        }
        catch (MsgException& e)
        {
@@ -1176,28 +1520,29 @@ EXPORT_API int msg_get_thread_id_by_address(msg_handle_t handle, msg_struct_list
        return err;
 }
 
-
-EXPORT_API int msg_get_thread(msg_handle_t handle, msg_thread_id_t thread_id, msg_struct_t msg_thread)
+EXPORT_API int msg_get_message_list2(msg_handle_t handle, const msg_struct_t msg_list_conditions, msg_struct_list_s *msg_list)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
-       if (handle == NULL || msg_thread == NULL ) {
-               MSG_FATAL("handle or msg_thread is NULL");
-               return -EINVAL;
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
        }
 
-       MsgHandle* pHandle = (MsgHandle*)handle;
-       msg_struct_s *msgThread = (msg_struct_s *)msg_thread;
-       if (msgThread->type != MSG_STRUCT_THREAD_INFO) {
-               MSG_FATAL("Invaild type. type [%d]", msgThread->type);
+       if (handle == NULL) {
                return MSG_ERR_INVALID_PARAMETER;
        }
 
-       MSG_THREAD_VIEW_S* pThreadInfo = (MSG_THREAD_VIEW_S *)msgThread->data;
+       MsgHandle* pHandle = (MsgHandle*)handle;
+       msg_struct_s *pStruct = (msg_struct_s *)msg_list_conditions;
 
        try
        {
-               err = pHandle->getThread(thread_id, pThreadInfo);
+               err = pHandle->getMessageList((MSG_LIST_CONDITION_S *)pStruct->data, msg_list);
        }
        catch (MsgException& e)
        {
@@ -1208,20 +1553,28 @@ EXPORT_API int msg_get_thread(msg_handle_t handle, msg_thread_id_t thread_id, ms
        return err;
 }
 
-
-EXPORT_API int msg_get_message_list(msg_handle_t handle, msg_folder_id_t folder_id, msg_thread_id_t thread_id, msg_message_type_t msg_type, msg_storage_id_t storage_id, msg_struct_list_s *msg_list)
+EXPORT_API int msg_get_media_list(msg_handle_t handle, msg_thread_id_t thread_id, msg_list_handle_t *msg_list)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL) {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
 
        try
        {
-               err = pHandle->getMessageList(folder_id, thread_id, msg_type, storage_id, msg_list);
+               err = pHandle->getMediaList(thread_id, msg_list);
        }
        catch (MsgException& e)
        {
@@ -1229,28 +1582,48 @@ EXPORT_API int msg_get_message_list(msg_handle_t handle, msg_folder_id_t folder_
                return MSG_ERR_STORAGE_ERROR;
        }
 
+
        return err;
 }
 
-static int msg_thread_get_msg_type(int mainType, int subType)
+static int msg_get_msg_type(int mainType, int subType)
 {
        if (mainType == MSG_SMS_TYPE)
        {
-               if (subType == MSG_CB_SMS)
-                       return MSG_TYPE_SMS_CB;
-               else if (subType == MSG_JAVACB_SMS)
-                       return MSG_TYPE_SMS_JAVACB;
-               else if (subType == MSG_WAP_SI_SMS || subType == MSG_WAP_SL_SMS)
-                       return MSG_TYPE_SMS_WAPPUSH;
-               else if (subType == MSG_MWI_VOICE_SMS || subType == MSG_MWI_FAX_SMS
-                               || subType == MSG_MWI_EMAIL_SMS || subType == MSG_MWI_OTHER_SMS)
-                       return MSG_TYPE_SMS_MWI;
-               else    if (subType == MSG_SYNCML_CP)
-                       return MSG_TYPE_SMS_SYNCML;
-               else    if (subType == MSG_REJECT_SMS)
-                       return MSG_TYPE_SMS_REJECT;
-               else
-                       return MSG_TYPE_SMS;
+       switch (subType) {
+                       case MSG_CB_SMS :
+                               return MSG_TYPE_SMS_CB;
+                       case MSG_JAVACB_SMS :
+                               return MSG_TYPE_SMS_JAVACB;
+                       case MSG_WAP_SI_SMS :
+                       case MSG_WAP_SL_SMS :
+                               return MSG_TYPE_SMS_WAPPUSH;
+                       case MSG_MWI_VOICE_SMS :
+                       case MSG_MWI_FAX_SMS :
+                       case MSG_MWI_EMAIL_SMS :
+                       case MSG_MWI_OTHER_SMS :
+                               return MSG_TYPE_SMS_MWI;
+                       case MSG_SYNCML_CP :
+                               return MSG_TYPE_SMS_SYNCML;
+                       case MSG_REJECT_SMS :
+                               return MSG_TYPE_SMS_REJECT;
+                       case MSG_ETWS_SMS :
+                               return MSG_TYPE_SMS_ETWS_PRIMARY;
+                       case MSG_CMAS_PRESIDENTIAL :
+                               return MSG_TYPE_SMS_CMAS_PRESIDENTIAL;
+                       case MSG_CMAS_EXTREME :
+                               return MSG_TYPE_SMS_CMAS_EXTREME;
+                       case MSG_CMAS_SEVERE :
+                               return MSG_TYPE_SMS_CMAS_SEVERE;
+                       case MSG_CMAS_AMBER :
+                               return MSG_TYPE_SMS_CMAS_AMBER;
+                       case MSG_CMAS_TEST :
+                               return MSG_TYPE_SMS_CMAS_TEST;
+                       case MSG_CMAS_OPERATOR_DEFINED :
+                               return MSG_TYPE_SMS_CMAS_OPERATOR_DEFINED;
+                       default :
+                               return MSG_TYPE_SMS;
+       }
        }
        else if (mainType == MSG_MMS_TYPE)
        {
@@ -1268,7 +1641,7 @@ static int msg_thread_get_msg_type(int mainType, int subType)
 
 int msg_syncml_info_get_int(void *syncml_info, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MSG_SYNCML_MESSAGE_S *pSync = (MSG_SYNCML_MESSAGE_S *)syncml_info;
        switch(field)
        {
@@ -1279,7 +1652,7 @@ int msg_syncml_info_get_int(void *syncml_info, int field)
                result = pSync->pinCode;
                break;
        default:
-               result = -1;
+               result = MSG_ERR_INVALID_PARAMETER;
                break;
        }
        return result;
@@ -1287,7 +1660,7 @@ int msg_syncml_info_get_int(void *syncml_info, int field)
 
 int msg_count_info_get_int(void *count_info, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MSG_COUNT_INFO_S *pCount = (MSG_COUNT_INFO_S *)count_info;
        switch(field)
        {
@@ -1304,7 +1677,7 @@ int msg_count_info_get_int(void *count_info, int field)
                result = pCount->nMms;
                break;
        default:
-               result = -1;
+               result = MSG_ERR_INVALID_PARAMETER;
                break;
        }
        return result;
@@ -1312,7 +1685,7 @@ int msg_count_info_get_int(void *count_info, int field)
 
 int msg_thread_count_get_int(void *count_info, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MSG_THREAD_COUNT_INFO_S *pCount = (MSG_THREAD_COUNT_INFO_S *)count_info;
        switch(field)
        {
@@ -1329,7 +1702,7 @@ int msg_thread_count_get_int(void *count_info, int field)
                result = pCount->mmsMsgCount;
                break;
        default:
-               result = -1;
+               result = MSG_ERR_INVALID_PARAMETER;
                break;
        }
        return result;
@@ -1337,7 +1710,7 @@ int msg_thread_count_get_int(void *count_info, int field)
 
 int msg_thread_index_get_int(void *index_info, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MSG_THREAD_LIST_INDEX_S *pIndex = (MSG_THREAD_LIST_INDEX_S *)index_info;
        switch(field)
        {
@@ -1345,7 +1718,7 @@ int msg_thread_index_get_int(void *index_info, int field)
                result = pIndex->contactId;
                break;
        default:
-               result = -1;
+               result = MSG_ERR_INVALID_PARAMETER;
                break;
        }
        return result;
@@ -1353,7 +1726,7 @@ int msg_thread_index_get_int(void *index_info, int field)
 
 int msg_sortrule_get_int(void *sort_info, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MSG_SORT_RULE_S *pSort = (MSG_SORT_RULE_S *)sort_info;
        switch(field)
        {
@@ -1361,7 +1734,7 @@ int msg_sortrule_get_int(void *sort_info, int field)
                result = pSort->sortType;
                break;
        default:
-               result = -1;
+               result = MSG_ERR_INVALID_PARAMETER;
                break;
        }
        return result;
@@ -1369,7 +1742,7 @@ int msg_sortrule_get_int(void *sort_info, int field)
 
 int msg_folder_info_get_int(void *folder_info, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MSG_FOLDER_INFO_S *pFolder = (MSG_FOLDER_INFO_S *)folder_info;
        switch(field)
        {
@@ -1380,7 +1753,7 @@ int msg_folder_info_get_int(void *folder_info, int field)
                result = pFolder->folderType;
                break;
        default:
-               result = -1;
+               result = MSG_ERR_INVALID_PARAMETER;
                break;
        }
        return result;
@@ -1388,7 +1761,7 @@ int msg_folder_info_get_int(void *folder_info, int field)
 
 int msg_thread_info_get_int(void *data, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MSG_THREAD_VIEW_S *pThread = (MSG_THREAD_VIEW_S *)data;
 
        switch(field)
@@ -1397,7 +1770,7 @@ int msg_thread_info_get_int(void *data, int field)
                result = pThread->threadId;
                break;
        case MSG_THREAD_MSG_TYPE_INT :
-               result = msg_thread_get_msg_type(pThread->mainType, pThread->subType);
+               result = msg_get_msg_type(pThread->mainType, pThread->subType);
                break;
        case MSG_THREAD_MSG_TIME_INT :
                result = pThread->threadTime;
@@ -1415,15 +1788,73 @@ int msg_thread_info_get_int(void *data, int field)
                result = pThread->mmsCnt;
                break;
        default:
-               result = -1;
+               result = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return result;
+}
+
+
+int msg_conv_info_get_int(void *data, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_CONVERSATION_VIEW_S *pConv = (MSG_CONVERSATION_VIEW_S *)data;
+
+       switch(field)
+       {
+       case MSG_CONV_MSG_ID_INT :
+               result = pConv->msgId;
+               break;
+       case MSG_CONV_MSG_THREAD_ID_INT :
+               result = pConv->threadId;
+               break;
+       case MSG_CONV_MSG_FOLDER_ID_INT :
+               result = pConv->folderId;
+               break;
+       case MSG_CONV_MSG_TYPE_INT :
+               result = msg_get_msg_type(pConv->mainType, pConv->subType);
+               break;
+       case MSG_CONV_MSG_STORAGE_ID_INT :
+               result = pConv->storageId;
+               break;
+       case MSG_CONV_MSG_DISPLAY_TIME_INT :
+               result = pConv->displayTime;
+               break;
+       case MSG_CONV_MSG_SCHEDULED_TIME_INT :
+               result = pConv->scheduledTime;
+               break;
+       case MSG_CONV_MSG_NETWORK_STATUS_INT :
+               result = pConv->networkStatus;
+               break;
+       case MSG_CONV_MSG_DIRECTION_INT :
+               result = pConv->direction;
+               break;
+       case MSG_CONV_MSG_ATTACH_COUNT_INT :
+               result = pConv->attachCount;
+               break;
+       case MSG_CONV_MSG_TEXT_SIZE_INT :
+               result = pConv->textSize;
+               break;
+       case MSG_CONV_MSG_PAGE_COUNT_INT :
+               result = pConv->pageCount;
+               break;
+       case MSG_CONV_MSG_TCS_BC_LEVEL_INT :
+               result = pConv->tcs_bc_level;
+               break;
+       case MSG_CONV_MSG_SIM_INDEX_INT :
+               result = pConv->simIndex;
+               break;
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
                break;
        }
        return result;
 }
 
+
 int msg_search_condition_get_int(void *condition_info, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MSG_SEARCH_CONDITION_S *pCond = (MSG_SEARCH_CONDITION_S *)condition_info;
        switch(field)
        {
@@ -1437,32 +1868,89 @@ int msg_search_condition_get_int(void *condition_info, int field)
                result = pCond->reserved;
                break;
        default:
-               result = -1;
+               result = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return result;
+}
+
+
+int msg_list_condition_get_int(void *condition_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_LIST_CONDITION_S *pCond = (MSG_LIST_CONDITION_S *)condition_info;
+       switch(field)
+       {
+       case MSG_LIST_CONDITION_FOLDER_ID_INT:
+               result = pCond->folderId;
+               break;
+       case MSG_LIST_CONDITION_THREAD_ID_INT:
+                       result = pCond->threadId;
+                       break;
+       case MSG_LIST_CONDITION_STORAGE_ID_INT:
+                       result = pCond->storageId;
+                       break;
+       case MSG_LIST_CONDITION_MSGTYPE_INT:
+               result = pCond->msgType;
+               break;
+       case MSG_LIST_CONDITION_FROM_TIME_INT:
+               result = pCond->fromTime;
+               break;
+       case MSG_LIST_CONDITION_TO_TIME_INT:
+               result = pCond->toTime;
+               break;
+       case MSG_LIST_CONDITION_OFFSET_INT:
+               result = pCond->offset;
+               break;
+       case MSG_LIST_CONDITION_LIMIT_INT:
+               result = pCond->limit;
+               break;
+       case MSG_LIST_CONDITION_SIM_INDEX_INT:
+               result = pCond->simIndex;
+               break;
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
                break;
        }
        return result;
 }
 
+
 int msg_report_status_get_int(void *report_info, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MSG_REPORT_STATUS_INFO_S *pReport = (MSG_REPORT_STATUS_INFO_S *)report_info;
        switch(field)
        {
-       case MSG_REPORT_STATUS_DELIVERY_STATUS_INT:
-               result = pReport->deliveryStatus;
+       case MSG_REPORT_TYPE_INT:
+               result = pReport->type;
+               break;
+       case MSG_REPORT_STATUS_INT:
+               result = pReport->status;
                break;
-       case MSG_REPORT_STATUS_DELIVERY_TIME_INT:
-               result = pReport->deliveryStatusTime;
+       case MSG_REPORT_TIME_INT:
+               result = pReport->statusTime;
                break;
-       case MSG_REPORT_STATUS_READ_STATUS_INT:
-               result = pReport->readStatus;
+
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
                break;
-       case MSG_REPORT_STATUS_READ_TIME_INT:
-               result = pReport->readStatusTime;
+       }
+       return result;
+}
+
+char* msg_report_status_get_str(void *report_info, int field)
+{
+       char *result = NULL;
+       MSG_REPORT_STATUS_INFO_S *pReport = (MSG_REPORT_STATUS_INFO_S *)report_info;
+       switch(field)
+       {
+
+       case MSG_REPORT_ADDRESS_STR:
+               result = pReport->addressVal;
                break;
+
        default:
-               result = -1;
                break;
        }
        return result;
@@ -1504,6 +1992,43 @@ char *msg_thread_info_get_str(void *data, int field)
        return ret_str;
 }
 
+
+char *msg_conv_info_get_str(void *data, int field)
+{
+       char *ret_str = NULL;
+       MSG_CONVERSATION_VIEW_S *pConv = (MSG_CONVERSATION_VIEW_S *)data;
+
+       switch(field)
+       {
+       case MSG_CONV_MSG_SUBJECT_STR :
+               ret_str = pConv->subject;
+               break;
+       case MSG_CONV_MSG_ATTACH_NAME_STR :
+               ret_str = pConv->attachFileName;
+               break;
+       case MSG_CONV_MSG_AUDIO_NAME_STR :
+               ret_str = pConv->audioFileName;
+               break;
+       case MSG_CONV_MSG_IMAGE_THUMB_PATH_STR :
+               ret_str = pConv->imageThumbPath;
+               break;
+       case MSG_CONV_MSG_VIDEO_THUMB_PATH_STR :
+               ret_str = pConv->videoThumbPath;
+               break;
+       case MSG_CONV_MSG_TEXT_STR :
+               ret_str = pConv->pText;
+               break;
+       case MSG_CONV_MSG_1ST_MEDIA_PATH_STR :
+               ret_str = pConv->firstMediaPath;
+               break;
+       default:
+               break;
+       }
+
+       return ret_str;
+}
+
+
 char* msg_search_condition_get_str(void *condition_info, int field, int size)
 {
        char *result = NULL;
@@ -1516,7 +2041,6 @@ char* msg_search_condition_get_str(void *condition_info, int field, int size)
        case MSG_SEARCH_CONDITION_SEARCH_VALUE_STR:
                result = search_cond->pSearchVal;
                break;
-
        default:
                result = NULL;
                break;
@@ -1524,17 +2048,38 @@ char* msg_search_condition_get_str(void *condition_info, int field, int size)
        return result;
 }
 
-bool msg_sendopt_get_bool(void *send_opt, int field)
+
+char* msg_list_condition_get_str(void *condition_info, int field, int size)
+{
+       char *result = NULL;
+       MSG_LIST_CONDITION_S *cond = (MSG_LIST_CONDITION_S *)condition_info;
+       switch(field)
+       {
+       case MSG_LIST_CONDITION_ADDRESS_VALUE_STR:
+               result = cond->pAddressVal;
+               break;
+       case MSG_LIST_CONDITION_TEXT_VALUE_STR:
+               result = cond->pTextVal;
+               break;
+       default:
+               result = NULL;
+               break;
+       }
+       return result;
+}
+
+
+bool msg_sendopt_get_bool(void *send_opt, int field)
 {
        bool result = false;
        MSG_SENDINGOPT_S *sendopt = (MSG_SENDINGOPT_S *)send_opt;
        switch(field)
        {
        case MSG_SEND_OPT_SETTING_BOOL:
-               result = sendopt->bDeliverReq;
+               result = sendopt->bSetting;
                break;
        case MSG_SEND_OPT_KEEPCOPY_BOOL:
-               result = sendopt->bDeliverReq;
+               result = sendopt->bKeepCopy;
                break;
        case MSG_SEND_OPT_DELIVER_REQ_BOOL:
                result = sendopt->bDeliverReq;
@@ -1560,6 +2105,71 @@ bool msg_sortrule_get_bool(void *sort_rule, int field)
        return result;
 }
 
+bool msg_conv_get_bool(void *data, int field)
+{
+       bool result = false;
+       MSG_CONVERSATION_VIEW_S *pConv = (MSG_CONVERSATION_VIEW_S *)data;
+       switch(field)
+       {
+       case MSG_CONV_MSG_READ_BOOL:
+               result = pConv->bRead;
+               break;
+       case MSG_CONV_MSG_PROTECTED_BOOL:
+               result = pConv->bProtected;
+               break;
+       default:
+               break;
+       }
+       return result;
+}
+
+bool msg_thread_info_get_bool(void *data, int field)
+{
+       bool result = false;
+       MSG_THREAD_VIEW_S *pthreadInfo = (MSG_THREAD_VIEW_S *)data;
+       switch(field)
+       {
+       case MSG_THREAD_PROTECTED_BOOL:
+               result = pthreadInfo->bProtected;
+               break;
+       case MSG_THREAD_DRAFT_BOOL :
+               result = pthreadInfo->bDraft;
+               break;
+       case MSG_THREAD_SEND_FAILED_BOOL :
+               result = pthreadInfo->bSendFailed;
+               break;
+       case MSG_THREAD_SENDING_BOOL :
+               result = pthreadInfo->bSending;
+               break;
+       default:
+               break;
+       }
+       return result;
+}
+
+
+bool msg_list_condition_get_bool(void *data, int field)
+{
+       bool result = false;
+       MSG_LIST_CONDITION_S *pCond = (MSG_LIST_CONDITION_S *)data;
+       switch(field)
+       {
+       case MSG_LIST_CONDITION_PROTECTED_BOOL:
+               result = pCond->bProtected;
+               break;
+       case MSG_LIST_CONDITION_SCHEDULED_BOOL :
+               result = pCond->bScheduled;
+               break;
+       case MSG_LIST_CONDITION_AND_OPERATER_BOOL :
+               result = pCond->bAnd;
+               break;
+       default:
+               break;
+       }
+       return result;
+}
+
+
 int msg_sendopt_get_struct_handle(msg_struct_s *msg_struct, int field, void **value)
 {
        msg_error_t err =  MSG_SUCCESS;
@@ -1614,7 +2224,7 @@ int msg_thread_index_get_struct_handle(msg_struct_s *msg_struct, int field, void
        MSG_THREAD_LIST_INDEX_INFO_S *pIndex = (MSG_THREAD_LIST_INDEX_INFO_S *)msg_struct->data;
        switch(field)
        {
-       case MSG_SYNCML_INFO_MESSAGE_HND:
+       case MSG_THREAD_LIST_INDEX_ADDR_INFO_HND:
                *value = (void *)pIndex->msgAddrInfo;
                break;
        default:
@@ -1625,9 +2235,32 @@ int msg_thread_index_get_struct_handle(msg_struct_s *msg_struct, int field, void
        return err;
 }
 
+
+int msg_list_condition_get_struct_handle(msg_struct_s *msg_struct, int field, void **value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if(!msg_struct || !value)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_LIST_CONDITION_S *pCond = (MSG_LIST_CONDITION_S *)msg_struct->data;
+       switch(field)
+       {
+       case MSG_LIST_CONDITION_SORT_RULE_HND:
+               *value = (void *)pCond->sortRule;
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+
+       }
+       return err;
+}
+
+
 int msg_address_info_get_int(void *addr_info, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MSG_ADDRESS_INFO_S *pAddr = (MSG_ADDRESS_INFO_S *)addr_info;
        switch(field)
        {
@@ -1647,7 +2280,7 @@ int msg_address_info_get_int(void *addr_info, int field)
 }
 int msg_mms_sendopt_get_int(void *opt_info, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MMS_SENDINGOPT_S *pOpt = (MMS_SENDINGOPT_S *)opt_info;
        switch(field)
        {
@@ -1668,7 +2301,7 @@ int msg_mms_sendopt_get_int(void *opt_info, int field)
 
 int msg_reject_message_get_int(void *msg_info, int field)
 {
-       int result = -1;
+       int result = MSG_ERR_INVALID_PARAMETER;
        MSG_REJECT_MSG_INFO_S *pMsg = (MSG_REJECT_MSG_INFO_S *)msg_info;
        switch(field)
        {
@@ -1897,57 +2530,102 @@ int msg_folder_info_set_int(void *folder_info, int field, int value)
        return err;
 }
 
+
 int msg_search_condition_set_int(void *condition_info, int field, int value)
 {
        msg_error_t err =  MSG_SUCCESS;
        if(!condition_info)
                return MSG_ERR_NULL_POINTER;
 
-    MSG_SEARCH_CONDITION_S *pCond = (MSG_SEARCH_CONDITION_S *)condition_info;
-    switch(field)
-    {
-    case MSG_SEARCH_CONDITION_FOLDERID_INT:
+       MSG_SEARCH_CONDITION_S *pCond = (MSG_SEARCH_CONDITION_S *)condition_info;
+       switch(field)
+       {
+       case MSG_SEARCH_CONDITION_FOLDERID_INT:
                pCond->folderId = value;
                break;
-    case MSG_SEARCH_CONDITION_MSGTYPE_INT:
+       case MSG_SEARCH_CONDITION_MSGTYPE_INT:
                pCond->msgType = value;
                break;
-    case MSG_SEARCH_CONDITION_RESERVED_INT:
+       case MSG_SEARCH_CONDITION_RESERVED_INT:
                pCond->reserved = value;
                break;
-    default:
+       default:
                err = MSG_ERR_UNKNOWN;
                break;
-    }
+       }
 
        return err;
 }
 
-int msg_report_status_set_int(void *report_info, int field, int value)
+
+int msg_list_condition_set_int(void *condition_info, int field, int value)
 {
        msg_error_t err =  MSG_SUCCESS;
-       if(!report_info)
+       if(!condition_info)
                return MSG_ERR_NULL_POINTER;
 
-    MSG_REPORT_STATUS_INFO_S *pReport = (MSG_REPORT_STATUS_INFO_S *)report_info;
-    switch(field)
-    {
-    case MSG_REPORT_STATUS_DELIVERY_STATUS_INT:
-               pReport->deliveryStatus = value;
+       MSG_LIST_CONDITION_S *pCond = (MSG_LIST_CONDITION_S *)condition_info;
+       switch(field)
+       {
+       case MSG_LIST_CONDITION_FOLDER_ID_INT:
+               pCond->folderId = value;
+               break;
+       case MSG_LIST_CONDITION_THREAD_ID_INT:
+               pCond->threadId = value;
                break;
-    case MSG_REPORT_STATUS_DELIVERY_TIME_INT:
-               pReport->deliveryStatusTime = value;
+       case MSG_LIST_CONDITION_STORAGE_ID_INT:
+               pCond->storageId = value;
                break;
-    case MSG_REPORT_STATUS_READ_STATUS_INT:
-               pReport->readStatus = value;
+       case MSG_LIST_CONDITION_MSGTYPE_INT:
+               pCond->msgType = value;
                break;
-    case MSG_REPORT_STATUS_READ_TIME_INT:
-               pReport->readStatusTime = value;
+       case MSG_LIST_CONDITION_FROM_TIME_INT:
+               pCond->fromTime = value;
                break;
-    default:
+       case MSG_LIST_CONDITION_TO_TIME_INT:
+               pCond->toTime = value;
+               break;
+       case MSG_LIST_CONDITION_OFFSET_INT:
+               pCond->offset = value;
+               break;
+       case MSG_LIST_CONDITION_LIMIT_INT:
+               pCond->limit = value;
+               break;
+       case MSG_LIST_CONDITION_SIM_INDEX_INT:
+               pCond->simIndex = value;
+               break;
+       default:
                err = MSG_ERR_UNKNOWN;
                break;
-    }
+       }
+
+       return err;
+}
+
+
+int msg_report_status_set_int(void *report_info, int field, int value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!report_info)
+       return MSG_ERR_NULL_POINTER;
+
+       MSG_REPORT_STATUS_INFO_S *pReport = (MSG_REPORT_STATUS_INFO_S *)report_info;
+       switch(field)
+       {
+               case MSG_REPORT_TYPE_INT:
+                       pReport->type = value;
+               break;
+               case MSG_REPORT_STATUS_INT:
+                       pReport->status = value;
+               break;
+               case MSG_REPORT_TIME_INT:
+                       pReport->statusTime = value;
+               break;
+
+               default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+       }
 
        return err;
 }
@@ -1979,24 +2657,52 @@ int msg_search_condition_set_str(void *condition_info, int field, char *value, i
        if(!condition_info || !value)
                return MSG_ERR_NULL_POINTER;
 
-    MSG_SEARCH_CONDITION_S *search_cond = (MSG_SEARCH_CONDITION_S *)condition_info;
+       MSG_SEARCH_CONDITION_S *search_cond = (MSG_SEARCH_CONDITION_S *)condition_info;
 
-    switch(field)
-    {
-    case MSG_SEARCH_CONDITION_ADDRESS_VALUE_STR:
-               search_cond->pAddressVal = value;
+       switch(field)
+       {
+       case MSG_SEARCH_CONDITION_ADDRESS_VALUE_STR:
+               if(size)
+                       search_cond->pAddressVal = value;
+               break;
+       case MSG_SEARCH_CONDITION_SEARCH_VALUE_STR:
+               if(size)
+                       search_cond->pSearchVal = value;
                break;
-    case MSG_SEARCH_CONDITION_SEARCH_VALUE_STR:
-               search_cond->pSearchVal = value;
+       default:
+               err = MSG_ERR_UNKNOWN;
                break;
+       }
+       return err;
+}
 
-    default:
+
+int msg_list_condition_set_str(void *condition_info, int field, char *value, int size)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!condition_info || !value)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_LIST_CONDITION_S *cond = (MSG_LIST_CONDITION_S *)condition_info;
+
+       switch(field)
+       {
+       case MSG_LIST_CONDITION_ADDRESS_VALUE_STR:
+               if(size)
+                       cond->pAddressVal = value;
+               break;
+       case MSG_LIST_CONDITION_TEXT_VALUE_STR:
+               if(size)
+                       cond->pTextVal = value;
+               break;
+       default:
                err = MSG_ERR_UNKNOWN;
                break;
-    }
+       }
        return err;
 }
 
+
 int msg_sendopt_set_bool(void *send_opt, int field, bool value)
 {
        msg_error_t err =  MSG_SUCCESS;
@@ -2007,10 +2713,10 @@ int msg_sendopt_set_bool(void *send_opt, int field, bool value)
     switch(field)
     {
     case MSG_SEND_OPT_SETTING_BOOL:
-               sendopt->bDeliverReq = value;
+               sendopt->bSetting = value;
                break;
     case MSG_SEND_OPT_KEEPCOPY_BOOL:
-               sendopt->bDeliverReq = value;
+               sendopt->bKeepCopy = value;
                break;
     case MSG_SEND_OPT_DELIVER_REQ_BOOL:
                sendopt->bDeliverReq = value;
@@ -2028,19 +2734,46 @@ int msg_sortrule_set_bool(void *sort_rule, int field, bool value)
        if(!sort_rule)
                return MSG_ERR_NULL_POINTER;
 
-    MSG_SORT_RULE_S *pSort = (MSG_SORT_RULE_S *)sort_rule;
-    switch(field)
-    {
-    case MSG_SORT_RULE_ACSCEND_BOOL:
+       MSG_SORT_RULE_S *pSort = (MSG_SORT_RULE_S *)sort_rule;
+       switch(field)
+       {
+       case MSG_SORT_RULE_ACSCEND_BOOL:
                pSort->bAscending = value;
                break;
-    default:
+       default:
                err = MSG_ERR_UNKNOWN;
                break;
-    }
+       }
+       return err;
+}
+
+
+int msg_list_condition_set_bool(void *data, int field, bool value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!data)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_LIST_CONDITION_S *pCond = (MSG_LIST_CONDITION_S *)data;
+       switch(field)
+       {
+       case MSG_LIST_CONDITION_PROTECTED_BOOL:
+               pCond->bProtected = value;
+               break;
+       case MSG_LIST_CONDITION_SCHEDULED_BOOL:
+               pCond->bScheduled = value;
+               break;
+       case MSG_LIST_CONDITION_AND_OPERATER_BOOL:
+               pCond->bAnd = value;
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+       }
        return err;
 }
 
+
 int msg_sendopt_set_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s *value)
 {
        msg_error_t err =  MSG_SUCCESS;
@@ -2119,6 +2852,32 @@ int msg_thread_index_set_struct_handle(msg_struct_s *msg_struct, int field, msg_
        return err;
 }
 
+
+int msg_list_condition_set_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s *value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if(!msg_struct || !value)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_LIST_CONDITION_S *pCond = (MSG_LIST_CONDITION_S *)msg_struct->data;
+       msg_struct_s *pTmp = NULL;
+
+       switch(field)
+       {
+       case MSG_LIST_CONDITION_SORT_RULE_HND:
+               pTmp = (msg_struct_s *)pCond->sortRule;
+               memcpy(pTmp->data, value->data, sizeof(MSG_SORT_RULE_S));
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+
+       }
+       return err;
+}
+
+
 int msg_address_info_set_int(void *addrinfo, int field, int value)
 {
        msg_error_t err =  MSG_SUCCESS;
@@ -2222,6 +2981,30 @@ int msg_address_info_set_str(void *addr_info, int field, char *value, int size)
 
        return err;
 }
+
+int msg_media_info_set_str(void *media_info, int field, char *value, int size)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!media_info || !value)
+               return MSG_ERR_NULL_POINTER;
+       MSG_MEDIA_INFO_S *pAddr = (MSG_MEDIA_INFO_S *)media_info;
+    int _len = 0;
+
+    switch(field)
+    {
+    case MSG_MEDIA_ITEM_STR:
+        (size > MSG_FILEPATH_LEN_MAX)? _len = MSG_FILEPATH_LEN_MAX : _len = size;
+        memset(pAddr->media_item, 0x00, sizeof(pAddr->media_item));
+               strncpy(pAddr->media_item, value, _len);
+               break;
+    default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+    }
+
+       return err;
+}
+
 int msg_reject_message_set_str(void *msg_info, int field, char *value, int size)
 {
        msg_error_t err =  MSG_SUCCESS;
@@ -2278,8 +3061,245 @@ int msg_sms_sendopt_set_bool(void *option, int field, bool value)
                pOpt->bReplyPath = value;
                break;
     default:
-               err = MSG_ERR_UNKNOWN;
+       err = MSG_ERR_UNKNOWN;
+               break;
+    }
+       return err;
+}
+
+EXPORT_API int msg_add_push_event(msg_handle_t handle, const msg_struct_t push_event)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
+
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || push_event == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       msg_struct_s *pPush = (msg_struct_s *)push_event;
+
+       try
+       {
+               err = pHandle->addPushEvent((MSG_PUSH_EVENT_INFO_S *)pPush->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_delete_push_event(msg_handle_t handle, const msg_struct_t push_event)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
+
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || push_event == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       msg_struct_s *pPush = (msg_struct_s *)push_event;
+
+       try
+       {
+               err = pHandle->deletePushEvent((MSG_PUSH_EVENT_INFO_S *)pPush->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_update_push_event(msg_handle_t handle, const msg_struct_t src_event, const msg_struct_t dst_event)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
+
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || src_event == NULL || dst_event == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       msg_struct_s *pSrc = (msg_struct_s *)src_event;
+       msg_struct_s *pDst = (msg_struct_s *)dst_event;
+
+       try
+       {
+               err = pHandle->updatePushEvent((MSG_PUSH_EVENT_INFO_S *)pSrc->data, (MSG_PUSH_EVENT_INFO_S *)pDst->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+char* msg_push_config_get_str(void *event_info, int field, int size)
+{
+       char *result = NULL;
+       MSG_PUSH_EVENT_INFO_S *pEvent = (MSG_PUSH_EVENT_INFO_S *)event_info;
+       switch(field)
+       {
+    case MSG_PUSH_CONFIG_CONTENT_TYPE_STR:
+               result = pEvent->contentType;
+               break;
+    case MSG_PUSH_CONFIG_APPLICATON_ID_STR:
+               result = pEvent->appId;
+               break;
+    case MSG_PUSH_CONFIG_PACKAGE_NAME_STR:
+               result = pEvent->pkgName;
+               break;
+
+       default:
+               result = NULL;
+               break;
+       }
+       return result;
+}
+
+bool msg_push_config_get_bool(void *event_info, int field)
+{
+       bool result = false;
+       MSG_PUSH_EVENT_INFO_S *pEvent = (MSG_PUSH_EVENT_INFO_S *)event_info;
+       switch(field)
+       {
+    case MSG_PUSH_CONFIG_LAUNCH_BOOL:
+       result = pEvent->bLaunch;
+               break;
+       default:
+               break;
+       }
+       return result;
+}
+
+int msg_push_config_set_str(void *event_info, int field, char *value, int size)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!event_info || !value)
+               return MSG_ERR_NULL_POINTER;
+    MSG_PUSH_EVENT_INFO_S *pEvent = (MSG_PUSH_EVENT_INFO_S *)event_info;
+    int _len = 0;
+
+    switch(field)
+    {
+    case MSG_PUSH_CONFIG_CONTENT_TYPE_STR:
+        (size > MAX_WAPPUSH_CONTENT_TYPE_LEN)? _len = MAX_WAPPUSH_CONTENT_TYPE_LEN : _len = size;
+               strncpy(pEvent->contentType, value, _len);
+               break;
+    case MSG_PUSH_CONFIG_APPLICATON_ID_STR:
+        (size > MAX_WAPPUSH_ID_LEN)? _len = MAX_WAPPUSH_ID_LEN : _len = size;
+               strncpy(pEvent->appId, value, _len);
+               break;
+    case MSG_PUSH_CONFIG_PACKAGE_NAME_STR:
+        (size > MSG_FILEPATH_LEN_MAX)? _len = MSG_FILEPATH_LEN_MAX : _len = size;
+               strncpy(pEvent->pkgName, value, _len);
+               break;
+    default:
+       err = MSG_ERR_UNKNOWN;
+               break;
+    }
+
+       return err;
+}
+
+int msg_push_config_set_bool(void *event, int field, bool value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!event)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_PUSH_EVENT_INFO_S *pEvent = (MSG_PUSH_EVENT_INFO_S *)event;
+    switch(field)
+    {
+    case MSG_PUSH_CONFIG_LAUNCH_BOOL:
+       pEvent->bLaunch = value;
+               break;
+    default:
+       err = MSG_ERR_UNKNOWN;
                break;
     }
        return err;
 }
+
+char* msg_media_item_get_str(void *data, int field, int size)
+{
+       char *result = NULL;
+       MSG_MEDIA_INFO_S *pMedia = (MSG_MEDIA_INFO_S *)data;
+
+       switch(field)
+       {
+       case MSG_MEDIA_ITEM_STR:
+               result = pMedia->media_item;
+               break;
+       case MSG_MEDIA_MIME_TYPE_STR:
+               result = pMedia->mime_type;
+               break;
+       case MSG_MEDIA_THUMB_PATH_STR:
+               result = pMedia->thumb_path;
+               break;
+       default:
+               result = NULL;
+               break;
+       }
+       return result;
+}
+
+int msg_media_item_get_int(void *data, int field, int *value)
+{
+       if (!data || !value)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MEDIA_INFO_S *pMedia = (MSG_MEDIA_INFO_S *)data;
+
+       switch (field) {
+               case MSG_MEDIA_MESSAGE_ID_INT:
+                       *value = pMedia->msg_id;
+                       break;
+               default :
+                       ret = MSG_ERR_INVALID_PARAMETER;
+                       break;
+       }
+
+       return ret;
+}
index 7a269e0..8e8be87 100755 (executable)
@@ -1,24 +1,27 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <string.h>
 
+#include "MsgDebug.h"
 #include "MsgTypes.h"
 #include "MsgHandle.h"
+#include "MsgTextConvert.h"
 #include "MsgException.h"
+#include "MsgMemory.h"
 
 #include "msg_private.h"
 #include "msg.h"
                })\
 
 
+void __msg_release_list_item(gpointer data)
+{
+       if (data == NULL)
+               return;
+
+       msg_release_struct((msg_struct_t*)(&data));
+}
+
 
 EXPORT_API msg_struct_t msg_create_struct(int field)
 {
+       CHECK_MSG_SUPPORTED_RETURN_NULL(MSG_TELEPHONY_FEATURE);
        msg_struct_s *msg_struct = new msg_struct_s;
        memset(msg_struct, 0x00, sizeof(msg_struct_s));
 
        msg_struct->type = field;
+       msg_struct->data = NULL;
 
        switch(field)
        {
        case MSG_STRUCT_MESSAGE_INFO :
                msg_message_create_struct(msg_struct);
                break;
+       case MSG_STRUCT_CONV_INFO:
+       {
+               msg_struct->data = (void *)new MSG_CONVERSATION_VIEW_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_CONVERSATION_VIEW_S));
+               break;
+       }
        case MSG_STRUCT_FILTER:
        {
                msg_struct->data = (void *)new MSG_FILTER_S;
@@ -134,6 +153,20 @@ EXPORT_API msg_struct_t msg_create_struct(int field)
                memset(msg_struct->data, 0x00, sizeof(MSG_SEARCH_CONDITION_S));
                break;
        }
+       case MSG_STRUCT_MSG_LIST_CONDITION:
+       {
+               msg_struct->data = new MSG_LIST_CONDITION_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_LIST_CONDITION_S));
+
+               msg_struct_s *pStruct = new msg_struct_s;
+               ((MSG_LIST_CONDITION_S *)msg_struct->data)->sortRule = (msg_struct_t)pStruct;
+
+               pStruct->type = MSG_STRUCT_SORT_RULE;
+               pStruct->data = new MSG_SORT_RULE_S;
+               memset(pStruct->data, 0x00, sizeof(MSG_SORT_RULE_S));
+
+               break;
+       }
        case MSG_STRUCT_REPORT_STATUS_INFO:
        {
                msg_struct->data = new MSG_REPORT_STATUS_INFO_S;
@@ -142,27 +175,30 @@ EXPORT_API msg_struct_t msg_create_struct(int field)
        }
        case MSG_STRUCT_SETTING_SMSC_OPT :
        {
-        msg_struct->data = new MSG_SMSC_LIST_HIDDEN_S;
-        memset(msg_struct->data, 0x00, sizeof(MSG_SMSC_LIST_HIDDEN_S));
+               msg_struct->data = new MSG_SMSC_LIST_HIDDEN_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_SMSC_LIST_HIDDEN_S));
 
-        MSG_SMSC_LIST_HIDDEN_S *pTmp = (MSG_SMSC_LIST_HIDDEN_S *)msg_struct->data;
+               MSG_SMSC_LIST_HIDDEN_S *pTmp = (MSG_SMSC_LIST_HIDDEN_S *)msg_struct->data;
+               pTmp->simIndex = MSG_SIM_SLOT_ID_1; // default sim index
 
-        msg_struct_list_s *smsc_list = (msg_struct_list_s *)new msg_struct_list_s;
-        memset(smsc_list, 0x00, sizeof(msg_struct_list_s));
+               msg_struct_list_s *smsc_list = (msg_struct_list_s *)new msg_struct_list_s;
+               memset(smsc_list, 0x00, sizeof(msg_struct_list_s));
 
-        pTmp->smsc_list = smsc_list;
+               pTmp->smsc_list = smsc_list;
 
-        smsc_list->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t)*SMSC_LIST_MAX];
+               smsc_list->msg_struct_info = (msg_struct_t *)calloc(SMSC_LIST_MAX, sizeof(msg_struct_t));
 
-        msg_struct_s *pStructTmp = NULL;
+               if (smsc_list->msg_struct_info != NULL) {
+                       msg_struct_s *pStructTmp = NULL;
 
-        for (int i = 0; i < SMSC_LIST_MAX; i++) {
-                pStructTmp = (msg_struct_s *)new msg_struct_s;
-                pStructTmp->type = MSG_STRUCT_SETTING_SMSC_INFO;
-                pStructTmp->data = new MSG_SMSC_DATA_S;
-                memset(pStructTmp->data, 0x00, sizeof(MSG_SMSC_DATA_S));
-                smsc_list->msg_struct_info[i] = (msg_struct_t)pStructTmp;
-        }
+                       for (int i = 0; i < SMSC_LIST_MAX; i++) {
+                               pStructTmp = (msg_struct_s *)new msg_struct_s;
+                               pStructTmp->type = MSG_STRUCT_SETTING_SMSC_INFO;
+                               pStructTmp->data = new MSG_SMSC_DATA_S;
+                               memset(pStructTmp->data, 0x00, sizeof(MSG_SMSC_DATA_S));
+                               smsc_list->msg_struct_info[i] = (msg_struct_t)pStructTmp;
+                       }
+               }
                break;
        }
        case MSG_STRUCT_SETTING_SMSC_INFO :
@@ -173,27 +209,29 @@ EXPORT_API msg_struct_t msg_create_struct(int field)
        }
        case MSG_STRUCT_SETTING_CB_OPT :
        {
-        msg_struct->data = new MSG_CBMSG_OPT_HIDDEN_S;
-        memset(msg_struct->data, 0x00, sizeof(MSG_CBMSG_OPT_HIDDEN_S));
+               msg_struct->data = new MSG_CBMSG_OPT_HIDDEN_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_CBMSG_OPT_HIDDEN_S));
 
-        MSG_CBMSG_OPT_HIDDEN_S *pTmp = (MSG_CBMSG_OPT_HIDDEN_S *)msg_struct->data;
+               MSG_CBMSG_OPT_HIDDEN_S *pTmp = (MSG_CBMSG_OPT_HIDDEN_S *)msg_struct->data;
+               pTmp->simIndex = MSG_SIM_SLOT_ID_1; // default sim index
 
-        pTmp->channelData = (msg_struct_list_s *)new msg_struct_list_s;
-        memset(pTmp->channelData, 0x00, sizeof(msg_struct_list_s));
+               pTmp->channelData = (msg_struct_list_s *)new msg_struct_list_s;
+               memset(pTmp->channelData, 0x00, sizeof(msg_struct_list_s));
 
-        pTmp->channelData->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t)*CB_CHANNEL_MAX];
+               pTmp->channelData->msg_struct_info = (msg_struct_t *)calloc(CB_CHANNEL_MAX, sizeof(msg_struct_t));
 
-        msg_struct_s *pStructTmp = NULL;
+               if (pTmp->channelData->msg_struct_info != NULL) {
+                       msg_struct_s *pStructTmp = NULL;
 
-        for (int i = 0; i < CB_CHANNEL_MAX; i++) {
-                pStructTmp = (msg_struct_s *)new msg_struct_s;
-                pStructTmp->type = MSG_STRUCT_SETTING_CB_CHANNEL_INFO;
-                pStructTmp->data = new MSG_CB_CHANNEL_INFO_S;
-
-                memset(pStructTmp->data, 0x00, sizeof(MSG_CB_CHANNEL_INFO_S));
-                pTmp->channelData->msg_struct_info[i] = (msg_struct_t)pStructTmp;
-        }
+                       for (int i = 0; i < CB_CHANNEL_MAX; i++) {
+                               pStructTmp = (msg_struct_s *)new msg_struct_s;
+                               pStructTmp->type = MSG_STRUCT_SETTING_CB_CHANNEL_INFO;
+                               pStructTmp->data = new MSG_CB_CHANNEL_INFO_S;
 
+                               memset(pStructTmp->data, 0x00, sizeof(MSG_CB_CHANNEL_INFO_S));
+                               pTmp->channelData->msg_struct_info[i] = (msg_struct_t)pStructTmp;
+                       }
+               }
                break;
        }
        case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
@@ -204,8 +242,8 @@ EXPORT_API msg_struct_t msg_create_struct(int field)
        }
        case MSG_STRUCT_SETTING_SMS_SEND_OPT :
        {
-        msg_struct->data = new MSG_SMS_SENDOPT_S;
-        memset(msg_struct->data, 0x00, sizeof(MSG_SMS_SENDOPT_S));
+               msg_struct->data = new MSG_SMS_SENDOPT_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_SMS_SENDOPT_S));
                break;
        }
        case MSG_STRUCT_SETTING_MMS_SEND_OPT :
@@ -230,6 +268,8 @@ EXPORT_API msg_struct_t msg_create_struct(int field)
        {
                msg_struct->data = new MSG_VOICEMAIL_OPT_S;
                memset(msg_struct->data, 0x00, sizeof(MSG_VOICEMAIL_OPT_S));
+               MSG_VOICEMAIL_OPT_S *pTmp = (MSG_VOICEMAIL_OPT_S *)msg_struct->data;
+               pTmp->simIndex = MSG_SIM_SLOT_ID_1; // default sim index
                break;
        }
        case MSG_STRUCT_SETTING_GENERAL_OPT :
@@ -300,15 +340,24 @@ EXPORT_API msg_struct_t msg_create_struct(int field)
        case MSG_STRUCT_MMS_META:
        case MSG_STRUCT_MMS_SMIL_TEXT:
        case MSG_STRUCT_MMS_SMIL_AVI:
+       case MSG_STRUCT_MULTIPART_INFO:
                msg_struct->data = msg_mms_create_struct_data(field);
                break;
+       case MSG_STRUCT_PUSH_CONFIG_INFO:
+               msg_struct->data = new MSG_PUSH_EVENT_INFO_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_PUSH_EVENT_INFO_S));
+               break;
+       default :
+               delete msg_struct;
+               return NULL;
+               break;
        }
 
        return (msg_struct_t) msg_struct;
 }
 
 
-EXPORT_API int msg_release_struct(msg_struct_t *msg_struct_handle)
+static int _release_msg_struct(msg_struct_t *msg_struct_handle)
 {
        msg_error_t err = MSG_SUCCESS;
 
@@ -335,6 +384,27 @@ EXPORT_API int msg_release_struct(msg_struct_t *msg_struct_handle)
                *msg_struct_handle = NULL;
                break;
        }
+       case MSG_STRUCT_CONV_INFO:
+       {
+               MSG_CONVERSATION_VIEW_S *pConv = (MSG_CONVERSATION_VIEW_S*)(msg_struct->data);
+
+               if (pConv->multipart_list) {
+                       g_list_free_full((GList *)pConv->multipart_list, __msg_release_list_item);
+                       pConv->multipart_list = NULL;
+               }
+
+               if (pConv->pText) {
+                       delete [] pConv->pText;
+                       pConv->pText = NULL;
+               }
+
+               delete pConv;
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
        case MSG_STRUCT_THREAD_INFO:
        {
                delete (MSG_THREAD_VIEW_S*)(msg_struct->data);
@@ -442,6 +512,24 @@ EXPORT_API int msg_release_struct(msg_struct_t *msg_struct_handle)
 
                break;
        }
+       case MSG_STRUCT_MSG_LIST_CONDITION:
+       {
+               MSG_LIST_CONDITION_S *pCond = (MSG_LIST_CONDITION_S*)(msg_struct->data);
+               MSG_SORT_RULE_S *pSortRule = (MSG_SORT_RULE_S *)(((msg_struct_s *)pCond->sortRule)->data);
+
+               delete (MSG_SORT_RULE_S *)pSortRule;
+               ((msg_struct_s *)pCond->sortRule)->data = NULL;
+               delete (msg_struct_s *)pCond->sortRule;
+               pCond->sortRule = NULL;
+
+               delete (MSG_LIST_CONDITION_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+
+               break;
+       }
        case MSG_STRUCT_REPORT_STATUS_INFO:
        {
                delete (MSG_REPORT_STATUS_INFO_S*)(msg_struct->data);
@@ -514,6 +602,7 @@ EXPORT_API int msg_release_struct(msg_struct_t *msg_struct_handle)
        case MSG_STRUCT_MMS_META:
        case MSG_STRUCT_MMS_SMIL_TEXT:
        case MSG_STRUCT_MMS_SMIL_AVI:
+       case MSG_STRUCT_MULTIPART_INFO:
        {
                msg_mms_release_struct(&msg_struct);
                *msg_struct_handle = NULL;
@@ -530,13 +619,15 @@ EXPORT_API int msg_release_struct(msg_struct_t *msg_struct_handle)
 
                for (int i = 0; i < SMSC_LIST_MAX; i++) {
                        smsc_info = (msg_struct_s *)smsc_list->msg_struct_info[i];
-                       delete [] (MSG_SMSC_DATA_S*)(smsc_info->data);
-                       delete [] smsc_info;
+                       delete (MSG_SMSC_DATA_S*)(smsc_info->data);
+                       delete smsc_info;
                }
 
-               delete [] smsc_list->msg_struct_info;
+               g_free(smsc_list->msg_struct_info);
+
+               delete smsc_list;
 
-               delete [] (MSG_SMSC_LIST_HIDDEN_S*)pTmp;
+               delete pTmp;
                msg_struct->data = NULL;
 
                delete msg_struct;
@@ -563,13 +654,15 @@ EXPORT_API int msg_release_struct(msg_struct_t *msg_struct_handle)
 
                for (int i = 0; i < CB_CHANNEL_MAX; i++) {
                        cb_info = (msg_struct_s *)cb_list->msg_struct_info[i];
-                       delete [] (MSG_CB_CHANNEL_INFO_S*)(cb_info->data);
-                       delete [] cb_info;
+                       delete (MSG_CB_CHANNEL_INFO_S*)(cb_info->data);
+                       delete cb_info;
                }
 
-               delete [] cb_list->msg_struct_info;
+               g_free(cb_list->msg_struct_info);
 
-               delete [] (MSG_CBMSG_OPT_HIDDEN_S*)pTmp;
+               delete cb_list;
+
+               delete pTmp;
                msg_struct->data = NULL;
 
                delete msg_struct;
@@ -639,6 +732,33 @@ EXPORT_API int msg_release_struct(msg_struct_t *msg_struct_handle)
                *msg_struct_handle = NULL;
                break;
        }
+       case MSG_STRUCT_ADDRESS_INFO :
+       {
+               delete (MSG_ADDRESS_INFO_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_PUSH_CONFIG_INFO:
+       {
+               delete (MSG_PUSH_EVENT_INFO_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_MEDIA_INFO:
+       {
+               delete (MSG_MEDIA_INFO_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
        default :
                err = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -647,8 +767,21 @@ EXPORT_API int msg_release_struct(msg_struct_t *msg_struct_handle)
        return err;
 }
 
-int msg_release_list_struct(msg_struct_list_s *msg_struct_list)
+EXPORT_API int msg_release_struct(msg_struct_t *msg_struct_handle)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+
+       int ret = _release_msg_struct(msg_struct_handle);
+
+       // Release Memory
+       MsgReleaseMemory();
+
+       return ret;
+}
+
+EXPORT_API int msg_release_list_struct(msg_struct_list_s *msg_struct_list)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
        if (msg_struct_list == NULL)
@@ -661,20 +794,40 @@ int msg_release_list_struct(msg_struct_list_s *msg_struct_list)
        }
 
        if(msg_struct_list->nCount > 0) {
-               for(int i = 0; i < msg_struct_list->nCount; i++) {
-                       msg_release_struct(&(msg_struct_list->msg_struct_info[i]));
+               int structType = ((msg_struct_s *)msg_struct_list->msg_struct_info[0])->type;
+               int listCnt = msg_struct_list->nCount;
+
+               switch (structType)
+               {
+//             case MSG_STRUCT_ADDRESS_INFO :
+//             {
+//                     listCnt = MAX_TO_ADDRESS_CNT;
+//                     break;
+//             }
+               default :
+                       break;
+               }
+
+               for(int i = 0; i < listCnt; i++) {
+                       _release_msg_struct(&(msg_struct_list->msg_struct_info[i]));
                }
        }
 
        //free peer info list
-       delete [] msg_struct_list->msg_struct_info;
+       g_free(msg_struct_list->msg_struct_info);
        msg_struct_list->msg_struct_info = NULL;
 
+       msg_struct_list->nCount = 0;
+
+       // Release Memory
+       MsgReleaseMemory();
+
        return err;
 }
 
 EXPORT_API int msg_get_int_value(msg_struct_t msg_struct_handle, int field, int *value)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
 
        msg_error_t err = MSG_SUCCESS;
 
@@ -716,9 +869,15 @@ EXPORT_API int msg_get_int_value(msg_struct_t msg_struct_handle, int field, int
        case MSG_STRUCT_THREAD_INFO :
                *value = msg_thread_info_get_int(msg_struct->data, field);
                break;
+       case MSG_STRUCT_CONV_INFO :
+               *value = msg_conv_info_get_int(msg_struct->data, field);
+               break;
        case MSG_STRUCT_SEARCH_CONDITION :
                *value = msg_search_condition_get_int(msg_struct->data, field);
                break;
+       case MSG_STRUCT_MSG_LIST_CONDITION :
+               *value = msg_list_condition_get_int(msg_struct->data, field);
+               break;
        case MSG_STRUCT_REPORT_STATUS_INFO :
                *value = msg_report_status_get_int(msg_struct->data, field);
                break;
@@ -737,6 +896,9 @@ EXPORT_API int msg_get_int_value(msg_struct_t msg_struct_handle, int field, int
        case MSG_STRUCT_SENT_STATUS_INFO :
                *value = msg_sent_status_get_int((MSG_SENT_STATUS_S *)msg_struct->data, field);
                break;
+       case MSG_STRUCT_CB_MSG :
+               err = msg_cb_message_get_int_value (msg_struct->data, field, value);
+               break;
        case MSG_STRUCT_MMS:
        case MSG_STRUCT_MMS_PAGE:
        case MSG_STRUCT_MMS_MEDIA:
@@ -746,6 +908,7 @@ EXPORT_API int msg_get_int_value(msg_struct_t msg_struct_handle, int field, int
        case MSG_STRUCT_MMS_META:
        case MSG_STRUCT_MMS_SMIL_TEXT:
        case MSG_STRUCT_MMS_SMIL_AVI:
+       case MSG_STRUCT_MULTIPART_INFO:
                err = msg_mms_get_int_value(msg_struct, field, value);
                break;
        case MSG_STRUCT_SETTING_SMSC_OPT :
@@ -758,8 +921,12 @@ EXPORT_API int msg_get_int_value(msg_struct_t msg_struct_handle, int field, int
        case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
        case MSG_STRUCT_SETTING_GENERAL_OPT :
        case MSG_STRUCT_SETTING_MSGSIZE_OPT :
+       case MSG_STRUCT_SETTING_VOICE_MSG_OPT :
                err = msg_setting_get_int_value(msg_struct, field, value);
                break;
+       case MSG_STRUCT_MEDIA_INFO :
+               err = msg_media_item_get_int(msg_struct->data, field, value);
+               break;
        default :
                err = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -770,6 +937,7 @@ EXPORT_API int msg_get_int_value(msg_struct_t msg_struct_handle, int field, int
 
 EXPORT_API int msg_get_str_value(msg_struct_t msg_struct_handle, int field, char *src, int size)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
        if (msg_struct_handle == NULL)
@@ -808,6 +976,13 @@ EXPORT_API int msg_get_str_value(msg_struct_t msg_struct_handle, int field, char
                else
                        strncpy(src, ret_str, size);
                break;
+       case MSG_STRUCT_CONV_INFO :
+               ret_str = msg_conv_info_get_str(msg_struct->data, field);
+               if (ret_str == NULL)
+                       err = MSG_ERR_UNKNOWN;
+               else
+                       strncpy(src, ret_str, size);
+               break;
        case MSG_STRUCT_SEARCH_CONDITION :
                ret_str = msg_search_condition_get_str(msg_struct->data, field, size);
                if (ret_str == NULL)
@@ -815,6 +990,13 @@ EXPORT_API int msg_get_str_value(msg_struct_t msg_struct_handle, int field, char
                else
                        strncpy(src, ret_str, size);
                break;
+       case MSG_STRUCT_MSG_LIST_CONDITION :
+               ret_str = msg_list_condition_get_str(msg_struct->data, field, size);
+               if (ret_str == NULL)
+                       err = MSG_ERR_UNKNOWN;
+               else
+                       strncpy(src, ret_str, size);
+               break;
 
        case MSG_STRUCT_ADDRESS_INFO :
                ret_str = msg_address_info_get_str(msg_struct->data, field, size);
@@ -831,6 +1013,13 @@ EXPORT_API int msg_get_str_value(msg_struct_t msg_struct_handle, int field, char
                else
                        strncpy(src, ret_str, size);
                break;
+       case MSG_STRUCT_MEDIA_INFO :
+               ret_str = msg_media_item_get_str(msg_struct->data, field, size);
+               if (ret_str == NULL)
+                       err = MSG_ERR_UNKNOWN;
+               else
+                       strncpy(src, ret_str, size);
+               break;
        case MSG_STRUCT_MMS:
        case MSG_STRUCT_MMS_PAGE:
        case MSG_STRUCT_MMS_MEDIA:
@@ -840,13 +1029,32 @@ EXPORT_API int msg_get_str_value(msg_struct_t msg_struct_handle, int field, char
        case MSG_STRUCT_MMS_META:
        case MSG_STRUCT_MMS_SMIL_TEXT:
        case MSG_STRUCT_MMS_SMIL_AVI:
+       case MSG_STRUCT_MULTIPART_INFO:
                err = msg_mms_get_str_value(msg_struct, field, src, size);
                break;
+       case MSG_STRUCT_SETTING_GENERAL_OPT :
        case MSG_STRUCT_SETTING_SMSC_INFO :
        case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
        case MSG_STRUCT_SETTING_VOICE_MSG_OPT :
                err = msg_setting_get_str_value(msg_struct, field, src, size);
                break;
+       case MSG_STRUCT_PUSH_CONFIG_INFO :
+               ret_str = msg_push_config_get_str(msg_struct->data, field, size);
+               if (ret_str == NULL)
+                       err = MSG_ERR_UNKNOWN;
+               else
+                       strncpy(src, ret_str, size);
+               break;
+       case MSG_STRUCT_REPORT_STATUS_INFO:
+               ret_str = msg_report_status_get_str(msg_struct->data, field);
+               if (ret_str == NULL)
+                       err = MSG_ERR_UNKNOWN;
+               else
+                       strncpy(src, ret_str, size);
+               break;
+       case MSG_STRUCT_CB_MSG :
+               err = msg_cb_message_get_str_value(msg_struct->data, field, src, size);
+               break;
        default :
                err = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -857,6 +1065,7 @@ EXPORT_API int msg_get_str_value(msg_struct_t msg_struct_handle, int field, char
 
 EXPORT_API int msg_get_bool_value(msg_struct_t msg_struct_handle, int field, bool *value)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
        if (msg_struct_handle == NULL)
@@ -869,15 +1078,27 @@ EXPORT_API int msg_get_bool_value(msg_struct_t msg_struct_handle, int field, boo
 
        switch (msg_struct->type)
        {
+       case MSG_STRUCT_FILTER :
+               *value = msg_get_filter_info_bool(msg_struct->data, field);
+               break;
        case MSG_STRUCT_MESSAGE_INFO :
                err = msg_message_get_bool_value(msg_struct->data, field, value);
                break;
+       case MSG_STRUCT_THREAD_INFO :
+               *value = msg_thread_info_get_bool(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_CONV_INFO:
+               *value = msg_conv_get_bool(msg_struct->data, field);
+               break;
        case MSG_STRUCT_SENDOPT:
                *value = msg_sendopt_get_bool(msg_struct->data, field);
                break;
        case MSG_STRUCT_SORT_RULE:
                *value = msg_sortrule_get_bool(msg_struct->data, field);
                break;
+       case MSG_STRUCT_MSG_LIST_CONDITION:
+               *value = msg_list_condition_get_bool(msg_struct->data, field);
+               break;
        case MSG_STRUCT_MMS_SENDOPT:
                *value = msg_mms_sendopt_get_bool(msg_struct->data, field);
                break;
@@ -914,6 +1135,7 @@ EXPORT_API int msg_get_bool_value(msg_struct_t msg_struct_handle, int field, boo
 
 EXPORT_API int msg_get_struct_handle(msg_struct_t msg_struct_handle, int field, msg_struct_t *value)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
        if (msg_struct_handle == NULL)
@@ -938,6 +1160,9 @@ EXPORT_API int msg_get_struct_handle(msg_struct_t msg_struct_handle, int field,
        case MSG_STRUCT_THREAD_LIST_INDEX:
                err = msg_thread_index_get_struct_handle(msg_struct, field, (void **)value);
                break;
+       case MSG_STRUCT_MSG_LIST_CONDITION:
+               err = msg_list_condition_get_struct_handle(msg_struct, field, (void **)value);
+               break;
        case MSG_STRUCT_MMS_MEDIA:
                err = msg_mms_get_struct_handle(msg_struct, field, (msg_struct_s**)value);
                break;
@@ -954,6 +1179,7 @@ EXPORT_API int msg_get_struct_handle(msg_struct_t msg_struct_handle, int field,
 
 EXPORT_API int msg_get_list_handle(msg_struct_t msg_struct_handle, int field, void **value)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
        if (msg_struct_handle == NULL)
@@ -969,6 +1195,9 @@ EXPORT_API int msg_get_list_handle(msg_struct_t msg_struct_handle, int field, vo
        case MSG_STRUCT_MESSAGE_INFO :
                err = msg_message_get_list_hnd(msg_struct->data, field, value);
                break;
+       case MSG_STRUCT_CONV_INFO:
+               err = msg_conversation_get_list_hnd(msg_struct->data, field, value);
+               break;
        case MSG_STRUCT_MMS:
        case MSG_STRUCT_MMS_PAGE:
                err = msg_mms_get_list_handle(msg_struct, field, (msg_list_handle_t *)value);
@@ -987,6 +1216,7 @@ EXPORT_API int msg_get_list_handle(msg_struct_t msg_struct_handle, int field, vo
 
 EXPORT_API int msg_set_int_value(msg_struct_t msg_struct_handle, int field, int value)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
        if (msg_struct_handle == NULL)
@@ -1026,6 +1256,9 @@ EXPORT_API int msg_set_int_value(msg_struct_t msg_struct_handle, int field, int
        case MSG_STRUCT_SEARCH_CONDITION :
                err = msg_search_condition_set_int(msg_struct->data, field, value);
                break;
+       case MSG_STRUCT_MSG_LIST_CONDITION :
+               err = msg_list_condition_set_int(msg_struct->data, field, value);
+               break;
        case MSG_STRUCT_REPORT_STATUS_INFO :
                err = msg_report_status_set_int(msg_struct->data, field, value);
                break;
@@ -1062,6 +1295,7 @@ EXPORT_API int msg_set_int_value(msg_struct_t msg_struct_handle, int field, int
        case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
        case MSG_STRUCT_SETTING_GENERAL_OPT :
        case MSG_STRUCT_SETTING_MSGSIZE_OPT :
+       case MSG_STRUCT_SETTING_VOICE_MSG_OPT :
                err = msg_setting_set_int_value(msg_struct, field, value);
                break;
        default :
@@ -1074,6 +1308,7 @@ EXPORT_API int msg_set_int_value(msg_struct_t msg_struct_handle, int field, int
 
 EXPORT_API int msg_set_str_value(msg_struct_t msg_struct_handle, int field, char *value, int size)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
        if (msg_struct_handle == NULL)
@@ -1098,6 +1333,9 @@ EXPORT_API int msg_set_str_value(msg_struct_t msg_struct_handle, int field, char
        case MSG_STRUCT_SEARCH_CONDITION :
                err = msg_search_condition_set_str(msg_struct->data, field, value, size);
                break;
+       case MSG_STRUCT_MSG_LIST_CONDITION :
+               err = msg_list_condition_set_str(msg_struct->data, field, value, size);
+               break;
        case MSG_STRUCT_ADDRESS_INFO :
                err = msg_address_info_set_str(msg_struct->data, field, value, size);
                break;
@@ -1113,13 +1351,21 @@ EXPORT_API int msg_set_str_value(msg_struct_t msg_struct_handle, int field, char
        case MSG_STRUCT_MMS_META:
        case MSG_STRUCT_MMS_SMIL_TEXT:
        case MSG_STRUCT_MMS_SMIL_AVI:
+       case MSG_STRUCT_MULTIPART_INFO:
                err = msg_mms_set_str_value(msg_struct, field, value, size);
                break;
+       case MSG_STRUCT_SETTING_GENERAL_OPT :
        case MSG_STRUCT_SETTING_SMSC_INFO :
        case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
        case MSG_STRUCT_SETTING_VOICE_MSG_OPT :
                err = msg_setting_set_str_value(msg_struct, field, value, size);
                break;
+       case MSG_STRUCT_PUSH_CONFIG_INFO:
+               err = msg_push_config_set_str(msg_struct->data, field, value, size);
+               break;
+       case MSG_STRUCT_MEDIA_INFO :
+               err = msg_media_info_set_str(msg_struct->data, field, value, size);
+               break;
        default :
                err = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -1130,6 +1376,7 @@ EXPORT_API int msg_set_str_value(msg_struct_t msg_struct_handle, int field, char
 
 EXPORT_API int msg_set_bool_value(msg_struct_t msg_struct_handle, int field, bool value)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
        if (msg_struct_handle == NULL)
@@ -1142,6 +1389,9 @@ EXPORT_API int msg_set_bool_value(msg_struct_t msg_struct_handle, int field, boo
 
        switch (msg_struct->type)
        {
+       case MSG_STRUCT_FILTER :
+               err = msg_set_filter_info_bool(msg_struct->data, field, value);
+               break;
        case MSG_STRUCT_MESSAGE_INFO :
                err = msg_message_set_bool_value(msg_struct->data, field, value);
                break;
@@ -1151,6 +1401,9 @@ EXPORT_API int msg_set_bool_value(msg_struct_t msg_struct_handle, int field, boo
        case MSG_STRUCT_SORT_RULE:
                err = msg_sortrule_set_bool(msg_struct->data, field, value);
                break;
+       case MSG_STRUCT_MSG_LIST_CONDITION:
+               err = msg_list_condition_set_bool(msg_struct->data, field, value);
+               break;
        case MSG_STRUCT_MMS_SENDOPT:
                err = msg_mms_sendopt_set_bool(msg_struct->data, field, value);
                break;
@@ -1177,6 +1430,9 @@ EXPORT_API int msg_set_bool_value(msg_struct_t msg_struct_handle, int field, boo
        case MSG_STRUCT_SETTING_GENERAL_OPT :
                err = msg_setting_set_bool_value(msg_struct, field, value);
                break;
+       case MSG_STRUCT_PUSH_CONFIG_INFO:
+               err = msg_push_config_set_bool(msg_struct->data, field, value);
+               break;
        default :
                err = MSG_ERR_INVALID_PARAMETER;
                break;
@@ -1187,6 +1443,7 @@ EXPORT_API int msg_set_bool_value(msg_struct_t msg_struct_handle, int field, boo
 
 EXPORT_API int msg_set_struct_handle(msg_struct_t msg_struct_handle, int field, msg_struct_t value)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
        if (msg_struct_handle == NULL)
@@ -1211,6 +1468,9 @@ EXPORT_API int msg_set_struct_handle(msg_struct_t msg_struct_handle, int field,
        case MSG_STRUCT_THREAD_LIST_INDEX:
                err = msg_thread_index_set_struct_handle(msg_struct, field, (msg_struct_s *)value);
                break;
+       case MSG_STRUCT_MSG_LIST_CONDITION:
+               err = msg_list_condition_set_struct_handle(msg_struct, field, (msg_struct_s *)value);
+               break;
        case MSG_STRUCT_MMS_MEDIA:
                err = msg_mms_set_struct_handle(msg_struct, field, (msg_struct_s *)value);
                break;
@@ -1227,6 +1487,7 @@ EXPORT_API int msg_set_struct_handle(msg_struct_t msg_struct_handle, int field,
 
 EXPORT_API int msg_set_list_handle(msg_struct_t msg_struct_handle, int field, void *value)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
        if (msg_struct_handle == NULL)
@@ -1237,21 +1498,217 @@ EXPORT_API int msg_set_list_handle(msg_struct_t msg_struct_handle, int field, vo
        if (msg_struct->data == NULL)
                return MSG_ERR_NULL_POINTER;
 
+#if 0 // No operations
        switch (msg_struct->type)
        {
        default :
                err = MSG_ERR_INVALID_PARAMETER;
                break;
        }
+#endif
+
+       return err;
+}
+
+EXPORT_API int msg_list_add_item(msg_struct_t msg_struct_handle, int field, msg_struct_t *item)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       if (msg_struct_handle == NULL || item == NULL) {
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       msg_error_t err = MSG_SUCCESS;
+       msg_struct_s *msg_struct = (msg_struct_s *)msg_struct_handle;
+
+       switch(msg_struct->type) {
+       case MSG_STRUCT_MESSAGE_INFO:
+       {
+               err = msg_message_list_append(msg_struct_handle, field, item);
+       }
+       break;
+       case MSG_STRUCT_MMS:
+       case MSG_STRUCT_MMS_PAGE:
+       {
+               err = msg_mms_list_append(msg_struct_handle, field, item);
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
        return err;
 }
 
 EXPORT_API msg_struct_t msg_list_nth_data(msg_list_handle_t list_handle, int index)
 {
+       CHECK_MSG_SUPPORTED_RETURN_NULL(MSG_TELEPHONY_FEATURE);
+       if (list_handle == NULL) {
+               return NULL;
+       }
+
        return (msg_struct_t)g_list_nth_data((GList *)list_handle,(guint)index);
 }
 
 EXPORT_API int msg_list_length(msg_list_handle_t list_handle)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       if (list_handle == NULL) {
+               return 0;
+       }
+
        return (int)g_list_length((GList *)list_handle);
 }
+
+EXPORT_API int msg_list_clear(msg_struct_t msg_struct_handle, int field)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       if (msg_struct_handle == NULL) {
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       msg_error_t err = MSG_SUCCESS;
+       msg_struct_s *msg_struct = (msg_struct_s *)msg_struct_handle;
+
+       switch(msg_struct->type) {
+       case MSG_STRUCT_MESSAGE_INFO:
+       {
+               err = msg_message_list_clear(msg_struct_handle, field);
+       }
+       break;
+//     case MSG_STRUCT_MMS:
+//     case MSG_STRUCT_MMS_PAGE:
+//     {
+//             err = msg_mms_list_append(msg_struct_handle, field, item);
+//     }
+//     break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_list_free(msg_list_handle_t list_handle)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       if (list_handle == NULL) {
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       g_list_free_full((GList *)list_handle, __msg_release_list_item);
+       list_handle = NULL;
+
+       return MSG_SUCCESS;
+}
+
+
+EXPORT_API int msg_util_calculate_text_length(const char* msg_text, msg_encode_type_t msg_encode_type_to, unsigned int *text_size, unsigned int *segment_size, msg_encode_type_t *msg_encode_type_in)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_text == NULL || text_size == NULL || segment_size == NULL) {
+               err = MSG_ERR_INVALID_PARAMETER;
+               return err;
+       }
+
+       msg_encode_type_t encodeType = MSG_ENCODE_AUTO;
+       MSG_LANGUAGE_ID_T langId = MSG_LANG_ID_RESERVED;
+
+       int decodeLen = 0;
+       int bufSize = 0;
+       int textSize = 0;
+
+       bool bAbnormal = false;
+
+       textSize = strlen(msg_text);
+
+       bufSize = textSize * 4;
+
+       unsigned char decodeData[bufSize+1];
+       memset(decodeData, 0x00, sizeof(decodeData));
+
+       MsgTextConvert *textCvt = MsgTextConvert::instance();
+
+       *text_size = 0;
+       *segment_size = 0;
+
+       switch (msg_encode_type_to)
+       {
+       case MSG_ENCODE_GSM7BIT :
+               decodeLen = textCvt->convertUTF8ToGSM7bit(decodeData, bufSize, (const unsigned char*)msg_text, textSize, &langId, &bAbnormal);
+               break;
+       case MSG_ENCODE_UCS2 :
+               decodeLen = textCvt->convertUTF8ToUCS2(decodeData, bufSize, (const unsigned char*)msg_text, textSize);
+               break;
+       case MSG_ENCODE_AUTO :
+#ifndef FEATURE_SMS_CDMA
+               decodeLen = textCvt->convertUTF8ToAuto(decodeData, bufSize, (const unsigned char*)msg_text, textSize, &langId, &encodeType);
+#else
+               decodeLen = textCvt->convertUTF8ToAuto(decodeData, bufSize, (const unsigned char*)msg_text, textSize, &encodeType);
+#endif
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               return err;
+               break;
+       }
+
+       // calculate segment size.
+       int headerLen = 0;
+       int concat = 5;
+       int lang = 3;
+
+       int headerSize = 0;
+       int segSize = 0;
+
+       if (langId != MSG_LANG_ID_RESERVED) {
+               MSG_DEBUG("National Language Exists");
+               headerSize += lang;
+               headerLen = 1;
+       }
+
+       if (msg_encode_type_to == MSG_ENCODE_GSM7BIT || encodeType == MSG_ENCODE_GSM7BIT) {
+               MSG_DEBUG("MSG_ENCODE_GSM7BIT");
+
+               if ((decodeLen + headerSize) > 160) {
+                       headerLen = 1;
+                       segSize = ((140 - (headerLen + concat + headerSize)) * 8)/7;
+               }
+               else
+                       segSize = ((140 - headerLen - headerSize) * 8) / 7;
+
+               if (bAbnormal)
+                       *msg_encode_type_in = MSG_ENCODE_GSM7BIT_ABNORMAL;
+               else
+                       *msg_encode_type_in = MSG_ENCODE_GSM7BIT;
+
+       } else if (msg_encode_type_to == MSG_ENCODE_UCS2 || encodeType == MSG_ENCODE_UCS2) {
+               MSG_DEBUG("MSG_ENCODE_UCS2");
+
+//             if (((decodeLen+headerSize)/140) > 1)
+//                     segSize = 140 - (headerLen + concat + headerSize);
+               if (decodeLen > 140) {
+                       headerLen = 1;
+                       segSize = 140 - (headerLen + concat);
+               } else
+                       segSize = 140;
+
+               *msg_encode_type_in = MSG_ENCODE_UCS2;
+
+       } else {
+               MSG_DEBUG("Unsupported encode type.");
+               err = MSG_ERR_INVALID_PARAMETER;
+               return err;
+       }
+
+       MSG_DEBUG("decodeLen [%d] segSize [%d]", decodeLen, segSize);
+
+       *text_size = decodeLen;
+       *segment_size = segSize;
+
+       return err;
+}
index ec6dfd6..b386331 100755 (executable)
@@ -1,20 +1,21 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
+#include <privacy_checker_client.h>
 
 #include "MsgHandle.h"
 #include "MsgDebug.h"
 ==================================================================================================*/
 EXPORT_API int msg_submit_req(msg_handle_t handle, msg_struct_t req)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL ||req == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -58,11 +68,20 @@ EXPORT_API int msg_submit_req(msg_handle_t handle, msg_struct_t req)
 
 EXPORT_API int msg_reg_sent_status_callback(msg_handle_t handle, msg_sent_status_cb cb, void *user_param)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || cb == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -74,7 +93,10 @@ EXPORT_API int msg_reg_sent_status_callback(msg_handle_t handle, msg_sent_status
        catch (MsgException& e)
        {
                MSG_FATAL("%s", e.what());
-               return MSG_ERR_CALLBACK_ERROR;
+               if (e.errorCode() == MsgException::SERVER_READY_ERROR)
+                       return MSG_ERR_PERMISSION_DENIED;
+               else
+                       return MSG_ERR_CALLBACK_ERROR;
        }
 
        return err;
@@ -83,11 +105,20 @@ EXPORT_API int msg_reg_sent_status_callback(msg_handle_t handle, msg_sent_status
 
 EXPORT_API int msg_reg_sms_message_callback(msg_handle_t handle, msg_sms_incoming_cb cb, unsigned short port, void *user_param)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || cb == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -99,7 +130,10 @@ EXPORT_API int msg_reg_sms_message_callback(msg_handle_t handle, msg_sms_incomin
        catch (MsgException& e)
        {
                MSG_FATAL("%s", e.what());
-               return MSG_ERR_CALLBACK_ERROR;
+               if (e.errorCode() == MsgException::SERVER_READY_ERROR)
+                       return MSG_ERR_PERMISSION_DENIED;
+               else
+                       return MSG_ERR_CALLBACK_ERROR;
        }
 
        return err;
@@ -108,16 +142,25 @@ EXPORT_API int msg_reg_sms_message_callback(msg_handle_t handle, msg_sms_incomin
 
 EXPORT_API int msg_reg_mms_conf_message_callback(msg_handle_t handle, msg_mms_conf_msg_incoming_cb cb, const char *app_id, void *user_param)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || cb == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        if (app_id && strlen(app_id) > MAX_MMS_JAVA_APPID_LEN)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -129,7 +172,10 @@ EXPORT_API int msg_reg_mms_conf_message_callback(msg_handle_t handle, msg_mms_co
        catch (MsgException& e)
        {
                MSG_FATAL("%s", e.what());
-               return MSG_ERR_CALLBACK_ERROR;
+               if (e.errorCode() == MsgException::SERVER_READY_ERROR)
+                       return MSG_ERR_PERMISSION_DENIED;
+               else
+                       return MSG_ERR_CALLBACK_ERROR;
        }
 
        return err;
@@ -138,11 +184,20 @@ EXPORT_API int msg_reg_mms_conf_message_callback(msg_handle_t handle, msg_mms_co
 
 EXPORT_API int msg_reg_syncml_message_callback(msg_handle_t handle,  msg_syncml_msg_incoming_cb cb, void *user_param)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || cb == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -154,7 +209,10 @@ EXPORT_API int msg_reg_syncml_message_callback(msg_handle_t handle,  msg_syncml_
        catch (MsgException& e)
        {
                MSG_FATAL("%s", e.what());
-               return MSG_ERR_CALLBACK_ERROR;
+               if (e.errorCode() == MsgException::SERVER_READY_ERROR)
+                       return MSG_ERR_PERMISSION_DENIED;
+               else
+                       return MSG_ERR_CALLBACK_ERROR;
        }
 
        return err;
@@ -163,11 +221,20 @@ EXPORT_API int msg_reg_syncml_message_callback(msg_handle_t handle,  msg_syncml_
 
 EXPORT_API int msg_reg_lbs_message_callback(msg_handle_t handle, msg_lbs_msg_incoming_cb cb, void *user_param)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || cb == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -179,7 +246,10 @@ EXPORT_API int msg_reg_lbs_message_callback(msg_handle_t handle, msg_lbs_msg_inc
        catch (MsgException& e)
        {
                MSG_FATAL("%s", e.what());
-               return MSG_ERR_CALLBACK_ERROR;
+               if (e.errorCode() == MsgException::SERVER_READY_ERROR)
+                       return MSG_ERR_PERMISSION_DENIED;
+               else
+                       return MSG_ERR_CALLBACK_ERROR;
        }
 
        return err;
@@ -188,11 +258,20 @@ EXPORT_API int msg_reg_lbs_message_callback(msg_handle_t handle, msg_lbs_msg_inc
 
 EXPORT_API int msg_reg_syncml_message_operation_callback(msg_handle_t handle,  msg_syncml_msg_operation_cb cb, void *user_param)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || cb == NULL)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -204,7 +283,125 @@ EXPORT_API int msg_reg_syncml_message_operation_callback(msg_handle_t handle,  m
        catch (MsgException& e)
        {
                MSG_FATAL("%s", e.what());
-               return MSG_ERR_CALLBACK_ERROR;
+               if (e.errorCode() == MsgException::SERVER_READY_ERROR)
+                       return MSG_ERR_PERMISSION_DENIED;
+               else
+                       return MSG_ERR_CALLBACK_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_reg_push_message_callback(msg_handle_t handle,  msg_push_msg_incoming_cb cb, const char *app_id, void *user_param)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
+
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || cb == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (app_id && strlen(app_id) > MAX_WAPPUSH_ID_LEN)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regPushMessageCallback(cb, app_id, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               if (e.errorCode() == MsgException::SERVER_READY_ERROR)
+                       return MSG_ERR_PERMISSION_DENIED;
+               else
+                       return MSG_ERR_CALLBACK_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_reg_cb_message_callback(msg_handle_t handle, msg_cb_incoming_cb  cb, bool bsave, void *user_param)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
+
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || cb == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regCBMessageCallback(cb, bsave, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               if (e.errorCode() == MsgException::SERVER_READY_ERROR)
+                       return MSG_ERR_PERMISSION_DENIED;
+               else
+                       return MSG_ERR_CALLBACK_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_reg_report_message_callback(msg_handle_t handle, msg_report_msg_incoming_cb cb, void *user_param)
+{
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       msg_error_t err =  MSG_SUCCESS;
+
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
+       if (handle == NULL || cb == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regReportMessageCallback(cb, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               if (e.errorCode() == MsgException::SERVER_READY_ERROR)
+                       return MSG_ERR_PERMISSION_DENIED;
+               else
+                       return MSG_ERR_CALLBACK_ERROR;
        }
 
        return err;
@@ -213,11 +410,20 @@ EXPORT_API int msg_reg_syncml_message_operation_callback(msg_handle_t handle,  m
 
 EXPORT_API int msg_syncml_message_operation(msg_handle_t handle,  msg_message_id_t msgId)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_READ_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || msgId < 1)
        {
-               return -EINVAL;
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        MsgHandle* pHandle = (MsgHandle*)handle;
@@ -261,14 +467,14 @@ static int msg_send_single_sms(const char *phone_num, const char *sms_text, msg_
 {
        if (phone_num == NULL || sms_text == NULL || cb == NULL)
        {
-               MSG_DEBUG("Invalid parameter [%s] [%s] [%s]", phone_num, sms_text, cb);
-               return -EINVAL;
+               MSG_SEC_DEBUG("Invalid parameter [%s] [%s] [%s]", phone_num, sms_text, cb);
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        if (strlen(phone_num) > MAX_PHONE_NUMBER_LEN)
        {
-               MSG_DEBUG("Phone Number is too long [%s]", phone_num);
-               return -EINVAL;
+               MSG_SEC_DEBUG("Phone Number is too long [%s]", phone_num);
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        msg_struct_s req = {0,};
@@ -298,37 +504,56 @@ static int msg_send_single_sms(const char *phone_num, const char *sms_text, msg_
        msg_info.subType = MSG_NORMAL_SMS;
        msg_info.msgId = 0;
        msg_info.folderId = MSG_OUTBOX_ID;
+       msg_info.simIndex = MSG_SIM_SLOT_ID_1;
 
        /* fill the destination number in msgReq */
+       MSG_ADDRESS_INFO_S address = {0,};
+       memset(&address, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+       address.addressType = MSG_ADDRESS_TYPE_PLMN;
+       address.recipientType = MSG_RECIPIENTS_TYPE_TO;
+       snprintf(address.addressVal, MAX_ADDRESS_VAL_LEN, "%s", phone_num);
+
        msg_struct_list_s addr_list = {0,};
 
        addr_list.nCount = 1;
+       addr_list.msg_struct_info = (msg_struct_t *)calloc(1, sizeof(msg_struct_t));
+       if (addr_list.msg_struct_info) {
+               addr_list.msg_struct_info[0] = (msg_struct_t)new msg_struct_s;
+               msg_struct_s *pTmp;
+               pTmp = (msg_struct_s *)addr_list.msg_struct_info[0];
+               pTmp->type = MSG_STRUCT_ADDRESS_INFO;
+               pTmp->data = &address;
+       } else {
+               MSG_ERR("Memory error");
+               msg_close_msg_handle(&msgHandle);
+               return MSG_ERR_MEMORY_ERROR;
+       }
 
-       msg_struct_s addr_info[addr_list.nCount];
-       memset(addr_info, 0, sizeof(msg_struct_s) * addr_list.nCount);
-       addr_list.msg_struct_info = (msg_struct_t *)&addr_info;
+       msg_info.addr_list = (msg_struct_list_s *)&addr_list;
 
-       MSG_ADDRESS_INFO_S address[addr_list.nCount];
-       memset(address, 0, sizeof(MSG_ADDRESS_INFO_S) * addr_list.nCount);
+       msg_info.bPortValid = false;
 
-       for (int i = 0; i < addr_list.nCount; i++) {
-               addr_info[i].type = MSG_STRUCT_ADDRESS_INFO;
-               addr_info[i].data = (void *)&address[i];
+       /* fill the msg text in msgReq */
+       msg_info.dataSize = strlen(sms_text);
+       msg_info.pData = (void*)sms_text;
 
-               address[i].addressType = MSG_ADDRESS_TYPE_PLMN;
-               snprintf(address[i].addressVal, MAX_ADDRESS_VAL_LEN+1, "%s", phone_num);
+       /* Send option */
+       msg_struct_s sendOpt = {0,};
+       MSG_SENDINGOPT_S send_info;
+       memset(&send_info, 0x00, sizeof(MSG_SENDINGOPT_S));
 
-               address[i].recipientType = MSG_RECIPIENTS_TYPE_TO;
-       }
+       sendOpt.type = MSG_STRUCT_SENDOPT;
+       sendOpt.data = (void *)&send_info;
 
-       msg_info.addr_list = &addr_list;
+       msg_struct_s smsSendOpt = {0,};
+       SMS_SENDINGOPT_INFO_S sms_send_opt = {0,};
+       memset(&sms_send_opt, 0x00, sizeof(SMS_SENDINGOPT_INFO_S));
 
-       msg_info.bPortValid = false;
+       smsSendOpt.type = MSG_STRUCT_SMS_SENDOPT;
+       smsSendOpt.data = (void *)&sms_send_opt;
 
-       /* fill the msg text in msgReq */
-       msg_info.dataSize = strlen(sms_text);
-       msg_info.pData = (void*)malloc(msg_info.dataSize+1);
-       strncpy((char *)msg_info.pData, sms_text, msg_info.dataSize);
+       send_info.smsSendOpt = (msg_struct_t)&smsSendOpt;
 
        sentStatusCallback = cb;
 
@@ -344,9 +569,15 @@ static int msg_send_single_sms(const char *phone_num, const char *sms_text, msg_
 
        // sending message request
        msgReq.msg = (msg_struct_t)&msg;
+       msgReq.sendOpt = (msg_struct_t)&sendOpt;
 
        retVal = msg_submit_req(msgHandle, (msg_struct_t)&req);
 
+       if (addr_list.msg_struct_info) {
+               g_free(addr_list.msg_struct_info);
+               addr_list.msg_struct_info = NULL;
+       }
+
        if (retVal != MSG_SUCCESS)
        {
                MSG_DEBUG("msg_submit_req() is failed. Error Code = %d", retVal);
@@ -359,30 +590,40 @@ static int msg_send_single_sms(const char *phone_num, const char *sms_text, msg_
 
 EXPORT_API int msg_sms_send(const char *phone_num_list, const char *sms_text, msg_simple_sent_status_cb cb, void *user_param)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (phone_num_list == NULL || sms_text == NULL || cb == NULL)
        {
-               MSG_DEBUG("Invalid parameter [%s] [%s] [%s]", phone_num_list, sms_text, cb);
-               return -EINVAL;
+               MSG_SEC_DEBUG("Invalid parameter [%s] [%s] [%s]", phone_num_list, sms_text, cb);
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
        char trimmed_num[strlen(phone_num_list)+1];
        bzero(trimmed_num, strlen(phone_num_list)+1);
+       char *temp = NULL;
 
        msg_error_t retVal = msg_verify_number(phone_num_list, trimmed_num);
 
        if ( retVal != MSG_SUCCESS )
                return retVal;
 
-       for( char* cur_num = strtok(trimmed_num,", "); cur_num ; cur_num = strtok(NULL,", "))
+       for( char* cur_num = strtok_r(trimmed_num,", ", &temp); cur_num ; cur_num = strtok_r(NULL,", ", &temp))
        {
                if (strlen(cur_num) > MAX_PHONE_NUMBER_LEN)
                {
-                       MSG_DEBUG("Phone number is too long [%s], and sending is skipped", cur_num);
+                       MSG_SEC_DEBUG("Phone number is too long [%s], and sending is skipped", cur_num);
                        continue;
                }
 
-               MSG_DEBUG("phone number: [%s]", cur_num);
-               MSG_DEBUG("text: [%s]", sms_text);
+               MSG_SEC_DEBUG("phone number: [%s]", cur_num);
+               MSG_SEC_DEBUG("text: [%s]", sms_text);
                retVal = msg_send_single_sms(cur_num, sms_text, cb, user_param);
 
                if (retVal != MSG_SUCCESS)
@@ -395,8 +636,17 @@ EXPORT_API int msg_sms_send(const char *phone_num_list, const char *sms_text, ms
 
 EXPORT_API int msg_sms_send_message(msg_handle_t handle, msg_struct_t req)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || !req) {
                MSG_FATAL("handle or req is NULL");
                return MSG_ERR_NULL_POINTER;
@@ -429,6 +679,8 @@ EXPORT_API int msg_sms_send_message(msg_handle_t handle, msg_struct_t req)
        reqmsg->folderId = MSG_OUTBOX_ID; // outbox fixed
        reqmsg->networkStatus = MSG_NETWORK_SENDING;
 
+       MSG_DEBUG("Coding Scheme From App. = [%d]", reqmsg->encodeType);
+
        err = msg_submit_req(handle, req);
 
        if (err == MSG_SUCCESS)
@@ -442,8 +694,17 @@ EXPORT_API int msg_sms_send_message(msg_handle_t handle, msg_struct_t req)
 
 EXPORT_API int msg_mms_send_message(msg_handle_t handle, msg_struct_t req)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || !req)
        {
                MSG_FATAL("handle or req is NULL");
@@ -459,7 +720,7 @@ EXPORT_API int msg_mms_send_message(msg_handle_t handle, msg_struct_t req)
 
        MSG_MESSAGE_HIDDEN_S *reqmsg = (MSG_MESSAGE_HIDDEN_S*)msg_s->data;
 
-       if (reqmsg->dataSize <= 0)
+       if (reqmsg->mmsDataSize <= 0)
        {
                MSG_FATAL("MMS data size is invalid");
                return MSG_ERR_INVALID_PARAMETER;
@@ -483,14 +744,25 @@ EXPORT_API int msg_mms_send_message(msg_handle_t handle, msg_struct_t req)
 
 EXPORT_API int msg_mms_send_read_report(msg_handle_t handle, msg_message_id_t msgId, msg_read_report_status_t mms_read_status)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL)
        {
                return MSG_ERR_INVALID_PARAMETER;
        }
 
        msg_struct_t req_t = msg_create_struct(MSG_STRUCT_REQUEST_INFO);
+       if (req_t == NULL)
+               return MSG_ERR_NOT_SUPPORTED;
 
        msg_struct_s *req_s = (msg_struct_s *)req_t;
        MSG_REQUEST_S *req = (MSG_REQUEST_S *)req_s->data;
@@ -502,6 +774,7 @@ EXPORT_API int msg_mms_send_read_report(msg_handle_t handle, msg_message_id_t ms
        read_report_datasize = sizeof(msg_read_report_status_t);
        read_report_data = (void *)calloc(read_report_datasize, 1);
        if(read_report_data == NULL) {
+               msg_release_struct(&req_t);
                return MSG_ERR_MEMORY_ERROR;
        }
 
@@ -516,7 +789,7 @@ EXPORT_API int msg_mms_send_read_report(msg_handle_t handle, msg_message_id_t ms
        reqmsg->mainType = MSG_MMS_TYPE;
        reqmsg->subType = MSG_READREPLY_MMS;
 
-       reqmsg->dataSize = read_report_datasize;
+       reqmsg->mmsDataSize = read_report_datasize;
        reqmsg->pMmsData = read_report_data;
 
        err = msg_submit_req(handle, req_t);
@@ -537,8 +810,17 @@ EXPORT_API int msg_mms_send_read_report(msg_handle_t handle, msg_message_id_t ms
 
 EXPORT_API int msg_mms_forward_message(msg_handle_t handle, msg_struct_t req)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
        msg_error_t err =  MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || !req )
        {
                MSG_FATAL("handle or req is NULL");
@@ -572,8 +854,17 @@ EXPORT_API int msg_mms_forward_message(msg_handle_t handle, msg_struct_t req)
 
 EXPORT_API int msg_mms_retrieve_message(msg_handle_t handle, msg_struct_t req)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if ( handle == NULL|| !req)
        {
                MSG_FATAL("handle or req is NULL");
@@ -605,8 +896,17 @@ EXPORT_API int msg_mms_retrieve_message(msg_handle_t handle, msg_struct_t req)
 /* reject_msg_support */
 EXPORT_API int msg_mms_reject_message(msg_handle_t handle, msg_struct_t req)
 {
+       CHECK_MSG_SUPPORTED(MSG_TELEPHONY_MMS_FEATURE);
        msg_error_t err = MSG_SUCCESS;
 
+       //Privilege check
+       int ret = PRIV_MGR_ERROR_SUCCESS;
+       ret = privacy_checker_check_by_privilege(MSG_SERVICE_WRITE_PRIV_NAME);
+       if(ret != PRIV_MGR_ERROR_SUCCESS)
+       {
+               return MSG_ERR_PERMISSION_DENIED;
+       }
+
        if (handle == NULL || !req )
        {
                MSG_FATAL("handle or req is NULL");
diff --git a/mms-plugin.manifest b/mms-plugin.manifest
new file mode 100755 (executable)
index 0000000..2a0cec5
--- /dev/null
@@ -0,0 +1,5 @@
+<manifest>
+  <request>
+    <domain name="_"/>
+  </request>
+</manifest>
index 0c9ab19..d8f67c9 100755 (executable)
@@ -1,7 +1,7 @@
 #!/bin/sh
 ## A script for running msg-server in booting time.
-
-if [ ! -e /opt/etc/.hib_capturing ]; then
+PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
+#For log
+# Launch msg-server
 /usr/bin/msg-server &
-fi
 
diff --git a/msg-service-tools.manifest b/msg-service-tools.manifest
new file mode 100755 (executable)
index 0000000..c987f54
--- /dev/null
@@ -0,0 +1,10 @@
+<manifest>
+       <request>
+               <domain name="msg-service"/>
+       </request>
+
+       <assign>
+               <filesystem path="/etc/rc.d/init.d/msg-server" label="_" exec_label="none"/>
+               <filesystem path="/etc/config/sysinfo-message.xml" label="_"/>
+       </assign>
+</manifest>
diff --git a/msg-service.manifest b/msg-service.manifest
new file mode 100755 (executable)
index 0000000..138d9d6
--- /dev/null
@@ -0,0 +1,24 @@
+<manifest>
+       <define>
+               <domain name="msg-service" policy="restricted" plist="msg-service-tools"/>
+               <provide>
+                       <label name="msg-service::read"/>
+                       <label name="msg-service::write"/>
+               </provide>
+       </define>
+       <request>
+               <domain name="msg-service"/>
+       </request>
+       <assign>
+               <filesystem path="/usr/lib/libmsg_mapi.so.0" label="_"/>
+               <filesystem path="/usr/lib/libmsg_mapi.so.0.1.0" label="_"/>
+               <filesystem path="/usr/lib/libmsg_framework_handler.so" label="_"/>
+               <filesystem path="/usr/lib/libmsg_mms_plugin.so" label="_"/>
+               <filesystem path="/usr/lib/libmsg_plugin_manager.so" label="_"/>
+               <filesystem path="/usr/lib/libmsg_sms_plugin.so" label="_"/>
+               <filesystem path="/usr/lib/libmsg_transaction_manager.so" label="_"/>
+               <filesystem path="/usr/lib/libmsg_transaction_proxy.so" label="_"/>
+               <filesystem path="/usr/lib/libmsg_utils.so" label="_"/>
+               <filesystem path="/usr/lib/libmsg_vobject.so" label="_"/>
+       </assign>
+</manifest>
diff --git a/msg-service.rule b/msg-service.rule
new file mode 100755 (executable)
index 0000000..c273e71
--- /dev/null
@@ -0,0 +1,51 @@
+msg-service msg-service::db rw---- ------
+msg-service msg-service::vconf rw---- ------
+msg-service system::use_internet rw---- ------
+msg-service media-server rw---- ------
+msg-service system::vconf rwxat- ------
+msg-service system::vconf_inhouse rw---- ------
+msg-service system::vconf_setting r----- ------
+msg-service telephony_framework::api_sms rwx--- ------
+msg-service telephony_framework::api_sim rw---- ------
+msg-service telephony_framework::api_sat --x--- ------
+msg-service telephony_framework::api_ps_public rw---- ------
+msg-service telephony_framework::api_ps_private rw---- ------
+msg-service telephony_framework::api_ps_profile rw---- ------
+msg-service telephony_framework::properties rw---- ------
+msg-service contacts-service::svc r----- ------
+msg-service contacts-service::phonelog rw---- ------
+msg-service ug-setting-call-efl::vconf r----- ------
+msg-service org.tizen.browser::vconf_public r----- ------
+msg-service testmode::vconf r----- ------
+msg-service data-provider-master::notification rw---- ------
+msg-service data-provider-master::notification.client -w---- ------
+msg-service data-provider-master::badge rw---- ------
+msg-service data-provider-master::badge.client -w---- ------
+msg-service oma-dm-agent::vconf_external r----- ------
+msg-service deviced::display rw---- ------
+msg-service net-config rw---- ------
+msg-service connman rw---- ------
+msg-service connman::get rw---- ------
+msg-service connman::set rw---- ------
+msg-service connman::profile rw---- ------
+msg-service aul::launch --x--- ------
+msg-service alarm-server::alarm rw---- ------
+msg-service security-server::api-get-gid -w---- ------
+msg-service security-server::api-cookie-check -w---- ------
+msg-service security-server::api-privilege-by-pid -w---- ------
+msg-service device::app_logging -w---- ------
+msg-service device::sys_logging -w---- ------
+msg-service system::share -wx--- ------
+msg-service system::vconf_system r----l ------
+msg-service pkgmgr::db r----l ------
+msg-service ail::db r----- ------
+msg-service badge::db r----l ------
+msg-service notification::db r----l ------
+msg-service org.tizen.setting::default-resources r----l ------
+
+net-config msg-service rw---- ------
+connman msg-service rw---- ------
+system::use_internet msg-service rw---- ------
+org.tizen.quickpanel msg-service r-x--- ------
+org.tizen.indicator msg-service rwx--- ------
+org.tizen.lockscreen msg-service r-x--- ------
diff --git a/msg_helper/CMakeLists.txt b/msg_helper/CMakeLists.txt
deleted file mode 100755 (executable)
index 893f0ce..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
-PROJECT(msg-server CXX)
-
-SET(CMAKE_SKIP_BUILD_RPATH TRUE)
-
-IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
-       SET(CMAKE_BUILD_TYPE "Debug")
-ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
-MESSAGE("Build type: ${CMAKE_BUILD_TYPE}")
-
-SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
-
-##########################################################
-# Define Test App
-##########################################################
-
-SET(MSG-HELPER-SRCS
-       ${CMAKE_SOURCE_DIR}/msg_helper/MsgSensorWrapper.cpp
-       ${CMAKE_SOURCE_DIR}/msg_helper/MsgSoundPlayer.cpp
-       ${CMAKE_SOURCE_DIR}/msg_helper/main.cpp
-)
-
-INCLUDE_DIRECTORIES(
-    ${CMAKE_SOURCE_DIR}/include/mapi
-       ${CMAKE_SOURCE_DIR}/include/common
-       ${CMAKE_SOURCE_DIR}/include/framework
-       ${CMAKE_SOURCE_DIR}/include/msg_helper
-       ${CMAKE_SOURCE_DIR}/include/utils
-)
-
-INCLUDE(FindPkgConfig)
-pkg_check_modules(msg_helper_pkgs REQUIRED glib-2.0 dlog vconf devman_haptic mm-player mm-fileinfo mm-player svi sensor)
-
-FOREACH(flag ${msg_helper_pkgs_CFLAGS})
-       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
-ENDFOREACH(flag)
-
-SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
-
-ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
-
-SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
-
-ADD_EXECUTABLE(msg-helper ${MSG-HELPER-SRCS})
-TARGET_LINK_LIBRARIES(msg-helper ${msg_helper_pkgs_LDFLAGS} ${UTILS-LIB})
-
-INSTALL(TARGETS msg-helper DESTINATION bin)
-
diff --git a/msg_helper/MsgSoundPlayer.cpp b/msg_helper/MsgSoundPlayer.cpp
deleted file mode 100755 (executable)
index 10da84f..0000000
+++ /dev/null
@@ -1,429 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include <pthread.h>
-
-#include "MsgDebug.h"
-#include "MsgCppTypes.h"
-#include "MsgSettingTypes.h"
-#include "MsgGconfWrapper.h"
-#include "MsgUtilFile.h"
-#include "MsgHelper.h"
-
-#include <devman_managed.h>
-#include <svi.h>
-
-#include <mm_error.h>
-#include <mm_player.h>
-#include <mm_session_private.h>
-
-
-extern void worker_done();
-
-/*==================================================================================================
-                                     VARIABLES
-==================================================================================================*/
-static MMHandleType hPlayerHandle = 0;
-static bool bPlaying = false;
-static bool bVibrating = false;
-static int dev_handle;
-
-pthread_mutex_t muMmPlay = PTHREAD_MUTEX_INITIALIZER;
-pthread_cond_t cvMmPlay = PTHREAD_COND_INITIALIZER;
-
-/*==================================================================================================
-                                     FUNCTION IMPLEMENTATION
-==================================================================================================*/
-
-static gboolean MsgStopAndExit(void* data)
-{
-       MsgSoundPlayStop();
-       if(!bPlaying && !bVibrating)
-               worker_done();
-
-       return FALSE;
-}
-
-static gboolean MsgUninitAndExit(void* data)
-{
-       MsgSoundPlayUninit();
-       if(!bPlaying && !bVibrating)
-               worker_done();
-
-       return FALSE;
-}
-
-static gboolean MsgSoundMelodyTimeout(gpointer data)
-{
-       MSG_BEGIN();
-
-       MsgSoundPlayStop();
-       if(!bPlaying && !bVibrating)
-               worker_done();
-
-       MSG_END();
-
-       return FALSE;
-}
-
-
-static gboolean MsgSoundVibTimeout(gpointer data)
-{
-       MSG_BEGIN();
-
-       int ret = 0;
-
-       if (bVibrating == true) {
-               ret = device_haptic_stop_play(dev_handle);
-
-               if (ret != 0) {
-                       MSG_DEBUG("Fail to stop haptic : [%d]", ret);
-               }
-
-               ret = device_haptic_close(dev_handle);
-
-               if (ret != 0) {
-                       MSG_DEBUG("Fail to close haptic : [%d]", ret);
-               }
-
-               bVibrating = false;
-       }
-
-       if(!bPlaying && !bVibrating)
-               worker_done();
-
-       MSG_END();
-
-       return FALSE;
-}
-
-
-static int MsgSoundPlayCallback(int message, void *param, void *user_param)
-{
-       switch (message)
-       {
-               case MM_MESSAGE_ERROR:
-                       MSG_DEBUG("ERROR is happened.");
-                       g_idle_add (MsgUninitAndExit, NULL);
-                       break;
-               case MM_MESSAGE_BEGIN_OF_STREAM:
-                       MSG_DEBUG("Play is started.");
-                       break;
-               case MM_MESSAGE_END_OF_STREAM:
-               case MM_MESSAGE_STATE_INTERRUPTED:
-                       MSG_DEBUG("EOS or Interrupted.");
-                       g_idle_add (MsgStopAndExit, NULL);
-                       break;
-               default:
-                       MSG_DEBUG("message = %d", message);
-                       break;
-       }
-
-       return 1;
-}
-
-
-void* MsgPlayThread(void *data)
-{
-       MSG_BEGIN();
-
-       bool bSoundOn = false;
-       bool bVibrationOn = false;
-       int callStatus = 0;     /* 0 - off, 1 - sound, 2 - vibration */
-       int alertOnCall = 0;
-
-       char *msg_tone_file_path = NULL;
-       AutoPtr<char> buf(&msg_tone_file_path);
-
-       char *tmpFileFath = NULL;
-
-       tmpFileFath = MsgSettingGetString(VCONFKEY_SETAPPL_NOTI_MSG_RINGTONE_PATH_STR);
-
-       if (tmpFileFath == NULL || MsgGetFileSize(tmpFileFath) < 1) {
-               msg_tone_file_path = new char[MAX_SOUND_FILE_LEN];
-               strncpy(msg_tone_file_path, DEFAULT_FILE, MAX_SOUND_FILE_LEN-1);
-       } else {
-               msg_tone_file_path = new char[MAX_SOUND_FILE_LEN];
-               strncpy(msg_tone_file_path, tmpFileFath, MAX_SOUND_FILE_LEN-1);
-               free(tmpFileFath);
-               tmpFileFath = NULL;
-       }
-
-       MSG_DEBUG("Sound File [%s]", msg_tone_file_path);
-
-       MsgSettingGetBool(VCONFKEY_SETAPPL_SOUND_STATUS_BOOL, &bSoundOn);
-       MsgSettingGetBool(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, &bVibrationOn);
-
-       int err = MM_ERROR_NONE;
-
-       err = mm_session_init(MM_SESSION_TYPE_NOTIFY);
-
-       if(err != MM_ERROR_NONE)
-               MSG_DEBUG("MM Session Init Failed");
-       else
-               MSG_DEBUG("MM Session Init Success : %d", err);
-
-       hPlayerHandle = 0;
-
-       err = mm_player_create(&hPlayerHandle);
-
-       if (err != MM_ERROR_NONE) {
-               MSG_DEBUG("creating the player handle failed");
-               return NULL;
-       }
-
-       /* Setting the call back function msg_callback */
-       mm_player_set_message_callback(hPlayerHandle, MsgSoundPlayCallback, (void *)hPlayerHandle);
-
-       callStatus = MsgSettingGetInt(VCONFKEY_CALL_STATE);
-       MSG_DEBUG("Call Status = %d", callStatus);
-
-       if (callStatus > VCONFKEY_CALL_OFF && callStatus < VCONFKEY_CALL_STATE_MAX) {
-               alertOnCall = MsgSettingGetInt(VCONFKEY_CISSAPPL_ALERT_ON_CALL_INT);
-               MSG_DEBUG("Alert On Call = %d", alertOnCall);
-
-               if (alertOnCall == 0) {
-                       MSG_DEBUG("Call is active & Alert on Call - Off");
-               } else if (alertOnCall == 1) {
-                       MSG_DEBUG("Call is active & Alert on Call - Sound");
-
-                       if (bSoundOn)
-                               MsgSoundPlayMelody(msg_tone_file_path, false);
-               } else if (alertOnCall == 2) {
-                       MSG_DEBUG("Call is active & Alert on Call - Vibration");
-
-                       if (bVibrationOn)
-                               MsgSoundPlayVibration();
-               }
-       } else{
-               MSG_DEBUG("Call is not active");
-
-               if (bVibrationOn) {
-                       MSG_DEBUG("Play vibration.");
-                       MsgSoundPlayVibration();
-               }
-
-               if (bSoundOn) {
-                       MSG_DEBUG("Play sound.");
-                       MsgSoundPlayMelody(msg_tone_file_path, false);
-               }
-       }
-
-       err = mm_session_finish();
-
-       if (err != MM_ERROR_NONE)
-               MSG_DEBUG("MM Session Finish Failed");
-       else
-               MSG_DEBUG("MM Session Finish Success : %d", err);
-
-       if(!bPlaying && !bVibrating)
-               worker_done();
-
-       MSG_END();
-
-       return NULL;
-}
-
-
-msg_error_t MsgSoundPlayUninit()
-{
-       MSG_BEGIN();
-
-       int err = MM_ERROR_NONE;
-
-       /* Uninitializing the player module */
-       err = mm_player_unrealize(hPlayerHandle);
-
-       /* Destroying the player handle */
-       err = mm_player_destroy(hPlayerHandle);
-
-       pthread_mutex_lock(&muMmPlay);
-
-       bPlaying = false;
-
-       pthread_mutex_unlock(&muMmPlay);
-
-       pthread_cond_signal(&cvMmPlay);
-
-       hPlayerHandle = 0;
-
-       MSG_END();
-
-       return MSG_SUCCESS;
-}
-
-
-void MsgSoundPlayStart()
-{
-       MSG_BEGIN();
-
-       pthread_mutex_lock(&muMmPlay);
-
-       if (bPlaying == true) {
-               MSG_DEBUG("Ringtone is Playing...");
-               pthread_mutex_unlock(&muMmPlay);
-               return;
-       }
-
-       pthread_mutex_unlock(&muMmPlay);
-
-       pthread_t tid;
-
-       if (pthread_create(&tid, NULL, &MsgPlayThread, (void*)NULL) == 0) {
-               MSG_DEBUG("Ring alert thread created = %d", tid);
-       } else {
-               MSG_DEBUG("Creating Thread was failed");
-               return;
-       }
-
-       MSG_END();
-}
-
-
-void MsgSoundPlayStop()
-{
-       MSG_BEGIN();
-
-       pthread_mutex_lock(&muMmPlay);
-
-       if (bPlaying == false) {
-               MSG_DEBUG("Ringtone is Not Playing...");
-               pthread_mutex_unlock(&muMmPlay);
-               return;
-       }
-
-       pthread_mutex_unlock(&muMmPlay);
-
-       /* Stop playing media contents */
-       MSG_DEBUG("Before mm_player_stop, %p", hPlayerHandle);
-
-       int err = mm_player_stop(hPlayerHandle);
-
-       MSG_DEBUG("After mm_player_stop");
-
-       if (err != MM_ERROR_NONE) {
-               MSG_DEBUG("stopping the player handle failed");
-       }
-
-       MsgSoundPlayUninit();
-
-       MSG_END();
-}
-
-
-int MsgSoundPlayMelody(char *pMsgToneFilePath, bool bIncreasing)
-{
-       int err = MM_ERROR_NONE;
-
-       /* Setting fade in,out */
-       err = mm_player_set_attribute(hPlayerHandle, NULL, "sound_priority", 2, NULL);
-
-       if (err != MM_ERROR_NONE) {
-               MSG_DEBUG("error setting the profile attr");
-               return err;
-       }
-
-       /* Setting the Volume */
-       err = mm_player_set_attribute(hPlayerHandle, NULL, "sound_volume_type", MM_SOUND_VOLUME_TYPE_NOTIFICATION,
-                                                                                                       "profile_uri", pMsgToneFilePath, strlen(pMsgToneFilePath), NULL);
-
-       if (err != MM_ERROR_NONE) {
-               MSG_DEBUG("error setting the profile attr");
-               return err;
-       }
-
-       err = mm_player_realize(hPlayerHandle);
-
-       if (err != MM_ERROR_NONE) {
-               MSG_DEBUG("mm_player_realize() error : [%d]", err);
-               return err;
-       }
-
-       /* Add Timer to stop playing after 5 sec. */
-       int g_contact_timer = -1;
-       g_contact_timer = g_timeout_add(5500, (GSourceFunc)MsgSoundMelodyTimeout, NULL);
-
-       err = mm_player_start(hPlayerHandle);
-
-       if (err != MM_ERROR_NONE) {
-               MSG_DEBUG("mm_player_start, FAIL [%x]", err);
-               bPlaying = false;
-
-               return err;
-       }
-
-       bPlaying = true;
-
-       pthread_mutex_lock(&muMmPlay);
-
-       while (bPlaying)
-       {
-               MSG_DEBUG("Ring Alert Playing");
-               pthread_cond_wait(&cvMmPlay, &muMmPlay);
-       }
-
-       pthread_mutex_unlock(&muMmPlay);
-
-       MSG_DEBUG("Ring Alert Idle");
-
-       return err;
-}
-
-
-void MsgSoundPlayVibration()
-{
-       MSG_BEGIN();
-
-       int ret = 0;
-       int vibLevel = 0;
-       char ivtFilePath[MAX_SOUND_FILE_LEN] = {0,};
-
-       vibLevel = MsgSettingGetInt(VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT);
-
-       if (vibLevel > 0) {
-               bVibrating = true;
-
-               dev_handle = device_haptic_open(DEV_IDX_0, 0);
-
-               g_timeout_add(MSG_VIBRATION_INTERVAL , MsgSoundVibTimeout, NULL);
-
-               /* set timer to stop vibration, then play melody */
-               svi_get_path(SVI_TYPE_VIB, SVI_VIB_NOTIFICATION_MESSAGE, ivtFilePath, sizeof(ivtFilePath));
-               ret = device_haptic_play_file(dev_handle, ivtFilePath, HAPTIC_TEST_ITERATION, vibLevel);
-
-               if (ret != 0) {
-                       MSG_DEBUG("Fail to play haptic : [%d]", ret);
-               }
-       }
-
-       MSG_END();
-}
-
-
-int MsgSoundGetUnreadMsgCnt()
-{
-       int unreadCnt = 0;
-
-       /*  Get SMS Count */
-       unreadCnt = MsgSettingGetInt(VCONFKEY_MESSAGE_RECV_SMS_STATE);
-
-       /*  Get MMS Count */
-       unreadCnt += MsgSettingGetInt(VCONFKEY_MESSAGE_RECV_MMS_STATE);
-
-       MSG_DEBUG("unread count : [%d]", unreadCnt);
-
-       return unreadCnt;
-}
diff --git a/msg_helper/main.cpp b/msg_helper/main.cpp
deleted file mode 100755 (executable)
index 94115aa..0000000
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include <stdio.h>
-#include <glib.h>
-#include <sys/time.h>
-#include <stdlib.h>
-
-#include "MsgHelper.h"
-#include "MsgUtilFile.h"
-#include "MsgCppTypes.h"
-#include "MsgDebug.h"
-
-static GMainLoop *loop;
-
-static gboolean _worker_done(void* data)
-{
-       if (g_main_loop_is_running(loop))
-               g_main_loop_quit(loop);
-
-       return 0;
-}
-
-// may called by threads
-void worker_done()
-{
-       g_idle_add(_worker_done,NULL);
-}
-
-int main(int argc, char** argv)
-{
-
-       MSG_DEBUG("############### Start msg_helper ###############");
-
-#if !GLIB_CHECK_VERSION(2, 31, 0)
-       g_thread_init(NULL);
-#endif
-
-       bool notEnd = false;
-
-       if(argc < 1)
-       {
-               MSG_DEBUG("No arguments to run msg_helper.");
-               return 0;
-       }
-
-       MSG_DEBUG("argv[0] [%s] ", argv[0]);
-
-       if(strcmp(argv[0],MSG_SOUND_START)==0)
-       {
-               MsgSoundPlayStart();
-               notEnd = true;
-       }
-       else if(strcmp(argv[0],MSG_SOUND_STOP)==0)
-       {
-               MsgSoundPlayStop();
-       }
-
-       if(notEnd)
-       {
-               loop = g_main_loop_new(NULL, FALSE);
-
-               if (MsgSensorConnect() == MSG_SUCCESS)
-                       if (MsgRegSensorCB(&worker_done) != MSG_SUCCESS)
-                               MsgSensorDisconnect();
-
-               if (loop != NULL)
-               {
-                       MSG_DEBUG("Waiting for working jobs to be finished!!!");
-
-                       // Run GMainLoop
-                       g_main_loop_run(loop);
-               }
-               else
-               {
-                       MSG_DEBUG("Fail to create g_main_loop!!!");
-                       MsgSensorDisconnect();
-               }
-       }
-
-       return 0;
-}
diff --git a/packaging/msg-server.service b/packaging/msg-server.service
new file mode 100755 (executable)
index 0000000..458cbf6
--- /dev/null
@@ -0,0 +1,13 @@
+[Unit]
+Description=Message server
+After=tizen-runtime.target contacts-service.service
+Requires=tizen-runtime.target contacts-service.service
+
+[Service]
+Type=forking
+ExecStart=/etc/rc.d/init.d/msg-server
+Restart=always
+MemoryLimit=10M
+
+[Install]
+WantedBy=multi-user.target
index b626d5a..ba533a4 100755 (executable)
@@ -1,7 +1,7 @@
 Name:           msg-service
-Version:        0.9.0
+Version:        1.0.0
 Release:        1
-License:        Samsung
+License:        Apache-2.0
 Summary:        Messaging Framework Library
 Group:          System/Libraries
 Source0:        %{name}-%{version}.tar.gz
@@ -10,16 +10,27 @@ Requires(post): /usr/bin/sqlite3
 Requires(post): /usr/bin/vconftool
 Requires(post): /sbin/ldconfig
 Requires(postun): /sbin/ldconfig
+Requires(post): systemd
+Requires(postun): systemd
 BuildRequires: cmake
 BuildRequires: pkgconfig(alarm-service)
 BuildRequires: pkgconfig(aul)
+BuildRequires: pkgconfig(badge)
 BuildRequires: pkgconfig(capi-appfw-application)
-BuildRequires: pkgconfig(contacts-service)
+BuildRequires: pkgconfig(capi-network-connection)
+BuildRequires: pkgconfig(capi-system-info)
+BuildRequires: pkgconfig(capi-telephony)
+BuildRequires: pkgconfig(contacts-service2)
+BuildRequires: pkgconfig(csr-framework)
 BuildRequires: pkgconfig(db-util)
-BuildRequires: pkgconfig(devman_haptic)
+BuildRequires: pkgconfig(deviced)
 BuildRequires: pkgconfig(dlog)
-BuildRequires: pkgconfig(drm-client)
-BuildRequires: pkgconfig(glib-2.0)
+BuildRequires: pkgconfig(feedback)
+BuildRequires: pkgconfig(gio-2.0)
+BuildRequires: pkgconfig(gobject-2.0)
+BuildRequires: pkgconfig(iniparser)
+BuildRequires: pkgconfig(json-glib-1.0)
+BuildRequires: pkgconfig(lbs-dbus)
 BuildRequires: pkgconfig(libcurl)
 BuildRequires: pkgconfig(libsystemd-daemon)
 BuildRequires: pkgconfig(libxml-2.0)
@@ -28,14 +39,14 @@ BuildRequires: pkgconfig(media-thumbnail)
 BuildRequires: pkgconfig(mm-fileinfo)
 BuildRequires: pkgconfig(mm-player)
 BuildRequires: pkgconfig(mm-session)
-BuildRequires: pkgconfig(network)
-BuildRequires: pkgconfig(notification)
-BuildRequires: pkgconfig(pmapi)
+BuildRequires: pkgconfig(mm-sound)
 BuildRequires: pkgconfig(mmutil-imgp)
 BuildRequires: pkgconfig(mmutil-jpeg)
+BuildRequires: pkgconfig(notification)
+BuildRequires: pkgconfig(privacy-manager-client)
 BuildRequires: pkgconfig(security-server)
 BuildRequires: pkgconfig(sensor)
-BuildRequires: pkgconfig(svi)
+BuildRequires: pkgconfig(storage)
 BuildRequires: pkgconfig(tapi)
 BuildRequires: pkgconfig(vconf)
 
@@ -44,7 +55,7 @@ Description: Messaging Framework Library
 
 
 %package devel
-License:        Apache License v2.0
+License:        Apache-2.0
 Summary:        Messaging Framework Library (development)
 Requires:       %{name} = %{version}-%{release}
 Group:          Development/Libraries
@@ -54,7 +65,7 @@ Description: Messaging Framework Library (development)
 
 
 %package tools
-License:        Apache License v2.0
+License:        Apache-2.0
 Summary:        Messaging server application
 Requires:       %{name} = %{version}-%{release}
 Group:          TO_BU / FILL_IN
@@ -68,7 +79,7 @@ Description:  Messaging server application
 
 
 %package -n sms-plugin
-License:        Apache License v2.0
+License:        Apache-2.0
 Summary:        SMS plugin library
 Requires:       %{name} = %{version}-%{release}
 Group:          System/Libraries
@@ -79,7 +90,7 @@ Requires(postun): /sbin/ldconfig
 Description: SMS plugin library
 
 %package -n mms-plugin
-License:        Apache License v2.0
+License:        Apache-2.0
 Summary:        MMS plugin library
 Requires:       %{name} = %{version}-%{release}
 Group:          System/Libraries
@@ -92,195 +103,232 @@ Description: MMS plugin library
 %prep
 %setup -q
 
-
 %build
-cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix}
+
+cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} \
+%ifarch i586
+-D_TIZEN_I586_ENABLED:BOOL=ON
+%else
+-D_TIZEN_I586_ENABLED:BOOL=OFF
+%endif
+
 make %{?jobs:-j%jobs}
 
 %install
-
 rm -rf %{buildroot}
+mkdir -p %{buildroot}/usr/share/license
+mkdir -p %{buildroot}/etc/config
+
 %make_install
 
-mkdir -p  %{buildroot}%{_sysconfdir}/rc.d/rc3.d
-ln -s %{_sysconfdir}/rc.d/init.d/msg-server  %{buildroot}%{_sysconfdir}/rc.d/rc3.d/S70msg-server
-mkdir -p  %{buildroot}%{_sysconfdir}/rc.d/rc5.d
-ln -s %{_sysconfdir}/rc.d/init.d/msg-server  %{buildroot}%{_sysconfdir}/rc.d/rc5.d/S70msg-server
+mkdir -p %{buildroot}%{_libdir}/systemd/system/multi-user.target.wants
+ln -s ../msg-server.service %{buildroot}%{_libdir}/systemd/system/multi-user.target.wants/msg-server.service
+
+mkdir -p %{buildroot}/opt/usr/dbspace
+sqlite3 %{buildroot}/opt/usr/dbspace/.msg_service.db "PRAGMA journal_mode = PERSIST;"
+sqlite3 %{buildroot}/opt/usr/dbspace/.msg_service.db < %{buildroot}/usr/share/msg-service/msg-service-db.sql
+
+rm %{buildroot}/usr/share/msg-service/msg-service-db.sql
 
+%post tools
+/sbin/ldconfig
 
+chown :5000 /opt/usr/dbspace/.msg_service.db
+chown :5000 /opt/usr/dbspace/.msg_service.db-journal
+chmod 660 /opt/usr/dbspace/.msg_service.db
+chmod 660 /opt/usr/dbspace/.msg_service.db-journal
 
-mkdir -p %{buildroot}/opt/data/msg-service
+if [ -f /usr/lib/rpm-plugins/msm.so ]
+then
+       chsmack -a 'msg-service::db' /opt/usr/dbspace/.msg_service.db*
+fi
 
-%post tools -p /sbin/ldconfig
 %post -n sms-plugin -p /sbin/ldconfig
 %post -n mms-plugin -p /sbin/ldconfig
 
 %post
 /sbin/ldconfig
 
-if [ ! -f /opt/dbspace/.msg_service.db ]
+mkdir -p /opt/usr/data/msg-service
+chgrp db_msg_service /opt/usr/data/msg-service
+
+if [ -f /usr/lib/rpm-plugins/msm.so ]
 then
-    sqlite3 /opt/dbspace/.msg_service.db "PRAGMA journal_mode = PERSIST;
-
-    CREATE TABLE MSG_CONVERSATION_TABLE ( CONV_ID INTEGER NOT NULL , UNREAD_CNT INTEGER DEFAULT 0 , SMS_CNT INTEGER DEFAULT 0 , MMS_CNT INTEGER DEFAULT 0 , MAIN_TYPE INTEGER NOT NULL , SUB_TYPE INTEGER NOT NULL , MSG_DIRECTION INTEGER NOT NULL , DISPLAY_TIME INTEGER , DISPLAY_NAME TEXT , MSG_TEXT TEXT );
-    CREATE TABLE MSG_ADDRESS_TABLE ( ADDRESS_ID INTEGER PRIMARY KEY , CONV_ID INTEGER  NOT NULL , ADDRESS_TYPE INTEGER , RECIPIENT_TYPE INTEGER , ADDRESS_VAL TEXT , CONTACT_ID INTEGER , DISPLAY_NAME TEXT , FIRST_NAME TEXT , LAST_NAME TEXT , IMAGE_PATH TEXT , SYNC_TIME DATETIME , FOREIGN KEY (CONV_ID) REFERENCES MSG_CONVERSATION_TABLE (CONV_ID) );
-    CREATE TABLE MSG_FOLDER_TABLE ( FOLDER_ID INTEGER PRIMARY KEY , FOLDER_NAME TEXT NOT NULL , FOLDER_TYPE INTEGER DEFAULT 0 );
-    CREATE TABLE MSG_MESSAGE_TABLE ( MSG_ID INTEGER PRIMARY KEY , CONV_ID INTEGER NOT NULL , FOLDER_ID INTEGER NOT NULL , STORAGE_ID INTEGER NOT NULL , MAIN_TYPE INTEGER NOT NULL , SUB_TYPE INTEGER NOT NULL , DISPLAY_TIME DATETIME , DATA_SIZE INTEGER DEFAULT 0 , NETWORK_STATUS INTEGER DEFAULT 0 , READ_STATUS INTEGER DEFAULT 0 , PROTECTED INTEGER DEFAULT 0 , PRIORITY INTEGER DEFAULT 0 , MSG_DIRECTION INTEGER NOT NULL , SCHEDULED_TIME DATETIME , BACKUP INTEGER DEFAULT 0 , SUBJECT TEXT , MSG_DATA TEXT , THUMB_PATH TEXT , MSG_TEXT TEXT , DELIVERY_REPORT_STATUS INTEGER DEFAULT 0 , DELIVERY_REPORT_TIME DATETIME , READ_REPORT_STATUS INTEGER DEFAULT 0 , READ_REPORT_TIME DATETIME , ATTACHMENT_COUNT INTEGER DEFAULT 0 , FOREIGN KEY (CONV_ID) REFERENCES MSG_CONVERSATION_TABLE (CONV_ID) , FOREIGN KEY (FOLDER_ID) REFERENCES MSG_FOLDER_TABLE (FOLDER_ID) );
-    CREATE TABLE MSG_SIM_TABLE ( MSG_ID INTEGER , SIM_ID INTEGER NOT NULL , FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID) );
-    CREATE TABLE MSG_PUSH_TABLE ( MSG_ID INTEGER , ACTION INTEGER , CREATED INTEGER , EXPIRES INTEGER , ID TEXT , HREF TEXT , CONTENT TEXT , FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID) );
-    CREATE TABLE MSG_CBMSG_TABLE ( MSG_ID INTEGER , CB_MSG_ID INTEGER NOT NULL , FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID) );
-    CREATE TABLE MSG_SYNCML_TABLE ( MSG_ID INTEGER , EXT_ID INTEGER NOT NULL , PINCODE INTEGER NOT NULL , FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID) );
-    CREATE TABLE MSG_SMS_SENDOPT_TABLE ( MSG_ID INTEGER , DELREP_REQ INTEGER NOT NULL , KEEP_COPY INTEGER NOT NULL , REPLY_PATH INTEGER NOT NULL , FOREIGN KEY(MSG_ID) REFERENCES MSG_MESSAGE_TABLE(MSG_ID) );
-    CREATE TABLE MSG_FILTER_TABLE ( FILTER_ID INTEGER PRIMARY KEY , FILTER_TYPE INTEGER NOT NULL , FILTER_VALUE TEXT NOT NULL );
-    CREATE TABLE MSG_MMS_MESSAGE_TABLE ( MSG_ID INTEGER , TRANSACTION_ID TEXT , MESSAGE_ID TEXT , FWD_MESSAGE_ID TEXT , CONTENTS_LOCATION TEXT , FILE_PATH TEXT , VERSION INTEGER NOT NULL , DATA_TYPE INTEGER DEFAULT -1 , DATE DATETIME , HIDE_ADDRESS INTEGER DEFAULT 0 , ASK_DELIVERY_REPORT INTEGER DEFAULT 0 , REPORT_ALLOWED INTEGER DEFAULT 0 , READ_REPORT_ALLOWED_TYPE INTEGER DEFAULT 0 , ASK_READ_REPLY INTEGER DEFAULT 0 , READ INTEGER DEFAULT 0 , READ_REPORT_SEND_STATUS INTEGER DEFAULT 0 , READ_REPORT_SENT INTEGER DEFAULT 0 , PRIORITY INTEGER DEFAULT 0 , KEEP_COPY INTEGER DEFAULT 0 , MSG_SIZE INTEGER NOT NULL , MSG_CLASS INTEGER DEFAULT -1 , EXPIRY_TIME DATETIME , CUSTOM_DELIVERY_TIME INTEGER DEFAULT 0 , DELIVERY_TIME DATETIME , MSG_STATUS INTEGER DEFAULT -1 , FOREIGN KEY (MSG_ID) REFERENCES MSG_MESSAGE_TABLE (MSG_ID) );
-
-    CREATE INDEX MSG_CONVERSATION_INDEX ON MSG_CONVERSATION_TABLE(CONV_ID);
-    CREATE INDEX MSG_FOLDER_INDEX ON MSG_FOLDER_TABLE(FOLDER_ID);
-    CREATE INDEX MSG_MESSAGE_INDEX ON MSG_MESSAGE_TABLE(MSG_ID, CONV_ID, FOLDER_ID);
-
-    INSERT INTO MSG_FOLDER_TABLE VALUES (1, 'INBOX', 1);
-    INSERT INTO MSG_FOLDER_TABLE VALUES (2, 'OUTBOX', 2);
-    INSERT INTO MSG_FOLDER_TABLE VALUES (3, 'SENTBOX', 2);
-    INSERT INTO MSG_FOLDER_TABLE VALUES (4, 'DRAFT', 3);
-    INSERT INTO MSG_FOLDER_TABLE VALUES (5, 'CBMSGBOX', 1);
-    INSERT INTO MSG_FOLDER_TABLE VALUES (6, 'SPAMBOX', 4);
-    INSERT INTO MSG_FOLDER_TABLE VALUES (7, 'SMS TEMPLATE', 5);
-    INSERT INTO MSG_FOLDER_TABLE VALUES (8, 'MMS TEMPLATE', 5);"
+       chsmack -a "_" -e "_" /etc/rc.d/init.d/msg-server
 fi
 
-chown :6011 /opt/dbspace/.msg_service.db
-chown :6011 /opt/dbspace/.msg_service.db-journal
-
-
-chmod 660 /opt/dbspace/.msg_service.db
-chmod 660 /opt/dbspace/.msg_service.db-journal
-
-
 ########## Setting Config Value (Internal keys) ##########
 # Message Server Status
-vconftool set -t bool memory/msg/ready 0 -i
+vconftool set -t bool memory/msg/ready 0 -i -g 5000 -s system::vconf_inhouse
 
 # SMS Send Options
-vconftool set -t int db/msg/network_mode 2
+vconftool set -t int db/msg/network_mode 2 -g 5000 -s system::vconf_inhouse
 
 # New Message Count
-vconftool set -t int db/msg/recv_sms 0
-vconftool set -t int db/msg/recv_mms 0
+vconftool set -t int db/msg/recv_sms 0 -g 5000 -s system::vconf_inhouse
+vconftool set -t int db/msg/recv_mms 0 -g 5000 -s system::vconf_inhouse
 
 ########## Setting Config Value (Private keys) ##########
 # General Options
-vconftool set -t bool db/private/msg-service/general/keep_copy 1
-vconftool set -t bool db/private/msg-service/general/auto_erase 0
-vconftool set -t bool db/private/msg-service/general/block_msg 0
-vconftool set -t int db/private/msg-service/general/contact_sync_time 0
+vconftool set -t bool db/private/msg-service/general/keep_copy 1 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/general/auto_erase 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/general/block_msg 1 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/general/contact_sync_time 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/general/alert_rep_type 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/general/search_tags 31 -s msg-service::vconf -g 5000
+
+vconftool set -t int db/private/msg-service/general/page_limit 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/general/sms_mms_threshold 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/general/max_recipient 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/general/sms_storage 0 -s msg-service::vconf -g 5000
+
+vconftool set -t bool db/private/msg-service/general/block_unknown_msg 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/general/sms_limit 1000 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/general/mms_limit 100 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/general/notification 1 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/general/vibration 1 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/general/preview 1 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/general/ringtone_type 0 -s msg-service::vconf -g 5000
+vconftool set -t string db/private/msg-service/general/ringtone_path "" -s msg-service::vconf -g 5000
+
+vconftool set -t string db/private/msg-service/general/ua_profile "" -s msg-service::vconf -g 5000
+
+vconftool set -t int db/private/msg-service/general/msg_id_counter 0 -s msg-service::vconf -g 5000
 
 # SMS Send Options
-vconftool set -t int db/private/msg-service/sms_send/dcs 3
-vconftool set -t bool db/private/msg-service/sms_send/reply_path 0
-vconftool set -t bool db/private/msg-service/sms_send/delivery_report 0
-vconftool set -t int db/private/msg-service/sms_send/save_storage 1
-
-# SMSC
-vconftool set -t int db/private/msg-service/smsc/total_count 1
-vconftool set -t int db/private/msg-service/smsc/selected 0
-
-vconftool set -t int db/private/msg-service/smsc/pid/0 1
-vconftool set -t int db/private/msg-service/smsc/val_period/0 255
-vconftool set -t string db/private/msg-service/smsc/name/0 ""
-vconftool set -t int db/private/msg-service/smsc/ton/0 1
-vconftool set -t int db/private/msg-service/smsc/npi/0 1
-vconftool set -t string db/private/msg-service/smsc/address/0 ""
-
-vconftool set -t int db/private/msg-service/smsc/pid/1 0
-vconftool set -t int db/private/msg-service/smsc/val_period/1 0
-vconftool set -t string db/private/msg-service/smsc/name/1 ""
-vconftool set -t int db/private/msg-service/smsc/ton/1 0
-vconftool set -t int db/private/msg-service/smsc/npi/1 0
-vconftool set -t string db/private/msg-service/smsc/address/1 ""
-
-vconftool set -t int db/private/msg-service/smsc/pid/2 0
-vconftool set -t int db/private/msg-service/smsc/val_period/2 0
-vconftool set -t string db/private/msg-service/smsc/name/2 ""
-vconftool set -t int db/private/msg-service/smsc/ton/2 0
-vconftool set -t int db/private/msg-service/smsc/npi/2 0
-vconftool set -t string db/private/msg-service/smsc/address/2 ""
+vconftool set -t int db/private/msg-service/sms_send/dcs 3 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/sms_send/reply_path 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/sms_send/delivery_report 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/sms_send/save_storage 1 -s msg-service::vconf -g 5000
 
 # MMS Send Options
-vconftool set -t int db/private/msg-service/mms_send/msg_class 0
-vconftool set -t int db/private/msg-service/mms_send/priority 1
-vconftool set -t int db/private/msg-service/mms_send/expiry_time 0
-vconftool set -t int db/private/msg-service/mms_send/custom_delivery 0
-vconftool set -t bool db/private/msg-service/mms_send/sender_visibility 0
-vconftool set -t bool db/private/msg-service/mms_send/delivery_report 1
-vconftool set -t bool db/private/msg-service/mms_send/read_reply 1
-vconftool set -t bool db/private/msg-service/mms_send/keep_copy 0
-vconftool set -t bool db/private/msg-service/mms_send/body_replying 0
-vconftool set -t bool db/private/msg-service/mms_send/hide_recipients 0
-vconftool set -t bool db/private/msg-service/mms_send/report_allowed 1
-vconftool set -t int db/private/msg-service/mms_send/reply_charging 0
-vconftool set -t int db/private/msg-service/mms_send/reply_charging_deadline 0
-vconftool set -t int db/private/msg-service/mms_send/reply_charging_size 0
-vconftool set -t int db/private/msg-service/mms_send/delivery_time 0
-vconftool set -t int db/private/msg-service/mms_send/creation_mode 2
-
-# MMS Receive Options
-vconftool set -t int db/private/msg-service/mms_recv/home_network 0
-vconftool set -t int db/private/msg-service/mms_recv/abroad_network 0
-vconftool set -t bool db/private/msg-service/mms_recv/read_receipt 1
-vconftool set -t bool db/private/msg-service/mms_recv/delivery_receipt 1
-vconftool set -t bool db/private/msg-service/mms_recv/reject_unknown 0
-vconftool set -t bool db/private/msg-service/mms_recv/reject_advertisement 0
+vconftool set -t int db/private/msg-service/mms_send/msg_class 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_send/priority 1 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_send/expiry_time 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_send/custom_delivery 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_send/sender_visibility 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_send/delivery_report 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_send/read_reply 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_send/keep_copy 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_send/body_replying 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_send/hide_recipients 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_send/report_allowed 1 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_send/reply_charging 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_send/reply_charging_deadline 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_send/reply_charging_size 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_send/delivery_time 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_send/creation_mode 2 -s msg-service::vconf -g 5000
 
 # MMS Receive Options
-vconftool set -t int db/private/msg-service/mms_style/font_size 30
-vconftool set -t bool db/private/msg-service/mms_style/font_style/bold 0
-vconftool set -t bool db/private/msg-service/mms_style/font_style/italic 0
-vconftool set -t bool db/private/msg-service/mms_style/font_style/underline 0
-vconftool set -t int db/private/msg-service/mms_style/font_color/red 255
-vconftool set -t int db/private/msg-service/mms_style/font_color/green 255
-vconftool set -t int db/private/msg-service/mms_style/font_color/blue 255
-vconftool set -t int db/private/msg-service/mms_style/font_color/hue 255
-vconftool set -t int db/private/msg-service/mms_style/bg_color/red 0
-vconftool set -t int db/private/msg-service/mms_style/bg_color/green 0
-vconftool set -t int db/private/msg-service/mms_style/bg_color/blue 0
-vconftool set -t int db/private/msg-service/mms_style/bg_color/hue 255
-vconftool set -t int db/private/msg-service/mms_style/page_dur 2
-vconftool set -t int db/private/msg-service/mms_style/page_custom_dur 0
-vconftool set -t int db/private/msg-service/mms_style/page_dur_manual 0
+vconftool set -t int db/private/msg-service/mms_recv/home_network 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_recv/abroad_network 1 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_recv/read_receipt 1 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_recv/delivery_receipt 1 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_recv/reject_unknown 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_recv/reject_advertisement 0 -s msg-service::vconf -g 5000
+
+# MMS Style Options
+vconftool set -t int db/private/msg-service/mms_style/font_size 30 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_style/font_style/bold 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_style/font_style/italic 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/mms_style/font_style/underline 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_style/font_color/red 255 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_style/font_color/green 255 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_style/font_color/blue 255 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_style/font_color/hue 255 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_style/bg_color/red 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_style/bg_color/green 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_style/bg_color/blue 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_style/bg_color/hue 255 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_style/page_dur 2 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_style/page_custom_dur 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/mms_style/page_dur_manual 0 -s msg-service::vconf -g 5000
 
 # Push Msg Options
-vconftool set -t bool db/private/msg-service/push_msg/recv_option 1
-vconftool set -t int db/private/msg-service/push_msg/service_load 1
+vconftool set -t bool db/private/msg-service/push_msg/recv_option 1 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/push_msg/service_load 1 -s msg-service::vconf -g 5000
 
 # CB Msg Options
-vconftool set -t bool db/private/msg-service/cb_msg/receive 1 -f
-vconftool set -t int db/private/msg-service/cb_msg/max_sim_count 0
-vconftool set -t int db/private/msg-service/cb_msg/channel_count 0
-vconftool set -t bool db/private/msg-service/cb_msg/language/0 1 -f
-vconftool set -t bool db/private/msg-service/cb_msg/language/1 0
-vconftool set -t bool db/private/msg-service/cb_msg/language/2 0
-vconftool set -t bool db/private/msg-service/cb_msg/language/3 0
-vconftool set -t bool db/private/msg-service/cb_msg/language/4 0
-vconftool set -t bool db/private/msg-service/cb_msg/language/5 0
-vconftool set -t bool db/private/msg-service/cb_msg/language/6 0
-vconftool set -t bool db/private/msg-service/cb_msg/language/7 0
-vconftool set -t bool db/private/msg-service/cb_msg/language/8 0
-vconftool set -t bool db/private/msg-service/cb_msg/language/9 0
+vconftool set -t bool db/private/msg-service/cb_msg/receive 0 -f -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/cb_msg/save 0 -f -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/cb_msg/max_sim_count/1 0 -f -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/cb_msg/max_sim_count/2 0 -f -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/cb_msg/max_sim_count/3 0 -f -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/cb_msg/language/0 1 -f -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/cb_msg/language/1 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/cb_msg/language/2 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/cb_msg/language/3 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/cb_msg/language/4 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/cb_msg/language/5 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/cb_msg/language/6 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/cb_msg/language/7 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/cb_msg/language/8 0 -s msg-service::vconf -g 5000
+vconftool set -t bool db/private/msg-service/cb_msg/language/9 0 -s msg-service::vconf -g 5000
 
 # Voice Mail Options
-vconftool set -t string db/private/msg-service/voice_mail/voice_mail_number ""
+vconftool set -t string db/private/msg-service/voice_mail/voice_mail_number/1 "" -f -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/voice_mail/voice_mail_count/1 0 -f -s msg-service::vconf -g 5000
+vconftool set -t string db/private/msg-service/voice_mail/voice_mail_alphaid/1 "" -f -s msg-service::vconf -g 5000
+
+vconftool set -t string db/private/msg-service/voice_mail/voice_mail_number/2 "" -f -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/voice_mail/voice_mail_count/2 0 -f -s msg-service::vconf -g 5000
+vconftool set -t string db/private/msg-service/voice_mail/voice_mail_alphaid/2 "" -f -s msg-service::vconf -g 5000
+
+vconftool set -t string db/private/msg-service/voice_mail/voice_mail_number/3 "" -f -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/voice_mail/voice_mail_count/3 0 -f -s msg-service::vconf -g 5000
+vconftool set -t string db/private/msg-service/voice_mail/voice_mail_alphaid/3 "" -f -s msg-service::vconf -g 5000
 
 # MMS Size Options
-vconftool set -t int db/private/msg-service/size_opt/msg_size 300
+vconftool set -t int db/private/msg-service/size_opt/msg_size 300 -s msg-service::vconf -g 5000
 
 # SIM message count
-vconftool set -t int db/private/msg-service/sim_count/used_cnt 0
-vconftool set -t int db/private/msg-service/sim_count/total_cnt 0
+vconftool set -t int db/private/msg-service/sim_count/used_cnt/1 0 -f -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/sim_count/total_cnt/1 0 -f -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/sim_count/used_cnt/2 0 -f -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/sim_count/total_cnt/2 0 -f -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/sim_count/used_cnt/3 0 -f -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/sim_count/total_cnt/3 0 -f -s msg-service::vconf -g 5000
 
 # SIM information
-vconftool set -t int memory/private/msg-service/sim_changed 0 -i
-vconftool set -t string memory/private/msg-service/sim_imsi "" -i
-vconftool set -t bool memory/private/msg-service/national_sim 0 -i
+vconftool set -t int memory/private/msg-service/sim_changed/1 0 -i -f -s msg-service::vconf -g 5000
+vconftool set -t string memory/private/msg-service/sim_imsi/1 "" -i -f -s msg-service::vconf -g 5000
+vconftool set -t bool memory/private/msg-service/national_sim/1 0 -i -f -s msg-service::vconf -g 5000
+vconftool set -t string memory/private/msg-service/msisdn/1 "" -i -f -s msg-service::vconf -g 5000
+vconftool set -t string memory/private/msg-service/iccid/1 "" -i -f -s msg-service::vconf -g 5000
+
+vconftool set -t int memory/private/msg-service/sim_changed/2 0 -i -f -s msg-service::vconf -g 5000
+vconftool set -t string memory/private/msg-service/sim_imsi/2 "" -i -f -s msg-service::vconf -g 5000
+vconftool set -t bool memory/private/msg-service/national_sim/2 0 -i -f -s msg-service::vconf -g 5000
+vconftool set -t string memory/private/msg-service/msisdn/2 "" -i -f -s msg-service::vconf -g 5000
+vconftool set -t string memory/private/msg-service/iccid/2 "" -i -f -s msg-service::vconf -g 5000
+
+vconftool set -t int memory/private/msg-service/sim_changed/3 0 -i -f -s msg-service::vconf -g 5000
+vconftool set -t string memory/private/msg-service/sim_imsi/3 "" -i -f -s msg-service::vconf -g 5000
+vconftool set -t bool memory/private/msg-service/national_sim/3 0 -i -f -s msg-service::vconf -g 5000
+vconftool set -t string memory/private/msg-service/msisdn/3 "" -i -f -s msg-service::vconf -g 5000
+vconftool set -t string memory/private/msg-service/iccid/3 "" -i -f -s msg-service::vconf -g 5000
+vconftool set -t int  memory/private/msg-service/default_network_sim 0 -i -f -s msg-service::vconf -g 5000
+
+# SST information
+vconftool set -t bool memory/private/msg-service/sim_st/1 1 -i -f -s msg-service::vconf -g 5000
+vconftool set -t bool memory/private/msg-service/sim_mo_ctrl/1 0 -i -f -s msg-service::vconf -g 5000
+
+vconftool set -t bool memory/private/msg-service/sim_st/2 1 -i -f -s msg-service::vconf -g 5000
+vconftool set -t bool memory/private/msg-service/sim_mo_ctrl/2 0 -i -f -s msg-service::vconf -g 5000
+
+vconftool set -t bool memory/private/msg-service/sim_st/3 1 -i -f -s msg-service::vconf -g 5000
+vconftool set -t bool memory/private/msg-service/sim_mo_ctrl/3 0 -i -f -s msg-service::vconf -g 5000
+
+# Notification
+vconftool set -t int db/private/msg-service/notification_priv_id 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/voice_noti_id1 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/voice_noti_id2 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/cb_noti_priv_id 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/sim_msg_noti_priv_id 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/emergency_noti_id 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/sentfail_noti_id 0 -s msg-service::vconf -g 5000
+vconftool set -t int db/private/msg-service/sim_full_noti_id 0 -s msg-service::vconf -g 5000
+
 
 %postun -p /sbin/ldconfig
 
@@ -289,17 +337,17 @@ vconftool set -t bool memory/private/msg-service/national_sim 0 -i
 %postun -n mms-plugin -p /sbin/ldconfig
 
 %files
+%manifest msg-service.manifest
 %defattr(-,root,root,-)
-%dir /opt/data/msg-service
 %{_libdir}/libmsg_plugin_manager.so
 %{_libdir}/libmsg_mapi.so.*
 %{_libdir}/libmsg_framework_handler.so
 %{_libdir}/libmsg_transaction_manager.so
 %{_libdir}/libmsg_utils.so
+%{_libdir}/libmsg_externals.so
 %{_libdir}/libmsg_transaction_proxy.so
-%{_sysconfdir}/rc.d/init.d/msg-server
-%{_sysconfdir}/rc.d/rc3.d/S70msg-server
-%{_sysconfdir}/rc.d/rc5.d/S70msg-server
+%{_libdir}/libmsg_vobject.so
+/usr/share/license/msg-service/LICENSE.APLv2
 
 %files devel
 %defattr(-,root,root,-)
@@ -308,133 +356,27 @@ vconftool set -t bool memory/private/msg-service/national_sim 0 -i
 %{_includedir}/msg-service/*
 
 %files tools
+%manifest msg-service-tools.manifest
 %defattr(-,root,root,-)
-%{_bindir}/msg-helper
 %{_bindir}/msg-server
-%{_datadir}/media/Sherbet.wav
-%attr(0644,root,root)/usr/share/msg-service/plugin.cfg
+%config(noreplace) /opt/usr/dbspace/.msg_service.db*
+%{_sysconfdir}/rc.d/init.d/msg-server
+%{_libdir}/systemd/system/msg-server.service
+%{_libdir}/systemd/system/multi-user.target.wants/msg-server.service
+/usr/share/license/msg-service/LICENSE.APLv2
+/etc/smack/accesses.d/msg-service.rule
+/etc/config/*
 
 %files -n sms-plugin
+%manifest sms-plugin.manifest
 %defattr(-,root,root,-)
 %{_libdir}/libmsg_sms_plugin.so
+/usr/share/license/msg-service/LICENSE.APLv2
 
 %files -n mms-plugin
+%manifest mms-plugin.manifest
 %defattr(-,root,root,-)
 %{_libdir}/libmsg_mms_plugin.so
-%{_libdir}/libmsg_mms_language_pack.so
+/usr/share/license/msg-service/LICENSE.APLv2
 
 %changelog
-* Wed Aug 8 2012 KeeBum Kim <keebum.kim@samsung.com>
-- Apply New TAPI.
-- Modify transaction data size of sos recipient list.
-
-* Tue Aug 7 2012 KeeBum Kim <keebum.kim@samsung.com>
-- Fix contact sync defect.
-- New MessageFW API.
-
-* Fri Jul 27 2012 KeeBum Kim <keebum.kim@samsung.com>
-- Change devman_haptic.h to devman_managed.h.
-- Modify to set MSG_SERVER_READY before sim status check.
-- Fix bug in sim message save related operations.
-- Limit sim related APIs not to work on sim not available status.
-- Modify indicator icon image path & related.
-
-* Tue Jul 17 2012 KeeBum Kim <keebum.kim@samsung.com>
-- Modify MAX_SEGMENT_NUM to 15.
-- Modify MMplayer related to support interrupted event.
-- Fix bug in storage change callback which could cause on submit request.
-
-* Fri Jun 29 2012 Sangkoo Kim <sangkoo.kim@samsung.com>
-- Modify vconf key path for sos sending option.
-
-* Mon Jun 18 2012 Seunghwan Lee <sh.cat.lee@samsung.com>
-- Storage change callback for scheduled message
-- code chage to support glib2-2.32
-- Apply Backup && Restore of Mms Type
-
-* Fri Jun 15 2012 Sangkoo Kim <sangkoo.kim@samsung.com>
-- Update display time for scheduled message when it is sent.
-
-* Thu Jun 14 2012 Seunghwan Lee <sh.cat.lee@samsung.com>
-- Comment the test app in CMakefile.
-- Modify MMS BG color of vconf value.
-- Bug fixed wrong query in MsgStoCheckReadReportIsSent
-- Add '-i' option for vconf keys of memory type
-- Add smsc vconf keys(default value).
-- To avoid msg incoming sound and notification on SOS
-
-* Fri Jun 8 2012 Sangkoo Kim <sangkoo.kim@samsung.com>
-- Add '-i' option for vconf keys of memory type.
-- Add smsc vconf keys(default value).
-- To avoid msg incoming sound and notification on SOS state.
-- Change BGcolor to black && font colore to white.
-
-* Wed May 31 2012 Keebum Kim <keebum.kim@samsung.com>
-- Apply Mdm policy.
-- SOS message.
-- Fix horizontality development problem.
-- Remove vconf key for new message count. (db/badge/com.samsung.message)
-- Change vconf key path of "mms_send/msg_class" to private.
-
-* Thu May 24 2012 Keebum Kim <keebum.kim@samsung.com>
-- Add new MAPI.
-
-* Fri May 18 2012 Sangkoo Kim <sangkoo.kim@samsung.com>
-- Modify to support new DRM service.
-- Rename private vconf keys.
-- Modify .postinst and .spec file to pre-install used vconf keys.
-- Remove compile warnings.
-- Fix bug in manual retrieve operation.
-
-* Fri May 11 2012 Jaeyun Jeong <jyjeong@samsung.com>
-- Fix DB conflict which cause db lock.
-- Fix bug in Find My Mobile function.
-- Add '*' and '#' symbol as valid number.
-
-* Wed May 9 2012 Keebum Kim <keebum.kim@samsung.com>
-- Change mobile tracker related vconf key define values.
-- Apply MDM policy for allowing text messaging.
-- Fix bug for getting thumbnail path.
-- Enable functionality of scheduled message.
-- Change alarm setting of scheduled message from volatile type to non-volatile.
-- Fix error in search query.
-
-* Thu May 3 2012 Keebum Kim <keebum.kim@samsung.com>
-- Change some thread list related APIs to support DB change.
-- DB change to support multiple recipient.
-
-* Thu Apr 19 2012 Keebum Kim <keebum.kim@samsung.com>
-- Modify to manage contact sync time by vconf.
-- Use g_idle_add() routine for updating unread message count(vconf values).
-- apply try{}catch{} code for handling unexpected exception to avoid thread terminating.
-- Fix bug for allocated size of replacing string.
-- Resolve search problem for special characters.
-- add xmlFree.
-
-* Tue Apr 10 2012 Keebum Kim <keebum.kim@samsung.com>
-- Remove unused vconf keys.
-- Initialize SMSC selected_index.
-- Remove systemd related.
-
-* Thu Apr 05 2012 Jaeyun Jeong <jyjeong@samsung.com>
-- Add notification property(NOTIFICATION_PROP_DISPLAY_ONLY_SIMMODE)
-- Fix S1-2397/2417/2418/2419.
-- Remove sent status callback check during submit request.
-- Modify offset and limit operation on search.
-- Remove invalid folder and file.
-- Change browser launching API from aul to service-capi.
-- Remove unused file.
-- Invalid type checking is fixed.
-
-* Fri Mar 16 2012 Jaeyun Jeong <jyjeong@samsung.com>
-- Add #include <sys/stat.h> to support chmod related defines.
-- Fix DRM content issue(unregistered mo content)
-
-* Wed Mar 14 2012 Jaeyun Jeong <jyjeong@samsung.com>
-- Modify plugin configuration file location for FOTA.
-- Remove the db query which create sample data.
-
-* Wed Feb 29 2012 Jaeyun Jeong <jyjeong@samsung.com>
-- Update msg-service.spec for OBS.
-- Fix TC execute failure.
-- Fix S1-1419(Removed mms raw file issue after rebooting)
index f8c8eca..b0e1341 100755 (executable)
@@ -8,79 +8,44 @@ IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
 ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
 MESSAGE("Build type: ${CMAKE_BUILD_TYPE}")
 
-##########################################################
-# Define MMS Language Pack
-##########################################################
-
-SET(MMS-LANGUAGE-PACK-SRCS
-       LanguagePack/MmsPluginWmLngLatinUni.cpp
-       LanguagePack/MmsPluginWmLngString.cpp
-       LanguagePack/MmsPluginWmLngUTF8Uni.cpp
-       LanguagePack/MmsPluginWmLngUniUTF8.cpp
-)
-
-INCLUDE_DIRECTORIES(
-    ${CMAKE_SOURCE_DIR}/include/mapi
-       ${CMAKE_SOURCE_DIR}/include/common
-       ${CMAKE_SOURCE_DIR}/include/utils
-       ${CMAKE_CURRENT_SOURCE_DIR}/include
-)
-
-INCLUDE(FindPkgConfig)
-pkg_check_modules(mms_language_pkgs REQUIRED glib-2.0 dlog)
-
-FOREACH(flag ${mms_language_pkgs_CFLAGS})
-       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
-ENDFOREACH(flag)
-
-SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
-SET(CMAKE_CXX_FLAGS_DEBUG "-O2 -g")
-
-ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
-
-SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
-
-ADD_LIBRARY(${MMS-LANGUAGE-PACK-LIB} SHARED ${MMS-LANGUAGE-PACK-SRCS})
-TARGET_LINK_LIBRARIES(${MMS-LANGUAGE-PACK-LIB} ${mms_language_pkgs_LDFLAGS} ${UTILS-LIB})
-
-INSTALL(TARGETS ${MMS-LANGUAGE-PACK-LIB} LIBRARY DESTINATION lib)
 
 ##########################################################
 # Define MMS Plugin
 ##########################################################
 
 SET(MMS-PLUGIN-SRCS
+       MmsPluginCodecCommon.cpp
+       MmsPluginDecode.cpp
+       MmsPluginEncode.cpp
+       MmsPluginTextConvert.cpp
        MmsPluginTransport.cpp
        MmsPluginMain.cpp
        MmsPluginEventHandler.cpp
        MmsPluginStorage.cpp
        MmsPluginMessage.cpp
        MmsPluginMIME.cpp
-       MmsPluginDecode.cpp
-       MmsPluginAvCodec.cpp
-       MmsPluginDebug.cpp
        MmsPluginConnManWrapper.cpp
        MmsPluginUserAgent.cpp
        MmsPluginHttp.cpp
-       MmsPluginEncode.cpp
-       MmsPluginCodec.cpp
        MmsPluginInternal.cpp
-       MmsPluginContentCodec.cpp
-       MmsPluginSmil.cpp
-       MmsPluginSMILValidate.cpp
        MmsPluginDrm.cpp
+       MmsPluginUtil.cpp
+       MmsPluginTcs.cpp
+       MmsPluginComposer.cpp
+       MmsPluginAppBase.cpp
 )
 
 INCLUDE_DIRECTORIES(
        ${CMAKE_SOURCE_DIR}/include/common
        ${CMAKE_SOURCE_DIR}/include/framework
-       ${CMAKE_SOURCE_DIR}/include/msg_helper
        ${CMAKE_SOURCE_DIR}/include/utils
+       ${CMAKE_SOURCE_DIR}/include/externals
+       ${CMAKE_SOURCE_DIR}/include/mapi
        ${CMAKE_CURRENT_SOURCE_DIR}/include
 )
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(mms_plugin_pkgs REQUIRED glib-2.0 network libxml-2.0 drm-client libcurl mm-fileinfo mmutil-jpeg vconf dlog media-thumbnail)
+pkg_check_modules(mms_plugin_pkgs REQUIRED glib-2.0 libcurl mm-fileinfo mmutil-imgp mmutil-jpeg vconf dlog media-thumbnail csr-framework capi-network-connection db-util)
 
 FOREACH(flag ${mms_plugin_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
@@ -90,12 +55,13 @@ SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
 SET(CMAKE_CXX_FLAGS_DEBUG "-O2 -g")
 
 ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
-#ADD_DEFINITIONS("-DWno-write-strings")
+ADD_DEFINITIONS("-DFEATURE_JAVA_MMS")
 
 SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+SET(CMAKE_SHARED_LINKER_FLAGS "-Wl,--no-undefined")
 
 ADD_LIBRARY(${MMS-PLUGIN-LIB} SHARED ${MMS-PLUGIN-SRCS})
-TARGET_LINK_LIBRARIES(${MMS-PLUGIN-LIB} ${mms_plugin_pkgs_LDFLAGS} ${MMS-LANGUAGE-PACK-LIB} ${UTILS-LIB})
+TARGET_LINK_LIBRARIES(${MMS-PLUGIN-LIB} ${mms_plugin_pkgs_LDFLAGS} ${UTILS-LIB} ${EXTERNALS-LIB})
 
 INSTALL(TARGETS ${MMS-PLUGIN-LIB} LIBRARY DESTINATION lib)
 
diff --git a/plugin/mms_plugin/LanguagePack/MmsPluginWmLngLatinUni.cpp b/plugin/mms_plugin/LanguagePack/MmsPluginWmLngLatinUni.cpp
deleted file mode 100755 (executable)
index 1a34a55..0000000
+++ /dev/null
@@ -1,1131 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include "MsgDebug.h"
-#include "MmsPluginWmLngPack.h"
-#include "MmsPluginMessage.h"
-#include <stdlib.h>
-
-
-#define                MAX_ASCII                       256
-#define                MAX_ASCII_NUM           255
-
-static void     __WmLngReverseKeyCode(UCHAR *pOutStr, MCHAR *pInputStr, UINT len);
-static UINT     __WmLngLatin12UnicodeN(MCHAR *pOutStr, UCHAR *pInputStr, UINT len);
-static int      __WmLngConvertLatin12Unicode (MCHAR *des, UCHAR *str, UINT len);
-
-#define tabLatin2UniMax 93
-#define tabLatin3UniMax 87
-#define tabLatin4UniMax 96
-#define tabLatin8UniMax 60
-#define tabLatin15UniMax 96
-#define tabLatin5UniMax 96
-#define tabWin1251UniMax 128
-#define tabKoi8rUniMax 128
-#define tabKoi8uUniMax 128
-
-#define        SIM_SMSP_ALPHA_ID_MAX_LEN 30
-#define        SMS_MCHAR_TO_SIM_ALPHA_MASK 0x80
-#define        SMS_SIM_ALPHA_TO_MCHAR_MASK 0x7F
-
-
-/* latin2 table */
-typedef struct {
-       UCHAR latin2;
-       MCHAR unicode;
-}Latin2UniTable;
-
-const Latin2UniTable tabLatin2Uni[] = {
-       {0xA0,0x0020},{0xA1,0x0104},{0xA3,0x0141},{0xA4,0x00A4},{0xA5,0x013D},
-       {0xA6,0x015A},{0xA7,0x00A7},{0xA8,0x00A8},{0xA9,0x0160},{0xAA,0x015E},
-       {0xAB,0x0164},{0xAC,0x0179},{0xAD,0x00AD},{0xAE,0x017D},{0xAF,0x017B},
-       {0xB0,0x00B0},{0xB1,0x0105},{0xB2,0x00B8},{0xB3,0x0142},{0xB4,0x00B4},
-       {0xB5,0x012D},{0xB7,0x015B},{0xB8,0x00B8},{0xB9,0x0161},{0xBA,0x015F},
-       {0xBB,0x0165},{0xBC,0x017A},{0xBE,0x017E},{0xBF,0x017C},{0xC0,0x0154},
-       {0xC1,0x00C1},{0xC2,0x00C2},{0xC3,0x0102},{0xC4,0x00C4},{0xC5,0x0139},
-       {0xC6,0x0106},{0xC7,0x00C7},{0xC8,0x010C},{0xC9,0x00C9},{0xCA,0x0118},
-       {0xCB,0x00CB},{0xCC,0x0114},{0xCD,0x00CD},{0xCE,0x00CE},{0xCF,0x010E},
-       {0xD0,0x00D0},{0xD1,0x0143},{0xD2,0x0147},{0xD3,0x00D3},{0xD4,0x00D4},
-       {0xD5,0x0150},{0xD6,0x00D6},{0xD7,0x00D7},{0xD8,0x0158},{0xD9,0x016E},
-       {0xDA,0x00DA},{0xDB,0x0170},{0xDC,0x00DC},{0xDD,0x00DD},{0xDE,0x0162},
-       {0xDF,0x00DF},{0xE0,0x0155},{0xE1,0x00E1},{0xE2,0x00E2},{0xE3,0x0103},
-       {0xE4,0x00E4},{0xE5,0x013A},{0xE6,0x0107},{0xE7,0x00E7},{0xE8,0x010D},
-       {0xE9,0x00E9},{0xEA,0x0119},{0xEB,0x00EB},{0xEC,0x011B},{0xED,0x00ED},
-       {0xEE,0x00EE},{0xEF,0x010F},{0xF0,0x0111},{0xF1,0x0144},{0xF2,0x0148},
-       {0xF3,0x00F3},{0xF4,0x00F4},{0xF5,0x0151},{0xF6,0x00F6},{0xF7,0x00F7},
-       {0xF8,0x0159},{0xF9,0x016F},{0xFA,0x00FA},{0xFB,0x0171},{0xFC,0x00FC},
-       {0xFD,0x00FD},{0xFE,0x0163},{0xFF,0x00B7},
-};
-
-/* latin3 table */
-typedef struct {
-       UCHAR latin3;
-       MCHAR unicode;
-}Latin3UniTable;
-
-const Latin3UniTable tabLatin3Uni[] = {
-       {0xA0,0x0020},{0xA1,0x0126},{0xA2,0x02D8},{0xA3,0x00A3},{0xA4,0x00A4},
-       {0xA6,0x0124},{0xA7,0x00A7},{0xA8,0x00A8},{0xA9,0x0130},{0xAA,0x015E},
-       {0xAB,0x011E},{0xAC,0x0134},{0xAD,0x00AD},{0xAF,0x017B},{0xB0,0x00B0},
-       {0xB1,0x0127},{0xB2,0x00B2},{0xB3,0x00B3},{0xB4,0x00B4},{0xB5,0x00B5},
-       {0xB6,0x0125},{0xB7,0x00B7},{0xB8,0x00B8},{0xB9,0x0131},{0xBA,0x015F},
-       {0xBB,0x011F},{0xBC,0x0135},{0xBD,0x00BD},{0xBF,0x017C},{0xC0,0x00C0},
-       {0xC1,0x00C1},{0xC2,0x00C2},{0xC4,0x00C4},{0xC5,0x010A},{0xC6,0x0108},
-       {0xC7,0x00C7},{0xC8,0x00C8},{0xC9,0x00C9},{0xCA,0x00CA},{0xCB,0x00CB},
-       {0xCC,0x00CC},{0xCD,0x00CD},{0xCE,0x00CE},{0xCF,0x00CF},{0xD1,0x00D1},
-       {0xD2,0x00D2},{0xD3,0x00D3},{0xD4,0x00D4},{0xD6,0x00D6},{0xD7,0x00D7},
-       {0xD8,0x011C},{0xD9,0x00D9},{0xDA,0x00DA},{0xDB,0x00DB},{0xDC,0x00DC},
-       {0xDE,0x015C},{0xDF,0x00DF},{0xE0,0x00E0},{0xE1,0x00E1},{0xE2,0x00E2},
-       {0xE4,0x00E4},{0xE5,0x010B},{0xE6,0x0109},{0xE7,0x00E7},{0xE8,0x00E8},
-       {0xE9,0x00E9},{0xEA,0x00EA},{0xEB,0x00EB},{0xEC,0x00EC},{0xED,0x00ED},
-       {0xEE,0x00EE},{0xEF,0x00EF},{0xF1,0x00F1},{0xF2,0x00F2},{0xF3,0x00F3},
-       {0xF4,0x00F4},{0xF5,0x0121},{0xF6,0x00F6},{0xF7,0x00F7},{0xF8,0x011D},
-       {0xF9,0x00F9},{0xFA,0x00FA},{0xFB,0x00FB},{0xFC,0x00FC},{0xFD,0x016D},
-       {0xFE,0x015D},{0xFF,0x02D9},
-};
-/* latin4 table */
-typedef struct {
-       UCHAR latin4;
-       MCHAR unicode;
-}Latin4UniTable;
-
-const Latin4UniTable tabLatin4Uni[] = {
-       {0xA0,0x0020},{0xA1,0x0104},{0xA2,0x0138},{0xA3,0x0156},{0xA4,0x00A4},
-       {0xA5,0x0128},{0xA6,0x013B},{0xA7,0x00A7},{0xA8,0x00A8},{0xA9,0x0160},
-       {0xAA,0x0112},{0xAB,0x0122},{0xAC,0x0166},{0xAD,0x00AD},{0xAE,0x017D},
-       {0xAF,0x00AF},{0xB0,0x00B0},{0xB1,0x0105},{0xB2,0x02DB},{0xB3,0x0157},
-       {0xB4,0x00B4},{0xB5,0x0129},{0xB6,0x013C},{0xB7,0x02C7},{0xB8,0x00B8},
-       {0xB9,0x0161},{0xBA,0x0113},{0xBB,0x0123},{0xBC,0x0167},{0xBD,0x014A},
-       {0xBE,0x017E},{0xBF,0x014B},{0xC0,0x0100},{0xC1,0x00C1},{0xC2,0x00C2},
-       {0xC3,0x00C3},{0xC4,0x00C4},{0xC5,0x00C5},{0xC6,0x00C6},{0xC7,0x012E},
-       {0xC8,0x010C},{0xC9,0x00C9},{0xCA,0x0118},{0xCB,0x00CB},{0xCC,0x0116},
-       {0xCD,0x00CD},{0xCE,0x00CE},{0xCF,0x012A},{0xD0,0x0110},{0xD1,0x0145},
-       {0xD2,0x014C},{0xD3,0x0136},{0xD4,0x00D4},{0xD5,0x00D5},{0xD6,0x00D6},
-       {0xD7,0x00D7},{0xD8,0x00D8},{0xD9,0x0172},{0xDA,0x00DA},{0xDB,0x00DB},
-       {0xDC,0x00DC},{0xDD,0x0168},{0xDE,0x016A},{0xDF,0x00DF},{0xE0,0x0101},
-       {0xE1,0x00E1},{0xE2,0x00E2},{0xE3,0x00E3},{0xE4,0x00E4},{0xE5,0x00E5},
-       {0xE6,0x00E6},{0xE7,0x012F},{0xE8,0x010D},{0xE9,0x00E9},{0xEA,0x0119},
-       {0xEB,0x00EB},{0xEC,0x0117},{0xED,0x00ED},{0xEE,0x00EE},{0xEF,0x012B},
-       {0xF0,0x0111},{0xF1,0x0146},{0xF2,0x014D},{0xF3,0x0137},{0xF4,0x00F4},
-       {0xF5,0x00F5},{0xF6,0x00F6},{0xF7,0x00F7},{0xF8,0x00F8},{0xF9,0x0173},
-       {0xFA,0x00FA},{0xFB,0x00FB},{0xFC,0x00FC},{0xFD,0x0169},{0xFE,0x016B},
-       {0xFF,0x02D9},
-
-};
-/* latin8 table */
-typedef struct {
-       UCHAR latin8;
-       MCHAR unicode;
-}Latin8UniTable;
-
-const Latin8UniTable tabLatin8Uni[] = {
-       {0xA0,0x0020},{0xA2,0x00A2},{0xA3,0x00A3},{0xA4,0x00A4},{0xA5,0x00A5},
-       {0xA6,0x00A6},{0xA7,0x00A7},{0xA8,0x00A8},{0xA9,0x00A9},{0xAA,0x00D7},
-       {0xAB,0x00AB},{0xAC,0x00AC},{0xAD,0x00AD},{0xAE,0x00AE},{0xAF,0x203E},
-       {0xB0,0x00B0},{0xB1,0x00B1},{0xB2,0x00B2},{0xB3,0x00B3},{0xB4,0x00B4},
-       {0xB5,0x00B5},{0xB6,0x00B6},{0xB7,0x00B7},{0xB8,0x00B8},{0xB9,0x00B9},
-       {0xBA,0x00F7},{0xBB,0x00BB},{0xBC,0x00BC},{0xBD,0x00BD},{0xBE,0x00BE},
-       {0xDF,0x2017},{0xE0,0x05D0},{0xE1,0x05D1},{0xE2,0x05D2},{0xE3,0x05D3},
-       {0xE4,0x05D4},{0xE5,0x05D5},{0xE6,0x05D6},{0xE7,0x05D7},{0xE8,0x05D8},
-       {0xE9,0x05D9},{0xEA,0x05DA},{0xEB,0x05DB},{0xEC,0x05DC},{0xED,0x05DD},
-       {0xEE,0x05DE},{0xEF,0x05DF},{0xF0,0x05E0},{0xF1,0x05E1},{0xF2,0x05E2},
-       {0xF3,0x05E3},{0xF4,0x05E4},{0xF5,0x05E5},{0xF6,0x05E6},{0xF7,0x05E7},
-       {0xF8,0x05E8},{0xF9,0x05E9},{0xFA,0x05EA},{0xFD,0x200E},{0xFE,0x200F},
-};
-
-/* latin15 table */
-typedef struct {
-       UCHAR latin15;
-       MCHAR unicode;
-}Latin15UniTable;
-
-const Latin15UniTable tabLatin15Uni[] = {
-       {0xA0,0x0020},{0xA1,0x00A1},{0xA2,0x00A2},{0xA3,0x00A3},{0xA4,0x20AC},
-       {0xA5,0x00A5},{0xA6,0x0160},{0xA7,0x00A7},{0xA8,0x0161},{0xA9,0x00A9},
-       {0xAA,0x00AA},{0xAB,0x00AB},{0xAC,0x00AC},{0xAD,0x00AD},{0xAE,0x00AE},
-       {0xAF,0x00AF},{0xB0,0x00B0},{0xB1,0x00B1},{0xB2,0x00B2},{0xB3,0x00B3},
-       {0xB4,0x017D},{0xB5,0x00B5},{0xB6,0x00B6},{0xB7,0x00B7},{0xB8,0x017E},
-       {0xB9,0x00B9},{0xBA,0x00BA},{0xBB,0x00BB},{0xBC,0x0152},{0xBD,0x0153},
-       {0xBE,0x0178},{0xBF,0x00BF},{0xC0,0x00C0},{0xC1,0x00C1},{0xC2,0x00C2},
-       {0xC3,0x00C3},{0xC4,0x00C4},{0xC5,0x00C5},{0xC6,0x00C6},{0xC7,0x00C7},
-       {0xC8,0x00C8},{0xC9,0x00C9},{0xCA,0x00CA},{0xCB,0x00CB},{0xCC,0x00CC},
-       {0xCD,0x00CD},{0xCE,0x00CE},{0xCF,0x00CF},{0xD0,0x00D0},{0xD1,0x00D1},
-       {0xD2,0x00D2},{0xD3,0x00D3},{0xD4,0x00D4},{0xD5,0x00D5},{0xD6,0x00D6},
-       {0xD7,0x00D7},{0xD8,0x00D8},{0xD9,0x00D9},{0xDA,0x00DA},{0xDB,0x00DB},
-       {0xDC,0x00DC},{0xDD,0x00DD},{0xDE,0x00DE},{0xDF,0x00DF},{0xE0,0x00E0},
-       {0xE1,0x00E1},{0xE2,0x00E2},{0xE3,0x00E3},{0xE4,0x00E4},{0xE5,0x00E5},
-       {0xE6,0x00E6},{0xE7,0x00E7},{0xE8,0x00E8},{0xE9,0x00E9},{0xEA,0x00EA},
-       {0xEB,0x00EB},{0xEC,0x00EC},{0xED,0x00ED},{0xEE,0x00EE},{0xEF,0x00EF},
-       {0xF0,0x00F0},{0xF1,0x00F1},{0xF2,0x00F2},{0xF3,0x00F3},{0xF4,0x00F4},
-       {0xF5,0x00F5},{0xF6,0x00F6},{0xF7,0x00F7},{0xF8,0x00F8},{0xF9,0x00F9},
-       {0xFA,0x00FA},{0xFB,0x00FB},{0xFC,0x00FC},{0xFD,0x00FD},{0xFE,0x00FE},
-       {0xFF,0x00FF},
-};
-
-
-/* Win1251 table */
-typedef struct {
-       UCHAR win1251;
-       MCHAR unicode;
-}Win1251UniTable;
-const Win1251UniTable tabWin1251Uni[] = {
-       {0x80,0x0402},{0x81,0x0403},{0x82,0x201A},{0x83,0x0453},{0x84,0x201E},
-       {0x85,0x2026},{0x86,0x2020},{0x87,0x2021},{0x88,0x20AC},{0x89,0x2030},
-       {0x8A,0x0409},{0x8B,0x2039},{0x8C,0x040A},{0x8D,0x040C},{0x8E,0x040B},
-       {0x8F,0x040F},{0x90,0x0452},{0x91,0x2018},{0x92,0x2019},{0x93,0x201C},
-       {0x94,0x201D},{0x95,0x2022},{0x96,0x2013},{0x97,0x2014},{0x98,0x0000},
-       {0x99,0x2122},{0x9A,0x0459},{0x9B,0x203A},{0x9C,0x045A},{0x9D,0x045C},
-       {0x9E,0x045B},{0x9F,0x045F},{0xA0,0x00a0},{0xA1,0x040e},{0xA2,0x045e},
-       {0xA3,0x0408},{0xA4,0x00a4},{0xA5,0x0490},{0xA6,0x00a6},{0xA7,0x00a7},
-       {0xA8,0x0401},{0xA9,0x00a9},{0xAA,0x0404},{0xAB,0x00ab},{0xAC,0x00ac},
-       {0xAD,0x00ad},{0xAE,0x00ae},{0xAF,0x0407},{0xB0,0x00b0},{0xB1,0x00b1},
-       {0xB2,0x0406},{0xB3,0x0456},{0xB4,0x0491},{0xB5,0x00b5},{0xB6,0x00b6},
-       {0xB7,0x00b7},{0xB8,0x0451},{0xB9,0x2116},{0xBA,0x0454},{0xBB,0x00bb},
-       {0xBC,0x0458},{0xBD,0x0405},{0xBE,0x0455},{0xBF,0x0457},{0xC0,0x0410},
-       {0xC1,0x0411},{0xC2,0x0412},{0xC3,0x0413},{0xC4,0x0414},{0xC5,0x0415},
-       {0xC6,0x0416},{0xC7,0x0417},{0xC8,0x0418},{0xC9,0x0419},{0xCA,0x041a},
-       {0xCB,0x041b},{0xCC,0x041c},{0xCD,0x041d},{0xCE,0x041e},{0xCF,0x041f},
-       {0xD0,0x0420},{0xD1,0x0421},{0xD2,0x0422},{0xD3,0x0423},{0xD4,0x0424},
-       {0xD5,0x0425},{0xD6,0x0426},{0xD7,0x0427},{0xD8,0x0428},{0xD9,0x0429},
-       {0xDA,0x042a},{0xDB,0x042b},{0xDC,0x042c},{0xDD,0x042d},{0xDE,0x042e},
-       {0xDF,0x042f},{0xE0,0x0430},{0xE1,0x0431},{0xE2,0x0432},{0xE3,0x0433},
-       {0xE4,0x0434},{0xE5,0x0435},{0xE6,0x0436},{0xE7,0x0437},{0xE8,0x0438},
-       {0xE9,0x0439},{0xEA,0x043a},{0xEB,0x043b},{0xEC,0x043c},{0xED,0x043d},
-       {0xEE,0x043e},{0xEF,0x043f},{0xF0,0x0440},{0xF1,0x0441},{0xF2,0x0442},
-       {0xF3,0x0443},{0xF4,0x0444},{0xF5,0x0445},{0xF6,0x0446},{0xF7,0x0447},
-       {0xF8,0x0448},{0xF9,0x0449},{0xFA,0x044a},{0xFB,0x044b},{0xFC,0x044c},
-       {0xFD,0x044d},{0xFE,0x044e},{0xFF,0x044f}
-};
-
-
-/* Koi8-r table */
-typedef struct {
-       UCHAR koi8r;
-       MCHAR unicode;
-}Koi8rUniTable;
-const Koi8rUniTable tabKoi8rUni[] = {
-       {0x80,0x2500},{0x81,0x2502},{0x82,0x250C},{0x83,0x2510},{0x84,0x2514},
-       {0x85,0x2518},{0x86,0x251C},{0x87,0x2524},{0x88,0x252C},{0x89,0x2534},
-       {0x8A,0x253C},{0x8B,0x2580},{0x8C,0x2584},{0x8D,0x2588},{0x8E,0x258C},
-       {0x8F,0x2590},{0x90,0x2591},{0x91,0x2592},{0x92,0x2593},{0x93,0x2320},
-       {0x94,0x25A0},{0x95,0x2219},{0x96,0x221A},{0x97,0x2248},{0x98,0x2264},
-       {0x99,0x2265},{0x9A,0x00A0},{0x9B,0x2321},{0x9C,0x00B0},{0x9D,0x00B2},
-       {0x9E,0x00B7},{0x9F,0x00F7},{0xA0,0x2550},{0xA1,0x2551},{0xA2,0x2552},
-       {0xA3,0x0451},{0xA4,0x2553},{0xA5,0x2554},{0xA6,0x2555},{0xA7,0x2556},
-       {0xA8,0x2557},{0xA9,0x2558},{0xAA,0x2559},{0xAB,0x255A},{0xAC,0x255B},
-       {0xAD,0x255C},{0xAE,0x255D},{0xAF,0x255E},{0xB0,0x255F},{0xB1,0x2560},
-       {0xB2,0x2561},{0xB3,0x0401},{0xB4,0x2562},{0xB5,0x2563},{0xB6,0x2564},
-       {0xB7,0x2565},{0xB8,0x2566},{0xB9,0x2567},{0xBA,0x2568},{0xBB,0x2569},
-       {0xBC,0x256A},{0xBD,0x256B},{0xBE,0x256C},{0xBF,0x00A9},{0xC0,0x044E},
-       {0xC1,0x0430},{0xC2,0x0431},{0xC3,0x0446},{0xC4,0x0434},{0xC5,0x0435},
-       {0xC6,0x0444},{0xC7,0x0433},{0xC8,0x0445},{0xC9,0x0438},{0xCA,0x0439},
-       {0xCB,0x043A},{0xCC,0x043B},{0xCD,0x043C},{0xCE,0x043D},{0xCF,0x043E},
-       {0xD0,0x043F},{0xD1,0x044F},{0xD2,0x0440},{0xD3,0x0441},{0xD4,0x0442},
-       {0xD5,0x0443},{0xD6,0x0436},{0xD7,0x0432},{0xD8,0x044C},{0xD9,0x044B},
-       {0xDA,0x0437},{0xDB,0x0448},{0xDC,0x044D},{0xDD,0x0449},{0xDE,0x0447},
-       {0xDF,0x044A},{0xE0,0x042E},{0xE1,0x0410},{0xE2,0x0411},{0xE3,0x0426},
-       {0xE4,0x0414},{0xE5,0x0415},{0xE6,0x0424},{0xE7,0x0413},{0xE8,0x0425},
-       {0xE9,0x0418},{0xEA,0x0419},{0xEB,0x041A},{0xEC,0x041B},{0xED,0x041C},
-       {0xEE,0x041D},{0xEF,0x041E},{0xF0,0x041F},{0xF1,0x042F},{0xF2,0x0420},
-       {0xF3,0x0421},{0xF4,0x0422},{0xF5,0x0423},{0xF6,0x0416},{0xF7,0x0412},
-       {0xF8,0x042C},{0xF9,0x042B},{0xFA,0x0417},{0xFB,0x0428},{0xFC,0x042D},
-       {0xFD,0x0429},{0xFE,0x0427},{0xFF,0x042A}
-};
-
-
-
-/* Koi8-u table */
-typedef struct {
-       UCHAR koi8u;
-       MCHAR unicode;
-}Koi8uUniTable;
-
-const Koi8uUniTable tabKoi8uUni[] = {
-       {0x80,0x2500},{0x81,0x2502},{0x82,0x250C},{0x83,0x2510},{0x84,0x2514},
-       {0x85,0x2518},{0x86,0x251C},{0x87,0x2524},{0x88,0x252C},{0x89,0x2534},
-       {0x8A,0x253C},{0x8B,0x2580},{0x8C,0x2584},{0x8D,0x2588},{0x8E,0x258C},
-       {0x8F,0x2590},{0x90,0x2591},{0x91,0x2592},{0x92,0x2593},{0x93,0x2320},
-       {0x94,0x25A0},{0x95,0x2219},{0x96,0x221A},{0x97,0x2248},{0x98,0x2264},
-       {0x99,0x2265},{0x9A,0x00A0},{0x9B,0x2321},{0x9C,0x00B0},{0x9D,0x00B2},
-       {0x9E,0x00B7},{0x9F,0x00F7},{0xA0,0x2550},{0xA1,0x2551},{0xA2,0x2552},
-       {0xA3,0x0451},{0xA4,0x0454},{0xA5,0x2554},{0xA6,0x0456},{0xA7,0x0457},
-       {0xA8,0x2557},{0xA9,0x2558},{0xAA,0x2559},{0xAB,0x255A},{0xAC,0x255B},
-       {0xAD,0x0491},{0xAE,0x255D},{0xAF,0x255E},{0xB0,0x255F},{0xB1,0x2560},
-       {0xB2,0x2561},{0xB3,0x0401},{0xB4,0x0404},{0xB5,0x2563},{0xB6,0x0406},
-       {0xB7,0x0407},{0xB8,0x2566},{0xB9,0x2567},{0xBA,0x2568},{0xBB,0x2569},
-       {0xBC,0x256A},{0xBD,0x0490},{0xBE,0x256C},{0xBF,0x00A9},{0xC0,0x044E},
-       {0xC1,0x0430},{0xC2,0x0431},{0xC3,0x0446},{0xC4,0x0434},{0xC5,0x0435},
-       {0xC6,0x0444},{0xC7,0x0433},{0xC8,0x0445},{0xC9,0x0438},{0xCA,0x0439},
-       {0xCB,0x043A},{0xCC,0x043B},{0xCD,0x043C},{0xCE,0x043D},{0xCF,0x043E},
-       {0xD0,0x043F},{0xD1,0x044F},{0xD2,0x0440},{0xD3,0x0441},{0xD4,0x0442},
-       {0xD5,0x0443},{0xD6,0x0436},{0xD7,0x0432},{0xD8,0x044C},{0xD9,0x044B},
-       {0xDA,0x0437},{0xDB,0x0448},{0xDC,0x044D},{0xDD,0x0449},{0xDE,0x0447},
-       {0xDF,0x044A},{0xE0,0x042E},{0xE1,0x0410},{0xE2,0x0411},{0xE3,0x0426},
-       {0xE4,0x0414},{0xE5,0x0415},{0xE6,0x0424},{0xE7,0x0413},{0xE8,0x0425},
-       {0xE9,0x0418},{0xEA,0x0419},{0xEB,0x041A},{0xEC,0x041B},{0xED,0x041C},
-       {0xEE,0x041D},{0xEF,0x041E},{0xF0,0x041F},{0xF1,0x042F},{0xF2,0x0420},
-       {0xF3,0x0421},{0xF4,0x0422},{0xF5,0x0423},{0xF6,0x0416},{0xF7,0x0412},
-       {0xF8,0x042C},{0xF9,0x042B},{0xFA,0x0417},{0xFB,0x0428},{0xFC,0x042D},
-       {0xFD,0x0429},{0xFE,0x0427},{0xFF,0x042A}
-};
-
-
-/* Latin5 table */
-typedef struct {
-       UCHAR Latin5;
-       MCHAR unicode;
-}Latin5UniTable;
-
-const Latin5UniTable tabLatin5Uni[] = {
-       {0xA0,0x00A0},{0xA1,0x0401},{0xA2,0x0402},{0xA3,0x0403},{0xA4,0x0404},
-       {0xA5,0x0405},{0xA6,0x0406},{0xA7,0x0407},{0xA8,0x0408},{0xA9,0x0409},
-       {0xAA,0x040A},{0xAB,0x040B},{0xAC,0x040C},{0xAD,0x00AD},{0xAE,0x040E},
-       {0xAF,0x040F},{0xB0,0x0410},{0xB1,0x0411},{0xB2,0x0412},{0xB3,0x0413},
-       {0xB4,0x0414},{0xB5,0x0415},{0xB6,0x0416},{0xB7,0x0417},{0xB8,0x0418},
-       {0xB9,0x0419},{0xBA,0x041A},{0xBB,0x041B},{0xBC,0x041C},{0xBD,0x041D},
-       {0xBE,0x041E},{0xBF,0x041F},{0xC0,0x0420},{0xC1,0x0421},{0xC2,0x0422},
-       {0xC3,0x0423},{0xC4,0x0424},{0xC5,0x0425},{0xC6,0x0426},{0xC7,0x0427},
-       {0xC8,0x0428},{0xC9,0x0429},{0xCA,0x042A},{0xCB,0x042B},{0xCC,0x042C},
-       {0xCD,0x042D},{0xCE,0x042E},{0xCF,0x042F},{0xD0,0x0430},{0xD1,0x0431},
-       {0xD2,0x0432},{0xD3,0x0433},{0xD4,0x0434},{0xD5,0x0435},{0xD6,0x0436},
-       {0xD7,0x0437},{0xD8,0x0438},{0xD9,0x0439},{0xDA,0x043A},{0xDB,0x043B},
-       {0xDC,0x043C},{0xDD,0x043D},{0xDE,0x043E},{0xDF,0x043F},{0xE0,0x0440},
-       {0xE1,0x0441},{0xE2,0x0442},{0xE3,0x0443},{0xE4,0x0444},{0xE5,0x0445},
-       {0xE6,0x0446},{0xE7,0x0447},{0xE8,0x0448},{0xE9,0x0449},{0xEA,0x044A},
-       {0xEB,0x044B},{0xEC,0x044C},{0xED,0x044D},{0xEE,0x044E},{0xEF,0x044F},
-       {0xF0,0x2116},{0xF1,0x0451},{0xF2,0x0452},{0xF3,0x0453},{0xF4,0x0454},
-       {0xF5,0x0455},{0xF6,0x0456},{0xF7,0x0457},{0xF8,0x0458},{0xF9,0x0459},
-       {0xFA,0x045A},{0xFB,0x045B},{0xFC,0x045C},{0xFD,0x00A7},{0xFE,0x045E},
-       {0xFF,0x045F},
-
-};
-
-#define __LOCALCODE_TO_UTF8
-
-#ifdef __LOCALCODE_TO_UTF8
-
-bool __WmConvertCodeBufferSizeCheck (char *ftnName, int outBufSize, int requiredBufSize)
-{
-       if (outBufSize < requiredBufSize) {
-
-               if (outBufSize == sizeof(void*)) {  // if it is not array
-                       MSG_DEBUG("__WmConvertCodeBufferSizeCheck: Out buffer size seems to be small (%s)\n",ftnName);
-               } else {
-                       MSG_DEBUG("__WmConvertCodeBufferSizeCheck: Buffer size is too small %s: OutBuffer(%d), RequiredBufSize(%d)\n",ftnName,outBufSize,requiredBufSize);
-               }
-               return false;
-       }
-       return true;
-}
-
-
-
-MCHAR __WmLngSwapShort(MCHAR aShort)
-{
-       return ((aShort << 8) + (aShort >> 8));
-}
-
-/**
- * converting byte ordering between Network and device
- *
- * @param      mszOutput       [out] converted[destination] MCHAR buffer
- * @param      mszInput                [in]    source MCHAR buffer
- * @param      length          [in]    source MCHAR's string length (not byte count)
- *
- * @return     This function returns a true on success, or false on failure.
- */
-MCHAR* __WmLngSwapPCode(MCHAR *mszOutput, MCHAR *mszInput, int length)
-{
-       int     i;
-
-       for (i = 0; i < length; i++) {
-               if (mszInput[i] == (MCHAR)NULL)
-                       break;
-
-               mszOutput[i] = __WmLngSwapShort(mszInput[i]);
-       }
-
-       mszOutput[i] = '\0';
-
-       return mszOutput;
-}
-
-
-/**
- * This function convert character Processcode(Unicode) to Localcode(UTF8)
- *
- * @param      pszOutText      :       Output Buffer Pointer to LocalCode(UTF8)
- * @param      mszInText       :       Input Buffer Pointer to ProcessCode(UniCode)
- * @return     This function returns true on success, or false on failure.
- * @see                WmConvert2LCodeN
- */
-bool WmConvert2LCode(char *pszOutText, int outBufSize, MCHAR *mszInText)
-{
-       int charCount;
-       charCount = WmStrlen(mszInText);
-       if (charCount == 0)
-               pszOutText[0] = '\0';
-
-       if ((WmConvertPCode2UTF((UCHAR*)pszOutText, outBufSize, mszInText, charCount) == true)) {
-               return true;
-       } else {
-               MSG_DEBUG("WmConvert2LCode: Converting Unicode(%x) to utf8 code failed\n",mszInText);
-               return false;
-       }
-}
-
-/**
- * This function convert character Localcode(UTF8) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText                :       Input Buffer Pointer to LocalCode(UTF8)
- * @return     This function returns true on success, or false on failure.
- * @see                WmConvert2PCodeN
- */
-bool WmConvert2PCode(MCHAR *pmszOutText, int outBufSize, char *szInText)
-{
-       int byteCount;
-
-       byteCount = strlen((char*) szInText);
-
-       if (byteCount == 0)
-               pmszOutText[0] = '\0';
-
-       if((WmConvertUTF2PCode(pmszOutText, outBufSize,(UCHAR*)szInText, byteCount) == true)) {
-               return true;
-       } else {
-               MSG_DEBUG("WmConvert2PCode: Converting UTF8code(%x) to Unicode failed\n",szInText);
-               return false;
-       }
-}
-
-/**
- * This function convert N'th byte Localcode(UTF8) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to  ProcessCode(UniCode)
- * @param      szInText                :       Input Buffer Pointer to LocalCode(KSC5601)
- * @param      byteCount               :       byte number for converting character
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCode
- */
-bool WmConvert2PCodeN(MCHAR *pmszOutText, int outBufSize, char *szInText, int byteCount)
-{
-       if ((WmConvertUTF2PCode (pmszOutText, outBufSize, (UCHAR*)szInText, byteCount) == true)) {
-               return true;
-       } else {
-               MSG_DEBUG("WmConvert2PCodeN: Converting UTF8code(%x) to Unicode failed\n",szInText);
-               return false;
-       }
-}
-
-/**
- * This function convert N'th character Processcode(Unicode) to Localcode(UTF8)
- *
- * @param      pszOutText              :       Output Buffer Pointer to LocalCode(UTF8)
- * @param      mszInText               :       Input Buffer Pointer to ProcessCode(UniCode)
- * @param      charCount               :       number for convert n'th chararcter
- * @return     This function returns true on success, or false on failure.
- *
- * @see                WmConvert2LCode
- */
-bool WmConvert2LCodeN(char *pszOutText, int outBufSize, MCHAR *mszInText, int charCount)
-{
-       if ( (WmConvertPCode2UTF((UCHAR*)pszOutText, outBufSize, mszInText, charCount) == true)) {
-               return true;
-       } else {
-               MSG_DEBUG("WmConvert2LCodeN: Converting Unicode(%x) to utf8 code failed\n",mszInText);
-               return false;
-       }
-}
-
-/**
- * This function return output LocalCode Buffer Size
- *
- * @param      mszText :       Input ProcessCode String Pointer
- * @return     This function returns BufferSize for LocalCode
- *
- * @see                WmGetPcodeSize
- */
-int WmGetLCodeSize(MCHAR *mszText)
-{
-       int nBuffSize = 0;
-
-       if (mszText[0] == '\0')
-               return 0;
-
-       while (*mszText != '\0') {
-
-               if (0x0001 <= *mszText && *mszText <= 0x007F) {
-                       nBuffSize++;
-                       mszText++;
-               } else if ((*mszText == 0x0000) || (0x0080 <= *mszText && *mszText <= 0x07FF)) {
-                       nBuffSize += 2;
-                       mszText++;
-               } else {
-                       nBuffSize += 3;
-                       mszText++;
-               }
-       }
-       return nBuffSize;
-}
-
-
-/**
- * This function return output LocalCode Buffer Size
- *
- * @param      mszText :       Input ProcessCode String Pointer
- * @return     This function returns BufferSize for LocalCode
- *
- * @see                WmGetPcodeSize
- */
-int WmGetLCodeSizeN(MCHAR *mszText, int charCount)
-{
-       int nBuffSize = 0;
-       int i = 0;
-
-       if (mszText[0] == '\0')
-               return 0;
-
-       while ((*mszText != '\0') && (i < charCount)) {
-
-               if (0x0001 <= *mszText && *mszText <= 0x007F) {
-                       nBuffSize++;
-                       mszText++;
-               } else if ((*mszText == 0x0000) || (0x0080 <= *mszText && *mszText <= 0x07FF)) {
-                       nBuffSize += 2;
-                       mszText++;
-               } else {
-                       nBuffSize += 3;
-                       mszText++;
-               }
-               i++;
-       }
-       return nBuffSize;
-}
-#endif
-
-
-/**
- * This function convert character Localcode(Latin2) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText        :       Input Buffer Pointer to Latin2 code
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCodeN
- */
-bool WmConvertLatin2Code2PCode(MCHAR *pmszOutText, int outBufSize, char *szInText)
-{
-       int i = 0;
-       int j = 0;
-       int strLen = 0;
-       bool bInLatin2Table = false;
-
-       strLen = strlen((char *)szInText);
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, strLen) == false) {
-               MSG_DEBUG("WmConvertLatinCode2PCode: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       for (i = 0; i < strLen; i++) {
-               bInLatin2Table = false;
-               for (j = 0; j < tabLatin2UniMax; j++) {
-                       if ((UCHAR)szInText[i] == tabLatin2Uni[j].latin2) {
-                               pmszOutText[i] = tabLatin2Uni[j].unicode;
-                               bInLatin2Table = true;
-                       }
-               }
-               if (bInLatin2Table == false)
-                       pmszOutText[i] = (MCHAR)(UCHAR)szInText[i];
-       }
-       /* Latin2 -> UNICODE */
-       pmszOutText[strLen] = '\0';
-
-       return true;
-}
-
-
-/**
- * This function convert character Localcode(Latin3) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText        :       Input Buffer Pointer to Latin2 code
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCodeN
- */
-bool WmConvertLatin3Code2PCode(MCHAR *pmszOutText, int outBufSize, char *szInText)
-{
-       int i = 0;
-       int j = 0;
-       int strLen = 0;
-       bool bInLatin3Table = false;
-
-       strLen = strlen((char *)szInText);
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, strLen) == false) {
-               MSG_DEBUG("WmConvertLatinCode2PCode: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       for (i = 0; i < strLen; i++) {
-               bInLatin3Table = false;
-               for (j = 0; j < tabLatin3UniMax; j++) {
-                       if ((UCHAR)szInText[i] == tabLatin3Uni[j].latin3) {
-                               pmszOutText[i] = tabLatin3Uni[j].unicode;
-                               bInLatin3Table = true;
-                       }
-               }
-               if (bInLatin3Table == false)
-                       pmszOutText[i] = (MCHAR)(UCHAR)szInText[i];
-       }
-       /* Latin3 -> UNICODE */
-       pmszOutText[strLen] = '\0';
-
-       return true;
-}
-
-/**
- * This function convert character Localcode(Latin4) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText        :       Input Buffer Pointer to Latin2 code
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCodeN
- */
-bool WmConvertLatin4Code2PCode(MCHAR *pmszOutText, int outBufSize, char *szInText)
-{
-       int i = 0;
-       int j = 0;
-       int strLen = 0;
-       bool bInLatin4Table = false;
-
-       strLen = strlen((char *)szInText);
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, strLen) == false) {
-               MSG_DEBUG("WmConvertLatinCode2PCode: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       for (i = 0; i < strLen; i++) {
-               bInLatin4Table = false;
-               for (j = 0; j < tabLatin4UniMax; j++) {
-                       if ((UCHAR)szInText[i] == tabLatin4Uni[j].latin4) {
-                               pmszOutText[i] = tabLatin4Uni[j].unicode;
-                               bInLatin4Table = true;
-                       }
-               }
-               if (bInLatin4Table == false)
-                       pmszOutText[i] = (MCHAR)(UCHAR)szInText[i];
-       }
-       /* Latin4 -> UNICODE */
-       pmszOutText[strLen] = '\0';
-
-       return true;
-}
-
-/**
- * This function convert character Localcode(Latin8) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText        :       Input Buffer Pointer to Latin2 code
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCodeN
- */
-bool WmConvertLatin8Code2PCode(MCHAR *pmszOutText, int outBufSize, char *szInText)
-{
-       int i = 0;
-       int j = 0;
-       int strLen = 0;
-       bool bInLatin8Table = false;
-
-       strLen = strlen((char *)szInText);
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, strLen) == false) {
-               MSG_DEBUG("WmConvertLatinCode2PCode: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       for (i = 0; i < strLen; i++) {
-               bInLatin8Table = false;
-               for (j = 0; j < tabLatin8UniMax; j++) {
-                       if ((UCHAR)szInText[i] == tabLatin8Uni[j].latin8) {
-                               pmszOutText[i] = tabLatin8Uni[j].unicode;
-                               bInLatin8Table = true;
-                       }
-               }
-               if (bInLatin8Table == false)
-                       pmszOutText[i] = (MCHAR)(UCHAR)szInText[i];
-       }
-       /* Latin8 -> UNICODE */
-       pmszOutText[strLen] = '\0';
-
-       return true;
-}
-
-
-/**
- * This function convert character Localcode(Win1251) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText        :       Input Buffer Pointer to Win1251 code
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCodeN
- */
-bool WmConvertWin1251Code2PCode(MCHAR *pmszOutText, int outBufSize, char *szInText)
-{
-       int i = 0;
-       int j = 0;
-       int strLen = 0;
-       bool bInWin1251Table = false;
-
-       strLen = strlen((char *)szInText);
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, strLen) == false) {
-               MSG_DEBUG("WmConvertWin1251Code2PCode: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       for (i = 0; i < strLen; i++) {
-               bInWin1251Table = false;
-               for (j = 0; j < tabWin1251UniMax; j++) {
-                       if ((UCHAR)szInText[i] == tabWin1251Uni[j].win1251) {
-                               pmszOutText[i] = tabWin1251Uni[j].unicode;
-                               bInWin1251Table = true;
-                       }
-               }
-               if (bInWin1251Table == false)
-                       pmszOutText[i] = (MCHAR)(UCHAR)szInText[i];
-       }
-       /* Win1251 -> UNICODE */
-       pmszOutText[strLen] = '\0';
-
-       return true;
-}
-
-
-/**
- * This function convert character Localcode(Koi8-r) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText        :       Input Buffer Pointer to Koi8-r code
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCodeN
- */
-bool WmConvertKoi8rCode2PCode(MCHAR *pmszOutText, int outBufSize, char *szInText)
-{
-       int i = 0;
-       int j = 0;
-       int strLen = 0;
-       bool bInKoi8rTable = false;
-
-       strLen = strlen((char *)szInText);
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, strLen) == false) {
-               MSG_DEBUG("WmConvertKoi8rCode2PCode: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       for (i = 0; i < strLen; i++) {
-               bInKoi8rTable = false;
-               for (j = 0; j < tabKoi8rUniMax; j++) {
-                       if ((UCHAR)szInText[i] == tabKoi8rUni[j].koi8r) {
-                               pmszOutText[i] = tabKoi8rUni[j].unicode;
-                               bInKoi8rTable = true;
-                       }
-               }
-               if (bInKoi8rTable == false)
-                       pmszOutText[i] = (MCHAR)(UCHAR)szInText[i];
-       }
-       /* bInKoi8-rTable -> UNICODE */
-       pmszOutText[strLen] = '\0';
-
-       return true;
-}
-
-
-/**
- * This function convert character Localcode(Koi8-u) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText        :       Input Buffer Pointer to Koi8-u code
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCodeN
- */
-bool WmConvertKoi8uCode2PCode(MCHAR *pmszOutText, int outBufSize, char *szInText)
-{
-       int i = 0;
-       int j = 0;
-       int strLen = 0;
-       bool bInKoi8uTable = false;
-
-       strLen = strlen((char *)szInText);
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, strLen) == false) {
-               MSG_DEBUG("WmConvertKoi8uCode2PCode: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       for (i = 0; i < strLen; i++) {
-               bInKoi8uTable = false;
-               for (j = 0; j < tabKoi8uUniMax; j++) {
-                       if ((UCHAR)szInText[i] == tabKoi8uUni[j].koi8u) {
-                               pmszOutText[i] = tabKoi8uUni[j].unicode;
-                               bInKoi8uTable = true;
-                       }
-               }
-               if (bInKoi8uTable == false)
-                       pmszOutText[i] = (MCHAR)(UCHAR)szInText[i];
-       }
-       /* bInKoi8uTable -> UNICODE */
-       pmszOutText[strLen] = '\0';
-
-       return true;
-}
-
-
-/**
- * This function convert character Localcode(Latin15) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText        :       Input Buffer Pointer to Latin2 code
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCodeN
- */
-bool WmConvertLatin15Code2PCode(MCHAR *pmszOutText, int outBufSize, char *szInText)
-{
-       int i = 0;
-       int j = 0;
-       int strLen = 0;
-       bool bInLatin15Table = false;
-
-       strLen = strlen((char *)szInText);
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, strLen) == false) {
-               MSG_DEBUG("WmConvertLatinCode2PCode: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       for (i = 0; i < strLen; i++) {
-               bInLatin15Table = false;
-               for (j = 0; j < tabLatin15UniMax; j++) {
-                       if ((UCHAR)szInText[i] == tabLatin15Uni[j].latin15) {
-                               pmszOutText[i] = tabLatin15Uni[j].unicode;
-                               bInLatin15Table = true;
-                       }
-               }
-               if (bInLatin15Table == false)
-                       pmszOutText[i] = (MCHAR)(UCHAR)szInText[i];
-       }
-       /* Latin15 -> UNICODE */
-       pmszOutText[strLen] = '\0';
-
-       return true;
-}
-
-
-
-
-/**
- * This function convert character Localcode(Latin5) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText        :       Input Buffer Pointer to Latin5 code
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCodeN
- */
-bool WmConvertLatin5Code2PCode(MCHAR *pmszOutText, int outBufSize, char *szInText)
-{
-       int i = 0;
-       int j = 0;
-       int strLen = 0;
-       bool bInLatin5Table = false;
-
-       strLen = strlen((char *)szInText);
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, strLen) == false) {
-               MSG_DEBUG("WmConvertLatinCode2PCode: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       for (i = 0; i < strLen; i++) {
-               bInLatin5Table = false;
-               for (j = 0; j < tabLatin5UniMax; j++) {
-                       if ((UCHAR)szInText[i] == tabLatin5Uni[j].Latin5) {
-                               pmszOutText[i] = tabLatin5Uni[j].unicode;
-                               bInLatin5Table = true;
-                       }
-               }
-               if (bInLatin5Table == false)
-                       pmszOutText[i] = (MCHAR)(UCHAR)szInText[i];
-       }
-       /* Latin5 -> UNICODE */
-       pmszOutText[strLen] = '\0';
-
-       return true;
-}
-
-
-int WmGetLatin32UTFCodeSize(unsigned char *szSrc, int nChar)
-{
-       int bufferSize = 0;
-       int latin3Size = -1;
-       MCHAR *pmszText;
-
-       bufferSize = nChar*3+1;
-       pmszText = (MCHAR *)malloc(bufferSize);
-       if (!pmszText) {
-               MSG_DEBUG("WmGetLatin32UTFCodeSize: memory allocation is failed!\n");
-               return -1;
-       }
-       WmConvertLatin3Code2PCode(pmszText, bufferSize, (char*)szSrc);
-       latin3Size = WmGetLCodeSize(pmszText);
-       free(pmszText);
-       return latin3Size;
-}
-
-
-int WmGetLatin42UTFCodeSize(unsigned char *szSrc, int nChar)
-{
-       int bufferSize = 0;
-       int latin4Size = -1;
-       MCHAR *pmszText;
-
-       bufferSize = nChar*3+1;
-       pmszText = (MCHAR *)malloc(bufferSize);
-       if (!pmszText) {
-               MSG_DEBUG("WmGetLatin42UTFCodeSize: memory allocation is failed!\n");
-               return -1;
-       }
-       WmConvertLatin4Code2PCode(pmszText, bufferSize, (char*)szSrc);
-       latin4Size = WmGetLCodeSize(pmszText);
-       free(pmszText);
-       return latin4Size;
-}
-
-
-int WmGetLatin82UTFCodeSize(unsigned char *szSrc, int nChar)
-{
-       int bufferSize = 0;
-       int latin8Size = -1;
-       MCHAR *pmszText;
-
-       bufferSize = nChar*3+1;
-       pmszText = (MCHAR *)malloc(bufferSize);
-       if (!pmszText) {
-               MSG_DEBUG("WmGetLatin82UTFCodeSize: memory allocation is failed!\n");
-               return -1;
-       }
-       WmConvertLatin8Code2PCode(pmszText, bufferSize, (char*)szSrc);
-       latin8Size = WmGetLCodeSize(pmszText);
-       free(pmszText);
-       return latin8Size;
-}
-
-int WmGetLatin152UTFCodeSize(unsigned char *szSrc, int nChar)
-{
-       int bufferSize = 0;
-       int latin15Size = -1;
-       MCHAR *pmszText;
-
-       bufferSize = nChar*3+1;
-       pmszText = (MCHAR *)malloc(bufferSize);
-       if (!pmszText) {
-               MSG_DEBUG("WmGetLatin152UTFCodeSize: memory allocation is failed!\n");
-               return -1;
-       }
-       WmConvertLatin15Code2PCode(pmszText, bufferSize, (char*)szSrc);
-       latin15Size = WmGetLCodeSize(pmszText);
-       free(pmszText);
-       return latin15Size;
-}
-
-int WmGetLatin52UTFCodeSize(unsigned char *szSrc, int nChar)
-{
-       int bufferSize = 0;
-       int latin5Size = -1;
-       MCHAR *pmszText;
-
-       bufferSize = nChar*3+1;
-       pmszText = (MCHAR *)malloc(bufferSize);
-       if (!pmszText) {
-               MSG_DEBUG("WmGetLatin52UTFCodeSize: memory allocation is failed!\n");
-               return -1;
-       }
-       WmConvertLatin5Code2PCode(pmszText, bufferSize, (char*)szSrc);
-       latin5Size = WmGetLCodeSize(pmszText);
-       free(pmszText);
-       return latin5Size;
-}
-
-
-/**
- * This function convert character Localcode(Latin1) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText        :       Input Buffer Pointer to LocalCode(KSC5601)
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCodeN
- */
-bool WmConvertLatinCode2PCode(MCHAR *pmszOutText, int outBufSize, char *szInText)
-{
-       UINT strLen;
-
-       strLen = strlen((char *)szInText);
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, strLen) == false) {
-               MSG_DEBUG("WmConvertLatinCode2PCode: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       /* Latin1 -> UNICODE */
-       __WmLngConvertLatin12Unicode(pmszOutText,(UCHAR*)szInText,strLen);
-       pmszOutText[strLen] = '\0';
-
-       return true;
-}
-
-/**
- * This function convert N'th character Localcode(Latin1) to Processcode(Unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to  ProcessCode(UniCode)
- * @param      szInText        :       Input Buffer Pointer to LocalCode(KSC5601)
- * @param      charCount               :       number for convert n'th chararcter
- * @return     This function returns true on success, or false
- *                     on failure.
- * @see                WmConvert2PCode
- */
-bool WmConvertLatinCode2PCodeN(MCHAR *pmszOutText, int outBufSize, char *szInText, int charCount)
-{
-       int strLen;
-
-       if (charCount == 0) {
-               MSG_DEBUG("WmConvert2PCodeN: charCount is0\n");
-               pmszOutText[charCount] = '\0';
-       }
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, charCount) == false) {
-               MSG_DEBUG("WmConvertLatinCode2PCodeN: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       /* Latin1 -> UNICODE */
-       __WmLngLatin12UnicodeN (pmszOutText, (UCHAR*)szInText, charCount);
-
-       strLen = strlen((char *)szInText);
-       if(strLen < charCount) {
-               pmszOutText[strLen] = '\0';
-       } else {
-               pmszOutText[charCount] = '\0';
-       }
-
-       return true;
-}
-
-/*
- * This function convert character Processcode(Unicode) to Localcode(Latin1)
- *
- * @param      pOutStr         :       Output Buffer Pointer to LocalCode(Latin1)
- * @param      pInputStr       :       Input Buffer Pointer to ProcessCode(UniCode)
- * @param      len                     :       number for convert n'th chararcter
- * @return     void
- *
- * @see
- */
-static void __WmLngReverseKeyCode(UCHAR *pOutStr, MCHAR *pInputStr, UINT len)
-{
-       UCHAR *rear=NULL;
-       MCHAR *p;
-       UCHAR temp;
-
-       rear = pOutStr;
-
-       for (p = pInputStr; len > 0 && p; len--) {
-               if (*pInputStr < MAX_ASCII_NUM) {                  // ASCII String
-                       if (*p == 0)
-                               *rear = '\0';
-                       temp = (UCHAR)(*p);
-                       *rear = temp;
-                       rear++;
-                       p++;
-                       if(len == 1)
-                               *rear = '\0';
-               } else {
-                       *rear = 0x3F;
-                       rear++;
-                       p++;
-                       if(len == 1)
-                               *rear = '\0';
-               }
-               pInputStr = p;
-       }
-}
-
-
-/*
- * This function convert character Localcode(Latin1) to Processcode(Unicode)
- *
- * @param      des[in]         :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      str[in]         :       Input Buffer Pointer to LocalCode(Latin1)
- * @param      len[in]         :       number for convert n'th chararcter
- * @return     This function returns number for convert n'th chararcter on success
- *
- * @see
- */
-static int __WmLngConvertLatin12Unicode (MCHAR *des, UCHAR *str, UINT len)
-{
-       MCHAR *org;
-       org = des;
-       while (len>0) {
-               *des++ = *str++;
-               len--;
-       }
-
-       return (des - org) ;
-}
-
-/*
- * This function convert N'th character Localcode(Latin1) to Processcode(Unicode)
- *
- * @param      pOutStr         :       Output Buffer Pointer to  ProcessCode(UniCode)
- * @param      pInputStr       :       Input Buffer Pointer to LocalCode(Latin1)
- * @param      len                     :       number for convert n'th chararcter
- * @return     This function returns true on success, or false on failure.
- *
- * @see
- */
-static UINT __WmLngLatin12UnicodeN(MCHAR *pOutStr, UCHAR *pInputStr, UINT len)
-{
-       UINT n;
-
-       n = strlen((char*)pInputStr);
-
-       if(len > n)
-               len = n;
-
-       return __WmLngConvertLatin12Unicode (pOutStr, pInputStr, len);
-}
-
diff --git a/plugin/mms_plugin/LanguagePack/MmsPluginWmLngString.cpp b/plugin/mms_plugin/LanguagePack/MmsPluginWmLngString.cpp
deleted file mode 100755 (executable)
index 3fc2214..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include "MsgDebug.h"
-#include "MmsPluginWmLngPack.h"
-
-
-/**
- * return length of a string (character count of a string)
- * @param      mszInText [in]  input string pointer
- * @return     lenght of string
- *
- */
-int WmStrlen(const MCHAR *mszInText)
-{
-       register int n;
-
-       n=0;
-
-       while(*(mszInText+n) != '\0')
-               n++;
-
-       return n;
-}
-
diff --git a/plugin/mms_plugin/LanguagePack/MmsPluginWmLngUTF8Uni.cpp b/plugin/mms_plugin/LanguagePack/MmsPluginWmLngUTF8Uni.cpp
deleted file mode 100755 (executable)
index 315cee3..0000000
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include "MsgDebug.h"
-#include "MmsPluginWmLngPack.h"
-
-
-/* Local function */
-int __WmLngUTF2Unicode (unsigned short *des,unsigned char *src, int nChar);
-
-
-int __WmLngStrlenByByte(UCHAR *szInText, int byteCount)
-{
-       int nCount = 0;
-       while (byteCount > 0 && (*szInText != '\0')) {
-               if (*szInText < 0x80) {
-                       szInText++;
-                       byteCount--;
-               } else if  (((0xC0 <= *szInText) && (*szInText < 0xE0)) && (*(szInText+1) >= 0x80)) {
-                       szInText += 2;
-                       byteCount -= 2;
-               } else if  ((*szInText >= 0xE0) && (*(szInText+1) >= 0x80) && (*(szInText+2) >= 0x80)) {
-                       szInText += 3;
-                       byteCount -= 3;
-               } else {
-                       szInText++;
-                       byteCount--;
-                       MSG_DEBUG("__WmLngStrlenByByte: utf8 incorrect range!\n");
-               }
-               nCount++;
-       }
-       return (nCount+1)*sizeof(MCHAR);
-}
-
-/**
- * This function convert character n'th byte UTF8 character to ProcessCode(unicode)
- *
- * @param      pmszOutText             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      szInText                :       Input  Buffer Pointer to UTF8
- * @param      byteCount               :       byte number for converting the character
- * @return                                     :       This function returns true on success, or false
- *                                                             on failure.
- *
- * @see                WmConvertPCode2UTF
- */
-bool WmConvertUTF2PCode (MCHAR *pmszOutText, int outBufSize, UCHAR *szInText, int byteCount)
-{
-       int length;
-       if (byteCount == 0) {
-               pmszOutText[0] = '\0';
-               return true;
-       }
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pmszOutText, outBufSize, __WmLngStrlenByByte((UCHAR*)szInText, byteCount)) == false) {
-               MSG_DEBUG("WmConvertUTF2PCode: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       length = __WmLngUTF2Unicode (pmszOutText, szInText, byteCount);
-       if (length == -1) {
-               MSG_DEBUG("WmConvertUTF2PCode: __WmLngUTF2Unicode returns false!\n");
-               return false;
-       } else {
-               return true;
-       }
-}
-
-
-/*
- * change 1byte-encoded-UTF8 character to Unicode
- * @param      byte1   :       1byte character code
- * @return                     :       result of bit operation
- *
- *
- * @see
- */
-unsigned short __WmLngConvert1ByteChar (unsigned char byte1)
-{
-       unsigned short result;
-
-       result = 0;
-       result = (byte1 & 0x7F);
-
-       return result;
-}
-
-/*
- * change 2byte-encoded-UTF8 character to Unicode
- * @param      byte1   :       1'st byte character code
- * @param      byte2   :       2'st byte character code
- * @return                     :       result of bit operation
- *
- * @see
- */
-unsigned short __WmLngConvert2ByteChar (unsigned char byte1, unsigned char byte2)
-{
-       unsigned short result;
-       unsigned char hi;
-       unsigned char lo;
-
-       result = 0;
-
-       hi = byte1 & 0x1F;
-       lo = byte2 & 0x3F;
-
-       result = (hi << 6) | lo;
-
-       return result;
-}
-
-/*
- * change 3byte-encoded-UTF8 character to Unicode
- * @param      byte1   :       1'st character code
- * @param      byte2   :       2'st character code
- * @param      byte3   :       3'st character code
- * @return                     :       result of bit operation
- *
- * @see
- */
-unsigned short __WmLngConvert3ByteChar (unsigned char byte1, unsigned char byte2, unsigned char byte3)
-{
-       unsigned short result;
-       unsigned char hi;
-       unsigned char mid;
-       unsigned char lo;
-
-       result = 0;
-
-       hi = byte1 & 0x0F;
-       mid = byte2 & 0x3F;
-       lo = byte3 & 0x3F;
-
-       result = (hi << 12) | (mid << 6) | lo;
-
-       return result;
-}
-
-/*
- * This function convert character UTF8 to ProcessCode(unicode)
- *
- * @param      des             :       Output Buffer Pointer to ProcessCode(UniCode)
- * @param      src             :       Input  Buffer Pointer to UTF8
- * @param      nChar   :       number for convert n'th chararcter
- * @return                     :       This function returns number for convert n'th chararcter on success, or -1
- *                                             on failure.
- *
- * @see
- */
-
-int __WmLngUTF2Unicode (unsigned short *des,unsigned char *src, int nChar)
-{
-       unsigned short *org;
-
-       org = des;
-
-       while (nChar > 0 && (*src != '\0')) {
-               if (*src < 0x80) {
-                       *des = __WmLngConvert1ByteChar (*src);
-
-                       des++;
-                       src++;
-                       nChar--;
-               } else if  (((0xC0 <= *src) && (*src < 0xE0)) && (*(src+1) >= 0x80)) {
-                       *des = __WmLngConvert2ByteChar (*src, *(src+1));
-
-                       des++;
-                       src += 2;
-                       nChar -= 2;
-               } else if  ((*src >= 0xE0) && (*(src+1) >= 0x80) && (*(src+2) >= 0x80)) {
-                       *des = __WmLngConvert3ByteChar (*src, *(src+1), *(src+2));
-
-                       des++;
-
-                       src += 3;
-                       nChar -= 3;
-               } else {
-                       *des = __WmLngConvert1ByteChar (*src);
-                       des++;
-                       src++;
-                       nChar--;
-                       MSG_DEBUG("__WmLngUTF2Unicode: utf8 incorrect range!\n");
-               }
-       }
-       *des = 0;
-       return (des - org);
-}
-
-
diff --git a/plugin/mms_plugin/LanguagePack/MmsPluginWmLngUniUTF8.cpp b/plugin/mms_plugin/LanguagePack/MmsPluginWmLngUniUTF8.cpp
deleted file mode 100755 (executable)
index 1fd9d14..0000000
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include "MsgDebug.h"
-#include "MmsPluginWmLngPack.h"
-
-
-/* Local function */
-int __WmLngUnicode2UTF (unsigned char *des, unsigned short *src, int nChar);
-
-
-int __WmLngGetLCodeSizeN(MCHAR *mszText, int charCount)
-{
-       int nBuffSize = 0;
-
-       if (mszText[0] == '\0')
-               return 0;
-
-       while (charCount > 0 && *mszText != '\0') {
-
-               if (0x0001 <= *mszText && *mszText <= 0x007F) {
-                       nBuffSize++;
-                       mszText++;
-                       charCount--;
-               } else if((*mszText == 0x0000) || (0x0080 <= *mszText && *mszText <= 0x07FF)) {
-                       nBuffSize += 2;
-                       mszText++;
-                       charCount--;
-               } else {
-                       nBuffSize += 3;
-                       mszText++;
-                       charCount--;
-               }
-       }
-       return nBuffSize+1;     /* include NULL  */
-}
-
-/**
- * This function convert character ProcessCode(unicode) to UTF8
- *
- * @param      pszOutText      :       Output Buffer Pointer to UTF8
- * @param      mszInText       :       Input  Buffer Pointer to ProcessCode(UniCode)
- * @param      charCount       :       number for convert n'th chararcter
- * @return     This function returns true on success, or false
- *                     on failure.
- *
- * @see                WmConvertPCode2UTF
- */
-bool WmConvertPCode2UTF(UCHAR *pszOutText, int outBufSize, MCHAR *mszInText, int charCount)
-{
-       int length;
-
-       if (charCount == 0) {
-               pszOutText[0] = '\0';
-               return true;
-       }
-
-       if (__WmConvertCodeBufferSizeCheck((char*)pszOutText, outBufSize, __WmLngGetLCodeSizeN(mszInText, charCount)) == false) {
-               MSG_DEBUG("WmConvertPCode2UTF: Out buffer size seems to be small!\n");
-               return false;
-       }
-
-       length = __WmLngUnicode2UTF(pszOutText, mszInText, charCount);
-       if(length == -1) {
-               MSG_DEBUG("WmConvertPCode2UTF: __WmLngUnicode2UTF returns false!\n");
-               return false;
-       } else {
-               return true;
-       }
-}
-
-/*
- * This function convert character ProcessCode(unicode) to UTF8
- *
- * @param      des             :       Output Buffer Pointer to UTF8
- * @param      src             :       Input  Buffer Pointer to ProcessCode(UniCode)
- * @param      nChar   :       number for convert n'th chararcter
- * @return     This function returns number for convert n'th chararcter on success, or -1
- *                     on failure.
- *
- * @see                WmConvertPCode2UTF
- */
-int __WmLngUnicode2UTF (unsigned char *des, unsigned short *src, int nChar)
-{
-       unsigned char *org;
-       unsigned char t1;
-       unsigned char t2;
-       unsigned char t3;
-
-       org = des;
-
-       while (nChar > 0 && *src != '\0') {
-               if (0x0001 <= *src && *src <= 0x007F) {
-                       *des = (unsigned char) (*src & 0x007F);
-
-                       des++;
-                       src++;
-                       nChar--;
-               } else if  ((*src == 0x0000) || (0x0080 <= *src && *src <= 0x07FF)) {
-                       t2 = (unsigned char) (*src & 0x003F);                           //      right most 6 bit
-                       t1 = (unsigned char) ((*src & 0x07C0) >> 6);                    //      right most 5 bit
-
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
-
-                       des += 2;
-                       src += 1;
-                       nChar -= 1;
-               } else {
-                       t3 = (unsigned char) (*src & 0x003F);                                   //      right most 6 bit
-                       t2 = (unsigned char) ((*src & 0x0FC0) >> 6);                    //      right most 6 bit
-                       t1 = (unsigned char) ((*src & 0xF000) >> 12);                   //      right most 4 bit
-
-                       *des = 0xE0 | (t1 & 0x0F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
-                       *(des+2) = 0x80 | (t3 & 0x3F);
-
-                       des += 3;
-                       src += 1;
-                       nChar -= 1;
-               }
-       }
-
-       *des = 0;
-       return (des - org);
-}
-
-
-
diff --git a/plugin/mms_plugin/MmsPluginAppBase.cpp b/plugin/mms_plugin/MmsPluginAppBase.cpp
new file mode 100755 (executable)
index 0000000..c30d61a
--- /dev/null
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include "MsgMmsMessage.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginStorage.h"
+#include "MmsPluginMessage.h"
+#include "MmsPluginMIME.h"
+#include "MmsPluginAppBase.h"
+#include "MmsPluginUtil.h"
+#include "MmsPluginTcs.h"
+#include "MsgUtilFile.h"
+
+msg_error_t MmsMakePreviewInfo(int msgId, MMS_MESSAGE_DATA_S *pMmsMsg, bool allow_malware, const char *raw_filepath);
+
+MmsPluginAppBase::MmsPluginAppBase()
+{
+       memset(&mmsMsgData, 0x00, sizeof(mmsMsgData));
+}
+
+MmsPluginAppBase::MmsPluginAppBase(MMS_DATA_S *pMmsData)
+{
+       setMmsData(pMmsData);
+}
+
+MmsPluginAppBase::MmsPluginAppBase(MmsMsg *pMmsMsg)
+{
+       setMmsData(pMmsMsg);
+}
+
+MmsPluginAppBase::~MmsPluginAppBase()
+{
+       MsgMmsReleaseMmsLists(&mmsMsgData);
+}
+
+void MmsPluginAppBase::setMmsData(MmsMsg *pMmsMsg)
+{
+       MmsConvertMsgData(pMmsMsg, &mmsMsgData);
+}
+
+void MmsPluginAppBase::setMmsData(MMS_DATA_S *pMmsData)
+{
+       MsgMmsConvertMmsDataToMmsMessageData(pMmsData, &mmsMsgData);
+}
+
+void MmsPluginAppBase::makePreviewInfo(msg_message_id_t  msgId, bool allow_malware, const char *raw_filepath)
+{
+       MmsMakePreviewInfo(msgId, &mmsMsgData, allow_malware, raw_filepath);
+}
+
+void MmsPluginAppBase::getFirstPageTextFilePath(char *textBuf, int textBufSize)
+{
+
+       MMS_PAGE_S *pPage = NULL;
+       MMS_MEDIA_S *pMedia = NULL;
+
+       MMS_MESSAGE_DATA_S *pMmsMsgData = &mmsMsgData;
+
+       if (pMmsMsgData == NULL)
+               return;
+
+       // Get the text data from the 1st slide.
+       if (pMmsMsgData->pageCnt > 0) {
+
+               pPage = _MsgMmsGetPage(pMmsMsgData, 0);
+
+               if (pPage) {
+
+                       for (int j = 0; j < pPage->mediaCnt; ++j) {
+
+                               pMedia = _MsgMmsGetMedia(pPage, j);
+
+                               if (pMedia && pMedia->mediatype == MMS_SMIL_MEDIA_TEXT) {
+
+                                       MimeType mimeType = MIME_UNKNOWN;
+
+                                       MmsGetMimeTypeFromFileName(MIME_MAINTYPE_UNKNOWN, pMedia->szFilePath, &mimeType, NULL);
+
+                                       if (mimeType == MIME_TEXT_X_VCALENDAR || mimeType == MIME_TEXT_X_VCARD || mimeType == MIME_TEXT_X_VTODO || mimeType == MIME_TEXT_X_VNOTE) {
+                                               MSG_DEBUG("Media Type is Text, but Vobject file [%s]", pMedia->szFilePath);
+                                       } else {
+                                               MSG_DEBUG("Text path : [%s]", pMedia->szFilePath);
+                                               snprintf(textBuf, textBufSize, "%s", pMedia->szFilePath);//Set Text Filepath of First Pages
+                                       }
+                                       break;
+                               }
+                       }
+               }
+       }
+
+       return;
+}
+
+
+//FIXME::need to move AppBase
+msg_error_t MmsMakePreviewInfo(int msgId, MMS_MESSAGE_DATA_S *pMmsMsg, bool allow_malware, const char *raw_filepath)
+{
+       MMS_PAGE_S *pPage = NULL;
+       MMS_MEDIA_S *pMedia = NULL;
+       int bc_level = -1;
+
+       int ref_attach_count = 0;
+       const char * attachment_name = NULL;
+
+       if (pMmsMsg == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       MmsPluginStorage::instance()->removePreviewInfo(msgId); //remove exist previnfo
+
+       //scan malware in raw file
+       if (raw_filepath && strlen(raw_filepath) > 0 && MsgAccessFile(raw_filepath, F_OK) == true) {
+               int tcs_ret = MmsPluginTcsScanFile(raw_filepath, &bc_level);
+               if (tcs_ret == 0) {
+                       if (bc_level > -1) {
+                               MSG_DEBUG("malware exist, level = %d", bc_level);
+                               MmsPluginStorage::instance()->insertPreviewInfo(msgId, MSG_MMS_ITEM_TYPE_MALWARE, "malware", bc_level);
+                       }
+               }
+       }
+
+       //check ref type and increase attach count
+       if (pMmsMsg->pageCnt > 0) {
+               for (int i = 0; i < pMmsMsg->pageCnt; i++) {
+                       pPage = _MsgMmsGetPage(pMmsMsg, i);
+                       if (pPage) {
+                               for (int j = 0; j < pPage->mediaCnt; j++) {
+                                       pMedia = _MsgMmsGetMedia(pPage, j);
+                                       if (pMedia) { //IF Vobject type add to Attach in Preview data
+
+                                               MimeType mimeType = MIME_UNKNOWN;
+                                               MmsGetMimeTypeFromFileName(MIME_MAINTYPE_UNKNOWN, pMedia->szFilePath, &mimeType, NULL);
+                                               if (mimeType == MIME_TEXT_X_VCALENDAR || mimeType == MIME_TEXT_X_VCARD) {
+
+                                                       MSG_DEBUG("Unsupported File [%s] It will be add to attach list", pMedia->szFilePath);
+
+                                                       ref_attach_count++;
+
+                                                       if (attachment_name == NULL) {
+                                                               attachment_name = pMedia->szFileName;
+                                                       }
+                                               }
+
+                                       }
+                               }
+                       }
+               }
+       }
+
+
+       if (pMmsMsg->pageCnt > 0) {
+
+               MmsPluginStorage::instance()->insertPreviewInfo(msgId, MSG_MMS_ITEM_TYPE_PAGE, (char *)"pagecount", pMmsMsg->pageCnt);
+
+               pPage = _MsgMmsGetPage(pMmsMsg, 0);
+
+               if (pPage) {
+                       for (int j = 0; j < pPage->mediaCnt; j++) {
+
+                               pMedia = _MsgMmsGetMedia(pPage, j);
+
+                               if (pMedia == NULL) {
+                                       MSG_ERR("[%d]th pMedia is NULL", j);
+                                       continue;
+                               }
+
+                               MSG_SEC_DEBUG("pMedia's Name: %s", pMedia->szFilePath);
+
+                               if (allow_malware == false && bc_level > -1) {
+                                       if (pMedia->mediatype == MMS_SMIL_MEDIA_AUDIO) {
+                                               MmsPluginStorage::instance()->insertPreviewInfo(msgId, MSG_MMS_ITEM_TYPE_AUDIO, pMedia->szFileName);
+                                       }
+                               } else {
+
+                                       if (j == 0) { //First Page, First Media
+                                               MmsPluginStorage::instance()->insertPreviewInfo(msgId, MSG_MMS_ITEM_TYPE_1ST_MEDIA, pMedia->szFilePath);
+                                       }
+
+                                       if (pMedia->mediatype == MMS_SMIL_MEDIA_IMG || pMedia->mediatype == MMS_SMIL_MEDIA_VIDEO) {
+                                               char szFileName[MSG_FILENAME_LEN_MAX+1] = {0, };
+                                               char thumbPath[MSG_FILEPATH_LEN_MAX+1] = {0, };
+                                               char *pszExt = NULL;
+
+                                               memset(szFileName, 0x00, MSG_FILENAME_LEN_MAX+1);
+                                               memset(thumbPath, 0x00, MSG_FILEPATH_LEN_MAX);
+
+                                               MSG_DEBUG("drm type = %d, %s", pMedia->drmType, pMedia->szFilePath);
+
+                                               if (pMedia->drmType == MSG_DRM_TYPE_NONE) {
+
+                                                       snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%d.mms",msgId);
+
+                                                       if ((pszExt = strrchr(pMedia->szFilePath, '.')) != NULL && !strcasecmp(pszExt, ".png")) {
+                                                               snprintf(thumbPath, MSG_FILEPATH_LEN_MAX, "%s%s.png", MSG_THUMBNAIL_PATH, szFileName);
+                                                       } else {
+                                                               snprintf(thumbPath, MSG_FILEPATH_LEN_MAX, "%s%s.jpg", MSG_THUMBNAIL_PATH, szFileName);
+                                                       }
+
+                                                       if (MmsMakeImageThumbnail(pMedia->szFilePath, thumbPath) == true) {
+                                                               if (pMedia->mediatype == MMS_SMIL_MEDIA_IMG) {
+                                                                       MmsPluginStorage::instance()->insertPreviewInfo(msgId, MSG_MMS_ITEM_TYPE_IMG, thumbPath);
+                                                               } else {
+                                                                       MmsPluginStorage::instance()->insertPreviewInfo(msgId, MSG_MMS_ITEM_TYPE_VIDEO, thumbPath);
+                                                               }
+                                                       } else {
+                                                               MSG_DEBUG("Fail of generating thumbnail: %s to %s", pMedia->szFilePath, thumbPath);
+                                                       }
+                                               }
+                                       } else if (pMedia->mediatype == MMS_SMIL_MEDIA_AUDIO) {
+                                               MmsPluginStorage::instance()->insertPreviewInfo(msgId, MSG_MMS_ITEM_TYPE_AUDIO, pMedia->szFileName);
+                                       }
+                               }
+                       }
+               } // end for
+       } else {
+               MSG_DEBUG("There is no page");
+       }
+
+       int attachCnt = _MsgMmsGetAttachCount(pMmsMsg);
+       if (attachCnt > 0) {
+
+               MMS_ATTACH_S *pAttach = _MsgMmsGetAttachment(pMmsMsg, 0);
+
+               MmsPluginStorage::instance()->insertPreviewInfo(msgId, MSG_MMS_ITEM_TYPE_ATTACH, pAttach->szFileName, attachCnt);
+               MmsPluginStorage::instance()->updateMmsAttachCount(msgId, attachCnt); // for Get Message
+
+               if (attachment_name == NULL) {
+                       attachment_name = pAttach->szFileName;
+               }
+
+       } else {
+               MSG_DEBUG("There is no attachment");
+       }
+
+       if (attachCnt + ref_attach_count > 0 && attachment_name) {
+
+               MmsPluginStorage::instance()->insertPreviewInfo(msgId, MSG_MMS_ITEM_TYPE_ATTACH, attachment_name, attachCnt + ref_attach_count);
+               MmsPluginStorage::instance()->updateMmsAttachCount(msgId, attachCnt + ref_attach_count);
+       }
+
+       return MSG_SUCCESS;
+}
diff --git a/plugin/mms_plugin/MmsPluginAvCodec.cpp b/plugin/mms_plugin/MmsPluginAvCodec.cpp
deleted file mode 100755 (executable)
index 0631bdd..0000000
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include "MmsPluginAvCodec.h"
-#include <string.h>
-
-AvCodecType    AvGetFileCodecType(const char *szFileName)
-{
-       char szFileExt[FILEEXT_MAX] = {0, };
-       int iPos = 0;
-       int iStrLen = 0;
-       bool bMIME = false;
-
-       iStrLen = strlen(szFileName);
-
-       iPos = iStrLen;
-
-       while (iPos > 0) {
-               iPos--;
-
-               if (szFileName[iPos] == '.')
-                       break;
-               if (szFileName[iPos] == '/') {
-                       bMIME = true;
-                       break;
-               }
-       }
-
-       if (iPos == 0) {
-               return AV_CODEC_NONE;
-       }
-
-       if (FILEEXT_MAX > (iStrLen - iPos - 1)) {
-               strncpy(szFileExt, szFileName + iPos + 1, (iStrLen - iPos - 1));
-               szFileExt[iStrLen - iPos - 1] = '\0';
-       } else
-               return AV_CODEC_NONE;
-
-       if (strcasecmp(szFileExt, "mp3") == 0 || strcasecmp(szFileExt, "MP3") == 0)
-               return AV_DEC_AUDIO_MP3;
-
-       if (strcasecmp(szFileExt, "pvx") == 0 || strcasecmp(szFileExt, "PVX") == 0)
-               return AV_DEC_VIDEO_PVX;
-       else if (strcasecmp(szFileExt, "wav") == 0 || strcasecmp(szFileExt, "WAV") == 0) {
-#ifdef AV_DEBUG_MODE
-               if (!bMIME) {
-                       if (__AvValidWAVE(szFileName) == true)
-                               return AV_DEC_AUDIO_WAVE;
-                       else
-                               return AV_CODEC_NONE;
-               } else
-#endif
-                       return AV_DEC_AUDIO_WAVE;
-       } else if (strcasecmp(szFileExt, "aac") == 0 || strcasecmp(szFileExt, "AAC") == 0)
-               return AV_DEC_AUDIO_AAC;
-#ifdef AV_DEBUG_MODE
-       else if (strcasecmp(szFileExt, "wma") == 0 || strcasecmp(szFileExt, "WMA") == 0)
-               return AvWMFFGetFileType(szFileName);
-       else if (strcasecmp(szFileExt, "wmv") == 0 || strcasecmp(szFileExt, "WMV") == 0)
-               return AvWMFFGetFileType(szFileName);
-       else if (strcasecmp(szFileExt, "asf") == 0 || strcasecmp(szFileExt, "ASF") == 0)
-               return AvWMFFGetFileType(szFileName);
-#endif
-       else if (strcasecmp(szFileExt, "amr") == 0 || strcasecmp(szFileExt, "AMR") == 0 ||
-                       strcasecmp(szFileExt, "x-amr") == 0 || strcasecmp(szFileExt, "X-AMR") == 0) {
-#ifdef AV_DEBUG_MODE
-               if (!bMIME) {
-                       if (__AvValidAMR(szFileName) == true)
-                               return AV_DEC_AUDIO_AMR;
-                       else
-                               return AV_CODEC_NONE;
-               } else
-#endif
-                       return AV_DEC_AUDIO_AMR;
-       } else if (strcasecmp(szFileExt, "g7231") == 0 || strcasecmp(szFileExt, "G7231") == 0)
-               return AV_DEC_AUDIO_G723_1;
-       else if ((strcasecmp(szFileExt, "mid") == 0 || strcasecmp(szFileExt, "MID") == 0) ||
-                       (strcasecmp(szFileExt, "midi") == 0 || strcasecmp(szFileExt, "MIDI") == 0)) {
-#ifdef AV_DEBUG_MODE
-               if (!bMIME) {
-                       if (__AvValidMIDI(szFileName) == true)
-                               return AV_DEC_AUDIO_MIDI;
-                       else
-                               return AV_CODEC_NONE;
-               } else
-#endif
-                       return AV_DEC_AUDIO_MIDI;
-       } else if (strcasecmp(szFileExt, "mmf") == 0 || strcasecmp(szFileExt, "MMF") == 0 || strcasecmp(szFileExt, "x-mmf") == 0) {
-#ifdef AV_DEBUG_MODE
-               if (!bMIME) {
-                       if (__AvValidMMF(szFileName) == true)
-                               return AV_DEC_AUDIO_MMF;
-                       else
-                               return AV_CODEC_NONE;
-               } else
-#endif
-                       return AV_DEC_AUDIO_MMF;
-       } else if (strcasecmp(szFileExt, "pmd") == 0 || strcasecmp(szFileExt, "PMD") == 0) {
-                       return AV_DEC_AUDIO_MIDI;
-       } else if (strcasecmp(szFileExt, "xmf") == 0 || strcasecmp(szFileExt, "XMF") == 0 ||
-                               strcasecmp(szFileExt,  "mxmf") == 0 || strcasecmp(szFileExt,  "MXMF") == 0) {
-               return AV_DEC_AUDIO_XMF;
-       } else if (strcasecmp(szFileExt, "smp") == 0 || strcasecmp(szFileExt, "SMP") == 0) {
-#ifdef AV_DEBUG_MODE
-               if (!bMIME) {
-                       if (__AvValidSMP(szFileName) == true)
-                               return AV_DEC_AUDIO_ADPCM;
-                       else
-                               return AV_CODEC_NONE;
-               } else
-#endif
-                       return AV_DEC_AUDIO_ADPCM;
-       } else if (strcasecmp(szFileExt, "spm") == 0 || strcasecmp(szFileExt, "SPM") == 0) {
-#ifdef AV_DEBUG_MODE
-               if (!bMIME) {
-                       if (__AvValidMIDI(szFileName) == true)
-                               return AV_DEC_AUDIO_SPM;
-                       else
-                               return AV_CODEC_NONE;
-               } else
-#endif
-                       return AV_DEC_AUDIO_SPM;
-       } else if (strcasecmp(szFileExt, "spf") == 0 || strcasecmp(szFileExt, "SPF") == 0) {
-#ifdef AV_DEBUG_MODE
-               if (!bMIME) {
-                       if (__AvValidMMF(szFileName) == true)
-                               return AV_DEC_AUDIO_MMF_PHRASE_L1;
-                       else
-                               return AV_CODEC_NONE;
-               } else
-#endif
-                       return AV_DEC_AUDIO_MMF_PHRASE_L1;
-       } else if (strcasecmp(szFileExt, "imy") == 0 || strcasecmp(szFileExt, "IMY") == 0 ||
-               strcasecmp(szFileExt, "iMelody") == 0 || strcasecmp(szFileExt, "x-iMelody") == 0 ||
-               strcasecmp(szFileExt, "Melody") == 0) {
-#ifdef AV_DEBUG_MODE
-               if (!bMIME) {
-                       if (__AvValidIMELODY(szFileName) == true)
-                               return AV_DEC_AUDIO_IMELODY;
-                       else
-                               return AV_CODEC_NONE;
-               } else
-#endif
-                       return AV_DEC_AUDIO_IMELODY;
-       } else if (strcasecmp(szFileExt, "dtmf") == 0)
-               return AV_DEC_AUDIO_DTMF_TONE;
-       else if (strcasecmp(szFileExt, "h263") == 0 || strcasecmp(szFileExt, "H263") == 0)
-               return AV_DEC_VIDEO_H263;
-       else if (strcasecmp(szFileExt, "mp4") == 0 || strcasecmp(szFileExt, "MP4") == 0 ||
-                       strcasecmp(szFileExt, "mpeg4") == 0 || strcasecmp(szFileExt, "MPEG4") == 0 ||
-                       strcasecmp(szFileExt, "m4a") == 0 || strcasecmp(szFileExt, "M4A") == 0) {
-#ifdef AV_DEBUG_MODE
-               if (!bMIME) {
-                       AvCodecType avCodecType = AV_CODEC_NONE;
-                       FmFileAttribute fileAttrib;
-                       size_t strLen;
-                       UINT32  dateTime = 0;
-
-                       if (!DrmGetFileAttributes(szFileName, &fileAttrib)) {
-                               return AV_CODEC_NONE;
-                       } else {
-                               dateTime =  TmDateTimeToSeconds(&fileAttrib.dt);
-                               strLen = strlen(szFileName);
-                               if ((strnicmp(lastAccessFileInfo.szFileName, szFileName, strLen) == 0) &&
-                                       (lastAccessFileInfo.fileSize == fileAttrib.fileSize) &&
-                                       (lastAccessFileInfo.dateTime == dateTime)) {
-                                       return lastAccessFileInfo.codecType;
-                               } else {
-                                       avCodecType = AvMP4FFGetFileType(szFileName);
-
-                                       if (strcasecmp(szFileExt, "3ga") == 0 || strcasecmp(szFileExt, "3GA") == 0 ||
-                                               strcasecmp(szFileExt, "m4a") == 0 || strcasecmp(szFileExt, "M4A") == 0) {
-                                               if (avCodecType | AV_DEC_AUDIO_MPEG4)
-                                                       avCodecType = AV_DEC_AUDIO_MPEG4;
-                                       }
-
-                                       if (avCodecType != AV_CODEC_NONE) {
-                                               strncpy(lastAccessFileInfo.szFileName, szFileName, strLen);
-                                               lastAccessFileInfo.szFileName[strLen] = '\0';
-                                               lastAccessFileInfo.fileSize = fileAttrib.fileSize;
-                                               lastAccessFileInfo.dateTime = dateTime;
-                                               lastAccessFileInfo.codecType = avCodecType;
-                                       }
-                                       return avCodecType;
-                               }
-                       }
-               }
-#endif
-               return AV_DEC_VIDEO_MPEG4;
-       } else if (strcasecmp(szFileExt, "3gp") == 0 || strcasecmp(szFileExt, "3GP") == 0 ||
-               strcasecmp(szFileExt, "3ga") == 0 || strcasecmp(szFileExt, "3GA") == 0 ||
-               strcasecmp(szFileExt, "3gpp") == 0 || strcasecmp(szFileExt, "3GPP") == 0) {
-               return AV_CODEC_NONE;
-       } else if (strcasecmp(szFileExt, "sdp") == 0 || strcasecmp(szFileExt, "SDP") == 0)
-               return AV_DEC_VIDEO_MPEG4;
-       else
-               return AV_CODEC_NONE;
-}
diff --git a/plugin/mms_plugin/MmsPluginCodec.cpp b/plugin/mms_plugin/MmsPluginCodec.cpp
deleted file mode 100755 (executable)
index c55a5c1..0000000
+++ /dev/null
@@ -1,625 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include "MmsPluginCodec.h"
-#include "MsgMmsTypes.h"
-#include "MmsPluginMessage.h"
-#include "MmsPluginMIME.h"
-#include "MsgDebug.h"
-
-/* Reference : MMS-209-Encapsulation & WAP-203-WSP-20000504.pdf Table 39 */
-const MmsField gMmsField[MMS_MAX_FIELD_TYPE_COUNT][MMS_MAX_FIELD_VALUE_COUNT] =
-{
-       /* MMS Specific (MsgMmsMsg.h / MsgMmsUA.h) -----------------------*/
-
-       /* MmsCodeFieldCode */
-       {
-               {"Bcc", 0x01},                                                          //0
-               {"Cc", 0x02},
-               {"X-Mms-Content-Location", 0x03},
-               {"Content-Type", 0x04},
-               {"Date", 0x05},
-               {"X-Mms-Delivery-Report", 0x06},
-               {"X-Mms-Delivery-Time", 0x07},
-               {"X-Mms-Expiry", 0x08},
-               {"From", 0x09},
-               {"X-Mms-Message-Class", 0x0A},
-               {"Message-ID", 0x0B},                                           // 10
-               {"X-Mms-Message-Type", 0x0C},
-               {"X-Mms-MMS-Version", 0x0D},
-               {"X-Mms-Message-Size", 0x0E},
-               {"X-Mms-Priority", 0x0F},
-               {"X-Mms-Read-Reply", 0x10},
-               {"X-Mms-Report-Allowed", 0x11},
-               {"X-Mms-Response-Status", 0x12},
-               {"X-Mms-Retrieve-Status", 0x19},                        /* Add by MMSENC v1.1 */
-               {"X-Mms-Response-Text", 0x13},
-               {"X-Mms-Retrieve-Text", 0x1A},                          // 20   /* Add by MMSENC v1.1 */
-               {"X-Mms-Sender-Visibility", 0x14},
-               {"X-Mms-Status", 0x15},
-               {"Subject", 0x16},
-               {"To", 0x17},
-               {"X-Mms-Transaction-ID", 0x18},
-
-               /* Add by MMSENC v1.1 */
-               {"X-Mms-Read-Status", 0x1B},
-               {"X-Mms-Reply-Charging", 0x1C},
-               {"X-Mms-Reply-Charging-Deadline", 0x1D},        // 30
-               {"X-Mms-Reply-Charging-ID", 0x1E},
-               {"X-Mms-Reply-Charging-Size", 0x1F},
-               {"X-Mms-Previously-Sent-By", 0x20},
-               {"X-Mms-Previously-Sent-Date", 0x21},
-       },
-
-       /* MmsCodeParameterCode ( By WSP Table 38. Wellknown parameter Assignments ) */
-       {
-               {"Charset", 0x01},              // v1.1 base
-               {"Name", 0x05},                 // v1.1 base. 0x17 at v1.4
-               {"FileName", 0x06},             // v1.1 base. ox18 at v1.4
-               {"Type", 0x09},                 // v1.2 base
-               {"Start", 0x0A},                // v1.2 base. 0x19 at v1.4
-               {"Start-Info", 0x0B},   // v1.2 base. 0x1A at v1.4
-               {"boundary", 0xFF},             //laconic_javaParamFix
-               {"report-type", 0xFF},        // only used as parameter of Content-Type: multipart/report; report-type=delivery-status;
-#ifdef FEATURE_JAVA_MMS
-               {"Application-ID", 0xFF},
-               {"Reply-To-Application-ID", 0xFF},
-#endif
-       },
-
-       /* MmsCodeMsgBodyHeaderCode ( By WSP Table 39. Header Field Name Assignments ) */
-       {
-               {"Content-Transfer-Encoding", 0xFFFF},  // only text encoding, no binary number
-               {"Content-Disposition", 0x2E},                  // v1.1 base. 0x45 at v1.4
-               {"Content-ID", 0x40},                                   // v1.3 base
-               {"Content-Location", 0x0E},                             // v1.3 base
-               {"X-Oma-Drm-Separate-Delivery", 0xFF }, // DRM RO WAITING
-       },
-
-       /* MmsCodeMsgType */
-       {
-               {"m-send-req", 0x00},
-               {"m-send-conf", 0x01},
-               {"m-notification-ind", 0x02},
-               {"m-notifyresp-ind", 0x03},
-               {"m-retrieve-conf", 0x04},
-               {"m-acknowledge-ind", 0x05},
-               {"m-delivery-ind", 0x06},
-
-               /* Add by MMSENC v1.1 */
-               {"m-read-rec-ind", 0x07},
-               {"m-read-orig-ind", 0x08},
-               {"m-forward-req", 0x09},
-               {"m-forward-conf", 0x0A}
-       },
-
-       /* MmsCodeDeliveryReport */
-       {
-               { "Yes", 0x00 }, { "No", 0x01 }
-       },
-
-       /* MmsCodeTimeType */
-       {
-               { "relative", 0x01 }, { "absolute", 0x00 }
-       },
-
-       /* MmsCodeMsgClass */
-       {
-               {"Personal", 0x00},
-               {"Advertisement", 0x01},
-               {"Informational", 0x02},
-               {"Auto", 0x03}
-       },
-
-       /* MmsCodePriority */
-       {
-               { "Low", 0x00 }, { "Normal", 0x01 }, { "High", 0x02 }
-       },
-
-       /* MmsCodeResponseStatus */
-       {
-               {"Ok", 0x00},
-               {"Error-unspecified", 0x01},
-               {"Error-service-denied", 0x02},
-               {"Error-message-format-corrupt", 0x03},
-               {"Error-sending-address-unresolved", 0x04},
-               {"Error-message-not-found", 0x05},
-               {"Error-network-problem", 0x06},
-               {"Error-content-not-accepted", 0x07},
-               {"Error-unsupported-message", 0x08},
-
-               {"Error-transient-failure", 0x40},
-               {"Error-transient-sending-address-unresolved", 0x41},
-               {"Error-transient-message-not-found", 0x42},
-               {"Error-transient-network-problem", 0x43},
-
-               {"Error-transient-failure", 0x44}, //reserved for future
-               {"Error-transient-failure", 0x45},
-               {"Error-transient-failure", 0x46},
-               {"Error-transient-failure", 0x47},
-               {"Error-transient-failure", 0x48},
-               {"Error-transient-failure", 0x49},
-               {"Error-transient-failure", 0x4A},
-               {"Error-transient-failure", 0x4B},
-               {"Error-transient-failure", 0x4C},
-               {"Error-transient-failure", 0x4D},
-               {"Error-transient-failure", 0x4E},
-               {"Error-transient-failure", 0x4F},
-               {"Error-transient-failure", 0x50},
-               {"Error-transient-failure", 0x51},
-               {"Error-transient-failure", 0x52},
-               {"Error-transient-failure", 0x53},
-               {"Error-transient-failure", 0x54},
-               {"Error-transient-failure", 0x55},
-               {"Error-transient-failure", 0x56},
-               {"Error-transient-failure", 0x57},
-               {"Error-transient-failure", 0x58},
-               {"Error-transient-failure", 0x59},
-               {"Error-transient-failure", 0x5A},
-               {"Error-transient-failure", 0x5B},
-               {"Error-transient-failure", 0x5C},
-               {"Error-transient-failure", 0x5D},
-               {"Error-transient-failure", 0x5E},
-               {"Error-transient-failure", 0x5F},
-
-               {"Error-permanent-failure", 0x60},
-               {"Error-permanent-service-denied", 0x61},
-               {"Error-permanent-message-format-corrupt", 0x62},
-               {"Error-permanent-sending-address-unresolved", 0x63},
-               {"Error-permanent-message-not-found", 0x64},
-               {"Error-permanent-content-not-accepted", 0x65},
-               {"Error-permanent-reply-charging-limitations-not-met", 0x66},
-               {"Error-permanent-reply-charging-request-not-accepted", 0x67},
-               {"Error-permanent-reply-charging-forwarding-denied", 0x68},
-               {"Error-permanent-reply-charging-not-supported", 0x69},
-
-               {"Error-permanent-failure", 0x6A}, //reserved for future
-               {"Error-permanent-failure", 0x6B},
-               {"Error-permanent-failure", 0x6C},
-               {"Error-permanent-failure", 0x6D},
-               {"Error-permanent-failure", 0x6E},
-               {"Error-permanent-failure", 0x6F},
-               {"Error-permanent-failure", 0x70},
-               {"Error-permanent-failure", 0x71},
-               {"Error-permanent-failure", 0x72},
-               {"Error-permanent-failure", 0x73},
-               {"Error-permanent-failure", 0x74},
-               {"Error-permanent-failure", 0x75},
-               {"Error-permanent-failure", 0x76},
-               {"Error-permanent-failure", 0x77},
-               {"Error-permanent-failure", 0x78},
-               {"Error-permanent-failure", 0x79},
-               {"Error-permanent-failure", 0x7A},
-               {"Error-permanent-failure", 0x7B},
-               {"Error-permanent-failure", 0x7C},
-               {"Error-permanent-failure", 0x7D},
-               {"Error-permanent-failure", 0x7E},
-               {"Error-permanent-failure", 0x7F}
-
-
-       },
-
-       /* MmsCodeRetrieveStatus */
-       {
-               {"Ok", 0x00},
-               {"Error-transient-failure", 0x40},
-               {"Error-transient-message-not-found", 0x41},
-               {"Error-transient-network-problem", 0x42},
-
-               {"Error-transient-failure", 0x43}, //reserved for future
-               {"Error-transient-failure", 0x44},
-               {"Error-transient-failure", 0x45},
-               {"Error-transient-failure", 0x46},
-               {"Error-transient-failure", 0x47},
-               {"Error-transient-failure", 0x48},
-               {"Error-transient-failure", 0x49},
-               {"Error-transient-failure", 0x4A},
-               {"Error-transient-failure", 0x4B},
-               {"Error-transient-failure", 0x4C},
-               {"Error-transient-failure", 0x4D},
-               {"Error-transient-failure", 0x4E},
-               {"Error-transient-failure", 0x4F},
-               {"Error-transient-failure", 0x50},
-               {"Error-transient-failure", 0x51},
-               {"Error-transient-failure", 0x52},
-               {"Error-transient-failure", 0x53},
-               {"Error-transient-failure", 0x54},
-               {"Error-transient-failure", 0x55},
-               {"Error-transient-failure", 0x56},
-               {"Error-transient-failure", 0x57},
-               {"Error-transient-failure", 0x58},
-               {"Error-transient-failure", 0x59},
-               {"Error-transient-failure", 0x5A},
-               {"Error-transient-failure", 0x5B},
-               {"Error-transient-failure", 0x5C},
-               {"Error-transient-failure", 0x5D},
-               {"Error-transient-failure", 0x5E},
-               {"Error-transient-failure", 0x5F},
-
-               {"Error-permanent-failure", 0x60},
-               {"Error-permanent-service-denied", 0x61},
-               {"Error-permanent-message-not-found", 0x62},
-               {"Error-permanent-content-unsupported", 0x63},
-
-               {"Error-permanent-failure", 0x64}, //reserved for future
-               {"Error-permanent-failure", 0x65},
-               {"Error-permanent-failure", 0x66},
-               {"Error-permanent-failure", 0x67},
-               {"Error-permanent-failure", 0x68},
-               {"Error-permanent-failure", 0x69},
-               {"Error-permanent-failure", 0x6A},
-               {"Error-permanent-failure", 0x6B},
-               {"Error-permanent-failure", 0x6C},
-               {"Error-permanent-failure", 0x6D},
-               {"Error-permanent-failure", 0x6E},
-               {"Error-permanent-failure", 0x6F},
-               {"Error-permanent-failure", 0x70},
-               {"Error-permanent-failure", 0x71},
-               {"Error-permanent-failure", 0x72},
-               {"Error-permanent-failure", 0x73},
-               {"Error-permanent-failure", 0x74},
-               {"Error-permanent-failure", 0x75},
-               {"Error-permanent-failure", 0x76},
-               {"Error-permanent-failure", 0x77},
-               {"Error-permanent-failure", 0x78},
-               {"Error-permanent-failure", 0x79},
-               {"Error-permanent-failure", 0x7A},
-               {"Error-permanent-failure", 0x7B},
-               {"Error-permanent-failure", 0x7C},
-               {"Error-permanent-failure", 0x7D},
-               {"Error-permanent-failure", 0x7E},
-               {"Error-permanent-failure", 0x7F}
-
-       },
-
-       /* MmsCodeReadReply */
-       {
-               { "Yes", 0x00 }, { "No", 0x01 }
-       },
-
-       /* MmsCodeReportAllowed */
-       {
-               { "Yes", 0x00 }, { "No", 0x01 }
-       },
-
-       /* MmsCodeSenderVisibility */
-       {
-               { "Show", 0x01 }, { "Hide", 0x00 }
-       },
-
-       /* MmsCodeMsgStatus */
-       {
-               {"Expired", 0x00},
-               {"Retrieved", 0x01},
-               {"Rejected", 0x02},
-               {"Deferred", 0x03},
-               {"Unrecognised", 0x04},
-
-               /* Add by MMSENC v1.1 */
-               {"Indeterminate ", 0x05},
-               {"Forwarded", 0x06},
-
-               /* Add by MMSENC v1.2 */
-               {"Unreachable", 0x07 }
-
-       },
-
-       /* MmsCodeReadStatus */
-       {
-               {"Read", 0x00}, {"Deleted", 0x01}
-       },
-
-       /* MmsCodeAddressType */
-       {
-               {"present", 0x00}, {"insert", 0x01}
-       },
-
-
-       /* MSG Specific (MsgMIMEExtern.h) -----------------------*/
-
-       /* MmsCodeCharSet */
-       {
-               {"us-ascii", 0x03},
-               {"UTF-16", 0x03F7},
-               {"ISO-10646-UCS-2", 0x03E8},
-               {"UTF-8", 0x6A},
-
-               {"ISO-2022-KR", 0x25},
-               {"KS_C_5601-1987", 0x24},
-               {"EUC-KR", 0x26},
-               {"ISO-2022-JP", 0x27},
-               {"ISO-2022-JP-2", 0x28},
-
-               {"ISO_8859-1", 0x04},
-               {"ISO_8859-2", 0x05},
-               {"ISO-8859-3", 0x06},
-               {"ISO-8859-4", 0x07},
-               {"ISO-8859-5", 0x08},
-               {"ISO-8859-6", 0x09},
-               {"ISO-8859-6-E", 0x51},
-               {"ISO-8859-6-I", 0x52},
-               {"ISO-8859-7", 0x0a},
-               {"ISO-8859-8", 0x0b},
-               {"ISO-8859-8-I", 0x85},
-               {"ISO-8859-9", 0x0c},
-               {"ISO-8859-10", 0x0d},
-               {"ISO-8859-15", 0x6F},
-
-               {"Shift_JIS", 0x11},
-               {"EUC-JP", 0x13},
-               {"GB2312", 0x07E9},
-               {"BIG5", 0x0d},
-               {"WIN1251", 0xFF},
-               {"WINDOW-1251", 0xFF},
-               {"WINDOWS-1251", 0xFF},
-               {"KOI8-R", 0x0824},
-               {"KOI8-U", 0x0828},
-       },
-
-       /* MmsCodeReplyCharging, */
-       {
-               { "Requested", 0x00 },
-               { "Requested text only", 0x01 },
-               { "Accepted", 0x02 },
-               { "Accepted text only", 0x03 }
-       },
-
-
-       /* MSG Specific (MsgMIMEExtern.h) -----------------------*/
-
-       /* Content-Type (http://www.wapforum.org/wina/wsp-content-type.htm) */
-       /* this group(Content-Type) will be replaced by utyMime */
-       {
-               // {"Text/txt", 0x01},
-               {"Text/html", 0x02},
-               {"Text/plain", 0x03},
-               {"Text/vnd.wap.wml", 0x08},
-               {"Text/x-vCalendar", 0x06},
-               {"Text/x-vCard", 0x07},
-
-               {"Application/vnd.wap.multipart.*", 0x22},
-               {"Application/vnd.wap.multipart.mixed", 0x23},
-               {"Application/vnd.wap.multipart.related", 0x33},
-               {"Application/vnd.wap.multipart.alternative", 0x26},
-
-               {"application/vnd.oma.drm.message", 0x48},                      // 10
-               {"application/vnd.oma.drm.content", 0x49},
-               {"application/vnd.oma.drm.rights+xml", 0x4A},
-               {"application/vnd.oma.drm.rights+wbxml", 0x4B},
-
-               {"application/smil", 0xFFFF},
-               {"Multipart/mixed", 0x0c},
-               {"Multipart/related", 0x0B},
-               {"Multipart/alternative", 0x0F},
-
-               {"multipart/report", 0xffff},
-               {"Message/rfc822", 0xffff},
-
-       //   T E X T
-               {"Image/gif", 0x1D},                    // 20
-               {"Image/jpeg", 0x1E},
-               {"Image/jpg", 0xFFFF},
-               {"image/tiff", 0x1f},
-               {"Image/png", 0x20},
-
-
-               {"Image/vnd.wap.wbmp", 0x21},
-
-               {"Image/wbmp", 0xFFFF},
-               {"Image/pjpeg", 0xFFFF},
-
-               {"Image/bmp", 0xFFFF},
-
-       // A U D I O
-               {"Audio/basic", 0xFFFF},
-               {"Audio/mpeg", 0xFFFF},                 // 30
-               {"Audio/x-mpeg", 0xFFFF},
-               {"Audio/mp3", 0xFFFF},
-               {"audio/x-mp3", 0xFFFF},
-               {"audio/mpeg3", 0xFFFF},
-               {"audio/x-mpeg3", 0xFFFF},
-               {"audio/mpg", 0xFFFF},
-               {"audio/x-mpg", 0xFFFF},
-               {"audio/x-mpegaudio", 0xFFFF},
-               {"Audio/aac", 0xFFFF},                  // 39
-               {"Audio/g72", 0xFFFF},
-               {"Audio/amr", 0xFFFF},
-               {"audio/x-amr", 0xFFFF},
-               {"audio/x-mmf", 0xFFFF},
-               {"application/vnd.smaf",  0xffff},
-               {"application/x-smaf", 0xFFFF},
-               {"audio/mmf", 0xFFFF},
-
-               {"text/x-iMelody", 0xffff},
-               {"audio/x-iMelody", 0xffff},
-               {"audio/iMelody", 0xffff},              // 49
-               {"audio/mid",0xffff},
-               {"audio/midi", 0xffff},
-               {"audio/x-midi", 0xffff},
-               {"audio/sp-midi", 0xffff},
-               {"audio/wave", 0xffff},
-               {"audio/3gpp", 0xffff},
-               {"audio/vnd.rn-realaudio", 0xffff},
-               {"audio/x-pn-realaudio", 0xffff},
-               {"audio/mp4",  0xffff},
-
-       // V I D E O
-               {"video/mpeg4", 0xFFFF},
-               {"video/mp4", 0xffff},
-               {"video/x-mp4", 0xFFFF},
-               {"video/x-vp-mp4", 0xffff},
-               {"Video/h263", 0xFFFF},
-
-               {"video/3gpp", 0xffff},
-               {"video/3gp", 0xffff},
-               {"Video/avi", 0xFFFF},
-
-               {"video/sdp", 0xffff},                  // 70
-               {"application/vnd.rn-realmedia", 0xffff},
-               {"video/vnd.rn-realvideo", 0xffff},
-
-               {"application/octet-stream", 0xFFFF }
-       },
-
-       /* MmsCodeMsgDisposition : Wsp Header (By Wsp 8.4.2.53) */
-       {
-               {"form-data", 0x00},
-               {"attachment", 0x01},
-               {"inline", 0x02}
-       },
-
-       /* Content-transfer-encoding : HTTP Header(Binary Value is not assigned) */
-       {
-               {"7bit", 0x00},
-               {"8bit", 0x00},
-               {"binary", 0x00},
-               {"base64", 0x00},
-               {"quoted-printable", 0x00}
-       }
-};
-
-/* global variables */
-static char    gszMmsVersion[5] = {0, };
-
-char *_MmsGetTextValue(MmsCode i, int j)
-{
-       if (i == MmsCodeContentType) {
-               //apply UtyMime
-               return MimeGetMimeStringFromMimeInt(j);
-       }
-
-       return (char *)gMmsField[i][j].szText;
-}
-
-char *_MmsGetTextValuebyField(int field, int value)
-{
-       char *szValue = NULL;
-
-       switch (field) {
-       case MMS_CODE_MSGTYPE:
-               szValue = _MmsGetTextValue(MmsCodeMsgType, value);
-               break;
-
-       case MMS_CODE_MSGCLASS:
-               szValue = _MmsGetTextValue(MmsCodeMsgClass, value);
-               break;
-
-       case MMS_CODE_PRIORITY:
-               szValue = _MmsGetTextValue(MmsCodePriority, value);
-               break;
-
-       case MMS_CODE_SENDERVISIBILLITY:
-               szValue = _MmsGetTextValue(MmsCodeSenderVisibility, value);
-               break;
-
-       case MMS_CODE_DELIVERYREPORT:
-               szValue = _MmsGetTextValue(MmsCodeDeliveryReport, value);
-               break;
-
-       case MMS_CODE_READREPLY:
-               szValue = _MmsGetTextValue(MmsCodeReadReply, value);
-               break;
-
-       case MMS_CODE_MSGSTATUS:
-               szValue = _MmsGetTextValue(MmsCodeMsgStatus, value);
-               break;
-
-       case MMS_CODE_REPORTALLOWED:
-               szValue = _MmsGetTextValue(MmsCodeReportAllowed, value);
-               break;
-
-       case MMS_CODE_RESPONSESTATUS:
-               szValue = _MmsGetTextValue(MmsCodeResponseStatus, value);
-               break;
-
-       /* Add by MMSENC v1.1 */
-       case MMS_CODE_READSTATUS:
-               szValue = _MmsGetTextValue(MmsCodeReadStatus, value);
-               break;
-
-       default:
-               szValue = NULL;
-               break;
-       }
-
-       return szValue;
-}
-
-UINT16 _MmsGetBinaryValue(MmsCode i, int j)
-{
-       if (i == MmsCodeContentType) {
-               return MimeGetBinaryValueFromMimeInt((MimeType)j);
-       }
-
-       return gMmsField[i][j].binary;
-}
-
-// getting mime type (int) by binary type
-int _MmsGetBinaryType(MmsCode i, UINT16 value)
-{
-       MSG_BEGIN();
-
-       if (i == MmsCodeContentType) {
-               //apply UtyMime
-               return MimeGetMimeIntFromBi(value);
-       }
-
-       for (int j = 0; j < MMS_MAX_FIELD_VALUE_COUNT; j++) {
-               if (gMmsField[i][j].binary == value) {
-                       return j;
-               }
-       }
-
-       MSG_END();
-
-       return MIME_UNKNOWN;
-}
-
-int _MmsGetTextType(MmsCode i, char *pValue)
-{
-       int j = 0;
-
-       if (i == MmsCodeContentType) {
-               /*apply UtyMime */
-               return MimeGetMimeIntFromMimeString( pValue );
-       }
-
-       for (j = 0; j < MMS_MAX_FIELD_VALUE_COUNT; j++) {
-               if (gMmsField[i][j].szText != NULL) {
-                       if (strcasecmp( gMmsField[i][j].szText, pValue ) == 0) {
-                               return j;
-                       }
-               }
-       }
-
-       return -1;
-}
-
-UINT8 _MmsGetVersion(MmsMsg *pMsg)
-{
-       if (pMsg == NULL) {
-               return MMS_VERSION;
-       }
-
-       return pMsg->mmsAttrib.version;
-}
-
-bool _MmsSetVersion(int majorVer, int minorVer)
-{
-       snprintf(gszMmsVersion, sizeof(gszMmsVersion), "%d.%d", majorVer, minorVer);
-       return true;
-}
-
diff --git a/plugin/mms_plugin/MmsPluginCodecCommon.cpp b/plugin/mms_plugin/MmsPluginCodecCommon.cpp
new file mode 100755 (executable)
index 0000000..c8078d2
--- /dev/null
@@ -0,0 +1,1911 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include <ctype.h>
+#include "MmsPluginDebug.h"
+#include "MmsPluginCodecCommon.h"
+#include "MmsPluginMIME.h"
+#include "MmsPluginUtil.h"
+#include "MmsPluginTextConvert.h"
+
+#include <string>
+using namespace std;
+
+#define        MMS_MAX_FIELD_VALUE_COUNT       74
+#define        MMS_MAX_FIELD_TYPE_COUNT        21
+
+typedef struct {
+       const char *szText;
+       UINT16 binary;
+} MmsField;
+
+/* Reference : MMS-209-Encapsulation & WAP-203-WSP-20000504.pdf Table 39 */
+const MmsField gMmsField[MMS_MAX_FIELD_TYPE_COUNT][MMS_MAX_FIELD_VALUE_COUNT] =
+{
+       /* MMS Specific (MsgMmsMsg.h / MsgMmsUA.h) -----------------------*/
+
+       /* MmsCodeFieldCode */
+       {
+               {"Bcc", 0x01},                                                          //0
+               {"Cc", 0x02},
+               {"X-Mms-Content-Location", 0x03},
+               {"Content-Type", 0x04},
+               {"Date", 0x05},
+               {"X-Mms-Delivery-Report", 0x06},
+               {"X-Mms-Delivery-Time", 0x07},
+               {"X-Mms-Expiry", 0x08},
+               {"From", 0x09},
+               {"X-Mms-Message-Class", 0x0A},
+               {"Message-ID", 0x0B},                                           // 10
+               {"X-Mms-Message-Type", 0x0C},
+               {"X-Mms-MMS-Version", 0x0D},
+               {"X-Mms-Message-Size", 0x0E},
+               {"X-Mms-Priority", 0x0F},
+               {"X-Mms-Read-Reply", 0x10},
+               {"X-Mms-Report-Allowed", 0x11},
+               {"X-Mms-Response-Status", 0x12},
+               {"X-Mms-Retrieve-Status", 0x19},                        /* Add by MMSENC v1.1 */
+               {"X-Mms-Response-Text", 0x13},
+               {"X-Mms-Retrieve-Text", 0x1A},                          // 20   /* Add by MMSENC v1.1 */
+               {"X-Mms-Sender-Visibility", 0x14},
+               {"X-Mms-Status", 0x15},
+               {"Subject", 0x16},
+               {"To", 0x17},
+               {"X-Mms-Transaction-ID", 0x18},
+
+               /* Add by MMSENC v1.1 */
+               {"X-Mms-Read-Status", 0x1B},
+               {"X-Mms-Reply-Charging", 0x1C},
+               {"X-Mms-Reply-Charging-Deadline", 0x1D},        // 30
+               {"X-Mms-Reply-Charging-ID", 0x1E},
+               {"X-Mms-Reply-Charging-Size", 0x1F},
+               {"X-Mms-Previously-Sent-By", 0x20},
+               {"X-Mms-Previously-Sent-Date", 0x21},
+       },
+
+       /* MmsCodeParameterCode ( By WSP Table 38. Wellknown parameter Assignments ) */
+       {
+               {"Charset", 0x01},              // v1.1 base
+               {"Name", 0x05},                 // v1.1 base. 0x17 at v1.4
+               {"FileName", 0x06},             // v1.1 base. ox18 at v1.4
+               {"Type", 0x09},                 // v1.2 base
+               {"Start", 0x0A},                // v1.2 base. 0x19 at v1.4
+               {"Start-Info", 0x0B},   // v1.2 base. 0x1A at v1.4
+               {"boundary", 0xFF},             //laconic_javaParamFix
+               {"report-type", 0xFF},        // only used as parameter of Content-Type: multipart/report; report-type=delivery-status;
+#ifdef FEATURE_JAVA_MMS
+               {"Application-ID", 0xFF},
+               {"Reply-To-Application-ID", 0xFF},
+#endif
+       },
+
+       /* MmsCodeMsgBodyHeaderCode ( By WSP Table 39. Header Field Name Assignments ) */
+       {
+               {"Content-Transfer-Encoding", 0xFFFF},  // only text encoding, no binary number
+               {"Content-Disposition", 0x2E},                  // v1.1 base. 0x45 at v1.4
+               {"Content-ID", 0x40},                                   // v1.3 base
+               {"Content-Location", 0x0E},                             // v1.3 base
+               {"X-Oma-Drm-Separate-Delivery", 0xFF }, // DRM RO WAITING
+       },
+
+       /* MmsCodeMsgType */
+       {
+               {"m-send-req", 0x00},
+               {"m-send-conf", 0x01},
+               {"m-notification-ind", 0x02},
+               {"m-notifyresp-ind", 0x03},
+               {"m-retrieve-conf", 0x04},
+               {"m-acknowledge-ind", 0x05},
+               {"m-delivery-ind", 0x06},
+
+               /* Add by MMSENC v1.1 */
+               {"m-read-rec-ind", 0x07},
+               {"m-read-orig-ind", 0x08},
+               {"m-forward-req", 0x09},
+               {"m-forward-conf", 0x0A}
+       },
+
+       /* MmsCodeDeliveryReport */
+       {
+               { "Yes", 0x00 }, { "No", 0x01 }
+       },
+
+       /* MmsCodeTimeType */
+       {
+               { "relative", 0x01 }, { "absolute", 0x00 }
+       },
+
+       /* MmsCodeMsgClass */
+       {
+               {"Personal", 0x00},
+               {"Advertisement", 0x01},
+               {"Informational", 0x02},
+               {"Auto", 0x03}
+       },
+
+       /* MmsCodePriority */
+       {
+               { "Low", 0x00 }, { "Normal", 0x01 }, { "High", 0x02 }
+       },
+
+       /* MmsCodeResponseStatus */
+       {
+               {"Ok", 0x00},
+               {"Error-unspecified", 0x01},
+               {"Error-service-denied", 0x02},
+               {"Error-message-format-corrupt", 0x03},
+               {"Error-sending-address-unresolved", 0x04},
+               {"Error-message-not-found", 0x05},
+               {"Error-network-problem", 0x06},
+               {"Error-content-not-accepted", 0x07},
+               {"Error-unsupported-message", 0x08},
+
+               {"Error-transient-failure", 0x40},
+               {"Error-transient-sending-address-unresolved", 0x41},
+               {"Error-transient-message-not-found", 0x42},
+               {"Error-transient-network-problem", 0x43},
+
+               {"Error-permanent-failure", 0x60},
+               {"Error-permanent-service-denied", 0x61},
+               {"Error-permanent-message-format-corrupt", 0x62},
+               {"Error-permanent-sending-address-unresolved", 0x63},
+               {"Error-permanent-message-not-found", 0x64},
+               {"Error-permanent-content-not-accepted", 0x65},
+               {"Error-permanent-reply-charging-limitations-not-met", 0x66},
+               {"Error-permanent-reply-charging-request-not-accepted", 0x67},
+               {"Error-permanent-reply-charging-forwarding-denied", 0x68},
+               {"Error-permanent-reply-charging-not-supported", 0x69},
+       },
+
+       /* MmsCodeRetrieveStatus */
+       {
+               {"Ok", 0x00},
+               {"Error-transient-failure", 0x40},
+               {"Error-transient-message-not-found", 0x41},
+               {"Error-transient-network-problem", 0x42},
+
+               {"Error-permanent-failure", 0x60},
+               {"Error-permanent-service-denied", 0x61},
+               {"Error-permanent-message-not-found", 0x62},
+               {"Error-permanent-content-unsupported", 0x63},
+       },
+
+       /* MmsCodeReadReply */
+       {
+               { "Yes", 0x00 }, { "No", 0x01 }
+       },
+
+       /* MmsCodeReportAllowed */
+       {
+               { "Yes", 0x00 }, { "No", 0x01 }
+       },
+
+       /* MmsCodeSenderVisibility */
+       {
+               { "Show", 0x01 }, { "Hide", 0x00 }
+       },
+
+       /* MmsCodeMsgStatus */
+       {
+               {"Expired", 0x00},
+               {"Retrieved", 0x01},
+               {"Rejected", 0x02},
+               {"Deferred", 0x03},
+               {"Unrecognised", 0x04},
+
+               /* Add by MMSENC v1.1 */
+               {"Indeterminate ", 0x05},
+               {"Forwarded", 0x06},
+
+               /* Add by MMSENC v1.2 */
+               {"Unreachable", 0x07 }
+
+       },
+
+       /* MmsCodeReadStatus */
+       {
+               {"Read", 0x00}, {"Deleted", 0x01}
+       },
+
+       /* MmsCodeAddressType */
+       {
+               {"present", 0x00}, {"insert", 0x01}
+       },
+
+
+       /* MSG Specific (MsgMIMEExtern.h) -----------------------*/
+
+       /* MmsCodeCharSet */
+       {
+               {"US-ASCII", 0x03},
+               {"UTF-16", 0x03F7},
+               {"CSUNICODE", 0x03E8},
+               {"UTF-8", 0x6A},
+               {"ISO-2022-KR", 0x25},
+               {"KS_C_5601-1987", 0x24},
+               {"EUC-KR", 0x26},
+               {"ISO-2022-JP", 0x27},
+               {"ISO-2022-JP-2", 0x28},
+               {"ISO_8859-1", 0x04},
+               {"ISO_8859-2", 0x05},
+               {"ISO-8859-3", 0x06},
+               {"ISO-8859-4", 0x07},
+               {"ISO-8859-5", 0x08},
+               {"ISO-8859-6", 0x09},
+               {"ISO-8859-7", 0x0a},
+               {"ISO-8859-8", 0x0b},
+               {"ISO-8859-9", 0x0c},
+               {"ISO-8859-10", 0x0d},
+               {"ISO-8859-15", 0x6F},
+               {"SHIFT_JIS", 0x11},
+               {"EUC-JP", 0x13},
+               {"GB2312", 0x07E9},
+               {"BIG5", 0x0d},
+               {"WINDOWS-1251", 0x08CB},
+               {"KOI8-R", 0x0824},
+               {"KOI8-U", 0x0828},
+       },
+
+       /* MmsCodeReplyCharging, */
+       {
+               { "Requested", 0x00 },
+               { "Requested text only", 0x01 },
+               { "Accepted", 0x02 },
+               { "Accepted text only", 0x03 }
+       },
+
+
+//     OMNA WSP Content Type Numbers
+//     http://technical.openmobilealliance.org/tech/omna/omna-wsp-content-type.aspx
+       {
+       //NOT USED THIS TABLE
+       },
+
+       /* MmsCodeMsgDisposition : Wsp Header (By Wsp 8.4.2.53) */
+       {
+               {"form-data", 0x00},
+               {"attachment", 0x01},
+               {"inline", 0x02}
+       },
+
+       /* Content-transfer-encoding : HTTP Header(Binary Value is not assigned) */
+       {
+               {"7bit", 0x00},
+               {"8bit", 0x00},
+               {"binary", 0x00},
+               {"base64", 0x00},
+               {"quoted-printable", 0x00}
+       }
+};
+
+const char *MmsGetTextValue(MmsCode i, int j)
+{
+       if (i == MmsCodeContentType) {
+               //apply UtyMime
+               return MimeGetMimeStringFromMimeInt(j);
+       }
+
+       return (const char *)gMmsField[i][j].szText;
+}
+
+const char *MmsGetTextValuebyField(int field, int value)
+{
+       const char *szValue = NULL;
+
+       switch (field) {
+       case MMS_CODE_MSGTYPE:
+               szValue = MmsGetTextValue(MmsCodeMsgType, value);
+               break;
+
+       case MMS_CODE_MSGCLASS:
+               szValue = MmsGetTextValue(MmsCodeMsgClass, value);
+               break;
+
+       case MMS_CODE_PRIORITY:
+               szValue = MmsGetTextValue(MmsCodePriority, value);
+               break;
+
+       case MMS_CODE_SENDERVISIBILLITY:
+               szValue = MmsGetTextValue(MmsCodeSenderVisibility, value);
+               break;
+
+       case MMS_CODE_DELIVERYREPORT:
+               szValue = MmsGetTextValue(MmsCodeDeliveryReport, value);
+               break;
+
+       case MMS_CODE_READREPLY:
+               szValue = MmsGetTextValue(MmsCodeReadReply, value);
+               break;
+
+       case MMS_CODE_MSGSTATUS:
+               szValue = MmsGetTextValue(MmsCodeMsgStatus, value);
+               break;
+
+       case MMS_CODE_REPORTALLOWED:
+               szValue = MmsGetTextValue(MmsCodeReportAllowed, value);
+               break;
+
+       case MMS_CODE_RESPONSESTATUS:
+               szValue = MmsGetTextValue(MmsCodeResponseStatus, value);
+               break;
+
+       /* Add by MMSENC v1.1 */
+       case MMS_CODE_READSTATUS:
+               szValue = MmsGetTextValue(MmsCodeReadStatus, value);
+               break;
+
+       default:
+               szValue = NULL;
+               break;
+       }
+
+       return szValue;
+}
+
+UINT16 MmsGetBinaryValue(MmsCode i, int j)
+{
+       if (i == MmsCodeContentType) {
+               return MimeGetBinaryValueFromMimeInt((MimeType)j);
+       }
+
+       return gMmsField[i][j].binary;
+}
+
+int MmsGetBinaryType(MmsCode i, UINT16 value)
+{
+
+       for (int j = 0; j < MMS_MAX_FIELD_VALUE_COUNT; j++) {
+               if (gMmsField[i][j].binary == value) {
+                       MSG_DEBUG("code [%d], value [0x%02x], ret type [%d]", i, value, j);
+                       return j;
+               }
+       }
+
+       MSG_DEBUG("code [%d], value [0x%02x], ret type [Unknown]", i, value);
+       return -1;
+}
+
+int MmsGetTextType(MmsCode i, char *pValue)
+{
+       int j = 0;
+
+       if (i == MmsCodeContentType) {
+               /*apply UtyMime */
+               return MimeGetMimeIntFromMimeString( pValue );
+       }
+
+       for (j = 0; j < MMS_MAX_FIELD_VALUE_COUNT; j++) {
+               if (gMmsField[i][j].szText != NULL) {
+                       if (strcasecmp( gMmsField[i][j].szText, pValue ) == 0) {
+                               return j;
+                       }
+               }
+       }
+
+       return -1;
+}
+
+const char *MmsGetTextByCode(MmsCode i, UINT16 code)
+{
+       for (int j = 0; j < MMS_MAX_FIELD_VALUE_COUNT; j++) {
+               if (gMmsField[i][j].binary == code) {
+                       return gMmsField[i][j].szText;
+               }
+       }
+       return NULL;
+}
+
+
+
+/* ==================================================================
+ *     Decode/Encode inline base64 string
+ *
+ * base64 : 3*8bit -> 4*6bit & convert the value into A~Z, a~z, 0~9, +, or /
+ * pad(=) is needed when the end of the string is < 24bit.
+ *
+ *     Value Encoding  Value Encoding  Value Encoding  Value Encoding
+ *         0 A            17 R            34 i            51 z
+ *         1 B            18 S            35 j            52 '0'
+ *         2 C            19 T            36 k            53 1
+ *         3 D            20 U            37 l            54 2
+ *         4 E            21 V            38 m            55 3
+ *         5 F            22 W            39 n            56 4
+ *         6 G            23 X            40 o            57 5
+ *         7 H            24 Y            41 p            58 6
+ *         8 I            25 Z            42 q            59 7
+ *         9 J            26 a            43 r            60 8
+ *        10 K            27 b            44 s            61 9
+ *        11 L            28 c            45 t            62 +
+ *        12 M            29 d            46 u            63 /
+ *        13 N            30 e            47 v
+ *        14 O            31 f            48 w         (pad) =
+ *        15 P            32 g            49 x
+ *        16 Q            33 h            50 y
+ *
+ * (1) the final quantum = 24 bits : no "=" padding,
+ * (2) the final quantum = 8 bits : two "=" + two characters
+ * (3) the final quantum = 16 bits : one "=" + three characters
+ * ================================================================== */
+
+void *MsgDecodeBase64(unsigned char *pSrc, unsigned long srcLen, unsigned long *len)
+{
+       char c;
+       void *ret = NULL;
+       char *d = NULL;
+       short e = 0;
+
+       ret = malloc((size_t)(*len = 4 + ((srcLen * 3) / 4)));
+       d = (char *)ret;
+
+       if (ret == NULL) {
+               MSG_DEBUG("_MsgDecodeBase64: ret malloc Fail \n");
+               return NULL;
+       }
+
+       memset(ret, 0, (size_t)*len);
+       *len = 0;
+
+       while (srcLen-- > 0) {
+               c = *pSrc++;
+
+               /* Convert base64 character into original value */
+
+               if (isupper(c))
+                       c -= 'A';
+               else if (islower(c))
+                       c -= 'a' - 26;
+               else if (isdigit(c))
+                       c -= '0' - 52;
+               else if (c == '+')
+                       c = 62;
+               else if (c == '/')
+                       c = 63;
+               else if (c == '=') {
+                       switch (e++) {
+                       case 2:
+                               if (*pSrc != '=') {
+                                       *len = d - (char *)ret;
+                                       return ret;
+                               }
+                               break;
+                       case 3:
+                               e = 0;
+                               break;
+                       default:
+                               *len = d - (char *)ret;
+                               return ret;
+                       }
+                       continue;
+               } else
+                       continue;                                       // Actually, never get here
+
+               /* Pad 4*6bit character into 3*8bit character */
+
+               switch (e++) {
+               case 0:
+                       *d = c << 2;                    // byte 1: high 6 bits
+                       break;
+
+               case 1:
+                       *d++ |= c >> 4;                 // byte 1: low 2 bits
+                       *d = c << 4;                    // byte 2: high 4 bits
+                       break;
+
+               case 2:
+                       *d++ |= c >> 2;                 // byte 2: low 4 bits
+                       *d = c << 6;                    // byte 3: high 2 bits
+                       break;
+
+               case 3:
+                       *d++ |= c;                              // byte 3: low 6 bits
+                       e = 0;                                  // Calculate next unit.
+                       break;
+
+               default:
+                       MSG_DEBUG("_MsgDecodeBase64: Unknown paremeter\n");
+                       break;
+               }
+       }
+
+       *len = d - (char *)ret;                 // Calculate the size of decoded string.
+
+       return ret;
+}
+
+
+
+/* ==========================================
+ *     Decode/Encode inline base64 string
+ *
+ * quoted-printable := ([*(ptext / SPACE / TAB) ptext] ["="] CRLF)
+ *       ; Maximum line length of 76 characters excluding CRLF
+ *
+ * ptext := octet /<any ASCII character except "=", SPACE, or TAB>
+ *       ; characters not listed as "mail-safe" in Appendix B
+ *       ; are also not recommended.
+ *
+ * octet := "=" 2(DIGIT / "A" / "B" / "C" / "D" / "E" / "F")
+ *       ; octet must be used for characters > 127, =, SPACE, or TAB.
+ *
+ * ==========================================*/
+
+
+unsigned char *MsgDecodeQuotePrintable(unsigned char *pSrc, unsigned long srcLen, unsigned long *len)
+{
+       unsigned char *ret = NULL;
+       unsigned char *d = NULL;
+       unsigned char *s = NULL;                                        /* last non-blank */
+       unsigned char c;
+       unsigned char e;
+
+       d = s = ret = (unsigned char *)malloc((size_t)srcLen + 1);
+       if (ret == NULL) {
+               MSG_DEBUG("_MsgDecodeQuotePrintable: ret malloc Fail \n");
+               return NULL;
+       }
+
+       *len = 0;
+       pSrc[srcLen] = '\0';
+
+       while ((c = *pSrc++)!= '\0') {
+               switch (c) {
+               case '=':                                                       /* octet characters (> 127, =, SPACE, or TAB) */
+                       switch (c = *pSrc++) {
+                       case '\0':                                      /* end of string -> postpone to while */
+                               break;
+
+                       case '\015':                            /* CRLF */
+                               if (*pSrc == '\012')
+                                       pSrc++;
+                               break;
+
+                       default:                                        /* two hexes */
+                               if (!isxdigit(c)) {
+                                       *d = '\0';
+                                       *len = d - ret;
+                                       return ret;
+                               }
+
+                               if (isdigit(c))
+                                       e = c - '0';
+                               else
+                                       e = c - (isupper(c) ? 'A' - 10 : 'a' - 10);
+
+                               c = *pSrc++;
+                               if (!isxdigit(c)) {
+                                       *d = '\0';
+                                       *len = d - ret;
+                                       return ret;
+                               }
+
+                               if (isdigit(c))
+                                       c -= '0';
+                               else
+                                       c -= (isupper(c) ? 'A' - 10 : 'a' - 10);
+
+                               *d++ = c + (e << 4);
+                               s = d;
+                               break;
+                       }
+                       break;
+
+               case ' ':                                                       /* skip the blank */
+                       *d++ = c;
+                       break;
+
+               case '\015':                                            /* Line Feedback : to last non-blank character */
+                       d = s;
+                       break;
+
+               default:
+                       *d++ = c;                                               /* ASCII character */
+                       s = d;
+                       break;
+               }
+       }
+
+       *d = '\0';
+       *len = d - ret;
+
+       return ret;
+}
+
+
+/* ========================================
+ * Decode/Encode inline base64 string
+ * Inline base64 has no "\r\n" in it,
+ * and has charset and encoding sign in it
+ * ======================================== */
+bool MsgEncode2Base64(void *pSrc, unsigned long srcLen, unsigned long *len, unsigned char *ret)
+{
+       unsigned char *d = NULL;
+       unsigned char *s = (unsigned char *)pSrc;
+       char *v = (char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+       unsigned long i = ((srcLen + 2) / 3) * 4;
+
+       i += 2 * ((i / 60) + 1);
+       *len = i;
+
+       if (ret == NULL) {
+               MSG_DEBUG("_MsgEncode2Base64: ret Memory Alloc Fail \n");
+               return false;
+       }
+       memset(ret, 0, i);
+
+       d = ret;
+
+       /* Convert 3*8bit into 4*6bit */
+       for (i = 0; srcLen > 0; s += 3) {
+               *d++ = v[s[0] >> 2];                                                                                                                    // byte 1: high 6 bits of character-1
+               *d++ = v[((s[0] << 4) + (--srcLen ? (s[1] >> 4) : 0)) & 0x3f];                                  // byte 2: low 2 bits of character-1 and high 4 bits of character-2
+               *d++ = srcLen ? v[((s[1] << 2) + (--srcLen ? (s[2] >> 6) : 0)) & 0x3f] : '=';   // byte 3: low 4 bits of charcter-2 and high 2 bits of character-3
+               *d++ = srcLen ? v[s[2] & 0x3f] : '=';                                                                                   // byte 4: low 6 bits of character-3
+
+               if (srcLen)
+                       srcLen--;
+       }
+
+       *d = '\0';
+
+       if (((unsigned long)(d - ret)) != *len) {
+               *len = d - ret;
+               MSG_DEBUG("base64 encoding length = %d \n", *len);
+       }
+
+       return true;
+}
+
+int extract_encoded_word_param(char *encoded_word, char **charset,  char **encoding, char **encoded_text, unsigned int *encoded_word_size)
+{
+       char *start_ptr = NULL;
+       char *end_ptr = NULL;
+       char *q1_ptr = NULL;
+       char *q2_ptr = NULL;
+
+       char *char_set = NULL;
+       char *l_encoded_text = NULL;
+
+       char l_encoding[2] = {0,};
+
+       if (encoded_word == NULL)
+               goto __CATCH;
+
+       if ( 6 > strlen(encoded_word)) {
+               goto __CATCH;
+       }
+
+       start_ptr = encoded_word;
+
+       if ( (encoded_word[0] == '=' && encoded_word[1] == '?') //"=?"
+                        && ((q1_ptr = strchr(start_ptr + 2, MSG_CH_QUESTION)) != NULL) // '?'
+                        && ((q2_ptr = strchr(q1_ptr + 1, MSG_CH_QUESTION))!= NULL)             // '?'
+                        && ((end_ptr = strstr(q2_ptr + 1, MSG_STR_DEC_END))!= NULL)) //"?="
+       {
+
+               //extract character set
+               if ( q1_ptr - (start_ptr + 2) > 0 ) {
+
+                       char_set = (char*)calloc(1, q1_ptr - (start_ptr + 2) + 1);
+
+                       if (char_set) {
+                               strncpy(char_set, (char*)((start_ptr + 2)), q1_ptr - (start_ptr + 2));
+                               MSG_DEBUG("character set [%s][%d]", char_set, strlen(char_set));
+                       } else {
+                               MSG_DEBUG("fail to calloc");
+                               goto __CATCH;
+                       }
+               } else {
+                       MSG_DEBUG("character set is NULL");
+                       goto __CATCH;
+               }
+
+               //extract encode type
+               if ((*(q2_ptr - 1) == MSG_CH_BASE64_UPPER) || (*(q2_ptr - 1) == MSG_CH_BASE64_LOWER)
+                               || (*(q1_ptr + 1) == MSG_CH_BASE64_UPPER) || (*(q1_ptr + 1) == MSG_CH_BASE64_LOWER))
+               {
+                       l_encoding[0] = MSG_CH_BASE64_UPPER;
+               } else if ((*(q2_ptr-1) == MSG_CH_QPRINT_UPPER) || (*(q2_ptr-1) == MSG_CH_QPRINT_LOWER)
+                               || (*(q1_ptr+1) == MSG_CH_QPRINT_UPPER) || (*(q1_ptr+1) == MSG_CH_QPRINT_LOWER))
+               {
+                       //QPRINT
+                       l_encoding[0] = MSG_CH_QPRINT_UPPER;
+
+               } else {
+                       MSG_DEBUG("unknown encoding");
+                       goto __CATCH;
+               }
+
+               //extract encoded text
+               if (end_ptr - q2_ptr > 1) {
+                       l_encoded_text = (char*)calloc(1, end_ptr - q2_ptr);
+                       if (l_encoded_text == NULL)
+                               goto __CATCH;
+                       strncpy(l_encoded_text, (char*)(q2_ptr + 1), end_ptr - q2_ptr -1);
+
+                       MSG_DEBUG("encoded text [%s][%d]", l_encoded_text, strlen(l_encoded_text));
+               } else {
+                       MSG_DEBUG("encoded text is NULL");
+                       goto __CATCH;
+               }
+
+               *charset = char_set;
+               *encoding = g_strdup(l_encoding);
+               *encoded_text = l_encoded_text;
+               *encoded_word_size = end_ptr - start_ptr + 2;
+
+       } else {
+               MSG_DEBUG("It is not encoded word type");
+               return -1;
+       }
+
+       return 0;
+
+__CATCH:
+       MSG_FREE(char_set);
+       MSG_FREE(l_encoded_text);
+       return -1;
+}
+
+char *MsgDecodeText(const char *pOri)
+{
+       MSG_BEGIN();
+
+       char *pSrc = NULL;
+
+       char *encoded_word_start_ptr = NULL;
+       char *normal_word_start_ptr = NULL;
+
+       char *charset = NULL;
+       char *encoding = NULL;
+       char *encoded_text = NULL;
+       char *decoded_text = NULL;
+
+       char *return_string= NULL;
+       string result_string;
+
+       bool b_encoded_word = false;
+
+       unsigned int encoded_word_size = 0;
+       unsigned int total_len = 0;
+       unsigned int decoded_len = 0;
+
+       // copy original string
+       if (pOri == NULL || strlen(pOri) <= 0) {
+               MSG_DEBUG("Invalid parameter : [%s]", pOri);
+               return NULL;
+       }
+
+       pSrc = g_strdup(pOri);
+       total_len = strlen(pOri);
+
+       MSG_DEBUG("input text : [%s][%d]", pSrc, total_len);
+
+       normal_word_start_ptr = pSrc;
+
+       while (normal_word_start_ptr < pSrc + total_len) {
+
+               encoded_word_start_ptr = strstr(normal_word_start_ptr, MSG_STR_DEC_START);
+
+               b_encoded_word = false;
+
+               //Find encoded word
+               while (b_encoded_word == false && encoded_word_start_ptr != NULL ) {
+
+                       if (extract_encoded_word_param(encoded_word_start_ptr, &charset, &encoding, &encoded_text, &encoded_word_size) == 0) {
+
+                               if (charset && encoding && encoded_text && encoded_word_size > 0) {
+                                       b_encoded_word = true;
+                                       MSG_DEBUG("charset [%s], encoding [%s], encoded_text [%s], encoded_word_size [%d]", charset, encoding, encoded_text, encoded_word_size);
+                                       break;
+                               }
+
+                               MSG_FREE(charset);
+                               MSG_FREE(encoding);
+                               MSG_FREE(encoded_text);
+                               encoded_word_size = 0;
+                       }
+
+                       encoded_word_start_ptr = strstr(encoded_word_start_ptr+1, MSG_STR_DEC_START); //find next encoded_start_ptr
+
+               } // end of while
+
+               if (b_encoded_word) {
+
+                       //copy normal text
+                       if (encoded_word_start_ptr - normal_word_start_ptr > 0) {
+                               result_string.append(normal_word_start_ptr, encoded_word_start_ptr - normal_word_start_ptr);
+                               MSG_DEBUG("copy normal text : [%s]", result_string.c_str());
+                       }
+
+                       if (strcasecmp(encoding, "B") == 0) {
+
+                               MSG_DEBUG("Base64 encoded text [%s][%d]", encoded_text, strlen(encoded_text));
+
+                               decoded_text = (char *)MsgDecodeBase64((unsigned char *)encoded_text, strlen(encoded_text), (ULONG *)&decoded_len);
+
+                               if (decoded_text && decoded_len > 0) {
+
+                                       char *result_text = NULL;
+                                       int result_text_len = 0;
+
+                                       MSG_DEBUG("Base64 decoded text [%s][%d], outlen [%d]", decoded_text, strlen(decoded_text), decoded_len);
+
+                                       if (MmsPluginTextConvert("UTF-8", charset, decoded_text, decoded_len, &result_text, &result_text_len) == false) {
+                                               MSG_DEBUG("MmsPluginTextConvert Fail");
+                                       }
+
+                                       if(result_text) {
+                                               MSG_DEBUG("Text convert result [%s][%d]", result_text, strlen(result_text));
+
+                                               result_string.append(result_text, result_text_len);
+
+                                               MSG_FREE(result_text);
+                                       }
+
+                               } else {
+                                       MSG_DEBUG("Fail base64 decode");
+                               }
+
+                               MSG_FREE(decoded_text);
+
+                       } else if (strcasecmp(encoding, "Q") == 0) {
+
+                               char *result_text = NULL;
+                               int result_text_len = 0;
+
+                               MSG_DEBUG("Qprint encoded text [%s][%d]", encoded_text, strlen(encoded_text));
+
+                               decoded_text = (char *)MsgDecodeQuotePrintable((unsigned char *)encoded_text, strlen(encoded_text), (ULONG *)&decoded_len);
+
+                               if (decoded_text && decoded_len > 0) {
+
+                                       MSG_DEBUG("Qprint decoded text [%s][%d], outlen [%d]", decoded_text, strlen(decoded_text), decoded_len);
+
+                                       if (MmsPluginTextConvert("UTF-8", charset, decoded_text, decoded_len, &result_text, &result_text_len) == false) {
+                                               MSG_DEBUG("MmsPluginTextConvert Fail");
+                                       }
+
+                                       if(result_text) {
+                                               MSG_DEBUG("Text convert result [%s][%d]", result_text, strlen(result_text));
+
+                                               result_string.append(result_text, result_text_len);
+
+                                               MSG_FREE(result_text);
+                                       }
+
+                               } else {
+                                       MSG_DEBUG("Fail Qprint decode");
+                               }
+
+                               MSG_FREE(decoded_text);
+                       }
+
+                       normal_word_start_ptr = encoded_word_start_ptr+encoded_word_size; //next
+
+                       MSG_FREE(charset);
+                       MSG_FREE(encoding);
+                       MSG_FREE(encoded_text);
+                       encoded_word_size = 0;
+
+               } else {
+                       //copy remain normal text
+
+                       MSG_DEBUG("last text : [%s]", normal_word_start_ptr);
+
+                       result_string.append(normal_word_start_ptr);
+
+                       break;
+               }
+
+       } //end of while
+
+       if (result_string.length() > 0) {
+               return_string = g_strdup(result_string.c_str());
+               MSG_DEBUG("return string: [%s]", return_string);
+       }
+
+       MSG_FREE(pSrc);
+
+       MSG_END();
+       return return_string;
+}
+
+static char gszDebugStringBuf[50];
+
+static char *MmsDebugPrintUnknownValue(int value)
+{
+       snprintf(gszDebugStringBuf, sizeof(gszDebugStringBuf), "unknown value(%d)", value);
+       return gszDebugStringBuf;
+}
+
+
+const char *MmsDebugGetMimeType(MimeType mimeType)
+{
+       switch (mimeType) {
+       case MIME_APPLICATION_XML:
+               return "MIME_APPLICATION_XML";
+       case MIME_APPLICATION_WML_XML:
+               return "MIME_APPLICATION_WML_XML";
+       case MIME_APPLICATION_XHTML_XML:
+               return "MIME_APPLICATION_XHTML_XML";
+       case MIME_APPLICATION_JAVA_VM:
+               return "MIME_APPLICATION_JAVA_VM";
+       case MIME_APPLICATION_SMIL:
+               return "MIME_APPLICATION_SMIL";
+       case MIME_APPLICATION_JAVA_ARCHIVE:
+               return "MIME_APPLICATION_JAVA_ARCHIVE";
+       case MIME_APPLICATION_JAVA:
+               return "MIME_APPLICATION_JAVA";
+       case MIME_APPLICATION_OCTET_STREAM:
+               return "MIME_APPLICATION_OCTET_STREAM";
+       case MIME_APPLICATION_STUDIOM:
+               return "MIME_APPLICATION_STUDIOM";
+       case MIME_APPLICATION_FUNMEDIA:
+               return "MIME_APPLICATION_FUNMEDIA";
+       case MIME_APPLICATION_MSWORD:
+               return "MIME_APPLICATION_MSWORD";
+       case MIME_APPLICATION_PDF:
+               return "MIME_APPLICATION_PDF";
+       case MIME_APPLICATION_ASTERIC:
+               return "MIME_APPLICATION_ASTERIC";
+       case MIME_APPLICATION_VND_WAP_XHTMLXML:
+               return "MIME_APPLICATION_VND_WAP_XHTMLXML";
+       case MIME_APPLICATION_VND_WAP_WMLC:
+               return "MIME_APPLICATION_VND_WAP_WMLC";
+       case MIME_APPLICATION_VND_WAP_WMLSCRIPTC:
+               return "MIME_APPLICATION_VND_WAP_WMLSCRIPTC";
+       case MIME_APPLICATION_VND_WAP_WTA_EVENTC:
+               return "MIME_APPLICATION_VND_WAP_WTA_EVENTC";
+       case MIME_APPLICATION_VND_WAP_UAPROF:
+               return "MIME_APPLICATION_VND_WAP_UAPROF";
+       case MIME_APPLICATION_VND_WAP_SIC:
+               return "MIME_APPLICATION_VND_WAP_SIC";
+       case MIME_APPLICATION_VND_WAP_SLC:
+               return "MIME_APPLICATION_VND_WAP_SLC";
+       case MIME_APPLICATION_VND_WAP_COC:
+               return "MIME_APPLICATION_VND_WAP_COC";
+       case MIME_APPLICATION_VND_WAP_SIA:
+               return "MIME_APPLICATION_VND_WAP_SIA";
+       case MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML:
+               return "MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML";
+       case MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA:
+               return "MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA";
+       case MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES:
+               return "MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES";
+       case MIME_APPLICATION_VND_WAP_MULTIPART_MIXED:
+               return "MIME_APPLICATION_VND_WAP_MULTIPART_MIXED";
+       case MIME_APPLICATION_VND_WAP_MULTIPART_RELATED:
+               return "MIME_APPLICATION_VND_WAP_MULTIPART_RELATED";
+       case MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE:
+               return "MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE";
+       case MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC:
+               return "MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC";
+       case MIME_APPLICATION_VND_OMA_DD_XML:
+               return "MIME_APPLICATION_VND_OMA_DD_XML";
+       case MIME_APPLICATION_VND_OMA_DRM_MESSAGE:
+               return "MIME_APPLICATION_VND_OMA_DRM_MESSAGE";
+       case MIME_APPLICATION_VND_OMA_DRM_CONTENT:
+               return "MIME_APPLICATION_VND_OMA_DRM_CONTENT";
+       case MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML:
+               return "MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML";
+       case MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML:
+               return "MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML";
+       case MIME_APPLICATION_VND_SMAF:
+               return "MIME_APPLICATION_VND_SMAF";
+       case MIME_APPLICATION_VND_RN_REALMEDIA:
+               return "MIME_APPLICATION_VND_RN_REALMEDIA";
+       case MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE:
+               return "MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE";
+       case MIME_APPLICATION_VND_SAMSUNG_THEME:
+               return "MIME_APPLICATION_VND_SAMSUNG_THEME";
+       case MIME_APPLICATION_VND_EXCEL:
+               return "MIME_APPLICATION_VND_EXCEL";
+       case MIME_APPLICATION_X_HDMLC:
+               return "MIME_APPLICATION_X_HDMLC";
+       case MIME_APPLICATION_X_X968_USERCERT:
+               return "MIME_APPLICATION_X_X968_USERCERT";
+       case MIME_APPLICATION_X_WWW_FORM_URLENCODED:
+               return "MIME_APPLICATION_X_WWW_FORM_URLENCODED";
+       case MIME_APPLICATION_X_SMAF:
+               return "MIME_APPLICATION_X_SMAF";
+       case MIME_APPLICATION_X_FLASH:
+               return "MIME_APPLICATION_X_FLASH";
+       case MIME_APPLICATION_X_EXCEL:
+               return "MIME_APPLICATION_X_EXCEL";
+       case MIME_APPLICATION_X_POWERPOINT:
+               return "MIME_APPLICATION_X_POWERPOINT";
+
+       case MIME_AUDIO_BASIC:
+               return "MIME_AUDIO_BASIC";
+       case MIME_AUDIO_MPEG:
+               return "MIME_AUDIO_MPEG";
+       case MIME_AUDIO_MP3:
+               return "MIME_AUDIO_MP3";
+       case MIME_AUDIO_MPG3:
+               return "MIME_AUDIO_MPG3";
+       case MIME_AUDIO_MPEG3:
+               return "MIME_AUDIO_MPEG3";
+       case MIME_AUDIO_MPG:
+               return "MIME_AUDIO_MPG";
+       case MIME_AUDIO_AAC:
+               return "MIME_AUDIO_AAC";
+       case MIME_AUDIO_G72:
+               return "MIME_AUDIO_G72";
+       case MIME_AUDIO_AMR:
+               return "MIME_AUDIO_AMR";
+       case MIME_AUDIO_AMR_WB:
+               return "MIME_AUDIO_AMR_WB";
+       case MIME_AUDIO_MMF:
+               return "MIME_AUDIO_MMF";
+       case MIME_AUDIO_SMAF:
+               return "MIME_AUDIO_SMAF";
+       case MIME_AUDIO_IMELODY:
+               return "MIME_AUDIO_IMELODY";
+       case MIME_AUDIO_MELODY:
+               return "MIME_AUDIO_MELODY";
+       case MIME_AUDIO_MID:
+               return "MIME_AUDIO_MID";
+       case MIME_AUDIO_MIDI:
+               return "MIME_AUDIO_MIDI";
+       case MIME_AUDIO_X_MID:
+               return "MIME_AUDIO_X_MID";
+       case MIME_AUDIO_SP_MIDI:
+               return "MIME_AUDIO_SP_MIDI";
+       case MIME_AUDIO_WAVE:
+               return "MIME_AUDIO_WAVE";
+       case MIME_AUDIO_3GPP:
+               return "MIME_AUDIO_3GPP";
+       case MIME_AUDIO_MP4:
+               return "MIME_AUDIO_MP4";
+       case MIME_AUDIO_MP4A_LATM:
+               return "MIME_AUDIO_MP4A_LATM";
+       case MIME_AUDIO_VND_RN_REALAUDIO:
+               return "MIME_AUDIO_VND_RN_REALAUDIO";
+       case MIME_AUDIO_X_MPEG:
+               return "MIME_AUDIO_X_MPEG";
+       case MIME_AUDIO_X_MP3:
+               return "MIME_AUDIO_X_MP3";
+       case MIME_AUDIO_X_MPEG3:
+               return "MIME_AUDIO_X_MPEG3";
+       case MIME_AUDIO_X_MPG:
+               return "MIME_AUDIO_X_MPG";
+       case MIME_AUDIO_X_AMR:
+               return "MIME_AUDIO_X_AMR";
+       case MIME_AUDIO_X_MMF:
+               return "MIME_AUDIO_X_MMF";
+       case MIME_AUDIO_X_SMAF:
+               return "MIME_AUDIO_X_SMAF";
+       case MIME_AUDIO_X_IMELODY:
+               return "MIME_AUDIO_X_IMELODY";
+       case MIME_AUDIO_X_MIDI:
+               return "MIME_AUDIO_X_MIDI";
+       case MIME_AUDIO_X_MPEGAUDIO:
+               return "MIME_AUDIO_X_MPEGAUDIO";
+       case MIME_AUDIO_X_PN_REALAUDIO:
+               return "MIME_AUDIO_X_PN_REALAUDIO";
+       case MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO:
+               return "MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO";
+       case MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE:
+               return "MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE";
+       case MIME_AUDIO_X_WAV:
+               return "MIME_AUDIO_X_WAV";
+
+       case MIME_IMAGE_GIF:
+               return "MIME_IMAGE_GIF";
+       case MIME_IMAGE_JPEG:
+               return "MIME_IMAGE_JPEG";
+       case MIME_IMAGE_JPG:
+               return "MIME_IMAGE_JPG";
+       case MIME_IMAGE_TIFF:
+               return "MIME_IMAGE_TIFF";
+       case MIME_IMAGE_TIF:
+               return "MIME_IMAGE_TIF";
+       case MIME_IMAGE_PNG:
+               return "MIME_IMAGE_PNG";
+       case MIME_IMAGE_WBMP:
+               return "MIME_IMAGE_WBMP";
+       case MIME_IMAGE_PJPEG:
+               return "MIME_IMAGE_PJPEG";
+       case MIME_IMAGE_BMP:
+               return "MIME_IMAGE_BMP";
+       case MIME_IMAGE_SVG:
+               return "MIME_IMAGE_SVG";
+       case MIME_IMAGE_SVG1:
+               return "MIME_IMAGE_SVG1";
+       case MIME_IMAGE_VND_WAP_WBMP:
+               return "MIME_IMAGE_VND_WAP_WBMP";
+
+       case MIME_IMAGE_X_BMP:
+               return "MIME_IMAGE_X_BMP";
+
+       case MIME_MESSAGE_RFC822:
+               return "MIME_MESSAGE_RFC822";
+
+       case MIME_MULTIPART_MIXED:
+               return "MIME_MULTIPART_MIXED";
+       case MIME_MULTIPART_RELATED:
+               return "MIME_MULTIPART_RELATED";
+       case MIME_MULTIPART_ALTERNATIVE:
+               return "MIME_MULTIPART_ALTERNATIVE";
+       case MIME_MULTIPART_FORM_DATA:
+               return "MIME_MULTIPART_FORM_DATA";
+       case MIME_MULTIPART_BYTERANGE:
+               return "MIME_MULTIPART_BYTERANGE";
+       case MIME_MULTIPART_REPORT:
+               return "MIME_MULTIPART_REPORT";
+
+       case MIME_TEXT_TXT:
+               return "MIME_TEXT_TXT";
+       case MIME_TEXT_HTML:
+               return "MIME_TEXT_HTML";
+       case MIME_TEXT_PLAIN:
+               return "MIME_TEXT_PLAIN";
+       case MIME_TEXT_CSS:
+               return "MIME_TEXT_CSS";
+       case MIME_TEXT_XML:
+               return "MIME_TEXT_XML";
+       case MIME_TEXT_IMELODY:
+               return "MIME_TEXT_IMELODY";
+       case MIME_TEXT_CALENDAR:
+               return "MIME_TEXT_CALENDAR";
+       case MIME_TEXT_VND_WAP_WMLSCRIPT:
+               return "MIME_TEXT_VND_WAP_WMLSCRIPT";
+       case MIME_TEXT_VND_WAP_WML:
+               return "MIME_TEXT_VND_WAP_WML";
+       case MIME_TEXT_VND_WAP_WTA_EVENT:
+               return "MIME_TEXT_VND_WAP_WTA_EVENT";
+       case MIME_TEXT_VND_WAP_CONNECTIVITY_XML:
+               return "MIME_TEXT_VND_WAP_CONNECTIVITY_XML";
+       case MIME_TEXT_VND_WAP_SI:
+               return "MIME_TEXT_VND_WAP_SI";
+       case MIME_TEXT_VND_WAP_SL:
+               return "MIME_TEXT_VND_WAP_SL";
+       case MIME_TEXT_VND_WAP_CO:
+               return "MIME_TEXT_VND_WAP_CO";
+       case MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR:
+               return "MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR";
+       case MIME_TEXT_X_HDML:
+               return "MIME_TEXT_X_HDML";
+       case MIME_TEXT_X_VCALENDAR:
+               return "MIME_TEXT_X_VCALENDAR";
+       case MIME_TEXT_X_VCARD:
+               return "MIME_TEXT_X_VCARD";
+       case MIME_TEXT_X_IMELODY:
+               return "MIME_TEXT_X_IMELODY";
+       case MIME_TEXT_X_VTODO:
+               return "MIME_TEXT_X_VTODO";
+
+
+       case MIME_VIDEO_MPEG4:
+               return "MIME_VIDEO_MPEG4";
+       case MIME_VIDEO_MP4:
+               return "MIME_VIDEO_MP4";
+       case MIME_VIDEO_H263:
+               return "MIME_VIDEO_H263";
+       case MIME_VIDEO_3GPP:
+               return "MIME_VIDEO_3GPP";
+       case MIME_VIDEO_3GP:
+               return "MIME_VIDEO_3GP";
+       case MIME_VIDEO_AVI:
+               return "MIME_VIDEO_AVI";
+       case MIME_VIDEO_SDP:
+               return "MIME_VIDEO_SDP";
+       case MIME_VIDEO_MP4_ES:
+               return "MIME_VIDEO_MP4_ES";
+       case MIME_VIDEO_MPEG:
+               return "MIME_VIDEO_MPEG";
+       case MIME_VIDEO_VND_RN_REALVIDEO:
+               return "MIME_VIDEO_VND_RN_REALVIDEO";
+       case MIME_VIDEO_X_MP4:
+               return "MIME_VIDEO_X_MP4";
+       case MIME_VIDEO_X_PV_MP4:
+               return "MIME_VIDEO_X_PV_MP4";
+       case MIME_VIDEO_X_PN_REALVIDEO:
+               return "MIME_VIDEO_X_PN_REALVIDEO";
+       case MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO:
+               return "MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO";
+       default:
+               return MmsDebugPrintUnknownValue(mimeType);
+       }
+}
+
+
+/* MsgMmsMsg.h */
+const char *MmsDebugGetMmsReport(MmsReport report)
+{
+       switch (report) {
+       case MMS_REPORT_ERROR:
+               return "MMS_REPORT_ERROR";
+       case MMS_REPORT_YES:
+               return "MMS_REPORT_YES";
+       case MMS_REPORT_NO:
+               return "MMS_REPORT_NO";
+       }
+
+       return MmsDebugPrintUnknownValue(report);
+}
+
+
+const char *MmsDebugGetMmsReportAllowed(MmsReportAllowed reportAllowed)
+{
+       switch (reportAllowed) {
+       case MMS_REPORTALLOWED_ERROR:
+               return "MMS_REPORTALLOWED_ERROR";
+       case MMS_REPORTALLOWED_YES:
+               return "MMS_REPORTALLOWED_YES";
+       case MMS_REPORTALLOWED_NO:
+               return "MMS_REPORTALLOWED_NO";
+       }
+
+       return MmsDebugPrintUnknownValue(reportAllowed);
+}
+
+
+const char *MmsDebugGetMmsReadStatus(msg_read_report_status_t readStatus)
+{
+       _MSG_READ_REPORT_STATUS_E readReport = (_MSG_READ_REPORT_STATUS_E)readStatus;
+
+       switch (readReport) {
+       case MSG_READ_REPORT_NONE:
+               return "MMS_READSTATUS_NONE";
+       case MSG_READ_REPORT_IS_READ:
+               return "MMS_IS_READ";
+       case MSG_READ_REPORT_IS_DELETED:
+               return "MMS_IS_DELETED";
+       default:
+               break;
+       }
+
+       return MmsDebugPrintUnknownValue(readStatus);
+}
+
+const char *MmsDebugGetMsgType(MmsMsgType msgType)
+{
+       switch (msgType) {
+       case MMS_MSGTYPE_ERROR:
+               return "error";
+       case MMS_MSGTYPE_SEND_REQ:
+               return "send.req";
+       case MMS_MSGTYPE_SEND_CONF:
+               return "send.conf";
+       case MMS_MSGTYPE_NOTIFICATION_IND:
+               return "notification.ind";
+       case MMS_MSGTYPE_NOTIFYRESP_IND:
+               return "notifyResp.ind";
+       case MMS_MSGTYPE_RETRIEVE_CONF:
+               return "retrieve conf";
+       case MMS_MSGTYPE_ACKNOWLEDGE_IND:
+               return "acknowledge ind";
+       case MMS_MSGTYPE_DELIVERY_IND:
+               return "delivery ind";
+       case MMS_MSGTYPE_READREC_IND:
+               return "read rec ind";
+       case MMS_MSGTYPE_READORG_IND:
+               return "read org ind";
+       case MMS_MSGTYPE_FORWARD_REQ:
+               return "forward req";
+       case MMS_MSGTYPE_FORWARD_CONF:
+               return "forward conf";
+       case MMS_MSGTYPE_READ_REPLY:
+               return "read reply";
+       default:
+               return MmsDebugPrintUnknownValue(msgType);
+       }
+}
+
+const char *MmsDebugGetResponseStatus(MmsResponseStatus responseStatus)
+{
+       switch (responseStatus) {
+       case MMS_RESPSTATUS_ERROR:
+               return "error";
+       case MMS_RESPSTATUS_OK:
+               return "ok";
+       case MMS_RESPSTAUTS_ERROR_UNSPECIFIED:
+               return "unspecified";
+       case MMS_RESPSTAUTS_ERROR_SERVICEDENIED:
+               return "service denied";
+       case MMS_RESPSTAUTS_ERROR_MESSAGEFORMATCORRUPT:
+               return "message format corrupt";
+       case MMS_RESPSTAUTS_ERROR_SENDINGADDRESSUNRESOLVED:
+               return "sending address unresolved";
+       case MMS_RESPSTAUTS_ERROR_MESSAGENOTFOUND:
+               return "message not found";
+       case MMS_RESPSTAUTS_ERROR_NETWORKPROBLEM:
+               return "network problem";
+       case MMS_RESPSTAUTS_ERROR_CONTENTNOTACCEPTED:
+               return "content not accepted";
+       case MMS_RESPSTAUTS_ERROR_UNSUPPORTEDMESSAGE:
+               return "unsupported message";
+       case MMS_RESPSTAUTS_ERROR_TRANSIENT_FAILURE:
+               return "transient failure";
+       case MMS_RESPSTAUTS_ERROR_TRANSIENT_SENDING_ADDRESS_UNRESOLVED:
+               return "transient sending address unresolved";
+       case MMS_RESPSTAUTS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND:
+               return "transient message not found";
+       case MMS_RESPSTAUTS_ERROR_TRANSIENT_NETWORK_PROBLEM:
+               return "transient network problem";
+       case MMS_RESPSTAUTS_ERROR_PERMANENT_FAILURE:
+               return "permanent failure";
+       case MMS_RESPSTAUTS_ERROR_PERMANENT_SERVICE_DENIED:
+               return "permanent service denied";
+       case MMS_RESPSTAUTS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT:
+               return "permanent message format corrupt";
+       case MMS_RESPSTAUTS_ERROR_PERMANENT_SENDING_ADDRESS_UNRESOLVED:
+               return "permanent sending address unresolved";
+       case MMS_RESPSTAUTS_ERROR_PERMANENT_MESSAGE_NOT_FOUND:
+               return "permanent message not found";
+       case MMS_RESPSTAUTS_ERROR_PERMANENT_CONTENT_NOT_ACCEPTED:
+               return "permanent content not accepted";
+       case MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_LIMITATIONS_NOT_MET:
+               return "permanent reply charging limitations not met";
+       case MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_REQUEST_NOT_ACCEPTED:
+               return "permanent reply charging request not accepted";
+       case MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_FORWARDING_DENIED:
+               return "permanent reply charging forwarding denied";
+       case MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_NOT_SUPPORTED:
+               return "permanent reply charging not supported";
+       }
+
+       return MmsDebugPrintUnknownValue(responseStatus);
+}
+
+
+const char *MmsDebugGetRetrieveStatus(MmsRetrieveStatus retrieveStatus)
+{
+       switch (retrieveStatus) {
+       case MMS_RETRSTATUS_ERROR:
+               return "error";
+       case MMS_RETRSTATUS_OK:
+               return "ok";
+       case MMS_RETRSTATUS_TRANSIENT_FAILURE:
+               return "transient failure";
+       case MMS_RETRSTATUS_TRANSIENT_MESSAGE_NOT_FOUND:
+               return "transient message not found";
+       case MMS_RETRSTATUS_TRANSIENT_NETWORK_PROBLEM:
+               return "transient network problem";
+       case MMS_RETRSTATUS_PERMANENT_FAILURE:
+               return "permanent failure";
+       case MMS_RETRSTATUS_PERMANENT_SERVICE_DENIED:
+               return "permanent service denied";
+       case MMS_RETRSTATUS_PERMANENT_MESSAGE_NOT_FOUND:
+               return "permanent message not found";
+       case MMS_RETRSTATUS_PERMANENT_CONTENT_UNSUPPORT:
+               return "permanent content unsupport";
+       }
+
+       return MmsDebugPrintUnknownValue(retrieveStatus);
+}
+
+
+const char *MmsDebugGetMsgStatus(msg_delivery_report_status_t msgStatus)
+{
+       switch (msgStatus) {
+       case MSG_DELIVERY_REPORT_ERROR:
+               return "error";
+       case MSG_DELIVERY_REPORT_EXPIRED:
+               return "expired";
+       case MSG_DELIVERY_REPORT_SUCCESS:
+               return "retrieved";
+       case MSG_DELIVERY_REPORT_REJECTED:
+               return "rejected";
+       case MSG_DELIVERY_REPORT_DEFERRED:
+               return "deferred";
+       case MSG_DELIVERY_REPORT_UNRECOGNISED:
+               return "unrecognised";
+       case MSG_DELIVERY_REPORT_INDETERMINATE:
+               return "indeterminate";
+       case MSG_DELIVERY_REPORT_FORWARDED:
+               return "forwarded";
+       case MSG_DELIVERY_REPORT_UNREACHABLE:
+               return "unreachable";
+       }
+
+       return MmsDebugPrintUnknownValue(msgStatus);
+}
+
+
+const char *MmsDebugGetMsgClass(MmsMsgClass msgClass)
+{
+       switch (msgClass) {
+       case MMS_MSGCLASS_ERROR:
+               return "error";
+       case MMS_MSGCLASS_PERSONAL:
+               return "personal";
+       case MMS_MSGCLASS_ADVERTISEMENT:
+               return "advertisement";
+       case MMS_MSGCLASS_INFORMATIONAL:
+               return "information";
+       case MMS_MSGCLASS_AUTO:
+               return "auto";
+       }
+
+       return MmsDebugPrintUnknownValue(msgClass);
+}
+
+
+const char *MmsDebugGetDataType(MmsDataType dataType)
+{
+       switch (dataType) {
+       case MMS_DATATYPE_NONE:
+               return "MMS_DATATYPE_NONE";
+       case MMS_DATATYPE_READ:
+               return "MMS_DATATYPE_READ";
+       case MMS_DATATYPE_SENT:
+               return "MMS_DATATYPE_SENT";
+       case MMS_DATATYPE_NOTIFY:
+               return "MMS_DATATYPE_NOTIFY";
+       case MMS_DATATYPE_UNSENT:
+               return "MMS_DATATYPE_UNSENT";
+       case MMS_DATATYPE_DRAFT:
+               return "MMS_DATATYPE_DRAFT";
+       case MMS_DATATYPE_SENDING:
+               return "MMS_DATATYPE_SENDING";
+       case MMS_DATATYPE_DRM_RO_WAITING:
+               return "MMS_DATATYPE_DRM_RO_WAITING";
+       case MMS_DATATYPE_RETRIEVING:
+               return "MMS_DATATYPE_RETRIEVING";
+       case MMS_DATATYPE_UNRETV:
+               return "MMS_DATATYPE_UNRETV";
+       default:
+               return MmsDebugPrintUnknownValue(dataType);
+       }
+}
+
+bool MmsInitMsgType(MsgType *pMsgType)
+{
+       MSG_DEBUG("ptr : [%p]", pMsgType);
+       pMsgType->offset = 0;
+       pMsgType->size = 0;
+       pMsgType->contentSize = 0;
+       pMsgType->disposition = -1;
+       pMsgType->encoding = -1;
+       pMsgType->type = MIME_UNKNOWN;
+       pMsgType->section = -1;
+
+       pMsgType->szOrgFilePath[0] = '\0';
+       pMsgType->szContentID[0] = '\0';
+       pMsgType->szContentLocation[0] = '\0';
+
+       MmsInitMsgContentParam(&pMsgType->param);
+       MmsInitMsgDRMInfo(&pMsgType->drmInfo);
+
+       return true;
+}
+
+bool MmsInitMsgBody(MsgBody *pMsgBody)
+{
+       MSG_DEBUG("ptr : [%p]", pMsgBody);
+       pMsgBody->offset = 0;
+       pMsgBody->size = 0;
+       pMsgBody->body.pText = NULL;
+
+       MmsInitMsgType(&pMsgBody->presentationType);
+       pMsgBody->pPresentationBody = NULL;
+
+       memset(pMsgBody->szOrgFilePath, 0, MSG_FILEPATH_LEN_MAX + 1);
+
+       return true;
+}
+
+bool MmsInitMsgContentParam(MsgContentParam *pMsgContentParam)
+{
+       MSG_DEBUG("ptr : [%p]", pMsgContentParam);
+       pMsgContentParam->charset = MSG_CHARSET_UNKNOWN;
+       pMsgContentParam->type = MIME_UNKNOWN;
+       pMsgContentParam->szBoundary[0] = '\0';
+       pMsgContentParam->szFileName[0] = '\0';
+       pMsgContentParam->szName[0] = '\0';
+       pMsgContentParam->szStart[0] = '\0';
+       pMsgContentParam->szStartInfo[0] = '\0';
+       pMsgContentParam->pPresentation = NULL;
+       pMsgContentParam->reportType = MSG_PARAM_REPORT_TYPE_UNKNOWN; // only used as parameter of Content-Type: multipart/report; report-type
+#ifdef FEATURE_JAVA_MMS
+       pMsgContentParam->szApplicationID = NULL;
+       pMsgContentParam->szReplyToApplicationID = NULL;
+#endif
+       return true;
+}
+
+bool MmsInitMsgAttrib(MmsAttrib *pAttrib)
+{
+       MSG_DEBUG("MmsInitMsgAttrib");
+
+       pAttrib->bAskDeliveryReport = false;
+
+       pAttrib->bAskReadReply = false;
+       pAttrib->bRead = false;
+       pAttrib->bReportAllowed = false;
+       pAttrib->readReportAllowedType = MMS_RECEIVE_READ_REPORT_ALLOWED;
+       pAttrib->readReportSendStatus = MMS_RECEIVE_READ_REPORT_NO_SEND;
+       pAttrib->bReadReportSent = false;
+
+       pAttrib->bHideAddress = false;
+       pAttrib->date = 0;
+
+       pAttrib->deliveryTime.type = MMS_TIMETYPE_RELATIVE;
+       pAttrib->deliveryTime.time = 0;
+
+       pAttrib->expiryTime.type = MMS_TIMETYPE_RELATIVE;
+       pAttrib->expiryTime.time = 0;
+
+       memset(&pAttrib->expiryTime, 0, sizeof(MmsTimeStruct));
+       pAttrib->msgClass = MMS_MSGCLASS_PERSONAL;
+       pAttrib->msgStatus = MSG_DELIVERY_REPORT_NONE;
+       pAttrib->priority = MMS_PRIORITY_NORMAL;
+       pAttrib->responseStatus = MMS_RESPSTATUS_ERROR;
+       pAttrib->retrieveStatus = MMS_RETRSTATUS_ERROR;
+       pAttrib->contentType = MIME_UNKNOWN;
+       pAttrib->msgSize = 0;
+       pAttrib->bLeaveCopy = true;
+       pAttrib->version = MMS_VERSION;
+
+       memset(pAttrib->szFrom, 0, MSG_LOCALE_ADDR_LEN + 10);
+       memset(pAttrib->szResponseText, 0, MMS_LOCALE_RESP_TEXT_LEN + 1);
+       memset(pAttrib->szRetrieveText, 0, MMS_LOCALE_RESP_TEXT_LEN + 1);
+       memset(pAttrib->szSubject, 0, MSG_LOCALE_SUBJ_LEN + 1);
+       pAttrib->szTo = NULL;
+       pAttrib->szCc = NULL;
+       pAttrib->szBcc = NULL;
+
+       pAttrib->pMultiStatus = NULL;
+
+       pAttrib->replyCharge.chargeType = MMS_REPLY_NONE;
+       memset(&pAttrib->replyCharge.deadLine , 0, sizeof(MmsTimeStruct));
+       pAttrib->replyCharge.chargeSize = 0;
+       memset(pAttrib->replyCharge.szChargeID, 0, MMS_MSG_ID_LEN);
+
+       return true;
+}
+
+
+bool MmsInitMsgDRMInfo(MsgDRMInfo *pMsgDrmInfo)
+{
+       MSG_DEBUG("ptr : [%p]", pMsgDrmInfo);
+       pMsgDrmInfo->contentType = MIME_UNKNOWN;
+       pMsgDrmInfo->drmType = MSG_DRM_TYPE_NONE;
+
+       pMsgDrmInfo->szContentName = NULL;
+       pMsgDrmInfo->szContentURI = NULL;
+       pMsgDrmInfo->szContentDescription = NULL;
+       pMsgDrmInfo->szContentVendor = NULL;
+       pMsgDrmInfo->szRightIssuer = NULL;
+       pMsgDrmInfo->szDrm2FullPath = NULL;
+       pMsgDrmInfo->roWaitingTimerMax = 0;
+       pMsgDrmInfo->bFwdLock = false;
+       pMsgDrmInfo->bNoScreen = false;
+       pMsgDrmInfo->bNoRingTone = false;
+       pMsgDrmInfo->pszContentType = NULL;
+
+       return true;
+}
+
+void MmsReleaseMsgDRMInfo(MsgDRMInfo *pDrmInfo)
+{
+       MSG_DEBUG("_MsgFreeDRMInfo: S T A R T  !!! \n");
+
+       if (pDrmInfo == NULL) {
+               MSG_DEBUG("pDrmInfo is NULL");
+               return;
+       }
+
+       if (pDrmInfo->szContentDescription) {
+               free(pDrmInfo->szContentDescription);
+               pDrmInfo->szContentDescription = NULL;
+       }
+
+       if (pDrmInfo->szContentVendor) {
+               free(pDrmInfo->szContentVendor);
+               pDrmInfo->szContentVendor = NULL;
+       }
+
+       if (pDrmInfo->szContentName) {
+               free(pDrmInfo->szContentName);
+               pDrmInfo->szContentName = NULL;
+       }
+
+       if (pDrmInfo->szContentURI) {
+               free(pDrmInfo->szContentURI);
+               pDrmInfo->szContentURI = NULL;
+       }
+
+       if (pDrmInfo->szRightIssuer) {
+               free(pDrmInfo->szRightIssuer);
+               pDrmInfo->szRightIssuer = NULL;
+       }
+
+       if (pDrmInfo->szDrm2FullPath) {
+               free(pDrmInfo->szDrm2FullPath);
+               pDrmInfo->szDrm2FullPath = NULL;
+       }
+
+       pDrmInfo->contentType = MIME_UNKNOWN;
+       pDrmInfo->drmType = MSG_DRM_TYPE_NONE;
+}
+
+
+bool MmsReleaseMmsAttrib(MmsAttrib *pAttrib)
+{
+       MSG_BEGIN();
+
+       if (pAttrib == NULL) {
+               MSG_DEBUG("pAttrib is NULL");
+               return false;
+       }
+
+       if (pAttrib->szTo) {
+               free(pAttrib->szTo);
+               pAttrib->szTo = NULL;
+       }
+
+       if (pAttrib->szCc) {
+               free(pAttrib->szCc);
+               pAttrib->szCc = NULL;
+       }
+
+       if (pAttrib->szBcc) {
+               free(pAttrib->szBcc);
+               pAttrib->szBcc = NULL;
+       }
+
+       //check if pMultiStatus should be freed or not, because pMultiStatus is not allocated
+       if (pAttrib->pMultiStatus) {
+               MmsMsgMultiStatus *pMultiStatus = pAttrib->pMultiStatus;
+               MmsMsgMultiStatus *pCurStatus = NULL;
+
+               while (pMultiStatus != NULL ) {
+                       pCurStatus = pMultiStatus;
+                       pMultiStatus = pMultiStatus->pNext;
+
+                       if (pCurStatus) {
+                               free(pCurStatus);
+                               pCurStatus = NULL;
+                       }
+               }
+
+               pAttrib->pMultiStatus = NULL;
+       }
+
+
+       MSG_END();
+
+       return true;
+}
+
+bool MmsReleaseMsgBody(MsgBody *pBody, int type)
+{
+       MSG_BEGIN();
+
+       if (pBody == NULL) {
+               MSG_DEBUG("pBody == NULL \n" );
+               MSG_END();
+
+               return false;
+       }
+
+       switch (type) {
+       case MIME_MULTIPART_REPORT:
+       case MIME_APPLICATION_VND_OMA_DRM_MESSAGE:
+       case MIME_APPLICATION_VND_WAP_MULTIPART_MIXED:
+       case MIME_APPLICATION_VND_WAP_MULTIPART_RELATED:
+       case MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC:
+       case MIME_MULTIPART_MIXED:
+       case MIME_MULTIPART_RELATED:
+       case MIME_MULTIPART_ALTERNATIVE:
+       case MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE:
+               {
+                       MsgMultipart *pMulti = pBody->body.pMultipart;
+                       MsgMultipart *pCurrPart = NULL;
+                       MsgBody *pPresentation = pBody->pPresentationBody;
+                       while (pMulti != NULL) {
+                               pCurrPart = pMulti;
+
+                               pMulti = pMulti->pNext;
+
+                               if (pCurrPart) {
+                                       MmsReleaseMsgDRMInfo(&pCurrPart->type.drmInfo);
+
+                                       if (pCurrPart->pBody) {
+                                               if (pCurrPart->pBody->body.pText) {
+                                                       free(pCurrPart->pBody->body.pText);
+                                                       pCurrPart->pBody->body.pText = NULL;
+                                               }
+
+                                               free(pCurrPart->pBody);
+                                               pCurrPart->pBody = NULL;
+                                       }
+                                       free(pCurrPart);
+                                       pCurrPart = NULL;
+                               }
+                       }
+
+                       pBody->body.pMultipart = NULL;
+
+                       if (pPresentation) {
+                               if (pPresentation->body.pText) {
+                                       free(pPresentation->body.pText);
+                                       pPresentation->body.pText = NULL;
+                               }
+                               free(pPresentation);
+                               pBody->pPresentationBody = NULL;
+                       }
+
+                       MmsInitMsgType(&pBody->presentationType);
+
+                       break;
+               }
+
+       default:
+               /* Any single part */
+               if (pBody->body.pText) {
+                       free(pBody->body.pText);
+                       pBody->body.pText = NULL;
+               }
+
+               break;
+       }
+
+       MSG_END();
+       return true;
+}
+
+void MmsReleaseMmsMsg(MmsMsg *pMmsMsg)
+{
+       if (pMmsMsg) {
+               MmsReleaseMsgBody(&pMmsMsg->msgBody, pMmsMsg->msgType.type);
+               MmsReleaseMmsAttrib(&pMmsMsg->mmsAttrib);
+               bzero(pMmsMsg, sizeof(MmsMsg));
+       }
+}
+
+bool MmsPrintMulitpart(MsgMultipart *pMultipart, int index)
+{
+       MSG_DEBUG("------------------------------");
+       MSG_INFO("[%dth] multipart info", index);
+       MSG_INFO("header size [%d], body size [%d]", pMultipart->type.size, pMultipart->type.contentSize);
+       MSG_SEC_INFO("content type [%s]", MmsDebugGetMimeType((MimeType)pMultipart->type.type));
+       MSG_SEC_INFO("content ID [%s]", pMultipart->type.szContentID);
+       MSG_SEC_INFO("content location [%s]", pMultipart->type.szContentLocation);
+       MSG_SEC_INFO("parameter Name [%s]", pMultipart->type.param.szName);
+       MSG_SEC_INFO("parameter Filename[%s]", pMultipart->type.param.szFileName);
+
+       if (pMultipart->type.type == MIME_TEXT_PLAIN) {
+               MSG_SEC_INFO("text info : charset [%d], name [%s]", pMultipart->type.param.charset, pMultipart->type.param.szName);
+       }
+
+       if (pMultipart->type.drmInfo.drmType != MSG_DRM_TYPE_NONE) {
+               MSG_INFO("drm info");
+               MSG_INFO("drm type [%d] (0: NONE 1: Fowward Lock, 2:Combined Delivery, 3: Separated Delivery)", pMultipart->type.drmInfo.drmType);
+               MSG_SEC_INFO("drm content type [%s]", MmsDebugGetMimeType((MimeType)pMultipart->type.drmInfo.contentType));
+               MSG_SEC_INFO("drm content URI [%s]", pMultipart->type.drmInfo.szContentURI);
+               MSG_INFO("drm2FullPath [%s]", pMultipart->type.drmInfo.szDrm2FullPath);
+       }
+
+       MSG_DEBUG("------------------------------");
+       return true;
+}
+
+bool MmsIsTextType(int type)
+{
+       if (type == MIME_TEXT_PLAIN
+               || type == MIME_TEXT_HTML
+               || type == MIME_TEXT_VND_WAP_WML
+               || type == MIME_TEXT_X_VNOTE
+               || type == MIME_APPLICATION_SMIL
+               || type == MIME_TEXT_X_IMELODY)
+       {
+               return true;
+       } else {
+               return false;
+       }
+}
+
+bool MmsIsMultipart(int type)
+{
+       if (type == MIME_MULTIPART_RELATED
+               || type == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED
+               || type == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED
+               || type == MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC
+               || type == MIME_MULTIPART_MIXED
+               || type == MIME_MULTIPART_REPORT) {
+               return true;
+       } else {
+               return false;
+       }
+}
+
+bool MmsIsVitemContent(int type, char *pszName)
+{
+       switch (type) {
+       case MIME_TEXT_X_VCARD:
+       case MIME_TEXT_X_VCALENDAR:
+       case MIME_TEXT_X_VNOTE: // vnt
+       case MIME_TEXT_X_VTODO:
+       case MIME_TEXT_PLAIN:   // vbm - It SHOULD be distinguished from a normal text file.
+       {
+               char *pszExt = NULL;
+
+               if (!pszName)
+                       break;
+
+               // search file extension.
+               if ((pszExt = strrchr(pszName, '.')) == NULL)
+                       break;
+
+               if (!strcasecmp(pszExt, ".vbm")) {
+                       return true;
+               }
+
+               if (!strcasecmp(pszExt, ".vcs")) {
+                       return true;
+               }
+
+               if (!strcasecmp(pszExt, ".vcf")) {
+                       return true;
+               }
+
+               if (!strcasecmp(pszExt, ".vnt")) {
+                       return true;
+               }
+
+               if (!strcasecmp(pszExt, ".vts")) {
+                       return true;
+               }
+
+               break;
+       }
+       default:
+               break;
+       }
+
+       MSG_DEBUG("MmsIsVitemContent false.");
+       return false;
+}
+
+MsgMultipart *MmsAllocMultipart(void)
+{
+       MsgMultipart *pMultipart = NULL;
+
+       pMultipart = (MsgMultipart *)malloc(sizeof(MsgMultipart));
+
+       if (pMultipart == NULL)
+               goto __CATCH;
+
+       pMultipart->pBody = (MsgBody *)malloc(sizeof(MsgBody));
+
+       if (pMultipart->pBody == NULL)
+               goto __CATCH;
+
+       MmsInitMsgType(&pMultipart->type);
+       MmsInitMsgBody(pMultipart->pBody);
+
+       pMultipart->pNext = NULL;
+
+       return pMultipart;
+
+__CATCH:
+
+       if (pMultipart) {
+               if (pMultipart->pBody) {
+                       free(pMultipart->pBody);
+                       pMultipart->pBody = NULL;
+               }
+
+               free(pMultipart);
+               pMultipart = NULL;
+       }
+
+       return NULL;
+}
diff --git a/plugin/mms_plugin/MmsPluginComposer.cpp b/plugin/mms_plugin/MmsPluginComposer.cpp
new file mode 100755 (executable)
index 0000000..20f9c49
--- /dev/null
@@ -0,0 +1,226 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <errno.h>
+#include <sys/stat.h>
+
+#include "MsgCppTypes.h"
+#include "MsgStorageTypes.h"
+#include "MsgSettingTypes.h"
+#include "MsgUtilFile.h"
+#include "MsgGconfWrapper.h"
+#include "MsgMmsMessage.h"
+#include "MmsPluginTypes.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginMessage.h"
+#include "MmsPluginMIME.h"
+#include "MmsPluginStorage.h"
+#include "MmsPluginUtil.h"
+#include "MmsPluginTcs.h"
+#include "MsgSmil.h"
+
+
+#include "MmsPluginComposer.h"
+#include "MsgSerialize.h"
+
+bool composeSendReqHeader(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_DATA_S *pMsgData);
+
+MmsPluginComposer *MmsPluginComposer::pInstance = NULL;
+
+MmsPluginComposer *MmsPluginComposer::instance()
+{
+       if (!MmsPluginComposer::pInstance)
+               MmsPluginComposer::pInstance = new MmsPluginComposer();
+
+       return MmsPluginComposer::pInstance;
+}
+
+MmsPluginComposer::MmsPluginComposer(){}
+MmsPluginComposer::~MmsPluginComposer(){}
+
+void MmsPluginComposer::composeSendReq(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_DATA_S *pMmsData)
+{
+
+       if (pMsgInfo->msgType.subType == MSG_SENDREQ_MMS) {
+
+               if (pMmsData->header == NULL) {//send req from user
+                       pMmsData->header = MsgMmsCreateHeader();
+               }
+
+               if (pMmsData->header) {
+                       composeSendReqHeader(pMsgInfo, pSendOptInfo, pMmsData);
+                       //TODO:: apply MmsReplaceNonAsciiUtf8 to all multipart FileName;
+               }
+
+               int len = g_list_length(pMmsData->multipartlist);
+
+               for (int i = 0; i < len; i++) {
+
+                       MMS_MULTIPART_DATA_S *multipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(pMmsData->multipartlist, i);
+
+                       if (multipart) {
+                               if (multipart->type == MIME_UNKNOWN && strlen(multipart->szContentType) == 0) {
+                                       const char *content_type = NULL;
+                                       MmsGetMimeTypeFromFileName(MIME_MAINTYPE_UNKNOWN, multipart->szFileName, &multipart->type, &content_type);
+                                       snprintf(multipart->szContentType, sizeof(multipart->szContentType), "%s", content_type);
+                               }
+                       }
+               } //end for
+       }
+}
+
+MMSList *getAddressList(const MSG_MESSAGE_INFO_S *pMsgInfo, int recipientType)
+{
+       MSG_BEGIN();
+
+       MMSList * addressList = NULL;
+
+       int nAddressCnt = 0;
+
+       nAddressCnt = pMsgInfo->nAddressCnt;
+
+       // Calculate allocated buffer size
+       for (int i = 0; i < nAddressCnt; ++i) {
+
+               MSG_SEC_DEBUG("recipientType: %d, address value: %s", pMsgInfo->addressList[i].recipientType, pMsgInfo->addressList[i].addressVal);
+
+               if (pMsgInfo->addressList[i].recipientType == MSG_RECIPIENTS_TYPE_UNKNOWN)
+                       pMsgInfo->addressList[i].recipientType = MSG_RECIPIENTS_TYPE_TO;
+
+               if (pMsgInfo->addressList[i].recipientType == recipientType) {
+
+                       MMS_ADDRESS_DATA_S * pAddressData = NULL;
+                       if (pMsgInfo->addressList[i].addressType == MSG_ADDRESS_TYPE_PLMN) {
+                               pAddressData = MsgMmsCreateAddress(MSG_ADDRESS_TYPE_PLMN, pMsgInfo->addressList[i].addressVal);
+                       } else if (pMsgInfo->addressList[i].addressType == MSG_ADDRESS_TYPE_EMAIL) {
+                               pAddressData = MsgMmsCreateAddress(MSG_ADDRESS_TYPE_EMAIL, pMsgInfo->addressList[i].addressVal);
+                       } else
+                               ; // Need to consider IPV4, IPV6, and Alias formatted address
+
+                       if (pAddressData)
+                               addressList = g_list_append(addressList, pAddressData);
+               }
+       }
+
+       MSG_END();
+       return addressList;
+}
+
+bool composeSendReqHeader(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_DATA_S *pMsgData)
+{
+       MSG_BEGIN();
+
+       bool bAskDeliveryReport = false;
+       bool bAskReadReply = false;
+       MmsPriority priority;
+       MmsTimeStruct expiryTime;
+       MmsTimeStruct deliveryTime;
+       MmsMsgClass msgClass;
+
+       struct tm timeInfo;
+       time_t RawTime = 0;
+       time_t nTimeInSecs = 0;
+
+       MMS_HEADER_DATA_S *pHeaderData = pMsgData->header;
+       if (pSendOptInfo) {
+               if (pSendOptInfo->bSetting == false) {
+                       unsigned int settingTime;
+
+                       priority = (MmsPriority)MsgSettingGetInt(MMS_SEND_PRIORITY);
+
+                       settingTime = (unsigned int)MsgSettingGetInt(MMS_SEND_EXPIRY_TIME);
+                       if (settingTime == 0) {
+                               expiryTime.type = MMS_TIMETYPE_NONE;
+                               expiryTime.time = 0;
+                       } else {
+                               expiryTime.type = MMS_TIMETYPE_RELATIVE;
+                               expiryTime.time = settingTime;
+                       }
+
+                       settingTime = (unsigned int)MsgSettingGetInt(MMS_SEND_DELIVERY_TIME);
+                       if (settingTime == 0) {
+                               deliveryTime.type = MMS_TIMETYPE_NONE;
+                               deliveryTime.time = 0;
+                       } else {
+                               deliveryTime.type = MMS_TIMETYPE_RELATIVE;
+                               deliveryTime.time = (unsigned int)settingTime;
+                       }
+
+                       MsgSettingGetBool(MMS_SEND_DELIVERY_REPORT, &bAskDeliveryReport);
+                       MsgSettingGetBool(MMS_SEND_READ_REPLY, &bAskReadReply);
+               } else {
+                       priority = (MmsPriority)pSendOptInfo->option.mmsSendOptInfo.priority;
+
+                       expiryTime.type = pSendOptInfo->option.mmsSendOptInfo.expiryTime.type;
+                       expiryTime.time = pSendOptInfo->option.mmsSendOptInfo.expiryTime.time;
+
+                       deliveryTime.type = pSendOptInfo->option.mmsSendOptInfo.deliveryTime.type;
+                       deliveryTime.time = pSendOptInfo->option.mmsSendOptInfo.deliveryTime.time;
+
+                       bAskDeliveryReport = pSendOptInfo->bDeliverReq;
+                       bAskReadReply = pSendOptInfo->option.mmsSendOptInfo.bReadReq;
+               }
+
+               msgClass = (MmsMsgClass)MsgSettingGetInt(MMS_SEND_MSG_CLASS);
+
+               //set Header
+               time(&RawTime);
+               localtime_r(&RawTime, &timeInfo);
+               nTimeInSecs = mktime(&timeInfo);
+
+               pHeaderData->date = nTimeInSecs;
+
+               pHeaderData->bDeliveryReport = bAskDeliveryReport;
+               pHeaderData->delivery.type = deliveryTime.type;
+               pHeaderData->delivery.time = deliveryTime.time;
+
+               pHeaderData->expiry.type = expiryTime.type;
+               pHeaderData->expiry.time = expiryTime.time;
+
+               pHeaderData->messageClass = msgClass;
+               pHeaderData->messageType = MMS_MSGTYPE_SEND_REQ;
+               pHeaderData->mmsVersion = MMS_VERSION;
+               pHeaderData->mmsPriority = priority;
+               pHeaderData->bReadReport = bAskReadReply;
+               pHeaderData->bHideAddress = false;
+       }
+
+       if (pMsgData->smil) {
+               pHeaderData->contentType = MIME_APPLICATION_VND_WAP_MULTIPART_RELATED;
+       } else {
+               pHeaderData->contentType = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED;
+       }
+
+       char *content_type = MimeGetMimeStringFromMimeInt(pHeaderData->contentType);
+       if (content_type) {
+               snprintf(pHeaderData->szContentType, sizeof(pHeaderData->szContentType), "%s", content_type);
+       }
+
+       snprintf(pHeaderData->szSubject, sizeof(pHeaderData->szSubject), "%s", pMsgInfo->subject);
+
+       //setting adddress
+       pHeaderData->to = getAddressList(pMsgInfo, MSG_RECIPIENTS_TYPE_TO);
+       pHeaderData->cc = getAddressList(pMsgInfo, MSG_RECIPIENTS_TYPE_CC);
+       pHeaderData->bcc = getAddressList(pMsgInfo, MSG_RECIPIENTS_TYPE_BCC);
+
+       //snprintf(pHeaderData->szFrom, sizeof(pHeaderData->szFrom), "%s", pMmsMsg->mmsAttrib.szFrom);
+
+       return true;
+}
index d45e5b1..bb02aa6 100755 (executable)
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
+#include <errno.h>
+#include <glib.h>
 #include "MmsPluginConnManWrapper.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginHttp.h"
+#include "net_connection.h"
+#include "MmsPluginUtil.h"
 
-void network_print_profile(net_profile_info_t *ProfInfo)
+#define MMS_CONTEXT_INVOKE_WAIT_TIME   30
+#define MMS_CONNECTION_API_WAIT_TIME   420
+
+static Mutex g_mx;
+static CndVar g_cv;
+static connection_h g_connection = NULL;
+static connection_profile_h g_profile = NULL;
+
+void __connection_profile_print(connection_profile_h profile)
 {
-       int di = 0;
-
-       unsigned char *ipaddr;
-       unsigned char *netmaskaddr;
-       unsigned char *gwaddr;
-       net_dev_info_t *net_info;
-
-       if (ProfInfo->profile_type == NET_DEVICE_CELLULAR) {
-               ipaddr = (unsigned char *)&ProfInfo->ProfileInfo.Pdp.net_info.IpAddr.Data.Ipv4.s_addr;
-               netmaskaddr = (unsigned char *)&ProfInfo->ProfileInfo.Pdp.net_info.SubnetMask.Data.Ipv4.s_addr;
-               gwaddr = (unsigned char *)&ProfInfo->ProfileInfo.Pdp.net_info.GatewayAddr.Data.Ipv4.s_addr;
-               net_info = &(ProfInfo->ProfileInfo.Pdp.net_info);
+       int ret;
+       char *profile_id = NULL;
+       char *profile_name = NULL;
+       char *interface_name = NULL;
+       char *ip_address = NULL;
+       char *subnet_mask = NULL;
+       char *gateway_address = NULL;
+       char *dns_address = NULL;
+       char *proxy_address = NULL;
+       char *apn = NULL;
+       char *user_name = NULL;
+       char *password = NULL;
+       char *home_url = NULL;
+       bool is_roaming;
+
+       connection_profile_type_e profile_type;
+       connection_profile_state_e profile_state;
+       connection_ip_config_type_e ip_type = CONNECTION_IP_CONFIG_TYPE_NONE;
+       connection_proxy_type_e proxy_type;
+       connection_cellular_service_type_e service_type = CONNECTION_CELLULAR_SERVICE_TYPE_UNKNOWN;
+       connection_cellular_auth_type_e auth_type = CONNECTION_CELLULAR_AUTH_TYPE_NONE;
+
+       MSG_DEBUG("**************************************************************************************************");
+       ret = connection_profile_get_id(profile, &profile_id);
+       MSG_DEBUG("return value of connection_profile_get_id [%d]", ret);
+       MSG_SEC_INFO("Profile Id = [%s]", profile_id);
+
+       ret = connection_profile_get_name(profile, &profile_name);
+       MSG_SEC_INFO("Profile Name = [%s]", profile_name);
+
+       ret = connection_profile_get_type(profile, &profile_type);
+
+       if (profile_type == CONNECTION_PROFILE_TYPE_CELLULAR) {
+               MSG_SEC_INFO("Profile Type = [CELLULAR]");
+       } else if (profile_type == CONNECTION_PROFILE_TYPE_WIFI) {
+               MSG_SEC_INFO("Profile Type = [WIFI]");
+       } else if (profile_type == CONNECTION_PROFILE_TYPE_ETHERNET) {
+               MSG_SEC_INFO("Profile Type = [ETHERNET]");
+       } else if (profile_type == CONNECTION_PROFILE_TYPE_BT) {
+               MSG_SEC_INFO("Profile Type = [BT]");
        } else {
-               MSG_DEBUG("Error!!! Invalid profile type\n");
-               return;
+               MSG_SEC_INFO("Profile Type = Unknown [%d]", profile_type);
        }
 
-       MSG_DEBUG("**************************************************************************************************");
+       ret = connection_profile_get_network_interface_name(profile, &interface_name);
+       MSG_SEC_INFO("Profile Interface Name = [%s]", interface_name);
+
+       ret = connection_profile_get_state(profile, &profile_state);
+       if (profile_state == CONNECTION_PROFILE_STATE_DISCONNECTED) {
+               MSG_SEC_INFO("Profile State = [DISCONNECTED]");
+       } else if (profile_state == CONNECTION_PROFILE_STATE_ASSOCIATION) {
+               MSG_SEC_INFO("Profile State = [ASSOCIATION]");
+       } else if (profile_state == CONNECTION_PROFILE_STATE_CONFIGURATION) {
+               MSG_SEC_INFO("Profile State = [CONFIGURATION]");
+       } else if (profile_state == CONNECTION_PROFILE_STATE_CONNECTED) {
+               MSG_SEC_INFO("Profile State = [CONNECTED]");
+       } else {
+               MSG_SEC_INFO("Profile State = Unknown [%d]", profile_state);
+       }
 
-       MSG_DEBUG("Profile Name = [%s]\n", ProfInfo->ProfileName);
-
-       if (ProfInfo->ProfileState == NET_STATE_TYPE_IDLE)
-               MSG_DEBUG("Profile State = [idle]\n");
-       else if (ProfInfo->ProfileState == NET_STATE_TYPE_FAILURE)
-               MSG_DEBUG("Profile State = [failure]\n");
-       else if (ProfInfo->ProfileState == NET_STATE_TYPE_ASSOCIATION)
-               MSG_DEBUG("Profile State = [association]\n");
-       else if (ProfInfo->ProfileState == NET_STATE_TYPE_CONFIGURATION)
-               MSG_DEBUG("Profile State = [configuration]\n");
-       else if (ProfInfo->ProfileState == NET_STATE_TYPE_READY)
-               MSG_DEBUG("Profile State = [ready]\n");
-       else if (ProfInfo->ProfileState == NET_STATE_TYPE_ONLINE)
-               MSG_DEBUG("Profile State = [online]\n");
-       else if (ProfInfo->ProfileState == NET_STATE_TYPE_DISCONNECT)
-               MSG_DEBUG("Profile State = [disconnect]\n");
-       else
-               MSG_DEBUG("Profile State = [unknown]\n");
+       ret = connection_profile_get_ip_config_type(profile, CONNECTION_ADDRESS_FAMILY_IPV4, &ip_type);
+       MSG_SEC_INFO("Profile Ip Config Type = [%d]", ip_type);
 
-               MSG_DEBUG("Profile Type = [pdp]\n");
+       ret = connection_profile_get_ip_address(profile, CONNECTION_ADDRESS_FAMILY_IPV4, &ip_address);
+       MSG_SEC_INFO("Profile Ip Address = [%s]", ip_address);
 
-       if (ProfInfo->ProfileInfo.Pdp.ProtocolType == NET_PDP_TYPE_GPRS)
-               MSG_DEBUG("Profile Protocol Type = [GPRS]\n");
-       else if (ProfInfo->ProfileInfo.Pdp.ProtocolType == NET_PDP_TYPE_EDGE)
-               MSG_DEBUG("Profile Protocol Type = [EDGE]\n");
-       else if (ProfInfo->ProfileInfo.Pdp.ProtocolType == NET_PDP_TYPE_UMTS)
-               MSG_DEBUG("Profile Protocol Type = [UMTS]\n");
-       else
-               MSG_DEBUG("Profile Protocol Type = [NONE]\n");
+       ret = connection_profile_get_subnet_mask(profile, CONNECTION_ADDRESS_FAMILY_IPV4, &subnet_mask);
+       MSG_SEC_INFO("Profile Subnet Mask = [%s]", subnet_mask);
 
-       MSG_DEBUG("Profile APN = [%s]\n", ProfInfo->ProfileInfo.Pdp.Apn);
+       ret = connection_profile_get_gateway_address(profile, CONNECTION_ADDRESS_FAMILY_IPV4, &gateway_address);
+       MSG_SEC_INFO("Profile Gateway Address = [%s]", gateway_address);
 
-       if (ProfInfo->ProfileInfo.Pdp.AuthInfo.AuthType == NET_PDP_AUTH_PAP)
-               MSG_DEBUG("Profile Auth Type = [PAP]\n");
-       else if (ProfInfo->ProfileInfo.Pdp.AuthInfo.AuthType == NET_PDP_AUTH_CHAP)
-               MSG_DEBUG("Profile Auth Type = [CHAP]\n");
-       else
-               MSG_DEBUG("Profile Auth Type = [NONE]\n");
-
-       MSG_DEBUG("Profile Auth UserName = [%s]\n", ProfInfo->ProfileInfo.Pdp.AuthInfo.UserName);
-       MSG_DEBUG("Profile Auth Password = [%s]\n", ProfInfo->ProfileInfo.Pdp.AuthInfo.Password);
-       MSG_DEBUG("Profile Home URL = [%s]\n", ProfInfo->ProfileInfo.Pdp.HomeURL);
-       MSG_DEBUG("Profile MCC = [%s]\n", ProfInfo->ProfileInfo.Pdp.Mcc);
-       MSG_DEBUG("Profile MNC = [%s]\n", ProfInfo->ProfileInfo.Pdp.Mnc);
-       MSG_DEBUG("Profile Roaming = [%d]\n", (int)ProfInfo->ProfileInfo.Pdp.Roaming);
-       MSG_DEBUG("Profile Setup Required = [%d]\n", (int)ProfInfo->ProfileInfo.Pdp.SetupRequired);
-       MSG_DEBUG("Profile Favourite = [%d]\n", (int)ProfInfo->Favourite);
-       MSG_DEBUG("Profile Device Name = [%s]\n", net_info->DevName);
-       MSG_DEBUG("Profile DNS Count = [%d]\n", net_info->DnsCount);
-       for (di = 0; di < net_info->DnsCount; di++) {
-               unsigned char *dns = (unsigned char *)&net_info->DnsAddr[di].Data.Ipv4.s_addr;
-               MSG_DEBUG("Profile DNS Address %d = [%d.%d.%d.%d]\n", di+1, dns[0], dns[1], dns[2], dns[3]);
+       ret = connection_profile_get_dns_address(profile, 1, CONNECTION_ADDRESS_FAMILY_IPV4, &dns_address);
+       MSG_SEC_INFO("Profile Dns Address = [%s]", dns_address);
+
+       ret = connection_profile_get_proxy_type(profile, &proxy_type);
+       MSG_SEC_INFO("Profile Proxy Type = [%d]", proxy_type);
+
+       ret = connection_profile_get_proxy_address(profile, CONNECTION_ADDRESS_FAMILY_IPV4, &proxy_address);
+       MSG_SEC_INFO("Profile Proxy Address = [%s]", proxy_address);
+
+       ret = connection_profile_get_cellular_service_type(profile, &service_type);
+       if (service_type == CONNECTION_CELLULAR_SERVICE_TYPE_INTERNET) {
+               MSG_SEC_INFO("Profile Service Type = [INTERNET]");
+       } else if (service_type == CONNECTION_CELLULAR_SERVICE_TYPE_MMS) {
+               MSG_SEC_INFO("Profile Service Type = [MMS]");
+       } else if (service_type == CONNECTION_CELLULAR_SERVICE_TYPE_PREPAID_INTERNET) {
+               MSG_SEC_INFO("Profile Service Type = [PREPAID_INTERNET]");
+       } else if (service_type == CONNECTION_CELLULAR_SERVICE_TYPE_PREPAID_MMS) {
+               MSG_SEC_INFO("Profile Service Type = [PREPAID_MMS]");
+       } else if (service_type == CONNECTION_CELLULAR_SERVICE_TYPE_TETHERING) {
+               MSG_SEC_INFO("Profile Service Type = [TETHERING]");
+       } else if (service_type == CONNECTION_CELLULAR_SERVICE_TYPE_APPLICATION) {
+               MSG_SEC_INFO("Profile Service Type = [APPLICATION]");
+       } else {
+               MSG_SEC_INFO("Profile Service Type = [Unknown][%d]", service_type);
        }
 
-       if (net_info->IpConfigType == NET_IP_CONFIG_TYPE_DYNAMIC)
-               MSG_DEBUG("Profile IPv4 Method = [NET_IP_CONFIG_TYPE_DYNAMIC]\n");
-       else if (net_info->IpConfigType == NET_IP_CONFIG_TYPE_STATIC)
-               MSG_DEBUG("Profile IPv4 Method = [NET_IP_CONFIG_TYPE_STATIC]\n");
-       else if (net_info->IpConfigType == NET_IP_CONFIG_TYPE_FIXED)
-               MSG_DEBUG("Profile IPv4 Method = [NET_IP_CONFIG_TYPE_FIXED]\n");
-       else if (net_info->IpConfigType == NET_IP_CONFIG_TYPE_OFF)
-               MSG_DEBUG("Profile IPv4 Method = [NET_IP_CONFIG_TYPE_OFF]\n");
+       ret = connection_profile_get_cellular_apn(profile, &apn);
+       MSG_SEC_INFO("Profile Apn = [%s]", apn);
+
+       ret = connection_profile_get_cellular_auth_info(profile, &auth_type, &user_name, &password);
+       MSG_SEC_INFO("Profile Auth Type = [%d]", &auth_type);
+       MSG_SEC_INFO("Profile Auth Name = [%s]", &user_name);
+       MSG_SEC_INFO("Profile Auth Passward = [%s]", &password);
+
+       ret = connection_profile_get_cellular_home_url(profile, &home_url);
+       MSG_SEC_INFO("Profile Home Url = [%s]", home_url);
+
+       ret = connection_profile_is_cellular_roaming(profile, &is_roaming);
+       MSG_SEC_INFO("Profile Roaming = [%d]", is_roaming);
+       MSG_DEBUG("**************************************************************************************************");
+
+       MSG_FREE(profile_id);
+       MSG_FREE(profile_name);
+       MSG_FREE(interface_name);
+       MSG_FREE(ip_address);
+       MSG_FREE(subnet_mask);
+       MSG_FREE(gateway_address);
+       MSG_FREE(dns_address);
+       MSG_FREE(proxy_address);
+       MSG_FREE(apn);
+       MSG_FREE(user_name);
+       MSG_FREE(password);
+       MSG_FREE(home_url);
+}
+
+static void __connection_type_changed_cb(connection_type_e type, void* user_data)
+{
+       MSG_INFO("Type changed callback, connection type : %d", type);
+}
+
+static void __connection_ip_changed_cb(const char* ipv4_address, const char* ipv6_address, void* user_data)
+{
+       MSG_INFO("IP changed callback, IPv4 address : %s, IPv6 address : %s",
+                       ipv4_address, (ipv6_address ? ipv6_address : "NULL"));
+}
+
+static void __connection_proxy_changed_cb(const char* ipv4_address, const char* ipv6_address, void* user_data)
+{
+       MSG_INFO("Proxy changed callback, IPv4 address : %s, IPv6 address : %s",
+                       ipv4_address, (ipv6_address ? ipv6_address : "NULL"));
+}
+
+static void __connection_profile_opened_cb(connection_error_e result, void* user_data)
+{
+       if (result == CONNECTION_ERROR_NONE || result == CONNECTION_ERROR_ALREADY_EXISTS)
+               MSG_INFO("Connection open Succeeded [%d]", result);
        else
-               MSG_DEBUG("Profile IPv4 Method = [UNKNOWN]\n");
-
-       MSG_DEBUG("Profile IP Address = [%d.%d.%d.%d]\n", ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]);
-       MSG_DEBUG("Profile Netmask = [%d.%d.%d.%d]\n", netmaskaddr[0], netmaskaddr[1], netmaskaddr[2], netmaskaddr[3]);
-       MSG_DEBUG("Profile Gateway = [%d.%d.%d.%d]\n", gwaddr[0], gwaddr[1], gwaddr[2], gwaddr[3]);
-
-       if (net_info->ProxyMethod == NET_PROXY_TYPE_DIRECT)
-               MSG_DEBUG("Proxy Method = [direct]\n");
-       else if (net_info->ProxyMethod == NET_PROXY_TYPE_AUTO)
-               MSG_DEBUG("Proxy Method = [auto]\n");
-       else if (net_info->ProxyMethod == NET_PROXY_TYPE_MANUAL)
-               MSG_DEBUG("Proxy Method = [manual]\n");
+               MSG_ERR("Connection open Failed, err : %d", result);
+
+       MmsPluginCmAgent *cmAgent = MmsPluginCmAgent::instance();
+
+       cmAgent->connection_profile_open_callback(result, user_data);
+}
+
+static void __connection_profile_closed_cb(connection_error_e result, void* user_data)
+{
+       if (result ==  CONNECTION_ERROR_NONE)
+               MSG_INFO("Connection close Succeeded");
        else
-               MSG_DEBUG("Proxy Method = [unknown]\n");
+               MSG_ERR("Connection close Failed, err : %d", result);
 
-       MSG_DEBUG("Profile Proxy = [%s]\n", net_info->ProxyAddr);
+       MmsPluginCmAgent *cmAgent = MmsPluginCmAgent::instance();
 
-       MSG_DEBUG("**************************************************************************************************");
+       cmAgent->connection_profile_close_callback(result, user_data);
 }
 
 
+void __connection_profile_state_changed_cb(connection_profile_state_e state, void* user_data)
+{
+       MmsPluginCmAgent *cmAgent = MmsPluginCmAgent::instance();
+
+       cmAgent->connection_profile_state_changed_cb(state, user_data);
+
+}
 
-void network_evt_cb (net_event_info_t *event_cb, void *user_data)
+static gboolean __connection_create(void *pVoid)
 {
        MSG_BEGIN();
 
-       MmsPluginCmAgent::instance()->processCBdatas(event_cb, user_data);
+       bool ret = false;
+       bool *ret_val = (bool *)pVoid;
+
+       if (g_connection) {
+               MSG_INFO("connection already exist");
+               ret = true;
+       } else {
+               int err = connection_create(&g_connection);
+
+               if (CONNECTION_ERROR_NONE == err) {
+
+                       connection_cellular_state_e cellular_state;
+                       connection_type_e net_state;
+
+                       err = connection_get_cellular_state(g_connection, &cellular_state);
+
+                       err = connection_get_type(g_connection, &net_state);
+
+                       if (cellular_state == CONNECTION_CELLULAR_STATE_AVAILABLE
+                               || cellular_state == CONNECTION_CELLULAR_STATE_CONNECTED) {
+
+                               MSG_INFO("Client registration success [%p], cellular_state [%d], net_state [%d]", g_connection, cellular_state, net_state);
+
+                               err = connection_set_type_changed_cb(g_connection, __connection_type_changed_cb, NULL);
+
+                               err = connection_set_ip_address_changed_cb(g_connection, __connection_ip_changed_cb, NULL);
+
+                               err = connection_set_proxy_address_changed_cb(g_connection, __connection_proxy_changed_cb, NULL);
+
+                               ret = true;
+                       } else {
+
+                               MSG_INFO("Client registration Failed,  cellular state [%d], net_state [%d]", cellular_state, net_state);
+                               connection_destroy(g_connection);
+                               g_connection = NULL;
+                       }
+
+               } else {
+                       MSG_WARN("Client registration failed %d", err);
+               }
+       }
+
+       if (ret_val) {
+               *ret_val = ret;
+       }
 
        MSG_END();
+       return FALSE;
 }
 
+static gboolean __connection_destroy(void *pVoid)
+{
+       MSG_BEGIN();
 
-MmsPluginCmAgent *MmsPluginCmAgent::pInstance = NULL;
+       int rv;
 
-MmsPluginCmAgent *MmsPluginCmAgent::instance()
+       if (g_connection != NULL) {
+               rv = connection_destroy(g_connection);
+               g_connection = NULL;
+               MSG_INFO("connection destory !!");
+       } else {
+               MSG_ERR("Cannot connection destroy : Handle is NULL");
+               rv = CONNECTION_ERROR_INVALID_OPERATION;
+       }
+
+       MSG_DEBUG("return value of connection destroy [%d]", rv);
+
+       MSG_END();
+       return FALSE;
+}
+
+static gboolean __connection_profile_open(void *pVoid)
 {
-       if (!pInstance)
-               pInstance = new MmsPluginCmAgent();
+       MSG_BEGIN();
 
-       return pInstance;
+       int netOpenResult = MSG_CM_ERR_NONE;
+       int *ret_val = (int *)pVoid;
+       int err;
+
+       if (g_profile) {
+               MSG_WARN("connection profile Already exist!!, It will destroy");
+               connection_profile_unset_state_changed_cb(g_profile);
+               connection_profile_destroy(g_profile);
+               g_profile = NULL;
+       }
+
+       err = connection_get_default_cellular_service_profile(g_connection, CONNECTION_CELLULAR_SERVICE_TYPE_MMS, &g_profile);
+
+       if (err != CONNECTION_ERROR_NONE) {
+               MSG_ERR("connection_get_default_cellular_service_profile Failed!! [%d]", err);
+               netOpenResult = MSG_CM_ERR_UNKNOWN;
+       } else {
+
+               err = connection_profile_set_state_changed_cb(g_profile, __connection_profile_state_changed_cb, g_profile);
+
+               if (connection_open_profile(g_connection, g_profile, __connection_profile_opened_cb, NULL) != CONNECTION_ERROR_NONE) {
+                       MSG_ERR("Connection open Failed!!");
+                       netOpenResult = MSG_CM_ERR_UNKNOWN;
+               }
+
+
+       }
+
+       if (ret_val) {
+               *ret_val = netOpenResult;
+               MSG_DEBUG("[%d]", netOpenResult);
+       }
+
+       MSG_END();
+
+       return FALSE;
 }
 
-MmsPluginCmAgent::MmsPluginCmAgent()
+static gboolean __connection_profile_close(void *pVoid)
 {
        MSG_BEGIN();
 
-       isCmOpened = false;
-       bzero(&mmsProfile, sizeof (net_profile_info_t));
+       int netOpenResult = MSG_CM_ERR_NONE;
+
+       int *ret_val = (int *)pVoid;
+
+       if (g_profile) {
+               connection_profile_unset_state_changed_cb(g_profile);
+
+               if (connection_close_profile(g_connection, g_profile, __connection_profile_closed_cb, NULL) != CONNECTION_ERROR_NONE) {
+                       MSG_ERR("Connection close Failed!!");
+                       netOpenResult = MSG_CM_ERR_UNKNOWN;
+               }
+
+               connection_profile_destroy(g_profile);
+               g_profile = NULL;
+       }
+
+       if (ret_val) {
+               *ret_val = netOpenResult;
+       }
 
        MSG_END();
+
+       return FALSE;
 }
 
-MmsPluginCmAgent::~MmsPluginCmAgent()
+
+void context_invoke_end_cb(gpointer data)
 {
+       g_mx.lock();
 
+       MSG_INFO("@@ SIGNAL @@");
+
+       g_cv.signal();
+
+       g_mx.unlock();
 }
 
-bool MmsPluginCmAgent::registration()
+/*
+ * Network api should run at g_main_loop to receive callback
+ * */
+void context_invoke(GSourceFunc func, void *ret)
 {
        MSG_BEGIN();
 
-       bool registResult = true;
+       int time_ret = 0;
 
-       if (net_register_client((net_event_cb_t) network_evt_cb, NULL) != NET_ERR_NONE) {
-               MSG_DEBUG("Error!! net_register_client() failed.\n");
-               registResult = false;
+       g_mx.lock();
+
+       g_main_context_invoke_full(NULL, G_PRIORITY_DEFAULT, func, ret,  context_invoke_end_cb);
+
+       MSG_INFO("@@ WAIT @@");
+
+       time_ret = g_cv.timedwait(g_mx.pMutex(), MMS_CONTEXT_INVOKE_WAIT_TIME);
+
+       g_mx.unlock();
+
+       if (time_ret == ETIMEDOUT) {
+               MSG_INFO("@@ WAKE by timeout@@");
+       } else {
+               MSG_INFO("@@ WAKE by signal@@");
        }
 
        MSG_END();
+}
 
-       return registResult;
+MmsPluginCmAgent *MmsPluginCmAgent::pInstance = NULL;
+
+MmsPluginCmAgent *MmsPluginCmAgent::instance()
+{
+       if (!pInstance)
+               pInstance = new MmsPluginCmAgent();
+
+       return pInstance;
+}
+
+MmsPluginCmAgent::MmsPluginCmAgent()
+{
+       MSG_BEGIN();
+
+       isCmOpened = false;
+       waitProfileOpen = false;
+
+       home_url = NULL;
+       interface_name = NULL;
+       proxy_address = NULL;
+       MSG_END();
+}
+
+MmsPluginCmAgent::~MmsPluginCmAgent()
+{
+       MSG_FREE(home_url);
+       MSG_FREE(interface_name);
+       MSG_FREE(proxy_address);
 }
 
 bool MmsPluginCmAgent::open()
 {
        MSG_BEGIN();
 
-       if (!isCmOpened) {
-               if (!registration())
-                       return false;
+       int netOpenResult = MSG_CM_ERR_NONE;
+       int bConnection = false;
+       int time_ret = 0;
+       lock();
 
-               int netOpenResult = NET_ERR_NONE;
-               net_service_type_t service_type = NET_SERVICE_MMS;
+       //create connection
+       context_invoke(__connection_create, &bConnection);
 
-               netOpenResult = net_open_connection_with_preference(service_type);
-               if (netOpenResult != NET_ERR_NONE) {
-                       MSG_DEBUG("Error!! net_open_connection_with_profile() failed. [%d]", netOpenResult);
-                       deregistration();
-                       return false;
-               }
+       if (bConnection == false || g_connection == NULL) {
+               MSG_ERR("Failed __connection_create");
+               goto __ERR_RETURN;
+       }
 
-               MSG_DEBUG("WAITING UNTIL Network Connection Open.");
+       if (g_profile) {
+               MSG_WARN("connection profile already exist");
+               //TODO:: get data;
+               //goto __RETURN;
+       }
 
-               lock();
+       waitProfileOpen = true;
 
-               int time_ret = 0;
-               time_ret = cv.timedwait(mx.pMutex(), 50);
+       context_invoke(__connection_profile_open, &netOpenResult);
 
-               unlock();
+       if (netOpenResult != MSG_CM_ERR_NONE) {
+               MSG_ERR("Failed __connection_profile_open. [%d]", netOpenResult);
+               goto __ERR_RETURN;
+       }
 
-               if (time_ret == ETIMEDOUT) {
-                       MSG_DEBUG("Network Connection Open Time Out.");
-                       deregistration();
-                       return false;
-               } else {
-                       if(!isCmOpened) {
-                               MSG_DEBUG("Network connection open failed");
-                               deregistration();
-                               return false;
-                       }
-               }
+       MSG_INFO("## WAITING UNTIL __connection_profile_state CONNECT. ##");
+
+//     cv.wait(mx.pMutex());
+//     MSG_INFO("## WAKE by SIGNAL ##");
+
+       time_ret = cv.timedwait(mx.pMutex(), MMS_CONNECTION_API_WAIT_TIME); // isCmOpened will changed by processCBdatas
+
+       if (time_ret == ETIMEDOUT) {
+               MSG_WARN("## WAKE by timeout ##");
        } else {
-               MSG_DEBUG("Network is already opened.");
-               return false;
+               MSG_INFO("## WAKE by SIGNAL ##");
        }
 
+       if(isCmOpened == false) {
+               MSG_WARN("");
+               goto __ERR_RETURN;
+       }
+
+//__RETURN:
+       unlock();
        MSG_END();
+       return isCmOpened;
 
+__ERR_RETURN:
+       context_invoke(__connection_profile_close, NULL);
+       context_invoke( __connection_destroy, NULL);
+       unlock();
+       MSG_END();
        return isCmOpened;
 }
 
@@ -226,222 +493,255 @@ void MmsPluginCmAgent::close()
 {
        MSG_BEGIN();
 
-       if (isCmOpened) {
-               int netOpenResult = NET_ERR_NONE;
+       lock();
 
-               netOpenResult = net_close_connection(mmsProfile.ProfileName);
-               if (netOpenResult != NET_ERR_NONE) {
-                       MSG_DEBUG("Error!! net_close_connection() failed.\n");
-                       deregistration();
-                       return;
-               }
+       int netOpenResult = MSG_CM_ERR_NONE;
+       int time_ret = 0;
 
-               MSG_DEBUG("WAITING UNTIL Network Connection Close.");
+       isCmOpened = false;
 
-               lock();
+       if (g_profile == NULL) {
+               MSG_INFO("connection profile is NULL");
+               goto __RETURN;
+       }
 
-               int time_ret = 0;
-               time_ret = cv.timedwait(mx.pMutex(), 50);
+       context_invoke(__connection_profile_close, &netOpenResult);
 
-               unlock();
+       if (netOpenResult != MSG_CM_ERR_NONE) {
+               MSG_ERR("Failed __connection_profile_close. [%d]", netOpenResult);
+               goto __RETURN;
+       }
 
-               if (time_ret == ETIMEDOUT) {
-                       MSG_DEBUG("Network Connection Close Timed Out.");
-               }
+       MSG_INFO("## WAITING UNTIL connection_profile_close_callback ##");
+
+       time_ret = cv.timedwait(mx.pMutex(), MMS_CONNECTION_API_WAIT_TIME);
 
-               deregistration();
+       if (time_ret == ETIMEDOUT) {
+               MSG_WARN("## WAKE by timeout ##");
        } else {
-               MSG_DEBUG ("Network Connection is not opened.");
-               return;
+               MSG_INFO("## WAKE by SIGNAL ##");
        }
-}
 
 
-void MmsPluginCmAgent::deregistration()
-{
-       MSG_BEGIN();
+__RETURN:
+       if (g_connection)
+               context_invoke(__connection_destroy, NULL);
 
-       int netOpenResult = NET_ERR_NONE;
+       g_profile = NULL;
+       g_connection = NULL;
 
-       netOpenResult = net_deregister_client();
-       if (netOpenResult != NET_ERR_NONE)
-               MSG_DEBUG("Error!! net_deregister_client() failed. [%d]", netOpenResult);
-       else
-               MSG_DEBUG ("net_deregister_client() Success.");
+       MSG_FREE(this->home_url);
+       MSG_FREE(this->interface_name);
+       MSG_FREE(this->proxy_address);
+
+       unlock();
 
        MSG_END();
 }
 
-
-void MmsPluginCmAgent::processCBdatas(net_event_info_t *event_cb, void *user_data)
+//profile open callback
+void MmsPluginCmAgent::connection_profile_open_callback(connection_error_e result, void* user_data)
 {
-       MSG_BEGIN();
+       lock();
 
-       net_dev_info_t *dev_info = NULL;
-       net_profile_info_t *prof_info = NULL;
-
-       switch (event_cb->Event) {
-       case NET_EVENT_NET_CONFIGURE_RSP:
-               MSG_DEBUG("Received Network Configuration response: %d \n", event_cb->Error);
-               dev_info = (net_dev_info_t *)event_cb->Data;
-
-               /*Successful PDP Activation*/
-               if (event_cb->Error == NET_ERR_NONE) {
-                       char *ip = (char *)&dev_info->IpAddr.Data.Ipv4;
-                       char *netmask = (char *)&dev_info->SubnetMask.Data.Ipv4;
-                       char *gateway = (char *)&dev_info->GatewayAddr.Data.Ipv4;
-                       char *dns1 = (char *)&dev_info->DnsAddr[0].Data.Ipv4.s_addr;
-                       char *dns2 = (char *)&dev_info->DnsAddr[1].Data.Ipv4.s_addr;
-
-                       MSG_DEBUG("= IP address [%d.%d.%d.%d]\n",
-                                       (int)ip[0], ip[1], ip[2], ip[3]);
-                       MSG_DEBUG("= Netmask [%d.%d.%d.%d]\n",
-                                       (int)netmask[0], netmask[1], netmask[2], netmask[3]);
-                       MSG_DEBUG("= Gateway [%d.%d.%d.%d]\n",
-                                       (int)gateway[0], gateway[1], gateway[2], gateway[3]);
-                       MSG_DEBUG("= DNS address [%d.%d.%d.%d]\n",
-                                       (int)dns1[0], dns1[1], dns1[2], dns1[3]);
-                       MSG_DEBUG("= DNS2 address [%d.%d.%d.%d]\n",
-                                       (int)dns2[0], dns2[1], dns2[2], dns2[3]);
-                       MSG_DEBUG("= Device name [%s]\n", dev_info->DevName);
-                       MSG_DEBUG("= Profile name [%s]\n", dev_info->ProfileName);
-               } else {
-                       MSG_DEBUG("Error!!! Network Configuration Failed %d \n", event_cb->Error);
+       connection_cellular_state_e state;
+       connection_profile_h profile = NULL;
+       connection_profile_state_e  profile_state;
+       int err = CONNECTION_ERROR_NONE;
+
+       if (result == CONNECTION_ERROR_NONE || result == CONNECTION_ERROR_ALREADY_EXISTS) {
+
+               err = connection_get_cellular_state(g_connection, &state);
+
+               MSG_INFO("connection_get_cellular_state ret [%d], state [%d]", err, state);
+
+               err = connection_get_default_cellular_service_profile(g_connection, CONNECTION_CELLULAR_SERVICE_TYPE_MMS, &profile);
+               if (err != CONNECTION_ERROR_NONE || profile == NULL) {
+
+                       MSG_ERR("Failed connection_get_default_cellular_service_profile. err [%d], profile [%p]", err, profile);
+                       goto __SIGNAL_RETURN;
                }
-               break;
 
-               /*Response from Datacom for PDP Activation Request*/
-       case NET_EVENT_OPEN_IND:
-               MSG_DEBUG("Got Open Indication\n");
-               MSG_DEBUG("Received ACTIVATION response: %d \n", event_cb->Error);
-               break;
-       case NET_EVENT_OPEN_RSP:
-               MSG_DEBUG("Got Open RSP\n");
-               MSG_DEBUG("Received ACTIVATION response: %d \n", event_cb->Error);
-               prof_info = (net_profile_info_t *)event_cb->Data;
+               err = connection_profile_get_state(profile, &profile_state);
+
+               MSG_DEBUG("profile state [%d]", profile_state);
+
+               if (profile_state == CONNECTION_PROFILE_STATE_CONNECTED && waitProfileOpen == true) {
 
-               /*Successful PDP Activation*/
-               if (event_cb->Error == NET_ERR_NONE || event_cb->Error == NET_ERR_ACTIVE_CONNECTION_EXISTS) {
-                       network_print_profile(prof_info);
+                       __connection_profile_print(profile);
 
-                       lock();
+                       MSG_FREE(this->home_url);
+                       MSG_FREE(this->interface_name);
+                       MSG_FREE(this->proxy_address);
+
+                       err = connection_profile_get_cellular_home_url(profile, &this->home_url);
+                       if (err != CONNECTION_ERROR_NONE) {
+                               MSG_ERR("Failed connection_profile_get_cellular_home_url");
+                       }
+
+                       err = connection_profile_get_network_interface_name(profile, &this->interface_name);
+                       if (err != CONNECTION_ERROR_NONE) {
+                               MSG_ERR("Failed connection_profile_get_cellular_home_url");
+                       }
+
+                       err = connection_profile_get_proxy_address(profile, CONNECTION_ADDRESS_FAMILY_IPV4, &this->proxy_address);
+                       if (err != CONNECTION_ERROR_NONE) {
+                               MSG_ERR("Failed connection_profile_get_cellular_home_url");
+                       }
 
-                       memcpy(&mmsProfile, prof_info, sizeof(net_profile_info_t));
                        isCmOpened = true;
-                       signal();
 
-                       unlock();
+                       goto __SIGNAL_RETURN; //open success
+
                } else {
-                       MSG_DEBUG("Activation Failed %d \n", event_cb->Error); // open failed
-                       lock();
-                       isCmOpened = false;
-                       signal();
-                       unlock();
+                       goto __NO_SIGNAL_RETURN; //Just open success
                }
-               break;
-
-       case NET_EVENT_CLOSE_RSP:
-               MSG_DEBUG("Got Close RSP\n");
 
-               lock();
-
-               bzero(&mmsProfile, sizeof(net_profile_info_t));
+       } else {
+               MSG_ERR("connection open profile Failed!! [%d]", result);
                isCmOpened = false;
-               signal();
+               goto __SIGNAL_RETURN;
 
-               unlock();
-               break;
-
-       case NET_EVENT_CLOSE_IND:
-               MSG_DEBUG("Got Close IND\n");
-               break;
-       case NET_EVENT_PROFILE_MODIFY_IND:
-               MSG_DEBUG("Received Profile modified Indication\n");
-               MSG_DEBUG("No. of profile [%d]\n", event_cb->Datalength);
-               break;
-       case NET_EVENT_NET_STATE_IND:
-               MSG_DEBUG("Received NET_EVENT_NET_STATE_IND\n");
-               break;
-       default :
-               MSG_DEBUG("Error! Unknown Event = %d\n\n", event_cb->Event);
-               break;
        }
 
-       MSG_END();
+__NO_SIGNAL_RETURN: //Just Open
+       if (profile)
+               connection_profile_destroy(profile);
+       unlock();
+       return;
+
+__SIGNAL_RETURN: //Error or Already connected
+       if (profile)
+               connection_profile_destroy(profile);
+
+       if (waitProfileOpen == true) {//open fail
+               waitProfileOpen = false;
+               MSG_INFO("## SIGNAL ##");
+               signal();
+       }
+       unlock();
+       return;
 }
 
 
-bool MmsPluginCmAgent::getDeviceName(char *deviceName)
+void MmsPluginCmAgent::connection_profile_close_callback(connection_error_e result, void* user_data)
 {
-       if (!isCmOpened)
-               return false;
+       lock();
+       MSG_INFO("result [%d]", result);
+       MSG_INFO("## SIGNAL ##");
+       signal();
+
+       unlock();
+}
+
+void MmsPluginCmAgent::connection_profile_state_changed_cb(connection_profile_state_e state, void* user_data)
+{
+       MSG_BEGIN();
+
+       lock();
 
-       int deviceNameLength = strlen(mmsProfile.ProfileInfo.Pdp.net_info.DevName);
+       int err;
+       connection_profile_h profile = NULL;
 
-       if (deviceNameLength > 0) {
-               strncpy(deviceName, mmsProfile.ProfileInfo.Pdp.net_info.DevName, deviceNameLength);
-               deviceName[deviceNameLength] = '\0';
-               return true;
+       MSG_INFO("state [%d]", state);
+
+       if (state != CONNECTION_PROFILE_STATE_CONNECTED) {
+               isCmOpened = false;
+               goto __NO_SIGNAL_RETURN;
        }
 
-       return false;
-}
+       if (isCmOpened == true) {
+               MSG_INFO("already opened");
+               goto __SIGNAL_RETURN;
+       }
 
+       /* Should get profile to get latest profile info*/
+       err = connection_get_default_cellular_service_profile(g_connection, CONNECTION_CELLULAR_SERVICE_TYPE_MMS, &profile);
+       if (err != CONNECTION_ERROR_NONE || profile == NULL) {
 
-bool MmsPluginCmAgent::getHomeURL(char *homeURL)
-{
-       if (!isCmOpened)
-               return false;
+               MSG_ERR("Failed connection_get_default_cellular_service_profile. err [%d], profile [%p]", err, profile);
+               goto __SIGNAL_RETURN;
+       }
+
+       if (state == CONNECTION_PROFILE_STATE_CONNECTED ) {
+               __connection_profile_print(profile);
+
+               MSG_FREE(this->home_url);
+               MSG_FREE(this->interface_name);
+               MSG_FREE(this->proxy_address);
+
+               err = connection_profile_get_cellular_home_url(profile, &this->home_url);
+               if (err != CONNECTION_ERROR_NONE) {
+                       MSG_ERR("Failed connection_profile_get_cellular_home_url");
+               }
 
-       int homeURLLength = strlen(mmsProfile.ProfileInfo.Pdp.HomeURL);
+               err = connection_profile_get_network_interface_name(profile, &this->interface_name);
+               if (err != CONNECTION_ERROR_NONE) {
+                       MSG_ERR("Failed connection_profile_get_cellular_home_url");
+               }
+
+               err = connection_profile_get_proxy_address(profile, CONNECTION_ADDRESS_FAMILY_IPV4, &this->proxy_address);
+               if (err != CONNECTION_ERROR_NONE) {
+                       MSG_ERR("Failed connection_profile_get_cellular_home_url");
+               }
 
-       if (homeURLLength > 0) {
-               strncpy(homeURL, mmsProfile.ProfileInfo.Pdp.HomeURL, homeURLLength);
-               homeURL[homeURLLength] = '\0';
-               return true;
+               isCmOpened = true;
+               goto __SIGNAL_RETURN;
        }
 
-       return false;
-}
+__NO_SIGNAL_RETURN://Default
+       unlock();
+       return;
 
+__SIGNAL_RETURN: //Error or connected
+       if (profile)
+               connection_profile_destroy(profile);
+
+       if (waitProfileOpen == true) {
+               waitProfileOpen = false;
+               MSG_INFO("## SIGNAL ##");
+               signal();
+       }
+       unlock();
+       return;
+}
 
-bool MmsPluginCmAgent::getProxyAddr(char *proxyAddr)
+bool MmsPluginCmAgent::getInterfaceName(const char **deviceName)
 {
        if (!isCmOpened)
                return false;
 
-       int proxyAddrLength = strlen(mmsProfile.ProfileInfo.Pdp.net_info.ProxyAddr);
+       if (deviceName == NULL)
+               return false;
 
-       if (proxyAddrLength > 0) {
-               if (strchr(mmsProfile.ProfileInfo.Pdp.net_info.ProxyAddr, ':') == NULL)
-                       return false;
+       *deviceName = interface_name;
 
-               proxyAddrLength = proxyAddrLength - strlen(strchr(mmsProfile.ProfileInfo.Pdp.net_info.ProxyAddr, ':'));
-               strncpy(proxyAddr, mmsProfile.ProfileInfo.Pdp.net_info.ProxyAddr, proxyAddrLength);
-               proxyAddr[proxyAddrLength] = '\0';
+       return true;
+}
 
-               return true;
-       }
+bool MmsPluginCmAgent::getHomeUrl(const char **homeURL)
+{
+       if (!isCmOpened)
+               return false;
 
-       return false;
+       if (homeURL == NULL)
+               return false;
+
+       *homeURL = home_url;
+
+       return true;
 }
 
 
-int MmsPluginCmAgent::getProxyPort()
+bool MmsPluginCmAgent::getProxyAddr(const char **proxyAddr)
 {
        if (!isCmOpened)
-               return -1;
+               return false;
 
-       int proxyAddrLength = strlen(mmsProfile.ProfileInfo.Pdp.net_info.ProxyAddr);
+       if (proxyAddr == NULL)
+               return false;
 
-       if (proxyAddrLength > 0) {
-               char *pPort = strchr(mmsProfile.ProfileInfo.Pdp.net_info.ProxyAddr, ':') + 1;
-               if (pPort)
-                       return atoi(pPort);
-               else
-                       return -1;
-       }
+       *proxyAddr = proxy_address;
 
-       return -1;
+       return true;
 }
-
diff --git a/plugin/mms_plugin/MmsPluginContentCodec.cpp b/plugin/mms_plugin/MmsPluginContentCodec.cpp
deleted file mode 100755 (executable)
index b372ecf..0000000
+++ /dev/null
@@ -1,1068 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include <stdlib.h>
-#include <ctype.h>
-#include "MsgDebug.h"
-#include "MmsPluginCodec.h"
-#include "MmsPluginCodec.h"
-#include "MmsPluginMIME.h"
-#include "MmsPluginMessage.h"
-#include "MmsPluginWmLngPack.h"
-
-const int MSG_MAX_CH_PER_LINE = 75;
-
-/* ==================================================================
- *     Decode/Encode inline base64 string
- *
- * base64 : 3*8bit -> 4*6bit & convert the value into A~Z, a~z, 0~9, +, or /
- * pad(=) is needed when the end of the string is < 24bit.
- *
- *     Value Encoding  Value Encoding  Value Encoding  Value Encoding
- *         0 A            17 R            34 i            51 z
- *         1 B            18 S            35 j            52 '0'
- *         2 C            19 T            36 k            53 1
- *         3 D            20 U            37 l            54 2
- *         4 E            21 V            38 m            55 3
- *         5 F            22 W            39 n            56 4
- *         6 G            23 X            40 o            57 5
- *         7 H            24 Y            41 p            58 6
- *         8 I            25 Z            42 q            59 7
- *         9 J            26 a            43 r            60 8
- *        10 K            27 b            44 s            61 9
- *        11 L            28 c            45 t            62 +
- *        12 M            29 d            46 u            63 /
- *        13 N            30 e            47 v
- *        14 O            31 f            48 w         (pad) =
- *        15 P            32 g            49 x
- *        16 Q            33 h            50 y
- *
- * (1) the final quantum = 24 bits : no "=" padding,
- * (2) the final quantum = 8 bits : two "=" + two characters
- * (3) the final quantum = 16 bits : one "=" + three characters
- * ================================================================== */
-
-bool _MsgEncodeBase64(void *pSrc, unsigned long srcLen, unsigned long *len, unsigned char *ret)
-{
-       unsigned char *d = NULL;
-       unsigned char *s = (unsigned char *)pSrc;
-
-       char *v = (char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-       unsigned long i = ((srcLen + 2) / 3) * 4;
-
-       i += 2 * ((i / 60) + 1);
-       *len = i;
-
-       if (ret == NULL) {
-               MSG_DEBUG("_MsgEncodeBase64: ret Memory Alloc Fail \n");
-               return false;
-       }
-       memset(ret, 0, i);
-
-       d = ret;
-
-       /* Convert 3*8bit into 4*6bit */
-       for (i = 0; srcLen > 0; s += 3) {
-               *d++ = v[s[0] >> 2];                                                                                                                    // byte 1: high 6 bits of character-1
-               *d++ = v[((s[0] << 4) + (--srcLen ? (s[1] >> 4) : 0)) & 0x3f];                                  // byte 2: low 2 bits of character-1 and high 4 bits of character-2
-               *d++ = srcLen ? v[((s[1] << 2) + (--srcLen ? (s[2] >> 6) : 0)) & 0x3f] : '=';   // byte 3: low 4 bits of charcter-2 and high 2 bits of character-3
-               *d++ = srcLen ? v[s[2] & 0x3f] : '=';                                                                                   // byte 4: low 6 bits of character-3
-
-               if (srcLen)
-                       srcLen--;
-
-               /* Insert CRLF at every 60 characters */
-               if ((++i) == 15) {
-                       i = 0;
-                       *d++ = '\015';
-                       *d++ = '\012';
-               }
-       }
-
-       if (i == 15) {
-               *d++ = '\015';
-               *d++ = '\012';
-       }
-       *d = '\0';
-
-       if (((unsigned long)(d - ret)) != *len) {
-               *len = d - ret;
-               MSG_DEBUG("base64 encoding length = %d \n", *len);
-       }
-
-       return true;
-}
-
-
-void *_MsgDecodeBase64(unsigned char *pSrc, unsigned long srcLen, unsigned long *len)
-{
-       char c;
-       void *ret = NULL;
-       char *d = NULL;
-       short e = 0;
-
-       ret = malloc((size_t)(*len = 4 + ((srcLen * 3) / 4)));
-       d = (char *)ret;
-
-       if (ret == NULL) {
-               MSG_DEBUG("_MsgDecodeBase64: ret malloc Fail \n");
-               return NULL;
-       }
-
-       memset(ret, 0, (size_t)*len);
-       *len = 0;
-
-       while (srcLen-- > 0) {
-               c = *pSrc++;
-
-               /* Convert base64 character into original value */
-
-               if (isupper(c))
-                       c -= 'A';
-               else if (islower(c))
-                       c -= 'a' - 26;
-               else if (isdigit(c))
-                       c -= '0' - 52;
-               else if (c == '+')
-                       c = 62;
-               else if (c == '/')
-                       c = 63;
-               else if (c == '=') {
-                       switch (e++) {
-                       case 2:
-                               if (*pSrc != '=') {
-                                       *len = d - (char *)ret;
-                                       return ret;
-                               }
-                               break;
-                       case 3:
-                               e = 0;
-                               break;
-                       default:
-                               *len = d - (char *)ret;
-                               return ret;
-                       }
-                       continue;
-               } else
-                       continue;                                       // Actually, never get here
-
-               /* Pad 4*6bit character into 3*8bit character */
-
-               switch (e++) {
-               case 0:
-                       *d = c << 2;                    // byte 1: high 6 bits
-                       break;
-
-               case 1:
-                       *d++ |= c >> 4;                 // byte 1: low 2 bits
-                       *d = c << 4;                    // byte 2: high 4 bits
-                       break;
-
-               case 2:
-                       *d++ |= c >> 2;                 // byte 2: low 4 bits
-                       *d = c << 6;                    // byte 3: high 2 bits
-                       break;
-
-               case 3:
-                       *d++ |= c;                              // byte 3: low 6 bits
-                       e = 0;                                  // Calculate next unit.
-                       break;
-
-               default:
-                       MSG_DEBUG("_MsgDecodeBase64: Unknown paremeter\n");
-                       break;
-               }
-       }
-
-       *len = d - (char *)ret;                 // Calculate the size of decoded string.
-
-       return ret;
-}
-
-
-
-/* ==========================================
- *     Decode/Encode inline base64 string
- *
- * quoted-printable := ([*(ptext / SPACE / TAB) ptext] ["="] CRLF)
- *       ; Maximum line length of 76 characters excluding CRLF
- *
- * ptext := octet /<any ASCII character except "=", SPACE, or TAB>
- *       ; characters not listed as "mail-safe" in Appendix B
- *       ; are also not recommended.
- *
- * octet := "=" 2(DIGIT / "A" / "B" / "C" / "D" / "E" / "F")
- *       ; octet must be used for characters > 127, =, SPACE, or TAB.
- *
- * ==========================================*/
-
-bool _MsgEncodeQuotePrintable(unsigned char *pSrc, unsigned long srcLen, unsigned long *len, unsigned char *ret)
-{
-       unsigned long lp = 0;
-       unsigned char *d = ret;
-       char *hex = (char *)"0123456789ABCDEF";
-       unsigned char c;
-
-       if (ret == NULL) {
-               MSG_DEBUG("_MsgEncodeQuotePrintable: ret malloc Fail \n");
-               return false;
-       }
-
-       d = ret;
-
-       /*
-        * The type of srcLen is unsigned long
-        * The value of srcLen is decreased by 1 -> We can't check by "srcLen > 0".
-        */
-       while (srcLen-- > 0) {
-               /* Just copy CRLF */
-               if (((c = *pSrc++) == '\015') && (*pSrc == '\012') && srcLen) {
-                       *d++ = '\015';
-                       *d++ = *pSrc++;
-                       srcLen--;
-                       lp = 0;
-               } else {
-                       if (iscntrl(c) || (c == 0x7f) || (c & 0x80) || (c == '=') || ((c == ' ') && (*pSrc == '\015'))) {
-                               if ((lp += 3) > (unsigned long)MSG_MAX_CH_PER_LINE) {
-                                       *d++ = '=';
-                                       *d++ = '\015';
-                                       *d++ = '\012';
-                                       lp = 3;
-                               }
-
-                               *d++ = '=';                             /* quote character */
-                               *d++ = hex[c >> 4];             /* high order 4 bits */
-                               *d++ = hex[c & 0xf];    /* low order 4 bits */
-                       } else {
-                               /* Just copy ASCII character */
-                               if ((++lp) > (unsigned long)MSG_MAX_CH_PER_LINE) {
-                                       *d++ = '=';
-                                       *d++ = '\015';
-                                       *d++ = '\012';
-                                       lp = 1;
-                               }
-                               *d++ = c;
-                       }
-               }
-       }
-
-       *d = '\0';
-       *len = d - ret;
-
-       return true;
-}
-
-
-unsigned char *_MsgDecodeQuotePrintable(unsigned char *pSrc, unsigned long srcLen, unsigned long *len)
-{
-       unsigned char *ret = NULL;
-       unsigned char *d = NULL;
-       unsigned char *s = NULL;                                        /* last non-blank */
-       unsigned char c;
-       unsigned char e;
-
-       d = s = ret = (unsigned char *)malloc((size_t)srcLen + 1);
-       if (ret == NULL) {
-               MSG_DEBUG("_MsgDecodeQuotePrintable: ret malloc Fail \n");
-               return NULL;
-       }
-
-       *len = 0;
-       pSrc[srcLen] = '\0';
-
-       while ((c = *pSrc++)!= '\0') {
-               switch (c) {
-               case '=':                                                       /* octet characters (> 127, =, SPACE, or TAB) */
-                       switch (c = *pSrc++) {
-                       case '\0':                                      /* end of string -> postpone to while */
-                               break;
-
-                       case '\015':                            /* CRLF */
-                               if (*pSrc == '\012')
-                                       pSrc++;
-                               break;
-
-                       default:                                        /* two hexes */
-                               if (!isxdigit(c)) {
-                                       *d = '\0';
-                                       *len = d - ret;
-                                       return ret;
-                               }
-
-                               if (isdigit(c))
-                                       e = c - '0';
-                               else
-                                       e = c - (isupper(c) ? 'A' - 10 : 'a' - 10);
-
-                               c = *pSrc++;
-                               if (!isxdigit(c)) {
-                                       *d = '\0';
-                                       *len = d - ret;
-                                       return ret;
-                               }
-
-                               if (isdigit(c))
-                                       c -= '0';
-                               else
-                                       c -= (isupper(c) ? 'A' - 10 : 'a' - 10);
-
-                               *d++ = c + (e << 4);
-                               s = d;
-                               break;
-                       }
-                       break;
-
-               case ' ':                                                       /* skip the blank */
-                       *d++ = c;
-                       break;
-
-               case '\015':                                            /* Line Feedback : to last non-blank character */
-                       d = s;
-                       break;
-
-               default:
-                       *d++ = c;                                               /* ASCII character */
-                       s = d;
-                       break;
-               }
-       }
-
-       *d = '\0';
-       *len = d - ret;
-
-       return ret;
-}
-
-
-/* ========================================
- * Decode/Encode inline base64 string
- * Inline base64 has no "\r\n" in it,
- * and has charset and encoding sign in it
- * ======================================== */
-bool _MsgEncode2Base64(void *pSrc, unsigned long srcLen, unsigned long *len, unsigned char *ret)
-{
-       unsigned char *d = NULL;
-       unsigned char *s = (unsigned char *)pSrc;
-       char *v = (char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-       unsigned long i = ((srcLen + 2) / 3) * 4;
-
-       i += 2 * ((i / 60) + 1);
-       *len = i;
-
-       if (ret == NULL) {
-               MSG_DEBUG("_MsgEncode2Base64: ret Memory Alloc Fail \n");
-               return false;
-       }
-       memset(ret, 0, i);
-
-       d = ret;
-
-       /* Convert 3*8bit into 4*6bit */
-       for (i = 0; srcLen > 0; s += 3) {
-               *d++ = v[s[0] >> 2];                                                                                                                    // byte 1: high 6 bits of character-1
-               *d++ = v[((s[0] << 4) + (--srcLen ? (s[1] >> 4) : 0)) & 0x3f];                                  // byte 2: low 2 bits of character-1 and high 4 bits of character-2
-               *d++ = srcLen ? v[((s[1] << 2) + (--srcLen ? (s[2] >> 6) : 0)) & 0x3f] : '=';   // byte 3: low 4 bits of charcter-2 and high 2 bits of character-3
-               *d++ = srcLen ? v[s[2] & 0x3f] : '=';                                                                                   // byte 4: low 6 bits of character-3
-
-               if (srcLen)
-                       srcLen--;
-       }
-
-       *d = '\0';
-
-       if (((unsigned long)(d - ret)) != *len) {
-               *len = d - ret;
-               MSG_DEBUG("base64 encoding length = %d \n", *len);
-       }
-
-       return true;
-}
-
-
-char *_MsgDecodeText(char *pOri)
-{
-       MSG_BEGIN();
-
-       int size = 0;
-       int cnt = 0;
-       char *pSrc = NULL;
-       char *pTemp = NULL;
-       char *pRe = NULL;
-       char *pStrEnd = NULL;
-       char *pDecStart = NULL;
-       char *pDecEnd = NULL;
-       char *pDecQ = NULL;
-       char *pDecQ2 = NULL;
-       bool bEncoding = false;
-       int     nCharset = MSG_CHARSET_UTF8;
-       int     nChar = 0;
-       int     nByte = 0;
-       int     nTemp = 0;
-       char *pReturnStr = NULL;
-       char *pConvertedStr = NULL;
-       MCHAR *mszTempStr = NULL;
-
-       MCHAR *pmszOutTextStr = NULL;
-
-       char szTempBuf[MSG_LOCAL_TEMP_BUF_SIZE] = {0};
-
-       // copy original string
-       if (strlen(pOri) >= MSG_LOCAL_TEMP_BUF_SIZE) {
-               pSrc = MsgStrCopy( pOri );
-       } else {
-               memset(szTempBuf, 0, MSG_LOCAL_TEMP_BUF_SIZE);
-               strcpy(szTempBuf, pOri);
-
-               pSrc = szTempBuf;
-       }
-
-       // it can be one or more encoding methods in a line
-       while (1) {
-               cnt++;
-
-               bEncoding = false;
-
-               /*
-                 (ex) "=?euc-kr?B?Y2NqMjEyMw==?="
-
-                 pDecStart: charset                    (=?euc-kr?B?Y2NqMjEyMw==?=)
-                 pDecQ : Encoding type         (B?Y2NqMjEyMw==?=)
-                 pDecQ2        : Encoded text          (Y2NqMjEyMw==?=)
-                 pDecEnd       : Encoded of text       (?=)
-                */
-               if (pSrc == NULL)
-                       goto __CATCH;
-
-               if (((pDecStart = strstr(pSrc, MSG_STR_DEC_START)) != NULL)     //"=?"
-                    && ((pDecQ = strchr(pDecStart + 2, MSG_CH_QUESTION)) != NULL)      // '?'
-                    && ((pDecQ2 = strchr(pDecQ + 1, MSG_CH_QUESTION))!= NULL)          // '?'
-                    && ((pDecEnd = strstr(pDecQ2 + 1, MSG_STR_DEC_END))!= NULL)) {     //"=?"
-                       bEncoding = true;
-
-                       /* charset problem
-                        * pDecStart ~ pDecQ : charSet & MSG_CHARSET_USC2 ~ MSG_CHARSET_UTF8 & LATIN
-                        */
-
-                       *pDecQ = '\0';
-                       nCharset = _MsgGetCode(MSG_CHARSET, pDecStart + 2);
-                       *pDecQ = MSG_CH_QUESTION;
-               }
-
-               // End of encoding
-               if (!bEncoding)
-                       goto __RETURN;
-
-               // find end of string
-               pStrEnd = pSrc + strlen(pSrc);
-
-               // Decoding
-               if ((*(pDecQ2 - 1) == MSG_CH_BASE64_UPPER) ||
-                       (*(pDecQ2 - 1) == MSG_CH_BASE64_LOWER) ||
-                       (*(pDecQ + 1) == MSG_CH_BASE64_UPPER) ||
-                       (*(pDecQ + 1) == MSG_CH_BASE64_LOWER)) {
-                       pTemp = (char *)_MsgDecodeBase64((UCHAR *)(pDecQ2 + 1), (ULONG)(pDecEnd - pDecQ2 - 1), (ULONG *)&size);
-
-                       if (pTemp != NULL) {
-                               pTemp[size] = MSG_CH_NULL;
-
-                               if(pRe) {
-                                       free(pRe);
-                                       pRe = NULL;
-                               }
-
-                               pRe = (char *)malloc((pDecStart-pSrc) + size + (pStrEnd - (pDecEnd + 2)) + 1);
-                               if (pRe == NULL) {
-                                       MSG_DEBUG("_MsgDecodeText: pRemalloc fail \n");
-                                       free(pTemp);
-                                       pTemp = NULL;
-
-                                       goto __RETURN;
-                               }
-
-                               memcpy(pRe, pSrc, pDecStart - pSrc);
-                               memcpy(&pRe[pDecStart-pSrc], pTemp, size);
-                               memcpy(&pRe[(pDecStart - pSrc) + size], pDecEnd + 2, pStrEnd - (pDecEnd + 2));
-                               pRe[(pDecStart - pSrc) + size + (pStrEnd - (pDecEnd + 2))] = MSG_CH_NULL;
-
-                               free(pTemp);
-                               pTemp = NULL;
-
-                               if (pSrc != NULL && pSrc != szTempBuf) {
-                                       free(pSrc);
-                                       pSrc = NULL;
-                               }
-                       }
-               } else if ((*(pDecQ2-1) == MSG_CH_QPRINT_UPPER) ||
-                               (*(pDecQ2-1) == MSG_CH_QPRINT_LOWER) ||
-                               (*(pDecQ+1) == MSG_CH_QPRINT_UPPER) ||
-                               (*(pDecQ+1) == MSG_CH_QPRINT_LOWER)) {
-
-                       pTemp = (char *)_MsgDecodeQuotePrintable((UCHAR *)( pDecQ2 + 1 ), (ULONG)(pDecEnd - pDecQ2 - 1), (ULONG *)&size);
-
-                       if (pTemp != NULL) {
-                               int i;
-                               pTemp[size] = MSG_CH_NULL;
-
-                               for (i = 0; i < size; i++) {
-                                       if (pTemp[i] == MSG_CH_UNDERLINE) {
-                                               pTemp[i] = MSG_CH_SP;                         // change '_' to ' '
-                                       }
-                               }
-
-                               if(pRe) {
-                                       free(pRe);
-                                       pRe = NULL;
-                               }
-
-                               pRe = (char *)malloc((pDecStart - pSrc) + size + (pStrEnd - (pDecEnd + 2)) + 1);
-                               if (pRe == NULL) {
-                                       MSG_DEBUG("_MsgDecodeText: pRemalloc fail \n");
-                                       free(pTemp);
-                                       pTemp = NULL;
-
-                                       goto __RETURN;
-                               }
-
-                               memcpy(pRe, pSrc, pDecStart - pSrc);
-                               memcpy(&pRe[pDecStart - pSrc], pTemp, size);
-                               memcpy(&pRe[(pDecStart - pSrc) + size], pDecEnd + 2, pStrEnd - (pDecEnd + 2));
-                               pRe[(pDecStart - pSrc) + size + (pStrEnd - (pDecEnd + 2))] = MSG_CH_NULL;
-
-                               if (pTemp) {
-                                       free(pTemp);
-                                       pTemp = NULL;
-                               }
-
-                               if (pSrc != NULL && pSrc != szTempBuf) {
-                                       free(pSrc);
-                                       pSrc = NULL;
-                               }
-                       }
-               } else {
-                       goto __RETURN;
-               }
-       }
-
-__RETURN:
-
-       pTemp = pSrc;
-       nTemp = strlen(pSrc);
-
-       switch (nCharset) {
-       case MSG_CHARSET_UTF16:
-       case MSG_CHARSET_USC2:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_USC2 \n");
-
-               if (pTemp) {
-                       // mmf file name display patch
-                       if (((UINT8)pTemp[0] == 0xFF && (UINT8)pTemp[1] == 0xFE) || ((UINT8)pTemp[0] == 0xFE && (UINT8)pTemp[1] == 0xFF)) {
-
-                               nChar = (nTemp / 2 - 1);
-
-                               // Re check char-set
-                               if (MsgIsUTF8String((unsigned char *)pTemp + 2, nTemp - 2)) {
-                                       strncpy(pTemp, pTemp + 2, strlen(pTemp + 2));
-                                       nTemp = nTemp - 2;
-                                       MSG_DEBUG("_MsgDecodeText: real char-set = MSG_CHARSET_UTF8.\n");
-                                       break;
-                               }
-
-                               mszTempStr = (unsigned short *)malloc(nChar * sizeof(unsigned short));
-                               if (mszTempStr == NULL) {
-                                       MSG_DEBUG("_MsgDecodeText: 1. Memory Full !!! \n");
-                                       goto __CATCH;
-                               }
-
-                               memcpy(mszTempStr, ((unsigned short *)pTemp + 1), nChar * sizeof(unsigned short));
-
-                               nByte = MsgGetUnicode2UTFCodeSize(((unsigned short *)pTemp + 1), nChar);
-
-                               pConvertedStr = (char *)malloc(nByte + 1);
-                               if (pConvertedStr) {
-                                       MsgUnicode2UTF ((unsigned char *)pConvertedStr, nByte + 1, mszTempStr, nChar);
-                               }
-                       } else {
-                               nChar = (nTemp / 2);
-
-                               if (nChar == 0) {
-                                       nChar = 2;
-                               }
-
-                               // Re check char-set
-                               if (MsgIsUTF8String((unsigned char *)pTemp, nTemp)) {
-                                       MSG_DEBUG("_MsgDecodeText: real char-set = MSG_CHARSET_UTF8.\n");
-                                       break;
-                               }
-
-                               mszTempStr = (unsigned short *)malloc(nChar * sizeof(unsigned short));
-                               if (mszTempStr == NULL) {
-                                       MSG_DEBUG("_MsgDecodeText: 2. Memory Full !!! \n");
-                                       goto __CATCH;
-                               }
-
-                               memcpy(mszTempStr, ((unsigned short *)pTemp), nChar * sizeof(unsigned short));
-
-                               nByte = MsgGetUnicode2UTFCodeSize(((unsigned short *)pTemp), nChar);
-
-                               pConvertedStr = (char *)malloc(nByte + 1);
-                               if (pConvertedStr) {
-                                       MsgUnicode2UTF ((unsigned char *)pConvertedStr, nByte + 1, mszTempStr, nChar);
-                               }
-                       }
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_US_ASCII:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_US_ASCII \n");
-               break;
-
-       case MSG_CHARSET_UTF8:
-
-               /* UTF8 is  default charset of Messenger */
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_UTF8 \n");
-
-               break;
-
-       case MSG_CHARSET_ISO_8859_1:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_ISO_8859_1 \n");
-
-               nByte = nTemp * 3;
-
-               pmszOutTextStr = (unsigned short *)malloc(sizeof(MCHAR *) * (nByte + 1));
-               if (pmszOutTextStr == NULL) {
-                       MSG_DEBUG("_MsgDecodeText : Out Text String null !!! \n");
-                       goto __CATCH;
-               }
-
-               pConvertedStr = (char *)malloc(sizeof(char *) * (nByte + 1));
-               if (pConvertedStr) {
-                       WmConvertLatinCode2PCode(pmszOutTextStr, sizeof(MCHAR *) * (nByte + 1), pTemp);
-                       WmConvert2LCode(pConvertedStr, sizeof(char *) * (nByte + 1), pmszOutTextStr);
-               }
-
-               if (pmszOutTextStr) {
-                       free(pmszOutTextStr);
-                       pmszOutTextStr = NULL;
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_ISO_8859_2:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_ISO_8859_2 \n");
-
-               nByte = nTemp * 3;
-
-               pmszOutTextStr = (unsigned short *)malloc(sizeof(MCHAR *) * (nByte + 1));
-               if (pmszOutTextStr == NULL) {
-                       MSG_DEBUG("_MsgDecodeText : Out Text String null !!! \n");
-                       goto __CATCH;
-               }
-
-               pConvertedStr =  (char *)malloc(sizeof(char *) * (nByte + 1));
-               if (pConvertedStr) {
-                       WmConvertLatin2Code2PCode(pmszOutTextStr, sizeof(MCHAR *) * (nByte + 1), pTemp);
-                       WmConvert2LCode(pConvertedStr, sizeof(char *) * (nByte + 1), pmszOutTextStr);
-               }
-
-               if (pmszOutTextStr) {
-                       free(pmszOutTextStr);
-                       pmszOutTextStr = NULL;
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_ISO_8859_3:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_ISO_8859_3 \n");
-
-               nByte = WmGetLatin32UTFCodeSize((unsigned char *)pTemp, nTemp);
-
-               pmszOutTextStr = (unsigned short *)malloc(sizeof(MCHAR *) * (nByte + 1));
-               if (pmszOutTextStr == NULL) {
-                       MSG_DEBUG("_MsgDecodeText : Out Text String null !!! \n");
-                       goto __CATCH;
-               }
-
-               pConvertedStr = (char *)malloc(sizeof(char *) * (nByte + 1));
-               if (pConvertedStr) {
-                       WmConvertLatin3Code2PCode(pmszOutTextStr, sizeof(MCHAR *) * (nByte + 1), pTemp);
-                       WmConvert2LCode(pConvertedStr, sizeof(char *) * (nByte + 1), pmszOutTextStr);
-               }
-
-               if (pmszOutTextStr) {
-                       free(pmszOutTextStr);
-                       pmszOutTextStr = NULL;
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_ISO_8859_4:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_ISO_8859_4 \n");
-
-               nByte = WmGetLatin42UTFCodeSize((unsigned char *)pTemp, nTemp);
-
-               pmszOutTextStr = (unsigned short *)malloc(sizeof(MCHAR *) * (nByte + 1));
-               if (pmszOutTextStr == NULL) {
-                       MSG_DEBUG("_MsgDecodeText : Out Text String null !!! \n");
-                       goto __CATCH;
-               }
-
-               pConvertedStr = (char *)malloc(sizeof(char *) * (nByte + 1));
-               if (pConvertedStr) {
-                       WmConvertLatin4Code2PCode(pmszOutTextStr, sizeof(MCHAR *) * (nByte + 1), pTemp);
-                       WmConvert2LCode(pConvertedStr, sizeof(char *) * (nByte + 1), pmszOutTextStr);
-               }
-
-               if (pmszOutTextStr) {
-                       free(pmszOutTextStr);
-                       pmszOutTextStr = NULL;
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_ISO_8859_5:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_ISO_8859_5 \n");
-
-               nByte = WmGetLatin52UTFCodeSize((unsigned char *)pTemp, nTemp);
-
-               pmszOutTextStr = (unsigned short *)malloc(sizeof(MCHAR *) * (nByte + 1));
-               if (pmszOutTextStr == NULL) {
-                       MSG_DEBUG("_MsgDecodeText : Out Text String null !!! \n");
-                       goto __CATCH;
-               }
-
-               pConvertedStr = (char *)malloc(sizeof(char *) * (nByte + 1));
-               if (pConvertedStr) {
-                       WmConvertLatin5Code2PCode(pmszOutTextStr, sizeof(MCHAR *) * (nByte + 1), pTemp);
-                       WmConvert2LCode(pConvertedStr, sizeof(char *) * (nByte + 1), pmszOutTextStr);
-               }
-
-               if (pmszOutTextStr) {
-                       free(pmszOutTextStr);
-                       pmszOutTextStr = NULL;
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_ISO_8859_7:
-
-               /* Greek */
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_ISO_8859_9 \n");
-
-               nByte = MsgGetLatin72UTFCodeSize((unsigned char *)pTemp, nTemp);
-               pConvertedStr = (char *)malloc( nByte + 1);
-               if (pConvertedStr) {
-                       MsgLatin7code2UTF((unsigned char *)pConvertedStr, nByte + 1 , (unsigned char *)pTemp, nTemp);
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_ISO_8859_8:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_ISO_8859_8 \n");
-
-               nByte = WmGetLatin82UTFCodeSize((unsigned char *)pTemp, nTemp);
-
-               pmszOutTextStr = (unsigned short *)malloc(sizeof(MCHAR *) * (nByte + 1));
-               if (pmszOutTextStr == NULL) {
-                       MSG_DEBUG("_MsgDecodeText : Out Text String null !!! \n");
-                       goto __CATCH;
-               }
-
-               pConvertedStr = (char *)malloc(sizeof(char *) * (nByte + 1));
-               if (pConvertedStr) {
-                       WmConvertLatin8Code2PCode(pmszOutTextStr, sizeof(MCHAR *) * (nByte + 1), pTemp);
-                       WmConvert2LCode(pConvertedStr, sizeof(char *) * (nByte + 1), pmszOutTextStr);
-               }
-
-               if (pmszOutTextStr) {
-                       free(pmszOutTextStr);
-                       pmszOutTextStr = NULL;
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_ISO_8859_9:
-               /* Turkish */
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_ISO_8859_9 \n");
-
-               nByte = MsgGetLatin52UTFCodeSize((unsigned char *)pTemp, nTemp);
-               pConvertedStr = (char *)malloc(nByte + 1);
-               if (pConvertedStr) {
-                       MsgLatin5code2UTF((unsigned char *)pConvertedStr, nByte + 1 , (unsigned char *)pTemp, nTemp);
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_ISO_8859_15:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_ISO_8859_15 \n");
-
-               nByte = WmGetLatin152UTFCodeSize((unsigned char *)pTemp, nTemp);
-
-               pmszOutTextStr = (unsigned short *)malloc(sizeof(MCHAR *) * (nByte + 1));
-               if (pmszOutTextStr == NULL) {
-                       MSG_DEBUG("_MsgDecodeText : Out Text String null !!! \n");
-                       goto __CATCH;
-               }
-
-               pConvertedStr = (char *)malloc(sizeof(char *) * (nByte + 1));
-               if (pConvertedStr) {
-                       WmConvertLatin15Code2PCode(pmszOutTextStr, sizeof(MCHAR *) * (nByte + 1), pTemp);
-                       WmConvert2LCode(pConvertedStr, sizeof(char *) * (nByte + 1), pmszOutTextStr);
-               }
-
-               if (pmszOutTextStr) {
-                       free(pmszOutTextStr);
-                       pmszOutTextStr = NULL;
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_WIN1251:
-       case MSG_CHARSET_WINDOW_1251:
-       case MSG_CHARSET_WINDOWS_1251:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_WINDOWS_1251 \n");
-
-               nByte = nTemp * 3;
-
-               pmszOutTextStr = (unsigned short *)malloc(sizeof(MCHAR *) * (nByte + 1));
-               if (pmszOutTextStr == NULL) {
-                       MSG_DEBUG("_MsgDecodeText : Out Text String null !!! \n");
-                       goto __CATCH;
-               }
-
-               pConvertedStr = (char *)malloc(sizeof(char *) * (nByte + 1));
-               if (pConvertedStr) {
-                       WmConvertWin1251Code2PCode(pmszOutTextStr, sizeof(MCHAR *) * (nByte + 1), pTemp);
-                       WmConvert2LCode(pConvertedStr, sizeof(char *) * (nByte + 1), pmszOutTextStr);
-               }
-
-               if (pmszOutTextStr) {
-                       free(pmszOutTextStr);
-                       pmszOutTextStr = NULL;
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_KOI8_R:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_KOI8_R \n");
-
-               nByte = nTemp * 3;
-
-               pmszOutTextStr = (unsigned short *)malloc(sizeof(MCHAR *) * (nByte + 1));
-               if (pmszOutTextStr == NULL) {
-                       MSG_DEBUG("_MsgDecodeText : Out Text String null !!! \n");
-                       goto __CATCH;
-               }
-
-               pConvertedStr = (char *)malloc(sizeof(char *) * (nByte + 1));
-               if (pConvertedStr) {
-                       WmConvertKoi8rCode2PCode(pmszOutTextStr, sizeof(MCHAR *) * (nByte + 1), pTemp);
-                       WmConvert2LCode(pConvertedStr, sizeof(char *) * (nByte + 1), pmszOutTextStr);
-               }
-
-               if (pmszOutTextStr) {
-                       free(pmszOutTextStr);
-                       pmszOutTextStr = NULL;
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       case MSG_CHARSET_KOI8_U:
-
-               MSG_DEBUG("_MsgDecodeText: MSG_CHARSET_KOI8_U \n");
-
-               nByte = nTemp * 3;
-
-               pmszOutTextStr = (unsigned short *)malloc(sizeof(MCHAR *) * (nByte + 1));
-               if (pmszOutTextStr == NULL) {
-                       MSG_DEBUG("_MsgDecodeText : Out Text String null !!! \n");
-                       goto __CATCH;
-               }
-
-               pConvertedStr = (char *)malloc(sizeof(char *) * (nByte + 1));
-               if (pConvertedStr) {
-                       WmConvertKoi8uCode2PCode(pmszOutTextStr, sizeof(MCHAR *) * (nByte + 1), pTemp);
-                       WmConvert2LCode(pConvertedStr, sizeof(char *) * (nByte + 1), pmszOutTextStr);
-               }
-
-               if (pmszOutTextStr) {
-                       free(pmszOutTextStr);
-                       pmszOutTextStr = NULL;
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-
-       default:
-
-               MSG_DEBUG("_MsgDecodeText: Other charsets \n");
-
-               nByte = MsgGetLatin2UTFCodeSize((unsigned char *)pTemp, nTemp);
-               pConvertedStr = (char *)malloc(nByte + 1);
-               if (pConvertedStr) {
-                       MsgLatin2UTF((unsigned char *)pConvertedStr, nByte + 1, (unsigned char *)pTemp, nTemp);
-               }
-
-               pTemp = pConvertedStr;
-               nTemp = nByte;
-
-               break;
-       }
-
-       pReturnStr = (char *)malloc(nTemp + 1);
-       if (pReturnStr == NULL) {
-               goto __CATCH;
-       }
-       memset(pReturnStr, 0, nTemp + 1);
-
-       if (pTemp)
-               memcpy(pReturnStr, pTemp, nTemp);
-
-       if (pConvertedStr) {
-               free(pConvertedStr);
-               pConvertedStr = NULL;
-       }
-
-       if (mszTempStr) {
-               free(mszTempStr);
-               mszTempStr = NULL;
-       }
-
-       if(pRe) {
-               free(pRe);
-               pRe = NULL;
-       }
-
-       if (pSrc != NULL && pSrc != szTempBuf) {
-               free(pSrc);
-               pSrc = NULL;
-       }
-
-       return pReturnStr;
-
-__CATCH:
-
-       if (pConvertedStr) {
-               free(pConvertedStr);
-               pConvertedStr = NULL;
-       }
-
-       if (mszTempStr) {
-               free(mszTempStr);
-               mszTempStr = NULL;
-       }
-
-       if(pRe) {
-               free(pRe);
-               pRe = NULL;
-       }
-
-       if (pSrc != NULL && pSrc != szTempBuf) {
-               free(pSrc);
-               pSrc = NULL;
-       }
-
-       return NULL;
-}
-
-
-char *MsgEncodeText(char *pOri)
-{
-       ULONG nLen = 0;
-       char *szBuff = NULL;
-       int length  = 0;
-
-       length = (strlen(pOri) * 4) / 3 + 2 + 12 + 1 + 30;
-       szBuff = (char *)malloc(length + 1);
-
-       if (szBuff == NULL) {
-               // error handling
-               MSG_DEBUG("_MsgEncodeText: szBuff alloc is failed \n");
-               goto __CATCH;
-       }
-
-       memset(szBuff, 0 , length + 1);
-
-       snprintf(szBuff, length+1, "%s%s%c%c%c", MSG_STR_DEC_START, "utf-8", MSG_CH_QUESTION, MSG_CH_BASE64_LOWER, MSG_CH_QUESTION);
-
-       if (_MsgEncode2Base64((unsigned char *)pOri, strlen(pOri), &nLen, (unsigned char *)szBuff + 10) == false) {
-               MSG_DEBUG("_MsgEncodeText: MsgEncodeBase64() is failed \n");
-               goto __CATCH;
-       }
-
-       strcat(szBuff, MSG_STR_DEC_END);
-
-       return szBuff;
-
-__CATCH:
-       if (szBuff) {
-               free(szBuff);
-       }
-
-       return false;
-}
-
diff --git a/plugin/mms_plugin/MmsPluginDebug.cpp b/plugin/mms_plugin/MmsPluginDebug.cpp
deleted file mode 100755 (executable)
index c27fd33..0000000
+++ /dev/null
@@ -1,1365 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include <stdio.h>
-#include "MmsPluginMIME.h"
-#include "MmsPluginMessage.h"
-
-static char gszDebugStringBuf[50];
-
-static char *MmsDebugPrintUnknownValue(int value)
-{
-       printf(gszDebugStringBuf, "unknown value(%d)", value);
-       return gszDebugStringBuf;
-}
-
-
-const char *MmsDebugGetMimeType(MimeType mimeType)
-{
-       switch (mimeType) {
-       case MIME_APPLICATION_XML:
-               return "MIME_APPLICATION_XML";
-       case MIME_APPLICATION_WML_XML:
-               return "MIME_APPLICATION_WML_XML";
-       case MIME_APPLICATION_XHTML_XML:
-               return "MIME_APPLICATION_XHTML_XML";
-       case MIME_APPLICATION_JAVA_VM:
-               return "MIME_APPLICATION_JAVA_VM";
-       case MIME_APPLICATION_SMIL:
-               return "MIME_APPLICATION_SMIL";
-       case MIME_APPLICATION_JAVA_ARCHIVE:
-               return "MIME_APPLICATION_JAVA_ARCHIVE";
-       case MIME_APPLICATION_JAVA:
-               return "MIME_APPLICATION_JAVA";
-       case MIME_APPLICATION_OCTET_STREAM:
-               return "MIME_APPLICATION_OCTET_STREAM";
-       case MIME_APPLICATION_STUDIOM:
-               return "MIME_APPLICATION_STUDIOM";
-       case MIME_APPLICATION_FUNMEDIA:
-               return "MIME_APPLICATION_FUNMEDIA";
-       case MIME_APPLICATION_MSWORD:
-               return "MIME_APPLICATION_MSWORD";
-       case MIME_APPLICATION_PDF:
-               return "MIME_APPLICATION_PDF";
-       case MIME_APPLICATION_ASTERIC:
-               return "MIME_APPLICATION_ASTERIC";
-       case MIME_APPLICATION_VND_WAP_XHTMLXML:
-               return "MIME_APPLICATION_VND_WAP_XHTMLXML";
-       case MIME_APPLICATION_VND_WAP_WMLC:
-               return "MIME_APPLICATION_VND_WAP_WMLC";
-       case MIME_APPLICATION_VND_WAP_WMLSCRIPTC:
-               return "MIME_APPLICATION_VND_WAP_WMLSCRIPTC";
-       case MIME_APPLICATION_VND_WAP_WTA_EVENTC:
-               return "MIME_APPLICATION_VND_WAP_WTA_EVENTC";
-       case MIME_APPLICATION_VND_WAP_UAPROF:
-               return "MIME_APPLICATION_VND_WAP_UAPROF";
-       case MIME_APPLICATION_VND_WAP_SIC:
-               return "MIME_APPLICATION_VND_WAP_SIC";
-       case MIME_APPLICATION_VND_WAP_SLC:
-               return "MIME_APPLICATION_VND_WAP_SLC";
-       case MIME_APPLICATION_VND_WAP_COC:
-               return "MIME_APPLICATION_VND_WAP_COC";
-       case MIME_APPLICATION_VND_WAP_SIA:
-               return "MIME_APPLICATION_VND_WAP_SIA";
-       case MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML:
-               return "MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML";
-       case MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA:
-               return "MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA";
-       case MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES:
-               return "MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES";
-       case MIME_APPLICATION_VND_WAP_MULTIPART_MIXED:
-               return "MIME_APPLICATION_VND_WAP_MULTIPART_MIXED";
-       case MIME_APPLICATION_VND_WAP_MULTIPART_RELATED:
-               return "MIME_APPLICATION_VND_WAP_MULTIPART_RELATED";
-       case MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE:
-               return "MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE";
-       case MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC:
-               return "MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC";
-       case MIME_APPLICATION_VND_OMA_DD_XML:
-               return "MIME_APPLICATION_VND_OMA_DD_XML";
-       case MIME_APPLICATION_VND_OMA_DRM_MESSAGE:
-               return "MIME_APPLICATION_VND_OMA_DRM_MESSAGE";
-       case MIME_APPLICATION_VND_OMA_DRM_CONTENT:
-               return "MIME_APPLICATION_VND_OMA_DRM_CONTENT";
-       case MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML:
-               return "MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML";
-       case MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML:
-               return "MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML";
-       case MIME_APPLICATION_VND_SMAF:
-               return "MIME_APPLICATION_VND_SMAF";
-       case MIME_APPLICATION_VND_RN_REALMEDIA:
-               return "MIME_APPLICATION_VND_RN_REALMEDIA";
-       case MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE:
-               return "MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE";
-       case MIME_APPLICATION_VND_EXCEL:
-               return "MIME_APPLICATION_VND_EXCEL";
-       case MIME_APPLICATION_X_HDMLC:
-               return "MIME_APPLICATION_X_HDMLC";
-       case MIME_APPLICATION_X_X968_USERCERT:
-               return "MIME_APPLICATION_X_X968_USERCERT";
-       case MIME_APPLICATION_X_WWW_FORM_URLENCODED:
-               return "MIME_APPLICATION_X_WWW_FORM_URLENCODED";
-       case MIME_APPLICATION_X_SMAF:
-               return "MIME_APPLICATION_X_SMAF";
-       case MIME_APPLICATION_X_FLASH:
-               return "MIME_APPLICATION_X_FLASH";
-       case MIME_APPLICATION_X_EXCEL:
-               return "MIME_APPLICATION_X_EXCEL";
-       case MIME_APPLICATION_X_POWERPOINT:
-               return "MIME_APPLICATION_X_POWERPOINT";
-
-       case MIME_AUDIO_BASIC:
-               return "MIME_AUDIO_BASIC";
-       case MIME_AUDIO_MPEG:
-               return "MIME_AUDIO_MPEG";
-       case MIME_AUDIO_MP3:
-               return "MIME_AUDIO_MP3";
-       case MIME_AUDIO_MPG3:
-               return "MIME_AUDIO_MPG3";
-       case MIME_AUDIO_MPEG3:
-               return "MIME_AUDIO_MPEG3";
-       case MIME_AUDIO_MPG:
-               return "MIME_AUDIO_MPG";
-       case MIME_AUDIO_AAC:
-               return "MIME_AUDIO_AAC";
-       case MIME_AUDIO_G72:
-               return "MIME_AUDIO_G72";
-       case MIME_AUDIO_AMR:
-               return "MIME_AUDIO_AMR";
-       case MIME_AUDIO_AMR_WB:
-               return "MIME_AUDIO_AMR_WB";
-       case MIME_AUDIO_MMF:
-               return "MIME_AUDIO_MMF";
-       case MIME_AUDIO_SMAF:
-               return "MIME_AUDIO_SMAF";
-       case MIME_AUDIO_IMELODY:
-               return "MIME_AUDIO_IMELODY";
-       case MIME_AUDIO_MELODY:
-               return "MIME_AUDIO_MELODY";
-       case MIME_AUDIO_MID:
-               return "MIME_AUDIO_MID";
-       case MIME_AUDIO_MIDI:
-               return "MIME_AUDIO_MIDI";
-       case MIME_AUDIO_X_MID:
-               return "MIME_AUDIO_X_MID";
-       case MIME_AUDIO_SP_MIDI:
-               return "MIME_AUDIO_SP_MIDI";
-       case MIME_AUDIO_WAVE:
-               return "MIME_AUDIO_WAVE";
-       case MIME_AUDIO_3GPP:
-               return "MIME_AUDIO_3GPP";
-       case MIME_AUDIO_MP4:
-               return "MIME_AUDIO_MP4";
-       case MIME_AUDIO_MP4A_LATM:
-               return "MIME_AUDIO_MP4A_LATM";
-       case MIME_AUDIO_VND_RN_REALAUDIO:
-               return "MIME_AUDIO_VND_RN_REALAUDIO";
-       case MIME_AUDIO_X_MPEG:
-               return "MIME_AUDIO_X_MPEG";
-       case MIME_AUDIO_X_MP3:
-               return "MIME_AUDIO_X_MP3";
-       case MIME_AUDIO_X_MPEG3:
-               return "MIME_AUDIO_X_MPEG3";
-       case MIME_AUDIO_X_MPG:
-               return "MIME_AUDIO_X_MPG";
-       case MIME_AUDIO_X_AMR:
-               return "MIME_AUDIO_X_AMR";
-       case MIME_AUDIO_X_MMF:
-               return "MIME_AUDIO_X_MMF";
-       case MIME_AUDIO_X_SMAF:
-               return "MIME_AUDIO_X_SMAF";
-       case MIME_AUDIO_X_IMELODY:
-               return "MIME_AUDIO_X_IMELODY";
-       case MIME_AUDIO_X_MIDI:
-               return "MIME_AUDIO_X_MIDI";
-       case MIME_AUDIO_X_MPEGAUDIO:
-               return "MIME_AUDIO_X_MPEGAUDIO";
-       case MIME_AUDIO_X_PN_REALAUDIO:
-               return "MIME_AUDIO_X_PN_REALAUDIO";
-       case MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO:
-               return "MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO";
-       case MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE:
-               return "MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE";
-       case MIME_AUDIO_X_WAV:
-               return "MIME_AUDIO_X_WAV";
-
-       case MIME_IMAGE_GIF:
-               return "MIME_IMAGE_GIF";
-       case MIME_IMAGE_JPEG:
-               return "MIME_IMAGE_JPEG";
-       case MIME_IMAGE_JPG:
-               return "MIME_IMAGE_JPG";
-       case MIME_IMAGE_TIFF:
-               return "MIME_IMAGE_TIFF";
-       case MIME_IMAGE_TIF:
-               return "MIME_IMAGE_TIF";
-       case MIME_IMAGE_PNG:
-               return "MIME_IMAGE_PNG";
-       case MIME_IMAGE_WBMP:
-               return "MIME_IMAGE_WBMP";
-       case MIME_IMAGE_PJPEG:
-               return "MIME_IMAGE_PJPEG";
-       case MIME_IMAGE_BMP:
-               return "MIME_IMAGE_BMP";
-       case MIME_IMAGE_SVG:
-               return "MIME_IMAGE_SVG";
-       case MIME_IMAGE_SVG1:
-               return "MIME_IMAGE_SVG1";
-       case MIME_IMAGE_VND_WAP_WBMP:
-               return "MIME_IMAGE_VND_WAP_WBMP";
-
-       case MIME_IMAGE_X_BMP:
-               return "MIME_IMAGE_X_BMP";
-
-       case MIME_MESSAGE_RFC822:
-               return "MIME_MESSAGE_RFC822";
-
-       case MIME_MULTIPART_MIXED:
-               return "MIME_MULTIPART_MIXED";
-       case MIME_MULTIPART_RELATED:
-               return "MIME_MULTIPART_RELATED";
-       case MIME_MULTIPART_ALTERNATIVE:
-               return "MIME_MULTIPART_ALTERNATIVE";
-       case MIME_MULTIPART_FORM_DATA:
-               return "MIME_MULTIPART_FORM_DATA";
-       case MIME_MULTIPART_BYTERANGE:
-               return "MIME_MULTIPART_BYTERANGE";
-       case MIME_MULTIPART_REPORT:
-               return "MIME_MULTIPART_REPORT";
-
-       case MIME_TEXT_TXT:
-               return "MIME_TEXT_TXT";
-       case MIME_TEXT_HTML:
-               return "MIME_TEXT_HTML";
-       case MIME_TEXT_PLAIN:
-               return "MIME_TEXT_PLAIN";
-       case MIME_TEXT_CSS:
-               return "MIME_TEXT_CSS";
-       case MIME_TEXT_XML:
-               return "MIME_TEXT_XML";
-       case MIME_TEXT_IMELODY:
-               return "MIME_TEXT_IMELODY";
-       case MIME_TEXT_VND_WAP_WMLSCRIPT:
-               return "MIME_TEXT_VND_WAP_WMLSCRIPT";
-       case MIME_TEXT_VND_WAP_WML:
-               return "MIME_TEXT_VND_WAP_WML";
-       case MIME_TEXT_VND_WAP_WTA_EVENT:
-               return "MIME_TEXT_VND_WAP_WTA_EVENT";
-       case MIME_TEXT_VND_WAP_CONNECTIVITY_XML:
-               return "MIME_TEXT_VND_WAP_CONNECTIVITY_XML";
-       case MIME_TEXT_VND_WAP_SI:
-               return "MIME_TEXT_VND_WAP_SI";
-       case MIME_TEXT_VND_WAP_SL:
-               return "MIME_TEXT_VND_WAP_SL";
-       case MIME_TEXT_VND_WAP_CO:
-               return "MIME_TEXT_VND_WAP_CO";
-       case MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR:
-               return "MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR";
-       case MIME_TEXT_X_HDML:
-               return "MIME_TEXT_X_HDML";
-       case MIME_TEXT_X_VCALENDAR:
-               return "MIME_TEXT_X_VCALENDAR";
-       case MIME_TEXT_X_VCARD:
-               return "MIME_TEXT_X_VCARD";
-       case MIME_TEXT_X_IMELODY:
-               return "MIME_TEXT_X_IMELODY";
-
-       case MIME_VIDEO_MPEG4:
-               return "MIME_VIDEO_MPEG4";
-       case MIME_VIDEO_MP4:
-               return "MIME_VIDEO_MP4";
-       case MIME_VIDEO_H263:
-               return "MIME_VIDEO_H263";
-       case MIME_VIDEO_3GPP:
-               return "MIME_VIDEO_3GPP";
-       case MIME_VIDEO_3GP:
-               return "MIME_VIDEO_3GP";
-       case MIME_VIDEO_AVI:
-               return "MIME_VIDEO_AVI";
-       case MIME_VIDEO_SDP:
-               return "MIME_VIDEO_SDP";
-       case MIME_VIDEO_VND_RN_REALVIDEO:
-               return "MIME_VIDEO_VND_RN_REALVIDEO";
-       case MIME_VIDEO_X_MP4:
-               return "MIME_VIDEO_X_MP4";
-       case MIME_VIDEO_X_PV_MP4:
-               return "MIME_VIDEO_X_PV_MP4";
-       case MIME_VIDEO_X_PN_REALVIDEO:
-               return "MIME_VIDEO_X_PN_REALVIDEO";
-       case MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO:
-               return "MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO";
-       default:
-               return MmsDebugPrintUnknownValue(mimeType);
-       }
-}
-
-
-/* MsgMmsMsg.h */
-const char *MmsDebugGetMmsReport(MmsReport report)
-{
-       switch (report) {
-       case MMS_REPORT_ERROR:
-               return "MMS_REPORT_ERROR";
-       case MMS_REPORT_YES:
-               return "MMS_REPORT_YES";
-       case MMS_REPORT_NO:
-               return "MMS_REPORT_NO";
-       }
-
-       return MmsDebugPrintUnknownValue(report);
-}
-
-
-const char *MmsDebugGetMmsReportAllowed(MmsReportAllowed reportAllowed)
-{
-       switch (reportAllowed) {
-       case MMS_REPORTALLOWED_ERROR:
-               return "MMS_REPORTALLOWED_ERROR";
-       case MMS_REPORTALLOWED_YES:
-               return "MMS_REPORTALLOWED_YES";
-       case MMS_REPORTALLOWED_NO:
-               return "MMS_REPORTALLOWED_NO";
-       }
-
-       return MmsDebugPrintUnknownValue(reportAllowed);
-}
-
-
-const char *MmsDebugGetMmsReadStatus(msg_read_report_status_t readStatus)
-{
-       _MSG_READ_REPORT_STATUS_E readReport = (_MSG_READ_REPORT_STATUS_E)readStatus;
-
-       switch (readReport) {
-       case MSG_READ_REPORT_NONE:
-               return "MMS_READSTATUS_NONE";
-       case MSG_READ_REPORT_IS_READ:
-               return "MMS_IS_READ";
-       case MSG_READ_REPORT_IS_DELETED:
-               return "MMS_IS_DELETED";
-       }
-
-       return MmsDebugPrintUnknownValue(readStatus);
-}
-
-const char *MmsDebugGetMsgType(MmsMsgType msgType)
-{
-       switch (msgType) {
-       case MMS_MSGTYPE_ERROR:
-               return "error";
-       case MMS_MSGTYPE_SEND_REQ:
-               return "send.req";
-       case MMS_MSGTYPE_SEND_CONF:
-               return "send.conf";
-       case MMS_MSGTYPE_NOTIFICATION_IND:
-               return "notification.ind";
-       case MMS_MSGTYPE_NOTIFYRESP_IND:
-               return "notifyResp.ind";
-       case MMS_MSGTYPE_RETRIEVE_CONF:
-               return "retrieve conf";
-       case MMS_MSGTYPE_ACKNOWLEDGE_IND:
-               return "acknowledge ind";
-       case MMS_MSGTYPE_DELIVERY_IND:
-               return "delivery ind";
-       case MMS_MSGTYPE_READREC_IND:
-               return "read rec ind";
-       case MMS_MSGTYPE_READORG_IND:
-               return "read org ind";
-       case MMS_MSGTYPE_FORWARD_REQ:
-               return "forward req";
-       case MMS_MSGTYPE_FORWARD_CONF:
-               return "forward conf";
-       case MMS_MSGTYPE_READ_REPLY:
-               return "read reply";
-       default:
-               return MmsDebugPrintUnknownValue(msgType);
-       }
-}
-
-const char *MmsDebugGetResponseStatus(MmsResponseStatus responseStatus)
-{
-       switch (responseStatus) {
-       case MMS_RESPSTATUS_ERROR:
-               return "error";
-       case MMS_RESPSTATUS_OK:
-               return "ok";
-       case MMS_RESPSTAUTS_ERROR_UNSPECIFIED:
-               return "unspecified";
-       case MMS_RESPSTAUTS_ERROR_SERVICEDENIED:
-               return "service denied";
-       case MMS_RESPSTAUTS_ERROR_MESSAGEFORMATCORRUPT:
-               return "message format corrupt";
-       case MMS_RESPSTAUTS_ERROR_SENDINGADDRESSUNRESOLVED:
-               return "sending address unresolved";
-       case MMS_RESPSTAUTS_ERROR_MESSAGENOTFOUND:
-               return "message not found";
-       case MMS_RESPSTAUTS_ERROR_NETWORKPROBLEM:
-               return "network problem";
-       case MMS_RESPSTAUTS_ERROR_CONTENTNOTACCEPTED:
-               return "content not accepted";
-       case MMS_RESPSTAUTS_ERROR_UNSUPPORTEDMESSAGE:
-               return "unsupported message";
-       case MMS_RESPSTAUTS_ERROR_TRANSIENT_FAILURE:
-               return "transient failure";
-       case MMS_RESPSTAUTS_ERROR_TRANSIENT_SENDING_ADDRESS_UNRESOLVED:
-               return "transient sending address unresolved";
-       case MMS_RESPSTAUTS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND:
-               return "transient message not found";
-       case MMS_RESPSTAUTS_ERROR_TRANSIENT_NETWORK_PROBLEM:
-               return "transient network problem";
-       case MMS_RESPSTAUTS_ERROR_PERMANENT_FAILURE:
-               return "permanent failure";
-       case MMS_RESPSTAUTS_ERROR_PERMANENT_SERVICE_DENIED:
-               return "permanent service denied";
-       case MMS_RESPSTAUTS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT:
-               return "permanent message format corrupt";
-       case MMS_RESPSTAUTS_ERROR_PERMANENT_SENDING_ADDRESS_UNRESOLVED:
-               return "permanent sending address unresolved";
-       case MMS_RESPSTAUTS_ERROR_PERMANENT_MESSAGE_NOT_FOUND:
-               return "permanent message not found";
-       case MMS_RESPSTAUTS_ERROR_PERMANENT_CONTENT_NOT_ACCEPTED:
-               return "permanent content not accepted";
-       case MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_LIMITATIONS_NOT_MET:
-               return "permanent reply charging limitations not met";
-       case MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_REQUEST_NOT_ACCEPTED:
-               return "permanent reply charging request not accepted";
-       case MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_FORWARDING_DENIED:
-               return "permanent reply charging forwarding denied";
-       case MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_NOT_SUPPORTED:
-               return "permanent reply charging not supported";
-       }
-
-       return MmsDebugPrintUnknownValue(responseStatus);
-}
-
-
-const char *MmsDebugGetRetrieveStatus(MmsRetrieveStatus retrieveStatus)
-{
-       switch (retrieveStatus) {
-       case MMS_RETRSTATUS_ERROR:
-               return "error";
-       case MMS_RETRSTATUS_OK:
-               return "ok";
-       case MMS_RETRSTATUS_TRANSIENT_FAILURE:
-               return "transient failure";
-       case MMS_RETRSTATUS_TRANSIENT_MESSAGE_NOT_FOUND:
-               return "transient message not found";
-       case MMS_RETRSTATUS_TRANSIENT_NETWORK_PROBLEM:
-               return "transient network problem";
-       case MMS_RETRSTATUS_PERMANENT_FAILURE:
-               return "permanent failure";
-       case MMS_RETRSTATUS_PERMANENT_SERVICE_DENIED:
-               return "permanent service denied";
-       case MMS_RETRSTATUS_PERMANENT_MESSAGE_NOT_FOUND:
-               return "permanent message not found";
-       case MMS_RETRSTATUS_PERMANENT_CONTENT_UNSUPPORT:
-               return "permanent content unsupport";
-       }
-
-       return MmsDebugPrintUnknownValue(retrieveStatus);
-}
-
-
-const char *MmsDebugGetMsgStatus(msg_delivery_report_status_t msgStatus)
-{
-       switch (msgStatus) {
-       case MSG_DELIVERY_REPORT_ERROR:
-               return "error";
-       case MSG_DELIVERY_REPORT_EXPIRED:
-               return "expired";
-       case MSG_DELIVERY_REPORT_SUCCESS:
-               return "retrieved";
-       case MSG_DELIVERY_REPORT_REJECTED:
-               return "rejected";
-       case MSG_DELIVERY_REPORT_DEFERRED:
-               return "deferred";
-       case MSG_DELIVERY_REPORT_UNRECOGNISED:
-               return "unrecognised";
-       case MSG_DELIVERY_REPORT_INDETERMINATE:
-               return "indeterminate";
-       case MSG_DELIVERY_REPORT_FORWARDED:
-               return "forwarded";
-       case MSG_DELIVERY_REPORT_UNREACHABLE:
-               return "unreachable";
-       }
-
-       return MmsDebugPrintUnknownValue(msgStatus);
-}
-
-
-const char *MmsDebugGetMsgClass(MmsMsgClass msgClass)
-{
-       switch (msgClass) {
-       case MMS_MSGCLASS_ERROR:
-               return "error";
-       case MMS_MSGCLASS_PERSONAL:
-               return "personal";
-       case MMS_MSGCLASS_ADVERTISEMENT:
-               return "advertisement";
-       case MMS_MSGCLASS_INFORMATIONAL:
-               return "information";
-       case MMS_MSGCLASS_AUTO:
-               return "auto";
-       }
-
-       return MmsDebugPrintUnknownValue(msgClass);
-}
-
-
-const char *MmsDebugGetDataType(MmsDataType dataType)
-{
-       switch (dataType) {
-       case MMS_DATATYPE_NONE:
-               return "MMS_DATATYPE_NONE";
-       case MMS_DATATYPE_READ:
-               return "MMS_DATATYPE_READ";
-       case MMS_DATATYPE_SENT:
-               return "MMS_DATATYPE_SENT";
-       case MMS_DATATYPE_NOTIFY:
-               return "MMS_DATATYPE_NOTIFY";
-       case MMS_DATATYPE_UNSENT:
-               return "MMS_DATATYPE_UNSENT";
-       case MMS_DATATYPE_DRAFT:
-               return "MMS_DATATYPE_DRAFT";
-       case MMS_DATATYPE_SENDING:
-               return "MMS_DATATYPE_SENDING";
-       case MMS_DATATYPE_DRM_RO_WAITING:
-               return "MMS_DATATYPE_DRM_RO_WAITING";
-       case MMS_DATATYPE_RETRIEVING:
-               return "MMS_DATATYPE_RETRIEVING";
-       case MMS_DATATYPE_UNRETV:
-               return "MMS_DATATYPE_UNRETV";
-       default:
-               return MmsDebugPrintUnknownValue(dataType);
-       }
-}
-
-#ifdef MMS_PLUGIN_DEBUG_ENABLE
-bool
-MmsDebugPrintMsgAttributes(char *pszFunc, MmsAttrib *pAttrib, bool bAll)
-{
-       SysRequireEx(pAttrib != NULL, false);
-
-       if (pszFunc)
-               SysDebug((MID_MMS|DBG_MMS_COMMON,"%s ========= \n", pszFunc));
-
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "szSubject = %s \n", pAttrib->szSubject));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "contentType=%s \n", MmsDebugGetMimeType(pAttrib->contentType)));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "dataType=%s \n", MmsDebugGetDataType(pAttrib->dataType)));
-
-       if (pAttrib->specialMsgType != MMS_SPECIAL_MSG_TYPE_NONE)
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "spcialMsgType = %lu \n", pAttrib->specialMsgType));
-
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "date=%lu, msgSize=%lu, bRead=%lu\n", pAttrib->date, pAttrib->msgSize, pAttrib->bRead));
-
-       if (!bAll)
-               return true;
-
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "msgClass=%s, priority=%lu \n", MmsDebugGetMsgClass(pAttrib->msgClass), pAttrib->priority ));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "deliveryTime.type = %lu, time = %lu\n", pAttrib->deliveryTime.type, pAttrib->deliveryTime.time));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "expiryTime.type = %lu, time = %lu\n", pAttrib->expiryTime.type, pAttrib->expiryTime.time));
-
-       if (pAttrib->szTo && pAttrib->szTo[0] != 0)
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "szTo = %s \n", pAttrib->szTo));
-       if (pAttrib->szCc && pAttrib->szCc[0] != 0)
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "szCc = %s \n", pAttrib->szCc));
-       if (pAttrib->szBcc && pAttrib->szBcc[0] != 0)
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "szBcc = %s \n", pAttrib->szBcc));
-
-#if defined(_MMS_SUPPORT_RECEIVING_OPTION_PROMPT)
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "readReportAllowedType = %lu \n", pAttrib->readReportAllowedType));
-#endif
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "bAskDeliveryReport=%lu, bReportAllowed=%lu, bAskReadReply=%lu, bLeaveCopy=%lu \n",
-                       pAttrib->bAskDeliveryReport, pAttrib->bReportAllowed, pAttrib->bAskReadReply, pAttrib->bLeaveCopy));
-
-       if (pAttrib->bHideAddress)
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "bHideAddress=true\n"));
-
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "msgStatus = %s \n", MmsDebugGetMsgStatus(pAttrib->msgStatus)));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "responseStatus = %s \n", MmsDebugGetResponseStatus(pAttrib->responseStatus)));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "retrieveStatus = %s \n", MmsDebugGetRetrieveStatus(pAttrib->retrieveStatus)));
-
-       if (pAttrib->szResponseText && pAttrib->szResponseText[0] != 0)
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "szResponseText = %s \n", pAttrib->szResponseText));
-
-       if (pAttrib->szRetrieveText && pAttrib->szRetrieveText[0] != 0)
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "szRetrieveText = %s \n", pAttrib->szRetrieveText));
-
-       return true;
-}
-
-char *MmsDebugGetMsgDrmType(MsgDrmType drmType)
-{
-       switch (drmType) {
-       case MSG_DRM_TYPE_NONE:
-               return "MSG_DRM_TYPE_NONE";
-       case MSG_DRM_TYPE_FL:
-               return "MSG_DRM_TYPE_FL";
-       case MSG_DRM_TYPE_CD:
-               return "MSG_DRM_TYPE_CD";
-       case MSG_DRM_TYPE_SD:
-               return "MSG_DRM_TYPE_SD";
-       case MSG_DRM_TYPE_SSD:
-               return "MSG_DRM_TYPE_SSD";
-       }
-
-       return MmsDebugPrintUnknownValue(drmType);
-}
-
-char *MmsDebugGetDrmDeliveryMode(DrmDeliveryMode deliveryMode)
-{
-       switch (deliveryMode) {
-       case DRM_DELIVERYMODE_FORWARD_LOCK:
-               return "DRM_DELIVERYMODE_FORWARD_LOCK";
-       case DRM_DELIVERYMODE_COMBINED_DELIVERY:
-               return "DRM_DELIVERYMODE_COMBINED_DELIVERY";
-       case DRM_DELIVERYMODE_SEPARATE_DELIVERY:
-               return "DRM_DELIVERYMODE_SEPARATE_DELIVERY";
-       case DRM_DELIVERYMODE_SPECIAL_SEPARATE:
-               return "DRM_DELIVERYMODE_SPECIAL_SEPARATE";
-       }
-
-       return MmsDebugPrintUnknownValue(deliveryMode);
-}
-
-char *MmsDebugGetDrmRightState(DrmRightState rightState)
-{
-       switch (rightState) {
-       case DRMRIGHT_STATE_NORIGHTS:
-               return "DRMRIGHT_STATE_NORIGHTS";
-       case DRMRIGHT_STATE_INVALID_RIGHTS:
-               return "DRMRIGHT_STATE_INVALID_RIGHTS";
-       case DRMRIGHT_STATE_VALID_RIGHTS:
-               return "DRMRIGHT_STATE_VALID_RIGHTS";
-       case DRMRIGHT_STATE_EXPIRED_RIGHTS:
-               return "DRMRIGHT_STATE_EXPIRED_RIGHTS";
-       }
-
-       return MmsDebugPrintUnknownValue(rightState);
-}
-
-
-bool MmsDebugPrintDrmRight(DrmRight *pDrmRight)
-{
-       if (!pDrmRight)
-               return true;
-
-       if (pDrmRight->rightStatus == DRMRIGHT_STATE_NORIGHTS) {
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "rightStatus = %s \n", MmsDebugGetDrmRightState(pDrmRight->rightStatus)));
-               return true;
-       }
-
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "iDeliveryType = %s \n", MmsDebugGetDrmDeliveryMode(pDrmRight->iDeliveryType)));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "bestConstraint = %s \n", MmsDebugGetDrmConsumeMode(pDrmRight->bestConstraint)));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "bFirstIntervalRender = %d \n", pDrmRight->bFirstIntervalRender));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "rightStatus = %s \n", MmsDebugGetDrmRightState(pDrmRight->rightStatus)));
-
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "bValidIssuer = %d \n", pDrmRight->bValidIssuer));
-
-       return true;
-}
-
-char *MmsDebugPrintMsgDRMStatus(MsgDRMStatus status)
-{
-       switch (status) {
-       case MSG_DRM_STATUS_INVALID:
-               return "MSG_DRM_STATUS_INVALID";
-       case MSG_DRM_STATUS_VALID:
-               return "MSG_DRM_STATUS_VALID";
-       case MSG_DRM_STATUS_EXPIRED:
-               return "MSG_DRM_STATUS_EXPIRED";
-       }
-
-       return MmsDebugPrintUnknownValue(status);
-}
-
-
-bool MmsDebugPrintMulitpartEntry(MsgMultipart *pMultipart, int index)
-{
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "------------------------------\n"));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "%dth multipart info\n", index));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "header size=%d\n", pMultipart->type.size));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "body size=%d\n", pMultipart->type.contentSize));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "content type=%s\n", MmsDebugGetMimeType(pMultipart->type.type)));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "content ID=%s\n", pMultipart->type.szContentID));
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "content location=%s\n", pMultipart->type.szContentLocation));
-
-       if (pMultipart->type.type == MIME_TEXT_PLAIN) {
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "text info\n"));
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "charset=%d\n", pMultipart->type.param.charset));
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "text file name=%s\n", pMultipart->type.param.szName));
-       }
-
-       if (pMultipart->type.drmInfo.drmType != MSG_DRM_TYPE_NONE) {
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "drm info\n"));
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "drm type=%s\n", MmsDebugGetMsgDrmType(pMultipart->type.drmInfo.drmType)));
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "drm content type=%s\n", MmsDebugGetMimeType(pMultipart->type.drmInfo.contentType)));
-               SysDebug((MID_MMS|DBG_MMS_COMMON, "drm content URI=%s\n", pMultipart->type.drmInfo.szContentURI));
-       }
-       SysDebug((MID_MMS|DBG_MMS_COMMON, "------------------------------\n"));
-       return true;
-}
-
-
-bool MmsDebugPrintCurrentEventHandler(char *pszFunc, MmsDebugEvType evType)
-{
-       HEventHandler hMmsEH;
-       HEventHandler hSmsEH;
-       HEventHandler hEmailEH;
-       HEventHandler hCommonEH;
-       HEventHandler hCurrentEH;
-
-       hMmsEH          = WmGetEventHandlerByName(EHN_MMS);
-       hSmsEH          = WmGetEventHandlerByName(EHN_SMS);
-       hEmailEH        = WmGetEventHandlerByName(EHN_EMAIL);
-       hCommonEH       = WmGetEventHandlerByName(EHN_MESSENGER);
-       hCurrentEH      = WmGetCurrentEventHandler();
-
-       switch (evType) {
-       case MMS_DEBUG_EV_MMS:
-               SysRequireExf(hCurrentEH == hMmsEH, false, ("%s, hMmsEH=%d, hSmsEH=%d, hEmailEH=%d, hCommonEH=%d, hCurrentEH=%d\n",     \
-                                                       pszFunc, hMmsEH, hSmsEH, hEmailEH, hCommonEH, hCurrentEH));
-               break;
-
-       case MMS_DEBUG_EV_SMS:
-               SysRequireExf(hCurrentEH == hSmsEH, false, ("%s, hMmsEH=%d, hSmsEH=%d, hEmailEH=%d, hCommonEH=%d, hCurrentEH=%d\n",     \
-                                                       pszFunc, hMmsEH, hSmsEH, hEmailEH, hCommonEH, hCurrentEH));
-               break;
-
-       case MMS_DEBUG_EV_COMMON:
-               SysRequireExf(hCurrentEH == hCommonEH, false, ("%s, hMmsEH=%d, hSmsEH=%d, hEmailEH=%d, hCommonEH=%d, hCurrentEH=%d\n",  \
-                                                       pszFunc, hMmsEH, hSmsEH, hEmailEH, hCommonEH, hCurrentEH));
-               break;
-
-       case MMS_DEBUG_EV_EMAIL:
-               SysRequireExf(hCurrentEH == hEmailEH, false, ("%s, hMmsEH=%d, hSmsEH=%d, hEmailEH=%d, hCommonEH=%d, hCurrentEH=%d\n",   \
-                                                       pszFunc, hMmsEH, hSmsEH, hEmailEH, hCommonEH, hCurrentEH));
-               break;
-
-       case MMS_DEBUG_EV_NONE:
-       default:
-               SysDebug((MID_MMS,"%s, hMmsEH=%d, hSmsEH=%d, hEmailEH=%d, hCommonEH=%d, hCurrentEH=%d\n",       \
-                                                       pszFunc, hMmsEH, hSmsEH, hEmailEH, hCommonEH, hCurrentEH));
-               break;
-       }
-       return true;
-}
-
-
-char *DebugPrintGetRmResultInd(MmsRmResultInd indType)
-{
-       switch (indType) {
-       case RM_RESULTIND_NONE:
-               return "RM_RESULTIND_NONE";
-
-       case RM_RESULTIND_MANUAL_SEND:
-               return "RM_RESULTIND_MANUAL_SEND";
-
-       case RM_RESULTIND_AUTO_SEND:
-               return "RM_RESULTIND_AUTO_SEND";
-
-       case RM_RESULTIND_MANUAL_GET:
-               return "RM_RESULTIND_MANUAL_GET";
-
-       case RM_RESULTIND_AUTO_GET:
-               return "RM_RESULTIND_AUTO_GET";
-
-       case RM_RESULTIND_MANUAL_FORWARD:
-               return "RM_RESULTIND_MANUAL_FORWARD";
-       }
-
-       return MmsDebugPrintUnknownValue(indType);
-}
-
-
-char *DebugPrintHttpStatusCode(int status)
-{
-       switch (status) {
-       case HTTP_STATUS_100:
-               return "HTTP_STATUS_100";
-       case HTTP_STATUS_101:
-               return "HTTP_STATUS_101";
-
-       case HTTP_STATUS_200:
-               return "HTTP_STATUS_200";
-       case HTTP_STATUS_201:
-               return "HTTP_STATUS_201";
-       case HTTP_STATUS_202:
-               return "HTTP_STATUS_202";
-       case HTTP_STATUS_203:
-               return "HTTP_STATUS_203";
-       case HTTP_STATUS_204:
-               return "HTTP_STATUS_204";
-       case HTTP_STATUS_205:
-               return "HTTP_STATUS_205";
-       case HTTP_STATUS_206:
-               return "HTTP_STATUS_206";
-
-       case HTTP_STATUS_300:
-               return "HTTP_STATUS_300";
-       case HTTP_STATUS_301:
-               return "HTTP_STATUS_301";
-       case HTTP_STATUS_302:
-               return "HTTP_STATUS_302";
-       case HTTP_STATUS_303:
-               return "HTTP_STATUS_303";
-       case HTTP_STATUS_304:
-               return "HTTP_STATUS_304";
-       case HTTP_STATUS_305:
-               return "HTTP_STATUS_305";
-
-       case HTTP_STATUS_400:
-               return "HTTP_STATUS_400";
-       case HTTP_STATUS_401:
-               return "HTTP_STATUS_401";
-       case HTTP_STATUS_402:
-               return "HTTP_STATUS_402";
-       case HTTP_STATUS_403:
-               return "HTTP_STATUS_403";
-       case HTTP_STATUS_404:
-               return "HTTP_STATUS_404";
-       case HTTP_STATUS_405:
-               return "HTTP_STATUS_405";
-       case HTTP_STATUS_406:
-               return "HTTP_STATUS_406";
-       case HTTP_STATUS_407:
-               return "HTTP_STATUS_407";
-       case HTTP_STATUS_408:
-               return "HTTP_STATUS_408";
-       case HTTP_STATUS_409:
-               return "HTTP_STATUS_409";
-       case HTTP_STATUS_410:
-               return "HTTP_STATUS_410";
-       case HTTP_STATUS_411:
-               return "HTTP_STATUS_411";
-       case HTTP_STATUS_412:
-               return "HTTP_STATUS_412";
-       case HTTP_STATUS_413:
-               return "HTTP_STATUS_413";
-       case HTTP_STATUS_414:
-               return "HTTP_STATUS_414";
-       case HTTP_STATUS_415:
-               return "HTTP_STATUS_415";
-
-       case HTTP_STATUS_500:
-               return "HTTP_STATUS_500";
-       case HTTP_STATUS_501:
-               return "HTTP_STATUS_501";
-       case HTTP_STATUS_502:
-               return "HTTP_STATUS_502";
-       case HTTP_STATUS_503:
-               return "HTTP_STATUS_503";
-       case HTTP_STATUS_504:
-               return "HTTP_STATUS_504";
-       case HTTP_STATUS_505:
-               return "HTTP_STATUS_505";
-
-       case REASON_WTP_UNKNOWN:
-               return "REASON_WTP_UNKNOWN";
-       case REASON_WTP_PROTO_ERR:
-               return "REASON_WTP_PROTO_ERR";
-       case REASON_WTP_INVALID_TID:
-               return "REASON_WTP_INVALID_TID";
-       case REASON_WTP_NOT_IMPLEMENTED_CL2:
-               return "REASON_WTP_NOT_IMPLEMENTED_CL2";
-       case REASON_WTP_NOT_IMPLEMENTED_SAR:
-               return "REASON_WTP_NOT_IMPLEMENTED_SAR";
-       case REASON_WTP_NOT_IMPLEMENTEDU_ACK:
-               return "REASON_WTP_NOT_IMPLEMENTEDU_ACK";
-       case REASON_WTP_VERSIONONE:
-               return "REASON_WTP_VERSIONONE";
-       case REASON_WTP_CAPTEMP_EXCEED:
-               return "REASON_WTP_CAPTEMP_EXCEED";
-       case REASON_WTP_NO_RESPONSE:
-               return "REASON_WTP_NO_RESPONSE";
-       case REASON_WTP_MESSAGE_TOO_LARGE:
-               return "REASON_WTP_MESSAGE_TOO_LARGE";
-
-       case REASON_PROTOERR:
-               return "REASON_PROTOERR";       //  = 0xE0
-       case REASON_DISCONNECT:
-               return "REASON_DISCONNECT";
-       case REASON_SUSPEND:
-               return "REASON_SUSPEND";
-       case REASON_RESUME:
-               return "REASON_RESUME";
-       case REASON_CONGESTION:
-               return "REASON_CONGESTION";
-       case REASON_CONNECTERR:
-               return "REASON_CONNECTERR";
-       case REASON_MRUEXCEEDED:
-               return "REASON_MRUEXCEEDED";
-       case REASON_MOREXCEEDED:
-               return "REASON_MOREXCEEDED";
-       case REASON_PEERREQ:
-               return "REASON_PEERREQ";
-       case REASON_NETERR:
-               return "REASON_NETERR";
-       case REASON_USERREQ:
-               return "REASON_USERREQ";
-       /* added for ver 1.2 */
-       case REASON_USERRFS:
-               return "REASON_USERRFS";
-       case REASON_PND:
-               return "REASON_PND";
-       case REASON_USERDCR:
-               return "REASON_USERDCR";
-       case REASON_USERDCU:
-               return "REASON_USERDCU";
-       }
-
-       return MmsDebugPrintUnknownValue(status);
-}
-
-
-char *DebugPrintRmMethodType(MmsRmMethodType method)
-{
-       switch (method) {
-       case RM_METHOD_NONE:
-               return "RM_METHOD_NONE";
-       case RM_METHOD_GET:
-               return "RM_METHOD_GET";
-       case RM_METHOD_POST:
-               return "RM_METHOD_POST";
-       }
-
-       return MmsDebugPrintUnknownValue(method);
-}
-
-
-char *DebugPrintGetMmsRmNetState(MmsRmNetState state)
-{
-       switch (state) {
-       case RM_PROTO_IDLE:
-               return "RM_PROTO_IDLE";
-       case RM_PROTO_STARTING:
-               return "RM_PROTO_STARTING";
-       case RM_PROTO_STARTED:
-               return "RM_PROTO_STARTED";
-       case RM_PROTO_STOPPING:
-               return "RM_PROTO_STOPPING";
-
-       case RM_PROTO_WAITING:
-               return "RM_PROTO_WAITING";
-       case RM_PROTO_DISCONNECTING_OTHER_APP:
-               return "RM_PROTO_DISCONNECTING_OTHER_APP";
-       case RM_PROTO_DISCONNECTED_BY_OTHER_APP:
-               return "RM_PROTO_DISCONNECTED_BY_OTHER_APP";
-
-       case RM_PROTO_FAILED:
-               return "RM_PROTO_FAILED";
-       }
-
-       return MmsDebugPrintUnknownValue(state);
-}
-
-
-char *DebugPrintGetMmsRmEntityState(MmsRmExEntityState stateEx)
-{
-       switch (stateEx) {
-       case RM_ENTITY_IDLE:
-               return "RM_ENTITY_IDLE";
-       case RM_ENTITY_PROTO_STARTING:
-               return "RM_ENTITY_PROTO_STARTING";
-
-       case RM_ENTITY_CNXN_ESTABLISHING:
-               return "RM_ENTITY_CNXN_ESTABLISHING";
-       case RM_ENTITY_CNXN_ESTABLISHED:
-               return "RM_ENTITY_CNXN_ESTABLISHED";
-
-       case RM_ENTITY_SENDING_REQUEST:
-               return "RM_ENTITY_SENDING_REQUEST";
-       case RM_ENTITY_SENDING_REQ_N_NO_RESPONSE:
-               return "RM_ENTITY_SENDING_REQ_N_NO_RESPONSE";
-
-       case RM_ENTITY_SENDING_REQ_COMPLETED:
-               return "RM_ENTITY_SENDING_REQ_COMPLETED";
-
-       case RM_ENTITY_SENDING_REQ_FAILED:
-               return "RM_ENTITY_SENDING_REQ_FAILED";
-       case RM_ENTITY_SENDING_REQ_CANCELLED_BY_USER_CONFIRMED:
-               return "RM_ENTITY_SENDING_REQ_CANCELLED_BY_USER_CONFIRMED";
-       }
-
-       return MmsDebugPrintUnknownValue(stateEx);
-}
-
-
-char *MmsDebugPrintMmsRmResult(MmsRmResult result)
-{
-       switch (result) {
-       case MMS_RM_RESULT_SUCCESSED:
-               return "MMS_RM_RESULT_SUCCESSED";
-       case MMS_RM_RESULT_FAIL:
-               return "MMS_RM_RESULT_FAIL";
-       case MMS_RM_RESULT_FAIL_N_RETRY:
-               return "MMS_RM_RESULT_FAIL_N_RETRY";
-
-       case MMS_RM_RESULT_PROTO_STARTING_FAILED:
-               return "MMS_RM_RESULT_PROTO_STARTING_FAILED";
-
-       case MMS_RM_RESULT_DISCONNECT_MMS:
-               return "MMS_RM_RESULT_DISCONNECT_MMS";
-       case MMS_RM_RESULT_CLOSING_OTHER_APP_FAILED:
-               return "MMS_RM_RESULT_CLOSING_OTHER_APP_FAILED";
-
-       case MMS_RM_RESULT_SENDING_REQ_FAILED:
-               return "MMS_RM_RESULT_SENDING_REQ_FAILED";
-       case MMS_RM_RESULT_CANCELED_BY_USER:
-               return "MMS_RM_RESULT_CANCELED_BY_USER";
-       case MMS_RM_RESULT_CANCELED_FROM_RETRY_POPUP:
-               return "MMS_RM_RESULT_CANCELED_FROM_RETRY_POPUP";
-
-       case MMS_RM_RESULT_PROTO_FAILED:
-               return "MMS_RM_RESULT_PROTO_FAILED";
-       case MMS_RM_RESULT_DISCONNECTED_BY_OTHER:
-               return "MMS_RM_RESULT_DISCONNECTED_BY_OTHER";
-
-       case MMS_RM_RESULT_MEMORY_FULL:
-               return "MMS_RM_RESULT_MEMORY_FULL";
-       }
-
-       return MmsDebugPrintUnknownValue(result);
-}
-
-void MmsDebugPrintReqEntityInfo(MmsRmRequest *pEntity)
-{
-       SysDebug((MID_MMS,"     - proto state=%s\n", DebugPrintGetMmsRmNetState(_MmsRmNetGetState())));
-
-       if (_MmsRmNetGetProtoType() == MMS_RM_WAP_CONNORIENTED || _MmsRmNetGetProtoType() == MMS_RM_WTLS) {
-               SysDebug((MID_MMS,"     - wap cnxn state=%s\n", DebugPrintWspState(MmsRmWspGetCnxnState())));
-       }
-
-       if (!pEntity) {
-               SysDebug((MID_EXCEPTION, "MmsDebugPrintReqEntityInfo : pEntity is NULL. \n"));
-               return;
-       }
-
-       SysDebug((MID_MMS,"     - entity state=%s\n", DebugPrintGetMmsRmEntityState(pEntity->stateEx)));
-
-       if (pEntity->cb.result.bSend) {
-               if (pEntity->pduType == MMS_RM_READ_REPORT_V10) {
-                       SysDebug((MID_MMS,"     - sending read report v10\n"));
-               } else if (pEntity->pduType == MMS_RM_READ_REPORT_V11) {
-                       SysDebug((MID_MMS,"     - sending read report v11\n"));
-               } else {
-                       SysDebug((MID_MMS,"     - sending msg\n"));
-               }
-       } else {        // then receiving..
-               if (pEntity->cb.result.bAutoRetrieving) {
-                       SysDebug((MID_MMS,"     - retrieving(auto)\n"));
-               } else {
-                       SysDebug((MID_MMS,"     - retrieving(manual)\n"));
-               }
-       }
-
-       SysDebug((MID_MMS,"     - msgID=%d, trID=0x%x, pduType=%s\n", pEntity->msgID, pEntity->trId, MmsDebugPrintRmPduType(pEntity->pduType)));
-
-       if (pEntity->protoActvCount > 1) {
-               SysDebug((MID_MMS,"     - protoActvCount=%d\n", pEntity->protoActvCount));
-       }
-
-       if (pEntity->reqCount > 1) {
-               SysDebug((MID_MMS,"     - reqCount=%d\n", pEntity->reqCount));
-       }
-
-       if (pEntity->fullRetryCount > 1) {
-               SysDebug((MID_MMS,"     - fullRetryCount=%d\n", pEntity->fullRetryCount));
-       }
-}
-
-char *MmsDebugPrintHttpErrorCode(int errCode)
-{
-       switch (errCode) {
-       case HTTPERR_INVALID_PARAM:
-               return "HTTPERR_INVALID_PARAM";
-       case HTTPERR_UNKNOWN:
-               return "HTTPERR_UNKNOWN";
-       case HTTPERR_INVALID_PROXY:
-               return "HTTPERR_INVALID_PROXY";
-       case HTTPERR_OUT_OF_MEMORY:
-               return "HTTPERR_OUT_OF_MEMORY";
-       case HTTPERR_NO_RESPONSE:
-               return "HTTPERR_NO_RESPONSE";
-       case HTTPERR_INIT:
-               return "HTTPERR_INIT";
-       case HTTPERR_NETDOWN:
-               return "HTTPERR_NETDOWN";
-       case HTTPERR_TIMEOUT:
-               return "HTTPERR_TIMEOUT";
-       case HTTPERR_HOST_UNREACH:
-               return "HTTPERR_HOST_UNREACH";
-       case HTTPERR_CONN_RESET:
-               return "HTTPERR_CONN_RESET";
-       case HTTPERR_INTERNAL:
-               return "HTTPERR_INTERNAL";
-       case HTTPERR_CHUNKEDTR:
-               return "HTTPERR_CHUNKEDTR";
-       case HTTPERR_USER:
-               return "HTTPERR_USER";
-       case HTTPERR_TOO_BIG:
-               return "HTTPERR_TOO_BIG";
-       case HTTPERR_NOT_SUPPORTED_SVC:
-               return "HTTPERR_NOT_SUPPORTED_SVC";
-       case HTTPERR_NO_CONTENT:
-               return "HTTPERR_NO_CONTENT";
-       case HTTPERR_WRITEFAIL:
-               return "HTTPERR_WRITEFAIL";
-       case HTTPERR_AUTHFAIL:
-               return "HTTPERR_AUTHFAIL";
-
-       case HTTPERR_DNSFAIL:
-               return "HTTPERR_DNSFAIL";
-       case HTTPERR_UAGENT_NOT_ALLOWED:
-               return "HTTPERR_UAGENT_NOT_ALLOWED";
-
-       }
-       return MmsDebugPrintUnknownValue(errCode);
-}
-
-char *MmsDebugPrintProtoErrorCode(int errCode)
-{
-       switch (errCode) {
-       case PROTO_ERROR_NONE:
-               return "PROTO_ERROR_NONE";
-       /* Wireless stack errors */
-       case PROTO_ERROR_NO_SERVICE:
-               return "PROTO_ERROR_NO_SERVICE";
-       case PROTO_ERROR_INVALID_PARAM:
-               return "PROTO_ERROR_INVALID_PARAM";
-       case PROTO_ERROR_INVALID_APN:
-               return "PROTO_ERROR_INVALID_APN";
-       case PROTO_ERROR_INVALID_OP_MODE:
-               return "PROTO_ERROR_INVALID_OP_MODE";
-       case PROTO_ERROR_INVALID_PROTO_TYPE:
-               return "PROTO_ERROR_INVALID_PROTO_TYPE";
-       case PROTO_ERROR_INVALID_SERVICE_DOMAIN:
-               return "PROTO_ERROR_INVALID_SERVICE_DOMAIN";
-       case PROTO_ERROR_INVALID_PDP_DATA:
-               return "PROTO_ERROR_INVALID_PDP_DATA";
-       case PROTO_ERROR_INVALID_QOS:
-               return "PROTO_ERROR_INVALID_QOS";
-       case PROTO_ERROR_SESSION_DEACTIVATED:
-               return "PROTO_ERROR_SESSION_DEACTIVATED";
-       case PROTO_ERROR_AUTHENTICATION_FAILED:
-               return "PROTO_ERROR_AUTHENTICATION_FAILED";
-       case PROTO_ERROR_MOBILE_FAILURE:
-               return "PROTO_ERROR_MOBILE_FAILURE";
-       case PROTO_ERROR_NETWORK_FAILURE:
-               return "PROTO_ERROR_NETWORK_FAILURE";
-       case PROTO_ERROR_TIMEOUT:
-               return "PROTO_ERROR_TIMEOUT";
-       case PROTO_ERROR_NO_RESOURCE:
-               return "PROTO_ERROR_NO_RESOURCE";
-       case PROTO_ERROR_INVALID_CONTEXT_ID:
-               return "PROTO_ERROR_INVALID_CONTEXT_ID";
-       case PROTO_ERROR_MODEM_IN_USE:
-               return "PROTO_ERROR_MODEM_IN_USE";
-       case PROTO_ERROR_INVALID_SIM_STATE:
-               return "PROTO_ERROR_INVALID_SIM_STATE:";
-       case PROTO_ERROR_SERVICE_NOT_SUBSCRIBED:
-               return "PROTO_ERROR_SERVICE_NOT_SUBSCRIBED";
-       case PROTO_ERROR_SERVICE_NOT_IMPLEMENTED:
-               return "PROTO_ERROR_SERVICE_NOT_IMPLEMENTED";
-       case PROTO_ERROR_FDN_NOT_ALLOWED:
-               return "PROTO_ERROR_FDN_NOT_ALLOWED";
-       case PROTO_ERROR_CALL_INCOME:
-               return "PROTO_ERROR_CALL_INCOME";
-       case PROTO_ERROR_NOT_SUPPORT_3GCSD:
-               return "PROTO_ERROR_NOT_SUPPORT_3GCSD";
-       case PROTO_ERROR_UNKNOWN:
-               return "PROTO_ERROR_UNKNOWN";
-       case PROTO_ERROR_SI_OFFLINE:
-               return "PROTO_ERROR_SI_OFFLINE";
-       /* TCP/IP/PPP stack errors */
-       case PROTO_ERROR_TCPIP_UP:
-               return "PROTO_ERROR_TCPIP_UP";
-       case PROTO_ERROR_TCPIP_DOWN:
-               return "PROTO_ERROR_TCPIP_DOWN";
-       case PROTO_ERROR_PPP_UP:
-               return "PROTO_ERROR_PPP_UP";
-       case PROTO_ERROR_PPP_DOWN:
-               return "PROTO_ERROR_PPP_DOWN";
-       case PROTO_ERROR_WDP_INIT:
-               return "PROTO_ERROR_WDP_INIT";
-       /* ProtoMgr API call errors */
-       case PROTO_ERROR_ACTIVE_CONNECTIONS:
-               return "PROTO_ERROR_ACTIVE_CONNECTIONS";
-       case PROTO_ERROR_MAX_CONNECTIONS:
-               return "PROTO_ERROR_MAX_CONNECTIONS";
-       case PROTO_ERROR_INVALID_HANDLE:
-               return "PROTO_ERROR_INVALID_HANDLE";
-       case PROTO_ERROR_INVALID_CONTEXT:
-               return "PROTO_ERROR_INVALID_CONTEXT";
-       case PROTO_ERROR_INVALID_CALLBACK:
-               return "PROTO_ERROR_INVALID_CALLBACK";
-       case PROTO_ERROR_INVALID_EHN:
-               return "PROTO_ERROR_INVALID_EHN";
-       case PROTO_ERROR_INVALID_EVENTCLASS:
-               return "PROTO_ERROR_INVALID_EVENTCLASS";
-       case PROTO_ERROR_INVALID_REFTYPE:
-               return "PROTO_ERROR_INVALID_REFTYPE";
-       case PROTO_ERROR_INVALID_TIMEOUT:
-               return "PROTO_ERROR_INVALID_TIMEOUT";
-       case PROTO_ERROR_MAX_CLIENT:
-               return "PROTO_ERROR_MAX_CLIENT";
-       case PROTO_ERROR_MAX_ACCOUNT:
-               return "PROTO_ERROR_MAX_ACCOUNT";
-       case PROTO_ERROR_ACCESS_DENIED:
-               return "PROTO_ERROR_ACCESS_DENIED";
-       case PROTO_ERROR_REGISTRY_LOAD:
-               return "PROTO_ERROR_REGISTRY_LOAD";
-
-       case PROTO_ERROR_PCBROWSING_ON:
-               return "PROTO_ERROR_PCBROWSING_ON";
-       case PROTO_ERROR_REACTIVATION_REQ:
-               return "PROTO_ERROR_REACTIVATION_REQ";
-       case PROTO_ERROR_NO_PDP_ACTIVATED:
-               return "PROTO_ERROR_NO_PDP_ACTIVATED";
-
-       case PROTO_ERROR_MAX:
-               return "PROTO_ERROR_MAX";
-
-       }
-
-       return MmsDebugPrintUnknownValue(errCode);
-}
-
-
-char *DebugPrintWspResult(WspResult wspResult)
-{
-       switch (wspResult) {
-       case WSP_RESULT_NO_ERROR:
-               return "WSP_RESULT_NO_ERROR";
-       case WSP_RESULT_NO_SESSION:
-               return "WSP_RESULT_NO_SESSION";
-       case WSP_RESULT_NOT_SUITABLE:
-               return "WSP_RESULT_NOT_SUITABLE";
-
-       case WSP_RESULT_NOT_RESPONDING:
-               return "WSP_RESULT_NOT_RESPONDING";
-       case WSP_RESULT_MOP_EXCEED:
-               return "WSP_RESULT_MOP_EXCEED";
-       case WSP_RESULT_MOM_EXCEED:
-               return "WSP_RESULT_MOM_EXCEED";
-
-       case WSP_RESULT_UNABLE:
-               return "WSP_RESULT_UNABLE";
-       case WSP_RESULT_UNKNOWN:
-               return "WSP_RESULT_UNKNOWN";
-       case WSP_RESULT_WRONG_PARAM:
-               return "WSP_RESULT_WRONG_PARAM";
-
-       case WSP_RESULT_NO_MEMORY:
-               return "WSP_RESULT_NO_MEMORY";
-       case WSP_RESULT_NO_HANDLE:
-               return "WSP_RESULT_NO_HANDLE";
-
-       case WSP_RESULT_CAPABILITY_UNABLE:
-               return "WSP_RESULT_CAPABILITY_UNABLE";
-       case WSP_RESULT_UAGENT_NOT_ALLOWED:
-               return "WSP_RESULT_UAGENT_NOT_ALLOWED";
-       }
-
-       return MmsDebugPrintUnknownValue(wspResult);
-}
-
-
-char *DebugPrintWspState(MmsRmWapState wspState)
-{
-       switch (wspState) {     //gMmsRmWapState
-       case RM_WAP_IDLE:
-               return "RM_WAP_IDLE";
-       case RM_WAP_CONNECTING:
-               return "RM_WAP_CONNECTING";
-       case RM_WAP_CONNECTED:
-               return "RM_WAP_CONNECTED";
-       case RM_WAP_DISCONNECTING:
-               return "RM_WAP_DISCONNECTING";
-       case RM_WAP_SECURE_REDIRECT:
-               return "RM_WAP_SECURE_REDIRECT";
-       case RM_WAP_FAILED:
-               return "RM_WAP_FAILED";
-       case RM_WAP_WTLS_HANDSHAKING:
-               return "RM_WAP_WTLS_HANDSHAKING";
-       case RM_WAP_WTLS_HANDSHAKE_COMPLETED:
-               return "RM_WAP_WTLS_HANDSHAKE_COMPLETED";
-       }
-
-       return MmsDebugPrintUnknownValue(wspState);
-}
-
-
-char *MmsDebugPrintRmPduType(MmsRmPduType pduType)
-{
-       switch (pduType) {
-       case MMS_RM_PDU_TYPE:
-               return "MMS_RM_PDU_TYPE";
-
-       case MMS_RM_SEND_REQ:
-               return "MMS_RM_SEND_REQ";
-       case MMS_RM_GET_REQ_AUTO:
-               return "MMS_RM_GET_REQ_AUTO";
-       case MMS_RM_GET_REQ_MANUAL:
-               return "MMS_RM_GET_REQ_MANUAL";
-       case MMS_RM_NOTIFY_RESP_IND:
-               return "MMS_RM_NOTIFY_RESP_IND";
-       case MMS_RM_ACK_IND:
-               return "MMS_RM_ACK_IND";
-
-       case MMS_RM_NOTI_IND:
-               return "MMS_RM_NOTI_IND";
-       case MMS_RM_RETRIEVE_CONF:
-               return "MMS_RM_RETRIEVE_CONF";
-
-       case MMS_RM_READ_REPORT_V10:
-               return "MMS_RM_READ_REPORT_V10";
-       case MMS_RM_READ_REPORT_V11:
-               return "MMS_RM_READ_REPORT_V11";
-       }
-
-       return MmsDebugPrintUnknownValue(pduType);
-}
-
-
-char *MmsDebugPrintMailboxType(MsgMailboxType mailboxType)
-{
-       switch (mailboxType) {
-       case MSG_MAILBOX_WRITE:
-               return "MSG_MAILBOX_WRITE";
-       case MSG_MAILBOX_INBOX:
-               return "MSG_MAILBOX_INBOX";
-       case MSG_MAILBOX_DRAFT:
-               return "MSG_MAILBOX_DRAFT";
-       case MSG_MAILBOX_SENT:
-               return "MSG_MAILBOX_SENT";
-       case MSG_MAILBOX_MAILBOX:
-               return "MSG_MAILBOX_MAILBOX";
-       case MSG_MAILBOX_OUTBOX:
-               return "MSG_MAILBOX_OUTBOX";
-       case MSG_MAILBOX_TEMPLATE:
-               return "MSG_MAILBOX_TEMPLATE";
-       case MSG_MAILBOX_MYFOLDER:
-               return "MSG_MAILBOX_MYFOLDER";
-       case MSG_MAILBOX_MYFOLDER_LIST:
-               return "MSG_MAILBOX_MYFOLDER_LIST";
-       case MSG_MAILBOX_PRESET:
-               return "MSG_MAILBOX_PRESET";
-       }
-
-       return MmsDebugPrintUnknownValue(mailboxType);
-}
-#endif
-
index 5a2700d..4940178 100755 (executable)
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#include<stdio.h>
+#include <stdio.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <stdlib.h>
 #include <errno.h>
 
-#include "MsgDebug.h"
-#include "MsgException.h"
-#include "MmsPluginMessage.h"
-#include "MmsPluginStorage.h"
 #include "MsgUtilFile.h"
-#include "MmsPluginCodec.h"
+#include "MsgSmil.h"
+#include "MsgMmsMessage.h"
+
 #include "MmsPluginDebug.h"
-#include "MsgSettingTypes.h"
-#include "MsgSettingHandler.h"
-#include "MmsPluginInternal.h"
-#include "MmsPluginAvCodec.h"
+#include "MmsPluginDecode.h"
+#include "MmsPluginCodecCommon.h"
 #include "MmsPluginStorage.h"
-#include "MmsPluginSmil.h"
-#ifdef __SUPPORT_DRM__
+#include "MmsPluginDebug.h"
+#include "MmsPluginMIME.h"
+#include "MmsPluginTextConvert.h"
+#include "MmsPluginUtil.h"
+
 #include "MmsPluginDrm.h"
 #include "MsgDrmWrapper.h"
-#endif
 
+/*Decode wsp*/
+static int __MmsGetDecodeOffset(void);
+static bool __MmsDecodeInitialize(void);
+static void __MmsCleanDecodeBuff(void);
+static bool __MmsBinaryDecodeMovePointer(FILE *pFile, int offset, int totalLength);
+static bool    __MmsBinaryDecodeCheckAndDecreaseLength(int *pLength, int valueLength);
+
+static bool __MmsBinaryDecodeGetBytes(FILE *pFile, char *szBuff, int bufLen, int totalLength);         /* bufLen < gMmsDecodeMaxLen */
+static bool __MmsBinaryDecodeGetLongBytes(FILE *pFile, char *szBuff, int bufLen, int totalLength);     /* no bufLen limit */
+static bool __MmsBinaryDecodeGetOneByte(FILE *pFile, UINT8 *pOneByte, int totalLength);
 
-static bool _MmsBinaryDecodeGetBytes(FILE *pFile, char *szBuff, int bufLen, int totalLength);          /* bufLen < gMmsDecodeMaxLen */
-static bool _MmsBinaryDecodeGetLongBytes(FILE *pFile, char *szBuff, int bufLen, int totalLength);      /* no bufLen limit */
-static bool _MmsBinaryDecodeGetOneByte(FILE *pFile, UINT8 *pOneByte, int totalLength);
+static UINT32 __MmsHeaderDecodeIntegerByLength(FILE *pFile, UINT32 length, int totalLength);
 
+static bool __MmsBinaryDecodeInteger(FILE *pFile, UINT32 *pInteger, int *pIntLen, int totalLength);
+static bool __MmsDecodeLongInteger(FILE *pFile, UINT32 *pLongInteger, int totalLength);
 static int __MmsBinaryDecodeUintvar(FILE *pFile, UINT32 *pUintVar, int totalLength);
 static int __MmsDecodeValueLength(FILE *pFile, UINT32 *pValueLength, int totalLength);
 static int __MmsDecodeValueLength2(FILE *pFile, UINT32 *pValueLength, int totalLength);
+static int __MmsBinaryDecodeText(FILE *pFile, char *szBuff, int bufLen, int totalLength);
+static char *__MmsBinaryDecodeText2(FILE *pFile, int totalLength, int *pLength);
 static int __MmsBinaryDecodeQuotedString(FILE *pFile, char *szBuff, int bufLen, int totalLength);
 static bool __MmsBinaryDecodeEncodedString(FILE *pFile, char *szBuff, int bufLen, int totalLength);
-static bool __MmsBinaryDecodeInteger(FILE *pFile, UINT32 *pInteger, int *pIntLen, int totalLength);
+
 static bool __MmsBinaryDecodeCharset(FILE *pFile, UINT32 *nCharSet, int *pCharSetLen, int totalLength);
-static char *__MmsBinaryDecodeText2(FILE *pFile, int totalLength, int *pLength);
-static int __MmsBinaryDecodeText(FILE *pFile, char *szBuff, int bufLen, int totalLength);
-static UINT32 __MmsHeaderDecodeIntegerByLength(FILE *pFile, UINT32 length, int totalLength);
-static bool __MmsDecodeLongInteger(FILE *pFile, UINT32 *pLongInteger, int totalLength);
 static int __MmsDecodeGetFilename(FILE *pFile, char *szBuff, int bufLen, int totalLength);
 static MsgHeaderAddress *__MmsDecodeEncodedAddress(FILE *pFile, int totalLength);
 
-#ifdef __SUPPORT_DRM__
-bool __MmsParseDCFInfo(FILE *pFile, MsgDRMInfo *pDrmInfo, int totalLength);
-bool __MmsParseDCFHdr(FILE *pFile, MsgDRMInfo *pDrmInfo, UINT32 headerLen, int totalLength);
-bool MmsBinaryDecodeDRMMessage(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, unsigned int fullBodyLength, int totalLength);
-bool MmsBinaryDecodeDRMContent(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, unsigned int bodyLength, int totalLength);
-#endif
+static bool __MmsBinaryDecodeMultipart(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, int totalLength);
+static bool __MmsBinaryDecodeEachPart(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, int totalLength);
+static bool __MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, int totalLength);
+static bool __MmsBinaryDecodePartBody(FILE *pFile, UINT32 bodyLength, int totalLength);
+static bool __MmsBinaryDecodeEntries(FILE *pFile, UINT32 *npEntries, int totalLength);
+static bool __MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, int totalLength);
 
-static bool MmsBinaryDecodeMovePointer(FILE *pFile, int offset, int totalLength);
-bool MmsBinaryIsTextEncodedPart(FILE *pFile, int totalLength);
-static bool    __MmsBinaryDecodeCheckAndDecreaseLength(int *pLength, int valueLength);
+static int __MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength);
 
-bool __MmsTextDecodeMsgHeader(FILE *pFile);
-bool MmsTextDecodeMsgBody(FILE *pFile);
 
-char gszMmsLoadBuf1[MSG_MMS_DECODE_BUFFER_MAX + 1] = {0, };
-char gszMmsLoadBuf2[MSG_MMS_DECODE_BUFFER_MAX + 1] = {0, };
+//util funcion
+static void __MsgRemoveFilePath(char *pSrc);
+static bool __MsgChangeSpace(char *pOrg, char **ppNew);
+static void __MsgConfirmPresentationPart(MsgType *pMsgType, MsgBody *pMsgBody, MsgPresentaionInfo *pPresentationInfo);
+static MsgPresentationFactor __MsgIsPresentationEx(MsgType *multipartType, char* szStart, MimeType typeParam);
+static bool __MsgLoadDataToDecodeBuffer(FILE *pFile, char **ppBuf, int *pPtr, int *pOffset, char *pInBuf1, char *pInBuf2, int maxLen, int *npRead, int endOfFile);
+static bool __MsgFreeHeaderAddress(MsgHeaderAddress *pAddr);
+static bool __MsgCheckFileNameHasInvalidChar(char *szName);
 
-static char *gpCurMmsDecodeBuff = NULL;
-static int gCurMmsDecodeBuffPos = 0;   /* next decoding position in gpCurMmsDecodeBuff  */
-static int gMmsDecodeMaxLen = 0;
-static int gMmsDecodeCurOffset = 0;    /* current offset in file (last read) */
-static int gMmsDecodeBufLen = 0;               /* number of last read characters */
+static bool __MsgReplaceInvalidFileNameChar(char *szInText, char replaceChar);
+static char *__MsgGetStringUntilDelimiter(char *pszString, char delimiter);
+static bool __MsgParseParameter(MsgType *pType, char *pSrc);
+static char *__MsgSkipWS(char *s);
+static char *__MsgSkipComment(char *s, long trim);
 
-static char *gpMmsDecodeBuf1 = NULL;
-static char *gpMmsDecodeBuf2 = NULL;
+static char *__MsgConvertLatin2UTF8FileName(char *pSrc);
 
-MmsHeader      mmsHeader =
-{
-       false,                                                                  //bActive
-       NULL,                                                                   //pszOwner
-       -1,                                                                             //msgID
+//static bool __MsgIsPercentSign(char *pSrc);
+static bool __MsgIsMultipartRelated(int type);
+static bool __MsgIsPresentablePart(int type);
+static bool __MsgResolveNestedMultipart(MsgType *pPartType, MsgBody *pPartBody);
+static bool __MsgIsHexChar(char *pSrc);
+static char __MsgConvertHexValue(char *pSrc);
+static int __MsgConvertCharToInt(char ch);
+static bool __MsgCopyNestedMsgType(MsgType *pMsgType1, MsgType *pMsgType2);
+static bool __MsgCopyNestedMsgParam(MsgContentParam *pParam1, MsgContentParam *pParam2);
+static bool __MsgIsMultipartMixed(int type);
+
+static bool __MsgIsInvalidFileNameChar(char ch);
+
+static int __MsgGetLatin2UTFCodeSize(unsigned char *szSrc, int nChar);
+static int __MsgLatin2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar);
+static int __MsgCutUTFString(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar);
+static void __MsgMIMERemoveQuote(char *szSrc);
+static bool __MmsMultipartSaveAsTempFile(MsgType *pPartType, MsgBody *pPartBody, char *pszMailboxPath, char *pszMsgFilename, int index, bool bSave);
+
+static bool __MmsGetMediaPartData(MsgType *pPartType, MsgBody *pPartBody, FILE *pFile);
+static char *__MmsGetBinaryUTF8Data(char *pData, int nRead, int msgEncodingValue, int msgTypeValue, int msgCharsetValue, int *npRead);
+
+static bool __MsgMakeFileName(int iMsgType, char *szFileName, MsgDrmType drmType, int nUntitleIndex, char *outBuf, int outBufLen);
+
+
+__thread char gszMmsLoadBuf1[MSG_MMS_DECODE_BUFFER_MAX + 1] = {0, };
+__thread char gszMmsLoadBuf2[MSG_MMS_DECODE_BUFFER_MAX + 1] = {0, };
 
+__thread char *gpCurMmsDecodeBuff = NULL;
+__thread int gCurMmsDecodeBuffPos = 0; /* next decoding position in gpCurMmsDecodeBuff  */
+__thread int gMmsDecodeMaxLen = 0;
+__thread int gMmsDecodeCurOffset = 0;  /* current offset in file (last read) */
+__thread int gMmsDecodeBufLen = 0;             /* number of last read characters */
+
+__thread char *gpMmsDecodeBuf1 = NULL;
+__thread char *gpMmsDecodeBuf2 = NULL;
+
+__thread MmsHeader mmsHeader =
+{
        (MmsMsgType)MMS_MSGTYPE_ERROR,                  //MmsMsgType                    iType;
        "",                                                                             //char[]                                szTrID;
        //"",                                                                           //short int                             version;
@@ -136,54 +176,19 @@ MmsHeader mmsHeader =
        0,                                                                              //UINT32                                msgSize;
 };
 
-#ifdef __SUPPORT_DRM__
-
 #define        MMS_DRM2_CONVERT_BUFFER_MAX     4*1024
 const UINT32 MMS_UINTVAR_LENGTH_1 =  0x0000007f;               //7bit
 const UINT32 MMS_UINTVAR_LENGTH_2 =  0x00003fff;               //14bit
 const UINT32 MMS_UINTVAR_LENGTH_3 =  0x001fffff;               //21bit
 
-#endif
-
-
-bool _MmsDecodeInitialize(void)
+static bool __MmsDecodeInitialize(void)
 {
        MmsInitMsgType(&mmsHeader.msgType);
        MmsInitMsgBody(&mmsHeader.msgBody);
-
-       return true;
-}
-
-bool __MmsSetMmsHeaderOwner(int msgID, char* pszNewOwner)
-{
-       if (pszNewOwner) {
-               // set new owner
-               MSG_DEBUG("__MmsSetMmsHeaderOwner: set (%s, msgID=%d)\n", pszNewOwner, msgID);
-
-               if ((mmsHeader.pszOwner = (char*)malloc(strlen(pszNewOwner) + 1)) == NULL)
-                       return false;
-
-               memset (mmsHeader.pszOwner, 0, strlen(pszNewOwner) + 1) ;
-
-               strcpy(mmsHeader.pszOwner, pszNewOwner);
-               mmsHeader.bActive = true;
-               mmsHeader.msgID = msgID;
-       } else {
-               // delete current owner
-               if (mmsHeader.pszOwner) {
-                       MSG_DEBUG("__MmsSetMmsHeaderOwner: free (%s %d)\n", mmsHeader.pszOwner, msgID);
-                       free(mmsHeader.pszOwner);
-                       mmsHeader.pszOwner = NULL;
-               }
-               mmsHeader.bActive = false;
-               mmsHeader.msgID = -1;
-       }
-
        return true;
 }
 
-
-void _MmsInitHeader()
+void MmsInitHeader()
 {
        mmsHeader.type = MMS_MSGTYPE_ERROR;
 
@@ -191,10 +196,10 @@ void _MmsInitHeader()
        mmsHeader.version = MMS_VERSION;
        mmsHeader.date = 0;
 
-       MsgFreeHeaderAddress(mmsHeader.pFrom);
-       MsgFreeHeaderAddress(mmsHeader.pTo);
-       MsgFreeHeaderAddress(mmsHeader.pCc);
-       MsgFreeHeaderAddress(mmsHeader.pBcc);
+       __MsgFreeHeaderAddress(mmsHeader.pFrom);
+       __MsgFreeHeaderAddress(mmsHeader.pTo);
+       __MsgFreeHeaderAddress(mmsHeader.pCc);
+       __MsgFreeHeaderAddress(mmsHeader.pBcc);
 
        mmsHeader.pFrom = NULL;
        mmsHeader.pTo = NULL;
@@ -234,16 +239,26 @@ void _MmsInitHeader()
 
        memset(mmsHeader.szMsgID, 0, MMS_MSG_ID_LEN + 1);
        mmsHeader.msgSize = 0;
-#ifdef __SUPPORT_DRM__
        mmsHeader.drmType = MSG_DRM_TYPE_NONE;
-#endif
 
-       _MmsDecodeInitialize();
+       __MmsDecodeInitialize();
 }
 
+void MmsReleaseHeader(MmsHeader *mms)
+{
+       __MsgFreeHeaderAddress(mms->pFrom);
+       __MsgFreeHeaderAddress(mms->pTo);
+       __MsgFreeHeaderAddress(mms->pCc);
+       __MsgFreeHeaderAddress(mms->pBcc);
+
+       mmsHeader.pFrom = NULL;
+       mmsHeader.pTo = NULL;
+       mmsHeader.pCc = NULL;
+       mmsHeader.pBcc = NULL;
 
+}
 
-void _MmsCleanDecodeBuff(void)
+static void __MmsCleanDecodeBuff(void)
 {
        memset(gpMmsDecodeBuf1, 0, gMmsDecodeMaxLen + 1);
        memset(gpMmsDecodeBuf2, 0, gMmsDecodeMaxLen + 1);
@@ -252,19 +267,18 @@ void _MmsCleanDecodeBuff(void)
        gMmsDecodeBufLen = 0;
 }
 
-
-void _MmsRegisterDecodeBuffer(char *pInBuff1, char *pInBuff2, int maxLen)
+void MmsRegisterDecodeBuffer()
 {
-       gpMmsDecodeBuf1 = pInBuff1;
-       gpMmsDecodeBuf2 = pInBuff2;
+       gpMmsDecodeBuf1 = gszMmsLoadBuf1;
+       gpMmsDecodeBuf2 = gszMmsLoadBuf2;
        gpCurMmsDecodeBuff = NULL;
        gCurMmsDecodeBuffPos = 0;
-       gMmsDecodeMaxLen = maxLen;
+       gMmsDecodeMaxLen = MSG_MMS_DECODE_BUFFER_MAX;
        gMmsDecodeCurOffset = 0;
        gMmsDecodeBufLen = 0;
 }
 
-void _MmsUnregisterDecodeBuffer(void)
+void MmsUnregisterDecodeBuffer(void)
 {
        gpMmsDecodeBuf1 = NULL;
        gpMmsDecodeBuf2 = NULL;
@@ -276,12 +290,11 @@ void _MmsUnregisterDecodeBuffer(void)
 }
 
 
-int _MmsGetDecodeOffset(void)
+static int __MmsGetDecodeOffset(void)
 {
        return (gMmsDecodeCurOffset - gMmsDecodeBufLen + gCurMmsDecodeBuffPos);
 }
 
-
 static bool __MmsBinaryDecodeCheckAndDecreaseLength(int *pLength, int valueLength)
 {
        if (*pLength <= valueLength) {
@@ -336,6 +349,7 @@ static bool __MmsBinaryDecodeCheckAndDecreaseLength(int *pLength, int valueLengt
  */
 bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
 {
+       MSG_BEGIN();
        UINT16 fieldCode = 0xffff;
        UINT16 fieldValue = 0xffff;
        UINT8 oneByte = 0xff;
@@ -355,124 +369,124 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
        char *pLimitData = NULL;
        int nRead = 0;
 
-       MSG_DEBUG("MmsBinaryDecodeMsgHeader: pFile=%d, total len=%d\n", pFile, totalLength);
+       MSG_DEBUG("pFile ptr : [%p], total len = [%d]", pFile, totalLength);
 
-       _MmsCleanDecodeBuff();
+       __MmsCleanDecodeBuff();
 
-       if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos,
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos,
                                                                   &gMmsDecodeCurOffset, gpMmsDecodeBuf1, gpMmsDecodeBuf2,
                                                                   gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-               MSG_DEBUG("MmsBinaryDecodeMsgHeader: fail to load to buffer \n");
+               MSG_FATAL("fail to load to buffer");
                goto __CATCH;
        }
 
-       while (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength)) {
+       while (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength)) {
                fieldCode = oneByte & 0x7f;
 
-               switch (_MmsGetBinaryType(MmsCodeFieldCode, fieldCode)) {
+               switch (MmsGetBinaryType(MmsCodeFieldCode, fieldCode)) {
                case MMS_CODE_RESPONSESTATUS:
+               {
+                       MmsResponseStatus resposeStatus = MMS_RESPSTATUS_ERROR;
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: responseStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("responseStatus GetOneByte fail");
                                goto __CATCH;
                        }
 
-                       fieldValue = _MmsGetBinaryType(MmsCodeResponseStatus, (UINT16)(oneByte & 0x7F));
-
-                       if (fieldValue == 0xFFFF) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: responseStatus error\n");
-                               goto __CATCH;
-                       }
+                       fieldValue = oneByte;
 
-                       if (fieldValue >= 0x0044 && fieldValue <= 0x005F) {
-                               fieldValue = 0x0040;
-                       } else if (fieldValue >= 0x006A && fieldValue <= 0x007F) {
-                               fieldValue = 0x0060;
+                       // range 197 to 223 as it does to the value 192 (Error-transient-failure).
+                       // range 236 to 255 as it does to the value 224 (Error-permanent-failure).
+                       if (fieldValue >= 197 && fieldValue <= 223) {
+                               fieldValue = 192;
+                       } else if (fieldValue >= 236 && fieldValue <= 255) {
+                               fieldValue = 224;
                        }
 
-                       mmsHeader.responseStatus = (MmsResponseStatus)fieldValue;
+                       resposeStatus = (MmsResponseStatus)MmsGetBinaryType(MmsCodeResponseStatus, (UINT16)(fieldValue & 0x7F));
 
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: response status = %s\n", MmsDebugGetResponseStatus(mmsHeader.responseStatus));
+                       mmsHeader.responseStatus = (MmsResponseStatus)resposeStatus;
 
+                       MSG_SEC_INFO("X-Mms-Response-Status = [0x%02x][0x%02x][%s]", oneByte, fieldValue, MmsDebugGetResponseStatus(mmsHeader.responseStatus));
                        break;
-
+               }
                case MMS_CODE_RETRIEVESTATUS:
+               {
+                       MmsRetrieveStatus RetrieveStatus = MMS_RETRSTATUS_ERROR;
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: retrieveStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("retrieveStatus GetOneByte fail");
                                goto __CATCH;
                        }
 
-                       fieldValue = _MmsGetBinaryType(MmsCodeRetrieveStatus, (UINT16)(oneByte & 0x7F));
+                       fieldValue = oneByte;
 
-                       if (fieldValue == 0xFFFF) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: retrieveStatus error\n");
-                               goto __CATCH;
+                       //195 to 223 as it does to the value 192 (Error-transient-failure).
+                       //228 to 255 as it does to the value 224 (Error-permanent-failure).
+                       if (fieldValue >= 195 && fieldValue <= 223) {
+                               fieldValue = 192; // 192; Error-transient-failure
+                       } else if (fieldValue >= 228 && fieldValue <= 255) {
+                               fieldValue = 224; //224; Error-permanent-failure
                        }
 
-                       if (fieldValue >= 0x0043 && fieldValue <= 0x005F) {
-                               fieldValue = 0x0040; // 192; Error-transient-failure
-                       } else if (fieldValue >= 0x0064 && fieldValue <= 0x007F) {
-                               fieldValue = 0x0060; //224; Error-permanent-failure
-                       }
+                       RetrieveStatus = (MmsRetrieveStatus)MmsGetBinaryType(MmsCodeRetrieveStatus, (UINT16)(fieldValue & 0x7F));
 
-                       mmsHeader.retrieveStatus = (MmsRetrieveStatus)fieldValue;
+                       mmsHeader.retrieveStatus = (MmsRetrieveStatus)RetrieveStatus;
 
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: retrieve status = %s\n",
-                                                                                                                       MmsDebugGetRetrieveStatus(mmsHeader.retrieveStatus));
+                       MSG_SEC_INFO("X-Mms-Retrieve-Status = [0x%02x][0x%02x][%s]", oneByte, fieldValue, MmsDebugGetRetrieveStatus(mmsHeader.retrieveStatus));
 
                        break;
-
+               }
                case MMS_CODE_RESPONSETEXT:
 
                        if (__MmsBinaryDecodeEncodedString(pFile, mmsHeader.szResponseText, MMS_LOCALE_RESP_TEXT_LEN + 1, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : invalid MMS_CODE_RESPONSETEXT \n");
+                               MSG_DEBUG("invalid MMS_CODE_RESPONSETEXT");
                                goto __CATCH;
                        }
 
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: response text = %s\n", mmsHeader.szResponseText);
+                       MSG_SEC_INFO("X-Mms-Response-Text = [%s]", mmsHeader.szResponseText);
                        break;
 
                case MMS_CODE_RETRIEVETEXT:
 
                        if (__MmsBinaryDecodeEncodedString(pFile, mmsHeader.szRetrieveText, MMS_LOCALE_RESP_TEXT_LEN + 1, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : invalid MMS_CODE_RETRIEVETEXT \n");
+                               MSG_DEBUG("invalid MMS_CODE_RETRIEVETEXT");
                                goto __CATCH;
                        }
 
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: retrieve text = %s\n", mmsHeader.szResponseText);
+                       MSG_SEC_INFO("X-Mms-Retrieve-Text = [%s]", mmsHeader.szRetrieveText);
                        break;
 
                case MMS_CODE_MSGID:
 
                        if (__MmsBinaryDecodeText(pFile, mmsHeader.szMsgID, MMS_MSG_ID_LEN + 1, totalLength) < 0) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_MSGID is invalid\n");
+                               MSG_DEBUG("MMS_CODE_MSGID is invalid");
                                goto __CATCH;
                        }
 
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: msg id = %s\n", mmsHeader.szMsgID);
+                       MSG_SEC_INFO("Message-ID =[%s]", mmsHeader.szMsgID);
 
-                       if (MsgStrlen (mmsHeader.szMsgID) > 2)
-                               MsgMIMERemoveQuote (mmsHeader.szMsgID);
+                       if (strlen(mmsHeader.szMsgID) > 2)
+                               __MsgMIMERemoveQuote (mmsHeader.szMsgID);
 
                        break;
 
                case MMS_CODE_SUBJECT:
 
                        if (__MmsBinaryDecodeEncodedString(pFile, mmsHeader.szSubject, MSG_LOCALE_SUBJ_LEN + 1, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : invalid MMS_CODE_SUBJECT \n");
+                               MSG_DEBUG("invalid MMS_CODE_SUBJECT");
                                goto __CATCH;
                        }
 
-                       pLimitData = (char *)malloc(MSG_LOCALE_SUBJ_LEN + 1);
+                       pLimitData = (char *)calloc(1, MSG_LOCALE_SUBJ_LEN + 1);
 
                        if (pLimitData == NULL) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : pLimitData malloc fail \n");
+                               MSG_DEBUG("pLimitData calloc fail");
                                goto __CATCH;
                        }
 
-                       nRead = MsgCutUTFString((unsigned char*)pLimitData, MSG_LOCALE_SUBJ_LEN + 1, (unsigned char*)mmsHeader.szSubject, MSG_SUBJ_LEN);
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader : Subject edit.. \n");
+                       nRead = __MsgCutUTFString((unsigned char*)pLimitData, MSG_LOCALE_SUBJ_LEN + 1, (unsigned char*)mmsHeader.szSubject, MSG_SUBJ_LEN);
+                       MSG_DEBUG("Subject edit..");
 
                        if (nRead > MSG_LOCALE_SUBJ_LEN) {
                                memset(mmsHeader.szSubject, 0 , sizeof(mmsHeader.szSubject));
@@ -487,7 +501,7 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                                pLimitData = NULL;
                        }
 
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: subject = %s\n", mmsHeader.szSubject);
+                       MSG_SEC_INFO("Subject = [%s]", mmsHeader.szSubject);
                        break;
 
                case MMS_CODE_FROM:
@@ -495,12 +509,12 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                        /* Value-length (Address-present-token Encoded-string-value | Insert-address-token) */
 
                        if (__MmsDecodeValueLength(pFile, &valueLength, totalLength) <= 0) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_FROM is invalid\n");
+                               MSG_DEBUG("MMS_CODE_FROM is invalid");
                                goto __CATCH;
                        }
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: MMS_CODE_FROM GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("MMS_CODE_FROM GetOneByte fail");
                                goto __CATCH;
                        }
 
@@ -508,19 +522,19 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
 
                        valueLength--;
 
-                       if (oneByte == (_MmsGetBinaryValue(MmsCodeAddressType, MMS_ADDRESS_PRESENT_TOKEN)|0x80)) {
+                       if (oneByte == (MmsGetBinaryValue(MmsCodeAddressType, MMS_ADDRESS_PRESENT_TOKEN)|0x80)) {
                                if (valueLength > 0) {
                                        mmsHeader.pFrom = __MmsDecodeEncodedAddress(pFile, totalLength);
                                        if (mmsHeader.pFrom == NULL) {
-                                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_FROM __MmsDecodeEncodedAddress fail\n");
+                                               MSG_DEBUG("MMS_CODE_FROM __MmsDecodeEncodedAddress fail");
                                                goto __CATCH;
                                        }
                                } else {
-                                       mmsHeader.pFrom = (MsgHeaderAddress *)malloc(sizeof(MsgHeaderAddress));
+                                       mmsHeader.pFrom = (MsgHeaderAddress *)calloc(1, sizeof(MsgHeaderAddress));
                                        if (mmsHeader.pFrom == NULL)
                                                goto __CATCH;
 
-                                       mmsHeader.pFrom->szAddr = (char *)malloc(1);
+                                       mmsHeader.pFrom->szAddr = (char *)calloc(1, 1);
                                        if (mmsHeader.pFrom->szAddr == NULL) {
                                                free(mmsHeader.pFrom);
                                                mmsHeader.pFrom = NULL;
@@ -531,14 +545,14 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                                        mmsHeader.pFrom->pNext = NULL;
                                }
 
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: from = %s\n", mmsHeader.pFrom->szAddr);
+                               MSG_SEC_INFO("From = [%s]", mmsHeader.pFrom->szAddr);
                                // DRM_TEMPLATE - end
-                       } else if (oneByte == (_MmsGetBinaryValue(MmsCodeAddressType, MMS_INSERT_ADDRESS_TOKEN)|0x80)) {
+                       } else if (oneByte == (MmsGetBinaryValue(MmsCodeAddressType, MMS_INSERT_ADDRESS_TOKEN)|0x80)) {
                                /* Present Token only */
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_FROM insert token\n");
+                               MSG_SEC_INFO("From = [insert token]");
                        } else {
                                /* from data broken */
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: from addr broken\n");
+                               MSG_WARN("from addr broken");
                                gCurMmsDecodeBuffPos--;
                                goto __CATCH;
                        }
@@ -548,7 +562,7 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
 
                        pAddr = __MmsDecodeEncodedAddress(pFile, totalLength);
                        if (pAddr == NULL) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_TO __MmsDecodeEncodedAddress fail\n");
+                               MSG_DEBUG("MMS_CODE_TO __MmsDecodeEncodedAddress fail");
                                goto __CATCH;
                        }
 
@@ -561,14 +575,14 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                                pLastTo = pAddr;
                        }
 
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: to = %s\n", mmsHeader.pTo->szAddr);
+                       MSG_SEC_INFO("To = [%s]", pAddr->szAddr);
                        break;
 
                case MMS_CODE_BCC:
 
                        pAddr = __MmsDecodeEncodedAddress(pFile, totalLength);
                        if (pAddr == NULL) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_BCC __MmsDecodeEncodedAddress fail\n");
+                               MSG_DEBUG("MMS_CODE_BCC __MmsDecodeEncodedAddress fail");
                                goto __CATCH;
                        }
 
@@ -581,14 +595,14 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                                pLastBcc = pAddr;
                        }
 
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: bcc = %s\n", mmsHeader.pBcc->szAddr);
+                       MSG_SEC_INFO("Bcc = [%s]", pAddr->szAddr);
                        break;
 
                case MMS_CODE_CC:
 
                        pAddr = __MmsDecodeEncodedAddress(pFile, totalLength);
                        if (pAddr == NULL) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_CC __MmsDecodeEncodedAddress fail\n");
+                               MSG_DEBUG("MMS_CODE_CC __MmsDecodeEncodedAddress fail");
                                goto __CATCH;
                        }
 
@@ -600,44 +614,45 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                                        pLastCc->pNext = pAddr;
                                pLastCc = pAddr;
                        }
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: cc = %s\n", mmsHeader.pCc->szAddr);
+                       MSG_SEC_INFO("Cc = [%s]", pAddr->szAddr);
                        break;
 
                case MMS_CODE_CONTENTLOCATION:
 
                        if (__MmsBinaryDecodeText(pFile, mmsHeader.szContentLocation, MMS_LOCATION_LEN + 1, totalLength) < 0) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_CONTENTLOCATION is invalid\n");
+                               MSG_DEBUG("MMS_CODE_CONTENTLOCATION is invalid");
                                goto __CATCH;
                        }
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: content location = %s\n", mmsHeader.szContentLocation);
+                       MSG_SEC_DEBUG("X-Mms-Content-Location = [%s]", mmsHeader.szContentLocation);
                        break;
 
                case MMS_CODE_DATE:
 
                        if (__MmsDecodeLongInteger(pFile, (UINT32*)&mmsHeader.date, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_DATE is invalid\n");
+                               MSG_DEBUG("MMS_CODE_DATE is invalid");
                                goto __CATCH;
                        }
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: date = %d\n", mmsHeader.date);
+
+                       MSG_SEC_INFO("Date = [%u][%d]", mmsHeader.date, (const time_t *)&mmsHeader.date);
                        break;
 
                case MMS_CODE_DELIVERYREPORT:
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: deliveryReport GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("deliveryReport GetOneByte fail");
                                goto __CATCH;
                        }
 
-                       fieldValue = _MmsGetBinaryType(MmsCodeDeliveryReport, (UINT16)(oneByte & 0x7F));
+                       fieldValue = MmsGetBinaryType(MmsCodeDeliveryReport, (UINT16)(oneByte & 0x7F));
 
                        if (fieldValue == 0xFFFF) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: deliveryReport error\n");
+                               MSG_DEBUG("deliveryReport error");
                                goto __CATCH;
                        }
 
                        mmsHeader.deliveryReport = (MmsReport)fieldValue;
 
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: delivery report=%s\n", MmsDebugGetMmsReport(mmsHeader.deliveryReport));
+                       MSG_SEC_INFO("X-Mms-Delivery-Report =[0x%02x][%s]", oneByte, MmsDebugGetMmsReport(mmsHeader.deliveryReport));
                        break;
 
                case MMS_CODE_DELIVERYTIME:
@@ -645,24 +660,24 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                        /* value_length (absolute-token Long-integer | Relative-token Long-integer) */
 
                        if (__MmsDecodeValueLength(pFile, &valueLength, totalLength) <= 0) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : invalid MMS_CODE_DELIVERYTIME \n");
+                               MSG_DEBUG("invalid MMS_CODE_DELIVERYTIME");
                                goto __CATCH;
                        }
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: delivery time GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("delivery time GetOneByte fail");
                                goto __CATCH;
                        }
 
                        //DRM_TEMPLATE - start
                        valueLength--;
 
-                       if (oneByte == (_MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_ABSOLUTE)|0x80)) {
+                       if (oneByte == (MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_ABSOLUTE)|0x80)) {
                                mmsHeader.deliveryTime.type = MMS_TIMETYPE_ABSOLUTE;
 
                                if (valueLength > 0) {
                                        if (__MmsDecodeLongInteger(pFile, (UINT32*)&mmsHeader.deliveryTime.time, totalLength) == false) {
-                                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : invalid MMS_CODE_DELIVERYTIME\n");
+                                               MSG_DEBUG("invalid MMS_CODE_DELIVERYTIME");
                                                goto __CATCH;
                                        }
                                }
@@ -671,11 +686,11 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                                mmsHeader.deliveryTime.type = MMS_TIMETYPE_RELATIVE;
 
                                if (__MmsBinaryDecodeInteger(pFile, (UINT32*)&mmsHeader.deliveryTime.time, &tmpIntLen, totalLength) == false) {
-                                       MSG_DEBUG("MmsBinaryDecodeMsgHeader : __MmsBinaryDecodeInteger fail...\n");
+                                       MSG_DEBUG("__MmsBinaryDecodeInteger fail...");
                                        goto __CATCH;
                                }
                        }
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: delivery type=%d, time=%d\n", mmsHeader.deliveryTime.type, mmsHeader.deliveryTime.time);
+                       MSG_SEC_INFO("X-Mms-Delivery-Time : type = [%d], time= [%u]", mmsHeader.deliveryTime.type, mmsHeader.deliveryTime.time);
                        break;
 
                case MMS_CODE_EXPIRYTIME:
@@ -683,24 +698,24 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                        /* value_length(absolute-token Long-integer | Relative-token Long-integer) */
 
                        if (__MmsDecodeValueLength(pFile, &valueLength, totalLength) <= 0) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : invalid MMS_CODE_EXPIRYTIME \n");
+                               MSG_DEBUG("invalid MMS_CODE_EXPIRYTIME");
                                goto __CATCH;
                        }
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: expiry time GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("expiry time GetOneByte fail");
                                goto __CATCH;
                        }
 
                        // DRM_TEMPLATE - start
                        valueLength--;
 
-                       if (oneByte == (_MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_ABSOLUTE)|0x80)) {
+                       if (oneByte == (MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_ABSOLUTE)|0x80)) {
                                mmsHeader.expiryTime.type = MMS_TIMETYPE_ABSOLUTE;
 
                                if (valueLength > 0) {
                                        if (__MmsDecodeLongInteger(pFile, (UINT32*)&mmsHeader.expiryTime.time, totalLength) == false) {
-                                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_EXPIRYTIME is invalid\n");
+                                               MSG_DEBUG("MMS_CODE_EXPIRYTIME is invalid");
                                                goto __CATCH;
                                        }
                                }
@@ -709,122 +724,125 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                                mmsHeader.expiryTime.type = MMS_TIMETYPE_RELATIVE;
 
                                if (__MmsBinaryDecodeInteger(pFile, (UINT32*)&mmsHeader.expiryTime.time, &tmpIntLen, totalLength) == false) {
-                                       MSG_DEBUG("MmsBinaryDecodeMsgHeader : __MmsBinaryDecodeInteger fail...\n");
+                                       MSG_INFO("__MmsBinaryDecodeInteger fail...");
                                        goto __CATCH;
                                }
                        }
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: expiry = %d\n", mmsHeader.expiryTime.time);
+
+                       MSG_DEBUG("X-Mms-Expiry : type = [%d], time = [%u]", mmsHeader.expiryTime.type, mmsHeader.expiryTime.time);
                        break;
 
                case MMS_CODE_MSGCLASS:
 
                        /* Class-value = Class-identifier | Token Text */
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: msgClass GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgClass GetOneByte fail");
                                goto __CATCH;
                        }
 
                        if (oneByte > 0x7f) {
                                /* Class-identifier */
-                               mmsHeader.msgClass = (MmsMsgClass)_MmsGetBinaryType(MmsCodeMsgClass, (UINT16)(oneByte & 0x7F));
+                               mmsHeader.msgClass = (MmsMsgClass)MmsGetBinaryType(MmsCodeMsgClass, (UINT16)(oneByte & 0x7F));
                        } else {
                                if (__MmsBinaryDecodeText(pFile, szGarbageBuff, MSG_STDSTR_LONG, totalLength) < 0) {
-                                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: 1. __MmsBinaryDecodeText fail. (class)\n");
+                                       MSG_DEBUG("1. __MmsBinaryDecodeText fail. (class)");
                                        goto __CATCH;
                                }
                        }
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: msg class=%s\n", MmsDebugGetMsgClass(mmsHeader.msgClass));
+
+                       MSG_SEC_INFO("X-Mms-Message-Class =[%s]", MmsDebugGetMsgClass(mmsHeader.msgClass));
                        break;
 
                case MMS_CODE_MSGSIZE:
 
                        if (__MmsDecodeLongInteger(pFile, (UINT32*)&mmsHeader.msgSize, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_MSGSIZE is invalid\n");
+                               MSG_DEBUG("MMS_CODE_MSGSIZE is invalid");
                                goto __CATCH;
                        }
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: msg size = %d\n", mmsHeader.msgSize);
+
+                       MSG_SEC_INFO("X-Mms-Message-Size = [%d]", mmsHeader.msgSize);
                        break;
 
                case MMS_CODE_MSGSTATUS:
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: msgStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail");
                                goto __CATCH;
                        }
 
-                       mmsHeader.msgStatus =  (msg_delivery_report_status_t)_MmsGetBinaryType(MmsCodeMsgStatus, (UINT16)(oneByte & 0x7F));
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: msg status=%s \n", MmsDebugGetMsgStatus(mmsHeader.msgStatus)) ;
+                       mmsHeader.msgStatus =  (msg_delivery_report_status_t)MmsGetBinaryType(MmsCodeMsgStatus, (UINT16)(oneByte & 0x7F));
+                       MSG_SEC_INFO("X-Mms-Status = [%s]", MmsDebugGetMsgStatus(mmsHeader.msgStatus));
                        break;
 
                case MMS_CODE_MSGTYPE:
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: msgStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail");
                                goto __CATCH;
                        }
 
-                       mmsHeader.type = (MmsMsgType)_MmsGetBinaryType(MmsCodeMsgType, (UINT16)(oneByte & 0x7F));
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: msg type=%s\n", MmsDebugGetMsgType(mmsHeader.type));
+                       mmsHeader.type = (MmsMsgType)MmsGetBinaryType(MmsCodeMsgType, (UINT16)(oneByte & 0x7F));
+                       MSG_SEC_INFO("X-Mms-Message-Type = [%s]", MmsDebugGetMsgType(mmsHeader.type));
                        break;
 
                case MMS_CODE_PRIORITY:
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: msgStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail");
                                goto __CATCH;
                        }
-                       mmsHeader.priority = (MmsPriority)_MmsGetBinaryType(MmsCodePriority, (UINT16)(oneByte & 0x7F));
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: priority=%d\n", mmsHeader.priority);
+                       mmsHeader.priority = (MmsPriority)MmsGetBinaryType(MmsCodePriority, (UINT16)(oneByte & 0x7F));
+                       MSG_SEC_INFO("X-Mms-Priority = [%d]", mmsHeader.priority);
                        break;
 
                case MMS_CODE_READREPLY:
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: msgStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail");
                                goto __CATCH;
                        }
-                       mmsHeader.readReply = (MmsReport)_MmsGetBinaryType(MmsCodeReadReply, (UINT16)(oneByte & 0x7F));
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: read reply=%s \n", MmsDebugGetMmsReport(mmsHeader.readReply));
+                       mmsHeader.readReply = (MmsReport)MmsGetBinaryType(MmsCodeReadReply, (UINT16)(oneByte & 0x7F));
+                       MSG_SEC_INFO("X-Mms-Read-Report = [0x%02x][%s]", oneByte, MmsDebugGetMmsReport(mmsHeader.readReply));
                        break;
 
                case MMS_CODE_REPORTALLOWED:
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: msgStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail");
                                goto __CATCH;
                        }
-                       mmsHeader.reportAllowed =  (MmsReportAllowed)_MmsGetBinaryType(MmsCodeReportAllowed, (UINT16)(oneByte & 0x7F));
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: mmsHeader.reportAllowed=%d\n", MmsDebugGetMmsReportAllowed(mmsHeader.reportAllowed));
+                       mmsHeader.reportAllowed =  (MmsReportAllowed)MmsGetBinaryType(MmsCodeReportAllowed, (UINT16)(oneByte & 0x7F));
+                       MSG_SEC_INFO("X-Mms-Report-Allowed = [%d]", MmsDebugGetMmsReportAllowed(mmsHeader.reportAllowed));
                        break;
 
                case MMS_CODE_SENDERVISIBILLITY:
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: msgStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail");
                                goto __CATCH;
                        }
-                       mmsHeader.hideAddress= (MmsSenderVisible)!(_MmsGetBinaryType(MmsCodeSenderVisibility, (UINT16)(oneByte &0x7F)));
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: sender visible=%d \n", mmsHeader.hideAddress);
+                       mmsHeader.hideAddress= (MmsSenderVisible)!(MmsGetBinaryType(MmsCodeSenderVisibility, (UINT16)(oneByte &0x7F)));
+                       MSG_SEC_INFO("X-Mms-Sender-Visibility = [%d]", mmsHeader.hideAddress);
                        break;
 
                case MMS_CODE_TRID:
 
                        if (__MmsBinaryDecodeText(pFile, mmsHeader.szTrID, MMS_TR_ID_LEN + 1, totalLength) < 0) {
-                               MSG_DEBUG("Transaction ID Too Long \n");
+                               MSG_DEBUG("Transaction ID Too Long");
                                goto __CATCH;
                        }
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: trID = %s\n", mmsHeader.szTrID);
+                       MSG_SEC_INFO("X-Mms-Transaction-Id = [%s]", mmsHeader.szTrID);
                        break;
 
                case MMS_CODE_VERSION:
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: msgStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail");
                                goto __CATCH;
                        }
                        mmsHeader.version = oneByte;
 
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: ver = 0x%x\n", mmsHeader.version);
+                       MSG_SEC_INFO("X-Mms-MMS-Version = [0x%02x]", mmsHeader.version);
                        break;
 
                case MMS_CODE_CONTENTTYPE:
@@ -843,26 +861,26 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
 
                        /* Read-status-value = Read | Deleted without being read */
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: msgStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail");
                                goto __CATCH;
                        }
 
-                       mmsHeader.readStatus =  (msg_read_report_status_t)_MmsGetBinaryType(MmsCodeReadStatus, (UINT16)(oneByte & 0x7F));
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: read status=%s\n", MmsDebugGetMmsReadStatus(mmsHeader.readStatus));
+                       mmsHeader.readStatus =  (msg_read_report_status_t)MmsGetBinaryType(MmsCodeReadStatus, (UINT16)(oneByte & 0x7F));
+                       MSG_SEC_INFO("X-Mms-Read-Status = [%s]", MmsDebugGetMmsReadStatus(mmsHeader.readStatus));
                        break;
 
                case MMS_CODE_REPLYCHARGING:
 
                        /* Reply-charging-value = Requested | Requested text only | Accepted | Accepted text only */
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: msgStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail");
                                goto __CATCH;
                        }
 
-                       mmsHeader.replyCharge.chargeType =  (MmsReplyChargeType)_MmsGetBinaryType(MmsCodeReplyCharging, (UINT16)(oneByte & 0x7F));
-                       MSG_DEBUG("MmsBinaryDecodeMsgHeader: mmsHeader.reply charge=%d\n", mmsHeader.replyCharge.chargeType);
+                       mmsHeader.replyCharge.chargeType =  (MmsReplyChargeType)MmsGetBinaryType(MmsCodeReplyCharging, (UINT16)(oneByte & 0x7F));
+                       MSG_SEC_INFO("X-Mms-Reply-Charging = [%d]", mmsHeader.replyCharge.chargeType);
                        break;
 
                case MMS_CODE_REPLYCHARGINGDEADLINE:
@@ -870,16 +888,16 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                        /* Reply-charging-deadline-value = Value-length (Absolute-token Date-value | Relative-token Delta-seconds-value) */
 
                        if (__MmsDecodeValueLength(pFile, &valueLength, totalLength) <= 0) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : invalid MMS_CODE_REPLYCHARGINGDEADLINE \n");
+                               MSG_DEBUG("invalid MMS_CODE_REPLYCHARGINGDEADLINE");
                                goto __CATCH;
                        }
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: msgStatus GetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail");
                                goto __CATCH;
                        }
 
-                       if (oneByte == (_MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_ABSOLUTE) | 0x80)) {
+                       if (oneByte == (MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_ABSOLUTE) | 0x80)) {
                                mmsHeader.replyCharge.deadLine.type = MMS_TIMETYPE_ABSOLUTE;
                        } else {
                                mmsHeader.replyCharge.deadLine.type = MMS_TIMETYPE_RELATIVE;
@@ -890,31 +908,33 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
 
                        if (valueLength > 0) {
                                if (__MmsDecodeLongInteger(pFile, (UINT32*)&mmsHeader.replyCharge.deadLine.time, totalLength) == false) {
-                                       MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_REPLYCHARGINGDEADLINE is invalid\n");
+                                       MSG_DEBUG("MMS_CODE_REPLYCHARGINGDEADLINE is invalid");
                                        goto __CATCH;
                                }
                        }
+
+                       MSG_SEC_INFO("X-Mms-Reply-Charging-Deadline : type = [%d], time = [%u]", mmsHeader.replyCharge.deadLine.type, mmsHeader.replyCharge.deadLine.time);
                        // DRM_TEMPLATE - end
                        break;
 
                case MMS_CODE_REPLYCHARGINGID:
 
                        /* Reply-charging-ID-value = Text-string */
-
                        if (__MmsBinaryDecodeText(pFile, mmsHeader.replyCharge.szChargeID, MMS_MSG_ID_LEN + 1, totalLength) < 0) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: 1. __MmsBinaryDecodeText fail. (szReplyChargingID)\n");
+                               MSG_DEBUG("1. __MmsBinaryDecodeText fail. (szReplyChargingID)");
                                goto __CATCH;
                        }
+                       SECURE_SLOGD("X-Mms-Reply-Charging-ID = [%s]", mmsHeader.replyCharge.szChargeID);
                        break;
 
                case MMS_CODE_REPLYCHARGINGSIZE:
 
                        /* Reply-charging-size-value = Long-integer */
-
                        if (__MmsDecodeLongInteger(pFile, (UINT32*)&mmsHeader.replyCharge.chargeSize, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : MMS_CODE_REPLYCHARGINGSIZE is invalid\n");
+                               MSG_DEBUG("MMS_CODE_REPLYCHARGINGSIZE is invalid");
                                goto __CATCH;
                        }
+                       MSG_SEC_INFO("X-Mms-Reply-Charging-Size = [%d]", mmsHeader.replyCharge.chargeSize);
                        break;
 
                case MMS_CODE_PREVIOUSLYSENTBY:
@@ -925,18 +945,23 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                         * MMS_CODE_PREVIOUSLYSENTBY shall be a pair with MMS_CODE_PREVIOUSLYSENTDATE
                         */
 
+                       /*
+                        * fixme: There is no proper field to store this information.
+                        * Just increase pointer now.
+                        */
+
                        if (__MmsDecodeValueLength(pFile, &valueLength, totalLength) <= 0) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : 1. invalid MMS_CODE_PREVIOUSLYSENTBY \n");
+                               MSG_DEBUG("1. invalid MMS_CODE_PREVIOUSLYSENTBY");
                                goto __CATCH;
                        }
 
                        if (__MmsBinaryDecodeInteger(pFile, &tmpInteger, &tmpIntLen, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : 2. invalid MMS_CODE_PREVIOUSLYSENTBY \n");
+                               MSG_DEBUG("2. invalid MMS_CODE_PREVIOUSLYSENTBY");
                                goto __CATCH;
                        }
 
                        if (__MmsBinaryDecodeEncodedString(pFile, szGarbageBuff, MSG_STDSTR_LONG, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : invalid MMS_CODE_RETRIEVETEXT \n");
+                               MSG_DEBUG("invalid MMS_CODE_RETRIEVETEXT");
                                goto __CATCH;
                        }
                        break;
@@ -949,23 +974,27 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                         * MMS_CODE_PREVIOUSLYSENTDATE shall be a pair with MMS_CODE_PREVIOUSLYSENTBY
                         */
 
+                       /*
+                        * fixme: There is no proper field to store this information.
+                        * Just increase pointer now.
+                        */
+
                        if (__MmsDecodeValueLength(pFile, &valueLength, totalLength) <= 0) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : 1. invalid MMS_CODE_PREVIOUSLYSENTDATE \n");
+                               MSG_DEBUG("1. invalid MMS_CODE_PREVIOUSLYSENTDATE");
                                goto __CATCH;
                        }
 
                        if (__MmsBinaryDecodeInteger(pFile, &tmpInteger, &tmpIntLen, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : 2. invalid MS_CODE_PREVIOUSLYSENTDATE \n");
+                               MSG_DEBUG("2. invalid MS_CODE_PREVIOUSLYSENTDATE");
                                goto __CATCH;
                        }
 
                        if (__MmsDecodeLongInteger(pFile, (UINT32*)&tmpInteger, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeMsgHeader : 3. invalid MMS_CODE_PREVIOUSLYSENTDATE \n");
+                               MSG_DEBUG("3. invalid MMS_CODE_PREVIOUSLYSENTDATE");
                                goto __CATCH;
                        }
                        break;
 
-
                default:
 
                        /*
@@ -983,7 +1012,7 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
 
                                oneByte = 0x00;
 
-                               offset = _MmsGetDecodeOffset();
+                               offset = __MmsGetDecodeOffset();
                                if (offset >= totalLength)
                                        goto __RETURN;
 
@@ -991,11 +1020,11 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
 
                                while ((oneByte < 0x80) && (remainLength > 0)) {
                                        if (__MmsBinaryDecodeCheckAndDecreaseLength(&remainLength, 1) == false) {
-                                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: __MmsBinaryDecodeCheckAndDecreaseLength fail\n");
+                                               MSG_DEBUG("__MmsBinaryDecodeCheckAndDecreaseLength fail");
                                                goto __CATCH;
                                        }
-                                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                                               MSG_DEBUG("MmsBinaryDecodeMsgHeader: responseStatus GetOneByte fail\n");
+                                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                                               MSG_DEBUG("responseStatus GetOneByte fail");
                                                goto __CATCH;
                                        }
                                }
@@ -1006,7 +1035,7 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
                        break;
                }       /* switch */
 
-               offset = _MmsGetDecodeOffset();
+               offset = __MmsGetDecodeOffset();
                if (offset >= totalLength)
                        goto __RETURN;
 
@@ -1015,83 +1044,71 @@ bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
 
 __RETURN:
 
-       MSG_DEBUG("MmsBinaryDecodeMsgHeader: success\n");
-       return true;
-
+       if (mmsHeader.pTo == NULL && pLastTo) {
+               free(pLastTo);
+       }
 
-__CATCH:
-       MSG_DEBUG("MmsBinaryDecodeMsgHeader: failed\n");
+       if (mmsHeader.pCc == NULL && pLastCc) {
+               free(pLastCc);
+       }
 
-       return false;
-}
+       if (mmsHeader.pBcc == NULL && pLastBcc) {
+               free(pLastBcc);
+       }
 
-#ifdef FEATURE_JAVA_MMS
-// for JAVA MMS AppId - check later whether it can be handled by MmsBinaryDecodeMsgHeader
-bool MmsBinaryDecodeContentType(FILE *pFile, char *szFilePath, int totalLength)
-{
-       int length      = 0;
+       MSG_INFO("## Decode Header Success ##");
+       MSG_END();
+       return true;
 
-       MSG_DEBUG("MmsBinaryDecodeContentType:\n");
 
-       if (szFilePath != NULL)
-               strncpy(mmsHeader.msgType.szOrgFilePath, szFilePath, strlen(szFilePath));
-       mmsHeader.msgType.offset = _MmsGetDecodeOffset() - 1;           // + Content-Type code value
+__CATCH:
 
-       // read data(2K) from msg file(/User/Msg/Inbox/5) to gpCurMmsDecodeBuff for decoding
-       if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos,
-                                                                       &gMmsDecodeCurOffset, gpMmsDecodeBuf1, gpMmsDecodeBuf2,
-                                                                       gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-               MSG_DEBUG("MmsBinaryDecodeContentType: fail to load to buffer \n");
-               goto __CATCH;
+       if (mmsHeader.pTo == NULL && pLastTo) {
+               free(pLastTo);
        }
 
-       // msg's type [ex] related, mixed, single part (jpg, amr and etc)
-       length = MmsBinaryDecodeContentType(pFile, &mmsHeader.msgType, totalLength);
-       if (length == -1) {
-               MSG_DEBUG("MmsBinaryDecodeContentType: MMS_CODE_CONTENTTYPE is fail\n");
-               goto __CATCH;
+       if (mmsHeader.pCc == NULL && pLastCc) {
+               free(pLastCc);
        }
-       MSG_DEBUG("Content-Type: Application-ID:%s Reply-To-Application-ID:%s",mmsHeader.msgType.param.szApplicationID, mmsHeader.msgType.param.szReplyToApplicationID);
-
-       return true;
 
-__CATCH:
+       if (mmsHeader.pBcc == NULL && pLastBcc) {
+               free(pLastBcc);
+       }
 
+       MSG_FATAL("## Decode Header Fail ##");
+       MSG_END();
        return false;
 }
-#endif
 
 bool MmsBinaryDecodeMsgBody(FILE *pFile, char *szFilePath, int totalLength)
 {
+       MSG_BEGIN();
+
        int length = 0;
        int offset = 0;
 
-       MsgMultipart *pMultipart = NULL;
-
-       MSG_DEBUG("MmsBinaryDecodeMsgBody:\n");
-
        if (szFilePath != NULL)
-               strncpy(mmsHeader.msgType.szOrgFilePath, szFilePath , strlen(szFilePath));
+               snprintf(mmsHeader.msgType.szOrgFilePath, sizeof(mmsHeader.msgType.szOrgFilePath), "%s", szFilePath);
 
-       mmsHeader.msgType.offset = _MmsGetDecodeOffset() - 1;           // + Content-Type code value
+       mmsHeader.msgType.offset = __MmsGetDecodeOffset() - 1;          // + Content-Type code value
 
        // read data(2K) from msg file(/User/Msg/Inbox/5) to gpCurMmsDecodeBuff for decoding
-       if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos,
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos,
                                                                        &gMmsDecodeCurOffset, gpMmsDecodeBuf1, gpMmsDecodeBuf2,
                                                                        gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-               MSG_DEBUG("MmsBinaryDecodeMsgBody: fail to load to buffer \n");
+               MSG_DEBUG("fail to load to buffer");
                goto __CATCH;
        }
 
        // msg's type [ex] related, mixed, single part (jpg, amr and etc)
-       length = MmsBinaryDecodeContentType(pFile, &mmsHeader.msgType, totalLength);
+       length = __MmsBinaryDecodeContentType(pFile, &mmsHeader.msgType, totalLength);
        if (length == -1) {
-               MSG_DEBUG("MmsBinaryDecodeMsgBody: MMS_CODE_CONTENTTYPE is fail\n");
+               MSG_DEBUG("MMS_CODE_CONTENTTYPE is fail");
                goto __CATCH;
        }
 
-       mmsHeader.msgType.size   = length + 1;                                          // + Content-Type code value
-       mmsHeader.msgBody.offset = _MmsGetDecodeOffset();
+       mmsHeader.msgType.size   = length + 1; // + Content-Type code value
+       mmsHeader.msgBody.offset = __MmsGetDecodeOffset();
 
        switch (mmsHeader.msgType.type) {
        case MIME_APPLICATION_VND_WAP_MULTIPART_MIXED:
@@ -1105,14 +1122,14 @@ bool MmsBinaryDecodeMsgBody(FILE *pFile, char *szFilePath, int totalLength)
        case MIME_APPLICATION_VND_OMA_DRM_MESSAGE:
        case MIME_APPLICATION_VND_OMA_DRM_CONTENT:
 
-               MSG_DEBUG("__MmsBinaryMsgBodyDecode: Decode multipart\n");
+               MSG_DEBUG("Decode Multipart");
 
-               offset = _MmsGetDecodeOffset();
+               offset = __MmsGetDecodeOffset();
                if (offset >= totalLength)
                        goto __RETURN;
 
-               if (MmsBinaryDecodeMultipart(pFile, szFilePath, &mmsHeader.msgType, &mmsHeader.msgBody, totalLength) == false) {
-                       MSG_DEBUG("__MmsBinaryMsgBodyDecode: MmsBinaryDecodeMultipart is fail.\n");
+               if (__MmsBinaryDecodeMultipart(pFile, szFilePath, &mmsHeader.msgType, &mmsHeader.msgBody, totalLength) == false) {
+                       MSG_DEBUG("MmsBinaryDecodeMultipart is fail.");
                        goto __CATCH;
                }
                break;
@@ -1120,15 +1137,14 @@ bool MmsBinaryDecodeMsgBody(FILE *pFile, char *szFilePath, int totalLength)
        default:
 
                /* Single part message ---------------------------------------------- */
+               MSG_DEBUG("Decode Singlepart");
 
-               strcpy(mmsHeader.msgBody.szOrgFilePath, szFilePath);
-
-               offset = _MmsGetDecodeOffset();
+               offset = __MmsGetDecodeOffset();
                if (offset >= totalLength)
                        goto __RETURN;
 
-               if (MmsBinaryDecodePartBody(pFile, totalLength - mmsHeader.msgBody.offset, totalLength) == false) {
-                       MSG_DEBUG("__MmsBinaryMsgBodyDecode: MmsBinaryDecodePartBody is fail.(Single Part)\n");
+               if (__MmsBinaryDecodePartBody(pFile, totalLength - mmsHeader.msgBody.offset, totalLength) == false) {
+                       MSG_DEBUG("MmsBinaryDecodePartBody is fail.(Single Part)");
                        goto __CATCH;
                }
 
@@ -1138,48 +1154,17 @@ bool MmsBinaryDecodeMsgBody(FILE *pFile, char *szFilePath, int totalLength)
                break;
        }
 
-#ifdef __SUPPORT_DRM__
-       mmsHeader.drmType = MsgGetDRMType(&mmsHeader.msgType, &mmsHeader.msgBody);
-#endif
-
 __RETURN:
-
+       MSG_END();
        return true;
 
 __CATCH:
-
-       if (pMultipart) {
-               if (pMultipart->pBody) {
-                       if (pMultipart->pBody->body.pText) {
-                               free(pMultipart->pBody->body.pText);
-                               pMultipart->pBody->body.pText = NULL;
-                       }
-
-                       free(pMultipart->pBody);
-                       pMultipart->pBody = NULL;
-               }
-
-               free(pMultipart);
-               pMultipart = NULL;
-       }
-
        return false;
 }
 
-#if MMS_ENABLE_EXTEND_CFM
-// DRM (Extended)CFM
-//     Get Extended CFM value.
-static bool __MmsConvertString2Bool(char *pszValue)
-{
-       if (!strcasecmp(pszValue, "no"))
-               return true;
-
-       return false;
-}
-#endif
-
-bool MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, int totalLength)
+static bool __MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, int totalLength)
 {
+       MSG_BEGIN();
        UINT8 oneByte = 0;
        int charSetLen = 0;
        char *szTypeString = NULL;
@@ -1195,11 +1180,9 @@ bool MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, i
         * WAP-230-WSP-20010118-p, Proposed Version 18 January 2001 (pp.107)
         */
 
-       MSG_DEBUG("MmsBinaryDecodeParameter: \n");
-
        while (valueLength > 0) {
-               if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                       MSG_DEBUG("MmsBinaryDecodeContentType: paramCode _MmsBinaryDecodeGetOneByte fail\n");
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                       MSG_DEBUG("paramCode _MmsBinaryDecodeGetOneByte fail");
                        goto __CATCH;
                }
 
@@ -1210,7 +1193,7 @@ bool MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, i
                case 0x81: // charset
 
                        if (__MmsBinaryDecodeCharset(pFile, (UINT32*)&(pMsgType->param.charset), &charSetLen, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeContentType : __MmsBinaryDecodeCharset fail.\n");
+                               MSG_DEBUG("__MmsBinaryDecodeCharset fail.");
                                goto __CATCH;
                        }
 
@@ -1226,12 +1209,12 @@ bool MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, i
                                                                                         MSG_FILENAME_LEN_MAX -5,               // MSG_LOCALE_FILENAME_LEN_MAX + 1, :  change @ 110(Ui code have to change for this instead of DM)
                                                                                         totalLength);
                        if (length < 0) {
-                               MSG_DEBUG("MmsBinaryDecodeContentType : __MmsDecodeGetFilename fail. (name parameter)\n");
+                               MSG_DEBUG("__MmsDecodeGetFilename fail. (name parameter)");
                                goto __CATCH;
                        }
 
-                       if (MsgCheckFileNameHasInvalidChar(pMsgType->param.szName)) {
-                               _MsgReplaceInvalidFileNameChar(pMsgType->param.szName, '_');
+                       if (__MsgCheckFileNameHasInvalidChar(pMsgType->param.szName)) {
+                               __MsgReplaceInvalidFileNameChar(pMsgType->param.szName, '_');
                        }
 
                        if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, length) == false)
@@ -1244,12 +1227,12 @@ bool MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, i
                        memset(pMsgType->param.szFileName, 0, sizeof(pMsgType->param.szFileName));
                        length = __MmsDecodeGetFilename(pFile, pMsgType->param.szFileName, MSG_FILENAME_LEN_MAX -5, totalLength);
                        if (length < 0) {
-                               MSG_DEBUG("MmsBinaryDecodeContentType : __MmsDecodeGetFilename fail. (filename parameter)\n");
+                               MSG_DEBUG("__MmsDecodeGetFilename fail. (filename parameter)");
                                goto __CATCH;
                        }
 
-                       if (MsgCheckFileNameHasInvalidChar(pMsgType->param.szFileName)) {
-                               _MsgReplaceInvalidFileNameChar(pMsgType->param.szFileName, '_');
+                       if (__MsgCheckFileNameHasInvalidChar(pMsgType->param.szFileName)) {
+                               __MsgReplaceInvalidFileNameChar(pMsgType->param.szFileName, '_');
                        }
 
                        if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, length) == false)
@@ -1259,14 +1242,13 @@ bool MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, i
 
                case 0x89: //type = Constrained-encoding = Extension-Media | Short-integer
 
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                               MSG_DEBUG("MmsBinaryDecodeContentType: type _MmsBinaryDecodeGetOneByte fail\n");
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("type _MmsBinaryDecodeGetOneByte fail");
                                goto __CATCH;
                        }
 
                        if (oneByte > 0x7f) {
-                               pMsgType->param.type = _MmsGetBinaryType(MmsCodeContentType,
-                                                                                                                 (UINT16)(oneByte & 0x7f));
+                               pMsgType->param.type = MimeGetMimeIntFromBi((UINT16)(oneByte & 0x7f));//MmsGetBinaryType(MmsCodeContentType,(UINT16)(oneByte & 0x7f));
                                if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, 1) == false)
                                        goto __RETURN;
                        } else {
@@ -1274,8 +1256,7 @@ bool MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, i
 
                                textLength = 0;
                                szTypeString = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
-                               pMsgType->param.type = _MmsGetTextType(MmsCodeContentType, szTypeString);
-
+                               pMsgType->param.type = MimeGetMimeIntFromMimeString(szTypeString);
                                if (szTypeString) {
                                        free(szTypeString);
                                        szTypeString = NULL;
@@ -1326,7 +1307,7 @@ bool MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, i
                default:
 
                        if (paramCode > 0x7F) {
-                               MSG_DEBUG("MmsBinaryDecodeContentType: Unsupported parameter\n");
+                               MSG_DEBUG("Unsupported parameter");
 
                                // In case of the last byte of Parameter field, it should be returned without decreasing the gCurMmsDecodeBuffPos value.
                                valueLength++;
@@ -1357,7 +1338,7 @@ bool MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, i
                                /* Text-value */
 
                                if (__MmsBinaryDecodeInteger(pFile, &integer, &intLen, totalLength) == true) {
-                                       MSG_DEBUG("MmsBinaryDecodeContentType: Unsupported parameter(%d)\n", integer);
+                                       MSG_DEBUG("Unsupported parameter(%d)\n", integer);
                                        if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, intLen) == false)
                                                goto __RETURN;
                                } else {
@@ -1371,28 +1352,33 @@ bool MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, i
                                                        strncpy(pMsgType->param.szBoundary, szTypeValue, MSG_BOUNDARY_LEN);
 #ifdef FEATURE_JAVA_MMS
                                                } else if (strcasecmp(szTypeString, "Application-ID") == 0) {
-                                                       pMsgType->param.szApplicationID = (char*) malloc(textLength + 1);
-                                                       memset(pMsgType->param.szApplicationID,  0,  textLength + 1);
-                                                       strncpy(pMsgType->param.szApplicationID, szTypeValue, textLength);
-                                                       MSG_DEBUG("Application-ID:%s",pMsgType->param.szApplicationID);
+                                                       pMsgType->param.szApplicationID = (char*) calloc(1, textLength + 1);
+                                                       if (pMsgType->param.szApplicationID) {
+                                                               memset(pMsgType->param.szApplicationID,  0,  textLength + 1);
+                                                               strncpy(pMsgType->param.szApplicationID, szTypeValue, textLength);
+                                                               MSG_SEC_DEBUG("Application-ID:%s",pMsgType->param.szApplicationID);
+                                                       }
                                                } else if (strcasecmp(szTypeString,"Reply-To-Application-ID") == 0) {
-                                                       pMsgType->param.szReplyToApplicationID= (char*) malloc(textLength + 1);
-                                                       memset(pMsgType->param.szReplyToApplicationID, 0, textLength + 1);
-                                                       strncpy(pMsgType->param.szReplyToApplicationID, szTypeValue, textLength);
-                                                       MSG_DEBUG("ReplyToApplication-ID:%s",pMsgType->param.szReplyToApplicationID);
+                                                       pMsgType->param.szReplyToApplicationID = (char*) calloc(1, textLength + 1);
+                                                       if (pMsgType->param.szReplyToApplicationID) {
+                                                               memset(pMsgType->param.szReplyToApplicationID, 0, textLength + 1);
+                                                               strncpy(pMsgType->param.szReplyToApplicationID, szTypeValue, textLength);
+                                                               MSG_SEC_DEBUG("ReplyToApplication-ID:%s",pMsgType->param.szReplyToApplicationID);
+                                                       }
 #endif
                                                }
+
+                                               MSG_DEBUG("Unsupported parameter(%s)\n", szTypeValue);
                                                free(szTypeValue);
                                                szTypeValue = NULL;
 
-                                               MSG_DEBUG("MmsBinaryDecodeContentType: Unsupported parameter(%s)\n", szTypeValue);
                                                if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, textLength) == false)
                                                        goto __RETURN;
                                        }
                                }
 
                                if (szTypeString) {
-                                       MSG_DEBUG("MmsBinaryDecodeContentType: Unsupported parameter(%s)\n", szTypeString);
+                                       MSG_DEBUG("Unsupported parameter(%s)\n", szTypeString);
                                        free(szTypeString);
                                        szTypeString = NULL;
                                }
@@ -1410,19 +1396,14 @@ __RETURN:
                szTypeString = NULL;
        }
 
+       MSG_END();
        return true;
 
 __CATCH:
-
-       if (szTypeString) {
-               free(szTypeString);
-               szTypeString = NULL;
-       }
+       MSG_END();
        return false;
 }
 
-
-
 /**
  * Decode Encoded Content type
  *
@@ -1430,8 +1411,9 @@ __CATCH:
  * @param      pMsgType                [out] Decoded MsgType
  * @return     Decoded address list
  */
-int MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength)
+static int __MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength)
 {
+       MSG_BEGIN();
        UINT8 oneByte = 0;
        char *szTypeString = NULL;
        int valueLength = 0;
@@ -1449,9 +1431,6 @@ int MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength)
         * Media-type                   = (Well-known-media | Extension-Media) *(Parameter)
         */
 
-       MSG_DEBUG("MmsBinaryDecodeContentType: decoding content type..\n");
-
-
        length = __MmsDecodeValueLength(pFile, (UINT32*)&valueLength, totalLength);
        if (length <= 0) {
                /*
@@ -1461,14 +1440,17 @@ int MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength)
                 * Short-integer     = OCTET(1xxx xxxx)
                 */
 
-               if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                       MSG_DEBUG("MmsBinaryDecodeContentType: Constrained-media _MmsBinaryDecodeGetOneByte fail\n");
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                       MSG_DEBUG("Constrained-media _MmsBinaryDecodeGetOneByte fail");
                        goto __CATCH;
                }
 
                if (oneByte > 0x7F) {
                        /* Short-integer */
-                       pMsgType->type = _MmsGetBinaryType(MmsCodeContentType, (UINT16)(oneByte & 0x7F));
+                       pMsgType->type = MimeGetMimeIntFromBi((UINT16)(oneByte & 0x7f));
+
+                       MSG_SEC_DEBUG("Constrained-media : Short-integer : Content Type = [0x%04x], MimeType = [0x%04x]", oneByte, pMsgType->type);
+
                        length = 1;
                } else {
                        char *pszTemp = NULL;
@@ -1480,14 +1462,19 @@ int MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength)
                        szTypeString = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
 
                        if (szTypeString && (strchr(szTypeString, ';')) != NULL) {
-                               pszTemp = _MsgGetStringUntilDelimiter(szTypeString, ';');
+
+                               MSG_SEC_DEBUG("Constrained-media : Extension-Media : Content Type with delimiter = [%s]", szTypeString);
+
+                               pszTemp = __MsgGetStringUntilDelimiter(szTypeString, ';');
                                if (pszTemp) {
                                        free(szTypeString);
                                        szTypeString = pszTemp;
                                }
                        }
 
-                       pMsgType->type = _MmsGetTextType(MmsCodeContentType, szTypeString);
+                       pMsgType->type = MimeGetMimeIntFromMimeString(szTypeString);
+
+                       MSG_SEC_DEBUG("Constrained-media : Extension-Media : Content Type = [%s], MimeType = [0x%04x]", szTypeString, pMsgType->type);
 
                        length = textLength;
 
@@ -1504,14 +1491,15 @@ int MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength)
 
                length += valueLength;
 
-               if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                       MSG_DEBUG("MmsBinaryDecodeContentType: Well-known-media _MmsBinaryDecodeGetOneByte fail\n");
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                       MSG_DEBUG("Well-known-media _MmsBinaryDecodeGetOneByte fail");
                        goto __CATCH;
                }
 
                if (oneByte > 0x7F) {
                        /* Well-known-media */
-                       pMsgType->type = _MmsGetBinaryType(MmsCodeContentType, (UINT16)(oneByte & 0x7F));
+                       pMsgType->type = MimeGetMimeIntFromBi((UINT16)(oneByte & 0x7f));
+                       MSG_SEC_DEBUG("Content-general-form : Well-known-media : Content Type = [0x%04x], MimeType = [0x%04x]", oneByte, pMsgType->type);
                        valueLength--;
                } else {
                        /* Extension-Media */
@@ -1519,7 +1507,11 @@ int MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength)
 
                        textLength = 0;
                        szTypeString = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
-                       pMsgType->type = _MmsGetTextType(MmsCodeContentType, szTypeString);
+
+                       pMsgType->type = MimeGetMimeIntFromMimeString(szTypeString);
+
+                       MSG_SEC_DEBUG("Content-general-form : Extension-Media : Content Type = [%s], MimeType = [0x%04x]", szTypeString, pMsgType->type);
+
                        valueLength -= textLength;
 
                        if (szTypeString) {
@@ -1528,23 +1520,23 @@ int MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength)
                        }
                }
 
-               MSG_DEBUG("MmsBinaryDecodeContentType: content type=%s\n", MmsDebugGetMimeType((MimeType)pMsgType->type));
-
+               MSG_SEC_DEBUG("Content-Type = [%s]", MmsDebugGetMimeType((MimeType)pMsgType->type));
 
-               if (MmsBinaryDecodeParameter(pFile, pMsgType, valueLength, totalLength) == false) {
-                       MSG_DEBUG("MmsBinaryDecodeContentType: Content-Type parameter fail\n");
+               if (__MmsBinaryDecodeParameter(pFile, pMsgType, valueLength, totalLength) == false) {
+                       MSG_DEBUG("Content-Type parameter fail");
                        goto __CATCH;
                }
        }
 
+       MSG_END();
        return length;
 
 __CATCH:
+       MSG_END();
        return -1;
 }
 
-
-bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, int totalLength)
+static bool __MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, int totalLength)
 {
        UINT8 fieldCode = 0xff;
        int length = 0;
@@ -1574,8 +1566,8 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
         */
 
        while (headerLen > 0) {
-               if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                       MSG_DEBUG("MmsBinaryDecodePartHeader: field code GetOneByte fail\n");
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                       MSG_DEBUG("field code GetOneByte fail");
                        goto __CATCH;
                }
 
@@ -1590,72 +1582,64 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                        switch (fieldCode) {
                        case 0x0E:      //Content-Location
                        case 0x04:      //Content-Location
-
-                               pLatinBuff = (char *)malloc(MMS_CONTENT_ID_LEN + 1);
+                       {
+                               pLatinBuff = (char *)calloc(1, MMS_CONTENT_ID_LEN + 1);
                                if (pLatinBuff == NULL)
                                        goto __CATCH;
 
                                length = __MmsBinaryDecodeText(pFile, pLatinBuff, MMS_CONTENT_ID_LEN + 1, totalLength);
                                if (length == -1) {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader : __MmsBinaryDecodeQuotedString fail.\n");
+                                       MSG_DEBUG("__MmsBinaryDecodeQuotedString fail.");
                                        goto __CATCH;
                                }
 
-                               szSrc = MsgChangeHexString(pLatinBuff);
-
+                               szSrc = __MsgConvertLatin2UTF8FileName(pLatinBuff);
                                if (szSrc) {
-                                       strcpy(pLatinBuff, szSrc);
+                                       snprintf(pMsgType->szContentLocation, sizeof(pMsgType->szContentLocation), "%s", szSrc);
+                                       MSG_DEBUG("Content Location : [%s]", pMsgType->szContentLocation);
                                        free(szSrc);
                                        szSrc = NULL;
                                }
 
-                               textLength = strlen(pLatinBuff);
-
-                               if (MsgLatin2UTF ((unsigned char*)pMsgType->szContentLocation, MMS_CONTENT_ID_LEN + 1, (unsigned char*)pLatinBuff, textLength) < 0) {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader: MsgLatin2UTF fail \n");
-                                       goto __CATCH;
-                               }
-
                                free(pLatinBuff);
                                pLatinBuff = NULL;
 
                                if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, length) == false)
                                        goto __RETURN;
-
+                       }
                                break;
 
                        case 0x40:      // Content-ID
+                       {
+                               char szContentID[MMS_CONTENT_ID_LEN + 1] = {0, };
 
-                               pLatinBuff = (char *)malloc(MMS_CONTENT_ID_LEN + 1);
+                               pLatinBuff = (char *)calloc(1, MMS_CONTENT_ID_LEN + 1);
                                if (pLatinBuff == NULL)
                                        goto __CATCH;
 
                                length = __MmsBinaryDecodeQuotedString(pFile, pLatinBuff, MMS_CONTENT_ID_LEN + 1, totalLength);
 
                                if (length == -1) {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader : Content-ID __MmsBinaryDecodeQuotedString fail.\n");
+                                       MSG_DEBUG("Content-ID __MmsBinaryDecodeQuotedString fail.");
                                        goto __CATCH;
                                }
 
-                               szSrc = MsgChangeHexString(pLatinBuff);
-
+                               szSrc = __MsgConvertLatin2UTF8FileName(pLatinBuff);
                                if (szSrc) {
-                                       strcpy(pLatinBuff, szSrc);
+                                       snprintf(szContentID, sizeof(szContentID), "%s", szSrc);
+                                       MSG_DEBUG("Content ID : [%s]", szContentID);
                                        free(szSrc);
                                        szSrc = NULL;
                                }
 
-                               textLength = strlen(pLatinBuff);
-                               if (MsgLatin2UTF ((unsigned char*)pMsgType->szContentID, MMS_CONTENT_ID_LEN + 1, (unsigned char*)pLatinBuff, textLength) < 0) {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader: MsgLatin2UTF fail \n");
-                                       goto __CATCH;
-                               }
                                free(pLatinBuff);
                                pLatinBuff = NULL;
 
+                               MmsRemoveLessGreaterChar(szContentID, pMsgType->szContentID, sizeof(pMsgType->szContentID));//remove "< >"
+
                                if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, length) == false)
                                        goto __RETURN;
-
+                       }
                                break;
 
                        case 0x2E:      // Content-Disposition
@@ -1677,8 +1661,8 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
 
                                }
 
-                               if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader: Disposition value GetOneByte fail\n");
+                               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                                       MSG_DEBUG("Disposition value GetOneByte fail");
                                        goto __CATCH;
                                }
 
@@ -1686,18 +1670,18 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                                        valueLength--;
 
                                if (oneByte >= 0x80) {
-                                       pMsgType->disposition = _MmsGetBinaryType(MmsCodeMsgDisposition, (UINT16)(oneByte & 0x7F));
+                                       pMsgType->disposition = MmsGetBinaryType(MmsCodeMsgDisposition, (UINT16)(oneByte & 0x7F));
 
-                                       if (pMsgType->disposition == INVALID_HOBJ) {
-                                               MSG_DEBUG("MmsBinaryDecodePartHeader : Content-Disposition _MmsGetBinaryType fail.\n");
+                                       if (pMsgType->disposition == -1) {
+                                               MSG_DEBUG("Content-Disposition MmsGetBinaryType fail.");
                                                pMsgType->disposition = MSG_DISPOSITION_ATTACHMENT;             // default
                                        }
 
                                        if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, 1) == false)
                                                goto __RETURN;
 
-                                       if (MmsBinaryDecodeParameter(pFile, pMsgType, valueLength, totalLength) == false) {
-                                               MSG_DEBUG("MmsBinaryDecodePartHeader: Disposition parameter fail\n");
+                                       if (__MmsBinaryDecodeParameter(pFile, pMsgType, valueLength, totalLength) == false) {
+                                               MSG_DEBUG("Disposition parameter fail");
                                                goto __CATCH;
                                        }
 
@@ -1708,14 +1692,16 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                                        gCurMmsDecodeBuffPos--;
                                        valueLength++;
 
-                                       pLatinBuff = (char *)malloc(MSG_FILENAME_LEN_MAX);
+                                       pLatinBuff = (char *)calloc(1, MSG_FILENAME_LEN_MAX);
+                                       if (pLatinBuff == NULL)
+                                               goto __CATCH;
                                        memset(pLatinBuff, 0, MSG_FILENAME_LEN_MAX);
 
                                        textLength = __MmsBinaryDecodeText(pFile, pLatinBuff, MSG_FILENAME_LEN_MAX-1, totalLength);
 
 
                                        if (textLength < 0) {
-                                               MSG_DEBUG("MmsBinaryDecodePartHeader : Content-Disposition decodingfail. \n");
+                                               MSG_DEBUG("Content-Disposition decodingfail.");
                                                goto __CATCH;
                                        }
                                        free(pLatinBuff);
@@ -1726,9 +1712,9 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
 
                                        valueLength -= textLength;
 
-                                       if (MmsBinaryDecodeParameter(pFile, pMsgType, valueLength, totalLength) == false)
+                                       if (__MmsBinaryDecodeParameter(pFile, pMsgType, valueLength, totalLength) == false)
                                        {
-                                               MSG_DEBUG("MmsBinaryDecodePartHeader: Disposition parameter fail\n");
+                                               MSG_DEBUG("Disposition parameter fail");
                                                goto __CATCH;
                                        }
 
@@ -1741,8 +1727,8 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
 
                        case 0x0B:      //Content-Encoding
 
-                               if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader: Disposition value GetOneByte fail\n");
+                               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                                       MSG_DEBUG("Disposition value GetOneByte fail");
                                        goto __CATCH;
                                }
 
@@ -1762,7 +1748,7 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                                        cTemp = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
 
                                        if (cTemp == NULL) {
-                                               MSG_DEBUG("MmsBinaryDecodePartHeader : __MmsBinaryDecodeText2 fail...\n");
+                                               MSG_DEBUG("__MmsBinaryDecodeText2 fail...");
                                                goto __CATCH;
                                        }
 
@@ -1782,7 +1768,7 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                        case 0x0D:      //Content-Length
 
                                if (__MmsBinaryDecodeInteger(pFile, (UINT32*)&tmpInt, &tmpIntLen, totalLength) == false) {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader : __MmsBinaryDecodeInteger fail...\n");
+                                       MSG_DEBUG("__MmsBinaryDecodeInteger fail...");
                                        goto __CATCH;
                                }
 
@@ -1793,26 +1779,26 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
 
                        case 0x30:      //X-Wap-Content-URI skip this value
 
-                               MSG_DEBUG("MmsBinaryDecodePartHeader : X-Wap-Content-URI header.\n");
-                               pLatinBuff = (char *)malloc(MMS_TEXT_LEN);
+                               MSG_DEBUG("X-Wap-Content-URI header.");
+                               pLatinBuff = (char *)calloc(1, MMS_TEXT_LEN);
                                if (pLatinBuff == NULL)
                                        goto __CATCH;
 
                                length = __MmsBinaryDecodeText(pFile, pLatinBuff, MMS_TEXT_LEN, totalLength);
 
                                if (length == -1) {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader : __MmsBinaryDecodeQuotedString fail.\n");
+                                       MSG_DEBUG(" __MmsBinaryDecodeQuotedString fail.");
                                        goto __CATCH;
                                }
 
-                               MSG_DEBUG("MmsBinaryDecodePartHeader : X-Wap-Content-URI header decoded. Value length %d\n", length);
+                               MSG_DEBUG("X-Wap-Content-URI header decoded. Value length %d\n", length);
                                free(pLatinBuff);
                                pLatinBuff = NULL;
 
                                if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, length) == false)
                                        goto __RETURN;
 
-                               MSG_DEBUG("MmsBinaryDecodePartHeader : X-Wap-Content-URI header skipped.\n");
+                               MSG_DEBUG("X-Wap-Content-URI header skipped.");
 
                                break;
 
@@ -1828,13 +1814,13 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                                                Well-known-charset = Any-charset | Integer-value
                                                ; Both are encoded using values from Character Set Assignments table in Assigned Numbers
                                                Any-charset = <Octet 128>
-                                               ; Equivalent to the special RFC2616 charset value ¡°*¡±
+                                               ; Equivalent to the special RFC2616 charset value ��*��
                                        */
 
                                        int     charset = 0;
                                        int charSetLen = 0;
 
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader : Accept-charset. \n");
+                                       MSG_DEBUG("Accept-charset.");
 
                                        length = __MmsDecodeValueLength(pFile, &valueLength, totalLength);
                                        if (length > 0) {
@@ -1845,12 +1831,12 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
 
                                        if (__MmsBinaryDecodeInteger(pFile, (UINT32*)&charset, &charSetLen, totalLength) == false) {
                                                // We only support the well-known-charset format
-                                               MSG_DEBUG("MmsBinaryDecodePartHeader : __MmsBinaryDecodeInteger fail...\n");
+                                               MSG_DEBUG("__MmsBinaryDecodeInteger fail...");
                                                goto __CATCH;
                                        }
 
                                        if (charset > 0)
-                                               _MmsGetBinaryType(MmsCodeCharSet, (UINT16)charset);
+                                               MmsGetBinaryType(MmsCodeCharSet, (UINT16)charset);
 
                                        if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, charSetLen) == false)
                                                goto __RETURN;
@@ -1862,23 +1848,23 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
 
                                /* Other Content-xxx headers : Have valueLength */
 
-                               MSG_DEBUG("MmsBinaryDecodePartHeader : unknown Value = 0x%x\n", oneByte);
+                               MSG_WARN("unknown Value = 0x%x\n", oneByte);
 
                                length = __MmsDecodeValueLength(pFile, &valueLength, totalLength);
                                if (length <= 0) {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader : 1. invalid MMS_CODE_PREVIOUSLYSENTDATE \n");
+                                       MSG_WARN("invalid MMS_CODE_PREVIOUSLYSENTDATE");
                                        goto __CATCH;
                                }
 
                                if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, length) == false)
                                        goto __RETURN;
 
-                               szTemp = (char *)malloc(valueLength);
+                               szTemp = (char *)calloc(1, valueLength);
                                if (szTemp == NULL)
                                        goto __CATCH;
 
-                               if (_MmsBinaryDecodeGetBytes(pFile, szTemp, valueLength, totalLength) < 0) {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader : default _MmsBinaryDecodeGetBytes() fail\n");
+                               if (__MmsBinaryDecodeGetBytes(pFile, szTemp, valueLength, totalLength) == false) {
+                                       MSG_WARN("default _MmsBinaryDecodeGetBytes() fail");
                                        if (szTemp) {
                                                free(szTemp);
                                                szTemp = NULL;
@@ -1897,7 +1883,7 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                         * Application-specific-value = Text-string
                         */
 
-                       MSG_DEBUG(" MmsBinaryDecodePartHeader: Application-header = Token-text Application-specific-value \n");
+                       MSG_DEBUG(" Application-header = Token-text Application-specific-value");
 
                        gCurMmsDecodeBuffPos--;
 
@@ -1906,14 +1892,14 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                        textLength = 0;
                        pCode = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
                        if (pCode == NULL) {
-                               MSG_DEBUG("MmsBinaryDecodePartHeader: pCode is null\n");
+                               MSG_DEBUG("pCode is null");
                                goto __CATCH;
                        }
 
                        if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, textLength) == false)
                                goto __RETURN;
 
-                       MSG_DEBUG(" MmsBinaryDecodePartHeader: Token-text (%s) \n", pCode);
+                       MSG_DEBUG(" Token-text (%s) \n", pCode);
 
 
                        /* Application-specific-value */
@@ -1921,11 +1907,11 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                        textLength = 0;
                        pValue = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
                        if (pValue == NULL) {
-                               MSG_DEBUG("MmsBinaryDecodePartHeader: pValue is null\n");
+                               MSG_DEBUG("pValue is null");
                                goto __CATCH;
                        }
 
-                       MSG_DEBUG(" MmsBinaryDecodePartHeader: Application-specific-value (%s) \n", pValue);
+                       MSG_DEBUG(" Application-specific-value (%s) \n", pValue);
 
 
                        pParam = strchr(pValue, MSG_CH_ADDR_DELIMETER);
@@ -1934,44 +1920,48 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                                *pParam = '\0';
                        }
 
-                       switch (_MmsGetTextType(MmsCodeMsgBodyHeaderCode, pCode)) {
+                       switch (MmsGetTextType(MmsCodeMsgBodyHeaderCode, pCode)) {
                        case MMS_BODYHDR_TRANSFERENCODING:              // Content-Transfer-Encoding
-                               pMsgType->encoding = _MmsGetTextType(MmsCodeContentTransferEncoding, pValue);
+                               pMsgType->encoding = MmsGetTextType(MmsCodeContentTransferEncoding, pValue);
                                break;
 
                        case MMS_BODYHDR_CONTENTID:                             // Content-ID
+                       {
+                               char szContentID[MMS_CONTENT_ID_LEN + 1];
 
-                               pLatinBuff = (char *)malloc(MMS_CONTENT_ID_LEN + 1);
+                               pLatinBuff = (char *)calloc(1, MMS_CONTENT_ID_LEN + 1);
                                if (pLatinBuff == NULL)
                                {
                                        goto __CATCH;
                                }
 
-                               MsgMIMERemoveQuote (pValue);
+                               __MsgMIMERemoveQuote (pValue);
                                strncpy(pLatinBuff, pValue, MMS_MSG_ID_LEN);
 
                                length = strlen(pLatinBuff);
-                               if (MsgLatin2UTF ((unsigned char*)pMsgType->szContentID, MMS_CONTENT_ID_LEN + 1, (unsigned char*)pLatinBuff, length) < 0)
+                               if (__MsgLatin2UTF ((unsigned char*)szContentID, MMS_CONTENT_ID_LEN + 1, (unsigned char*)pLatinBuff, length) < 0)
                                {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader: MsgLatin2UTF fail \n");
+                                       MSG_DEBUG("MsgLatin2UTF fail");
                                        goto __CATCH;
                                }
 
+                               MmsRemoveLessGreaterChar(szContentID, pMsgType->szContentID, sizeof(pMsgType->szContentID));//remove "< >"
+
                                free(pLatinBuff);
                                pLatinBuff = NULL;
                                break;
-
+                       }
                        case MMS_BODYHDR_CONTENTLOCATION:               // Content-Location
 
-                               pLatinBuff = (char *)malloc(MMS_CONTENT_ID_LEN + 1);
+                               pLatinBuff = (char *)calloc(1, MMS_CONTENT_ID_LEN + 1);
                                if (pLatinBuff == NULL)
                                        goto __CATCH;
 
                                strncpy(pLatinBuff, pValue, MMS_MSG_ID_LEN);
 
                                length = strlen(pLatinBuff);
-                               if (MsgLatin2UTF ((unsigned char*)pMsgType->szContentLocation, MMS_CONTENT_ID_LEN + 1, (unsigned char*)pLatinBuff, length) < 0) {
-                                       MSG_DEBUG("MmsBinaryDecodePartHeader: MsgLatin2UTF fail \n");
+                               if (__MsgLatin2UTF ((unsigned char*)pMsgType->szContentLocation, MMS_CONTENT_ID_LEN + 1, (unsigned char*)pLatinBuff, length) < 0) {
+                                       MSG_DEBUG("MsgLatin2UTF fail");
                                        goto __CATCH;
                                }
 
@@ -1980,7 +1970,7 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                                break;
 
                        case MMS_BODYHDR_DISPOSITION:                   // Content-Disposition
-                               pMsgType->disposition = _MmsGetTextType(MmsCodeMsgDisposition, pValue);
+                               pMsgType->disposition = MmsGetTextType(MmsCodeMsgDisposition, pValue);
                                break;
 
                        case MMS_BODYHDR_X_OMA_DRM_SEPARATE_DELIVERY:   // DRM RO WAITING
@@ -1992,7 +1982,7 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
                        }
 
                        if (pParam) {
-                               _MsgParseParameter(pMsgType, pParam + 1);
+                               __MsgParseParameter(pMsgType, pParam + 1);
                                *pParam = ch;
                        }
                        if (pCode) {
@@ -2012,11 +2002,6 @@ bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, in
 
 __RETURN:
 
-       if (pLatinBuff) {
-               free(pLatinBuff);
-               pLatinBuff = NULL;
-       }
-
        if (szTemp) {
                free(szTemp);
                szTemp = NULL;
@@ -2052,8 +2037,7 @@ __CATCH:
        return false;
 }
 
-
-bool MmsBinaryDecodeEntries(FILE *pFile, UINT32 *npEntries, int totalLength)
+static bool __MmsBinaryDecodeEntries(FILE *pFile, UINT32 *npEntries, int totalLength)
 {
        int length = 0;
 
@@ -2062,7 +2046,7 @@ bool MmsBinaryDecodeEntries(FILE *pFile, UINT32 *npEntries, int totalLength)
                goto __CATCH;
        }
 
-       MSG_DEBUG("MmsBinaryDecodeEntries: Number of Entries = %d\n", *npEntries);
+       MSG_INFO("Number of Entries = [%d]", *npEntries);
 
        return true;
 
@@ -2070,9 +2054,7 @@ __CATCH:
        return false;
 }
 
-
-
-bool MmsBinaryDecodePartBody(FILE *pFile, UINT32 bodyLength, int totalLength)
+static bool __MmsBinaryDecodePartBody(FILE *pFile, UINT32 bodyLength, int totalLength)
 {
        int offset = 0;
 
@@ -2081,27 +2063,26 @@ bool MmsBinaryDecodePartBody(FILE *pFile, UINT32 bodyLength, int totalLength)
         * the only information used with msgBody.
         * If you need, add here more information
         */
+       MSG_BEGIN();
 
-       MSG_DEBUG("MmsBinaryDecodePartBody: \n");
-
-       offset = _MmsGetDecodeOffset();
+       offset = __MmsGetDecodeOffset();
        offset += bodyLength;
 
        if (MsgFseek(pFile, offset, SEEK_SET) < 0) {
-               MSG_DEBUG("MmsBinaryDecodePartBody: fail to seek file pointer \n");
+               MSG_DEBUG("fail to seek file pointer");
                goto __CATCH;
        }
 
-       _MmsCleanDecodeBuff();
+       __MmsCleanDecodeBuff();
 
        gMmsDecodeCurOffset = offset;
 
        if (offset >= totalLength)
                goto __RETURN;
 
-       if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
                                                                   gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-               MSG_DEBUG("_MmsBinaryDecodeGetOneByte: fail to load to buffer \n");
+               MSG_DEBUG("fail to load to buffer");
                goto __CATCH;
        }
 
@@ -2114,195 +2095,148 @@ __CATCH:
        return false;
 }
 
-
-static bool MmsBinaryDecodeMovePointer(FILE *pFile, int offset, int totalLength)
+static bool __MmsBinaryDecodeMovePointer(FILE *pFile, int offset, int totalLength)
 {
        if (offset > totalLength)
                goto __RETURN;
 
        if (MsgFseek(pFile, offset, SEEK_SET) < 0) {
-               MSG_DEBUG("MmsBinaryDecodeMovePointer: fail to seek file pointer \n");
+               MSG_DEBUG("fail to seek file pointer");
                goto __CATCH;
        }
 
-       _MmsCleanDecodeBuff();
+       __MmsCleanDecodeBuff();
 
        gMmsDecodeCurOffset = offset;
 
        if (offset == totalLength)
                goto __RETURN;
 
-       if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
                                                                        gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-               MSG_DEBUG("MmsBinaryDecodeMovePointer: fail to load to buffer \n");
-               goto __CATCH;
-       }
-
-__RETURN:
-       return true;
-
-__CATCH:
-       return false;
-}
-
-
-bool MmsBinaryIsTextEncodedPart(FILE *pFile, int totalLength)
-{
-       UINT8 oneByte   = 0;
-       int byteCount = 0;
-
-       byteCount++;                            //check 0x0D
-
-       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false)
+               MSG_DEBUG("fail to load to buffer");
                goto __CATCH;
-
-       if (oneByte != 0x0D) {
-               //it can be started "--" without 0x0D 0x0A
-               if (oneByte != 0x2D) {
-                       goto __CATCH;
-               } else {
-                       byteCount++;            // check 0x2D ('-')
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false)
-                               goto __CATCH;
-
-                       if (oneByte != 0x2D) {
-                               goto __CATCH;
-                       } else {
-                               goto __RETURN;
-                       }
-               }
-       } else {
-               byteCount++;                    //check 0x0A
-               if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false)
-                       goto __CATCH;
-
-               if (oneByte != 0x0A) {
-                       goto __CATCH;
-               } else {
-                       byteCount++;            // check 0x2D ('-')
-                       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false)
-                               goto __CATCH;
-
-                       if (oneByte != 0x2D) {
-                               goto __CATCH;
-                       } else {
-                               byteCount++;    // check 0x2D ('-')
-                               if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false)
-                                       goto __CATCH;
-
-                               if (oneByte != 0x2D) {
-                                       goto __CATCH;
-                               } else {
-                                       goto __RETURN;
-                               }
-                       }
-               }
        }
 
 __RETURN:
-       gCurMmsDecodeBuffPos -= byteCount;
        return true;
 
 __CATCH:
-       gCurMmsDecodeBuffPos -= byteCount;
        return false;
 }
 
-
-bool MmsBinaryDecodeMultipart(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, int totalLength)
+static bool __MmsBinaryDecodeMultipart(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, int totalLength)
 {
        UINT32 nEntries = 0;
        MsgMultipart *pMultipart = NULL;
        MsgMultipart *pLastMultipart = NULL;
-       MsgMultipart *pPreMultipart     = NULL;
+//     MsgMultipart *pPreMultipart     = NULL;
        int offset = 0;
        int     index = 0;
 
        MsgPresentationFactor factor = MSG_PRESENTATION_NONE;
        MsgPresentaionInfo presentationInfo;
 
-       MSG_DEBUG("MmsBinaryDecodeMultipart: total length=%d\n", totalLength);
+       MSG_DEBUG("pdu length = [%d]", totalLength);
 
        presentationInfo.factor = MSG_PRESENTATION_NONE;
        presentationInfo.pCurPresentation = NULL;
        presentationInfo.pPrevPart = NULL;
 
-       if (MmsBinaryDecodeEntries(pFile, &nEntries, totalLength) == false) {
-               MSG_DEBUG("MmsBinaryDecodeMultipart: MmsBinaryDecodeEntries is fail.\n");
+       if (__MmsBinaryDecodeEntries(pFile, &nEntries, totalLength) == false) {
+               MSG_DEBUG("MmsBinaryDecodeEntries is fail.");
                goto __CATCH;
        }
 
-       while (nEntries) {
-               MSG_DEBUG("MmsBinaryDecodeMultipart: decoding %dth multipart\n", index);
-
-               offset = _MmsGetDecodeOffset();
-               if (offset >= totalLength)
-                       goto __RETURN;
+       if (pMsgBody->body.pMultipart != NULL) {
+               pLastMultipart = pMsgBody->body.pMultipart;
+               MSG_DEBUG("previous multipart exist [%p]", pMsgBody->body.pMultipart);
+       } else {
+               MSG_DEBUG("first multipart");
+       }
+
+       while (nEntries) {
+               MSG_DEBUG("decoding [%d]th multipart", index);
+
+               offset = __MmsGetDecodeOffset();
+               if (offset >= totalLength) {
+                       MSG_DEBUG("offset is over totalLength");
+                       break;
+               }
 
-               if ((pMultipart = MsgAllocMultipart()) == NULL) {
-                       MSG_DEBUG("MmsBinaryDecodeMultipart: MsgAllocMultipart Fail \n");
+               if ((pMultipart = MmsAllocMultipart()) == NULL) {
+                       MSG_DEBUG("MsgAllocMultipart Fail");
                        goto __CATCH;
                }
 
-               if (MmsBinaryDecodeEachPart(pFile, szFilePath, &(pMultipart->type), pMultipart->pBody, totalLength) == false) {
-                       MSG_DEBUG("MmsBinaryDecodeMultipart: MmsBinaryDecodeEachPart is fail.(nEntries = %d)\n", nEntries);
+               if (__MmsBinaryDecodeEachPart(pFile, szFilePath, &(pMultipart->type), pMultipart->pBody, totalLength) == false) {
+                       MSG_DEBUG("MmsBinaryDecodeEachPart is fail.(nEntries = %d)\n", nEntries);
                        goto __CATCH;
                }
 
-               if (pMsgType->param.type == MIME_APPLICATION_SMIL) {
-                       factor = MsgIsPresentationEx(&(pMultipart->type), pMsgType->param.szStart, (MimeType)pMsgType->param.type);
+               if (pMultipart->type.type == MIME_APPLICATION_SMIL) {
+                       factor = __MsgIsPresentationEx(&(pMultipart->type), pMsgType->param.szStart, (MimeType)pMsgType->param.type);
+                       if (factor == MSG_PRESENTATION_NONE) {
+                               factor = MSG_PRESENTATION_TYPE_BASE;
+                       }
                } else {
                        factor = MSG_PRESENTATION_NONE;
                }
+
                // priority 1 : content type match, 2: content location, 3: type
                if (presentationInfo.factor < factor) {
                        // Presentation part
                        presentationInfo.factor = factor;
-                       presentationInfo.pPrevPart = pPreMultipart;
+                       presentationInfo.pPrevPart = pLastMultipart;
                        presentationInfo.pCurPresentation = pMultipart;
                }
 
-               if (pMsgBody->body.pMultipart == NULL) {
-                       /* first multipart */
+               /* first multipart */
+               if (pLastMultipart == NULL) {
                        pMsgBody->body.pMultipart = pMultipart;
-                       pLastMultipart                    = pMultipart;
-                       pPreMultipart                     = NULL;
-               } else if (pLastMultipart != NULL) {
-                       pPreMultipart = pLastMultipart;
-
-                       pLastMultipart->pNext   = pMultipart;
-                       pLastMultipart                  = pMultipart;
+                       pLastMultipart = pMultipart;
+//                     pPreMultipart = NULL;
+               } else {
+                       pLastMultipart->pNext = pMultipart;
+                       pLastMultipart = pMultipart;
+//                     pPreMultipart = pMultipart;
                }
 
                pMsgType->contentSize += pMultipart->pBody->size;
 
                nEntries--;
-               pPreMultipart = pMultipart;
-               MmsDebugPrintMulitpartEntry(pMultipart, index++);
+
+               MmsPrintMulitpart(pMultipart, index++);
 
        }
 
        pMsgBody->size = totalLength - pMsgBody->offset;
 
-#ifdef __SUPPORT_DRM__
-       if (MmsDrm2GetConvertState() != MMS_DRM2_CONVERT_REQUIRED)
-#endif
-               MsgConfirmPresentationPart(pMsgType, pMsgBody, &presentationInfo);
+       __MsgConfirmPresentationPart(pMsgType, pMsgBody, &presentationInfo);
 
-       if (MsgResolveNestedMultipart(pMsgType, pMsgBody) == false) {
-               MSG_DEBUG("MmsBinaryDecodeMultipart : MsgResolveNestedMultipart failed \n");
+       if (__MsgResolveNestedMultipart(pMsgType, pMsgBody) == false) {
+               MSG_DEBUG("MsgResolveNestedMultipart failed");
                goto __CATCH;
        }
 
-__RETURN:
+//__RETURN:
        return true;
 
 __CATCH:
+       if (pMultipart) {
+               if (pMultipart->pBody) {
+                       free(pMultipart->pBody);
+                       pMultipart->pBody = NULL;
+               }
+
+               free(pMultipart);
+               pMultipart = NULL;
+       }
+
        return false;
 }
 
-
-bool MmsBinaryDecodeEachPart(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, int totalLength)
+static bool __MmsBinaryDecodeEachPart(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, int totalLength)
 {
        int     length = 0;
        bool bSuccess = false;
@@ -2310,72 +2244,67 @@ bool MmsBinaryDecodeEachPart(FILE *pFile, char *szFilePath, MsgType *pMsgType, M
        UINT32 bodyLength = 0;
        int offset = 0;
 
-       MSG_DEBUG("MmsBinaryDecodeEachPart: total length=%d\n", totalLength);
+       MSG_DEBUG("pdu length = [%d]", totalLength);
 
        /* header length */
-
        if (__MmsBinaryDecodeUintvar(pFile, &headerLength, totalLength) <= 0) {
-               MSG_DEBUG("MmsBinaryDecodeEachPart: Get header length fail \n");
+               MSG_DEBUG("Get header length fail");
                goto __CATCH;
        }
 
-       offset = _MmsGetDecodeOffset();
+       offset = __MmsGetDecodeOffset();
        if (offset >= totalLength)
                goto __RETURN;
 
-
        /* body length */
-
        if (__MmsBinaryDecodeUintvar(pFile, &bodyLength, totalLength) <= 0) {
-               MSG_DEBUG("MmsBinaryDecodeEachPart: Get body length fail\n");
+               MSG_DEBUG("Get body length fail");
                goto __CATCH;
        }
 
-
-       offset = _MmsGetDecodeOffset();
+       offset = __MmsGetDecodeOffset();
        if (offset >= totalLength)
                goto __RETURN;
 
-
        /* Content Type */
        if (szFilePath != NULL)
-               strncpy(pMsgType->szOrgFilePath, szFilePath, strlen(szFilePath));
+               snprintf(pMsgType->szOrgFilePath, sizeof(pMsgType->szOrgFilePath), "%s", szFilePath);
 
-       pMsgType->offset = _MmsGetDecodeOffset();
+       pMsgType->offset = __MmsGetDecodeOffset();
        pMsgType->size = headerLength;
        pMsgType->contentSize = bodyLength;
 
        if (pMsgType->offset > totalLength)
                goto __RETURN;
 
-       length = MmsBinaryDecodeContentType(pFile, pMsgType, totalLength);
+       length = __MmsBinaryDecodeContentType(pFile, pMsgType, totalLength);
        if (length <= 0) {
-               MSG_DEBUG("MmsBinaryDecodeEachPart: Decode contentType Fail \n");
+               MSG_DEBUG("Decode contentType Fail");
                goto __CATCH;
        }
 
-       offset = _MmsGetDecodeOffset();
+       offset = __MmsGetDecodeOffset();
        if (offset >= totalLength)
                goto __RETURN;
 
 
        /* Part Header */
 
-       if (MmsBinaryDecodePartHeader(pFile, pMsgType, headerLength - length, totalLength) == false) {
-               MSG_DEBUG("MmsBinaryDecodeEachPart: Decode contentHeader Fail \n");
+       if (__MmsBinaryDecodePartHeader(pFile, pMsgType, headerLength - length, totalLength) == false) {
+               MSG_DEBUG("Decode contentHeader Fail");
                goto __CATCH;
        }
 
-       offset = _MmsGetDecodeOffset();
+       offset = __MmsGetDecodeOffset();
        if (offset >= totalLength)
                goto __RETURN;
 
        /* Part Body */
 
        if (szFilePath != NULL)
-               strncpy(pMsgBody->szOrgFilePath, szFilePath, strlen(szFilePath));
+               snprintf(pMsgBody->szOrgFilePath, sizeof(pMsgBody->szOrgFilePath), "%s", szFilePath);
 
-       pMsgBody->offset = _MmsGetDecodeOffset();
+       pMsgBody->offset = __MmsGetDecodeOffset();
        pMsgBody->size   = bodyLength;
 
        if (pMsgBody->offset > totalLength)
@@ -2391,1183 +2320,1114 @@ bool MmsBinaryDecodeEachPart(FILE *pFile, char *szFilePath, MsgType *pMsgType, M
        case MIME_MULTIPART_RELATED:
        case MIME_MULTIPART_ALTERNATIVE:
 
-               MSG_DEBUG("MmsBinaryDecodeEachPart: Decode multipart\n");
-
-               if (MmsBinaryDecodeMultipart(pFile, szFilePath, pMsgType, pMsgBody, totalLength) == false) {
-                       MSG_DEBUG("MmsBinaryDecodeEachPart: MmsBinaryDecodeMultipart is fail.\n");
+               MSG_DEBUG("Multipart");
+               if (__MmsBinaryDecodeMultipart(pFile, szFilePath, pMsgType, pMsgBody, totalLength) == false) {
+                       MSG_DEBUG("MmsBinaryDecodeMultipart is fail");
                        goto __CATCH;
                }
 
-               offset = _MmsGetDecodeOffset();
-               if (offset >= totalLength)
-                       goto __RETURN;
-
-               break;
-
-
-#ifdef __SUPPORT_DRM__
-
-       case MIME_APPLICATION_VND_OMA_DRM_MESSAGE: /* Contains forwardLock OR combined-delivery media part */
-               MSG_DEBUG("MmsBinaryDecodeEachPart: MIME_APPLICATION_VND_OMA_DRM_MESSAGE Part \n");
-
-               if (MmsDrm2GetConvertState() != MMS_DRM2_CONVERT_NOT_FIXED && MmsDrm2GetConvertState() != MMS_DRM2_CONVERT_REQUIRED) {
-
-                       if (MmsBinaryDecodeDRMContent(pFile, szFilePath, pMsgType, pMsgBody, bodyLength, totalLength) == false)
-                               goto __CATCH;
-               } else {
-                       MmsDrm2SetConvertState(MMS_DRM2_CONVERT_REQUIRED);
-
-                       bSuccess = MmsBinaryDecodePartBody(pFile, bodyLength, totalLength);
-                       if (bSuccess == false) {
-                               MSG_DEBUG("MmsBinaryDecodeEachPart: Decode contentBody Fail \n");
-                               goto __CATCH;
-                       }
-               }
-               offset = _MmsGetDecodeOffset();
-               if (offset >= totalLength)
-                       goto __RETURN;
-
-               break;
-
-       case MIME_APPLICATION_VND_OMA_DRM_CONTENT: /* Contains seperate-delivery media part (DCF) */
-
-               MSG_DEBUG("MmsBinaryDecodeEachPart: MIME_APPLICATION_VND_OMA_DRM_CONTENT Part \n");
-
-               if (MmsBinaryDecodeDRMContent(pFile, szFilePath, pMsgType, pMsgBody, bodyLength, totalLength) == false)
-                       goto __CATCH;
-
-               offset = _MmsGetDecodeOffset();
+               offset = __MmsGetDecodeOffset();
                if (offset >= totalLength)
                        goto __RETURN;
 
                break;
-#endif
 
        default:
-               MSG_DEBUG("MmsBinaryDecodeEachPart: Other normal Part \n");
+               MSG_DEBUG("Normal Part");
 
-               bSuccess = MmsBinaryDecodePartBody(pFile, bodyLength, totalLength);
+               bSuccess = __MmsBinaryDecodePartBody(pFile, bodyLength, totalLength);
                if (bSuccess == false) {
-                       MSG_DEBUG("MmsBinaryDecodeEachPart: Decode contentBody Fail \n");
+                       MSG_DEBUG("Decode contentBody Fail");
                        goto __CATCH;
                }
 
-               offset = _MmsGetDecodeOffset();
+               offset = __MmsGetDecodeOffset();
                if (offset >= totalLength)
                        goto __RETURN;
 
                break;
        }
 
+       MSG_END();
        return true;
 
 __RETURN:
-
+       MSG_END();
        return true;
 
 __CATCH:
-
+       MSG_END();
        return false;
 }
 
-#ifdef __SUPPORT_DRM__
-bool __MmsParseDCFInfo(FILE *pFile, MsgDRMInfo *pDrmInfo, int totalLength)
+/* --------------------------------------------------------------------
+ *
+ *     B  I  N  A  R  Y       D  E  C  D  E      U  T  I  L  I  T  Y
+ *
+ * --------------------------------------------------------------------*/
+
+bool __MmsBinaryDecodeGetOneByte(FILE *pFile, UINT8 *pOneByte, int totalLength)
 {
-       UINT8 version = 0;
-       UINT8 contentTypeLen = 0;
-       UINT8 contentURILen = 0;
-       char *szContentType     = NULL;
-       char *szContentURI = NULL;
-
-       if (_MmsBinaryDecodeGetOneByte(pFile, &version, totalLength) == false) {
-               MSG_DEBUG("__MmsParseDCFInfo: [version] GetOneByte fail\n");
-               goto __CATCH;
-       }
+       int length = gMmsDecodeMaxLen - gCurMmsDecodeBuffPos;
 
-       if (_MmsBinaryDecodeGetOneByte(pFile, &contentTypeLen, totalLength) == false) {
-               MSG_DEBUG("__MmsParseDCFInfo: [contentTypeLen] GetOneByte fail\n");
+       if (pFile == NULL || pOneByte == NULL)
+       {
+               MSG_DEBUG("invalid file or buffer");
                goto __CATCH;
        }
 
-       if (_MmsBinaryDecodeGetOneByte(pFile, &contentURILen, totalLength) == false) {
-               MSG_DEBUG("__MmsParseDCFInfo: [contentURILen] GetOneByte fail\n");
-               goto __CATCH;
+       if (length < 1) {
+               if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                          gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+                       MSG_DEBUG("fail to load to buffer");
+                       goto __CATCH;
+               }
        }
 
-       //Get media content-type (mime-type)
-       szContentType = (char *)malloc(contentTypeLen + 1);
-       if (szContentType == NULL)
-               goto __CATCH;
-
-       memset(szContentType, 0, contentTypeLen + 1);
+       *pOneByte = gpCurMmsDecodeBuff[gCurMmsDecodeBuffPos++];
 
-       if (_MmsBinaryDecodeGetBytes(pFile, szContentType, contentTypeLen + 1, totalLength) < 0) {
-               MSG_DEBUG("__MmsParseDCFInfo : contentType is invalid\n");
-               goto __CATCH;
-       }
-       gCurMmsDecodeBuffPos--;
-       pDrmInfo->contentType = (MsgContentType)_MsgGetCode(MSG_TYPE, szContentType);
+       return true;
 
+__CATCH:
+       return false;
+}
 
-       //Get content-ID - 1.remover "cid:",   2.resolve "%hexa",   3.and copy the string
-       szContentURI = (char *)malloc(contentURILen + 1);
-       if (szContentURI == NULL)
-               goto __CATCH;
+/*
+ * @remark: bufLen < gMmsDecodeMaxLen
+ */
+bool __MmsBinaryDecodeGetBytes(FILE *pFile, char *szBuff, int bufLen, int totalLength)
+{
+       int length = gMmsDecodeMaxLen - gCurMmsDecodeBuffPos;
+       int i = 0;
 
-       memset(szContentURI, 0, contentURILen + 1);
 
-       if (_MmsBinaryDecodeGetBytes(pFile, szContentURI, contentURILen + 1, totalLength) < 0) {
-               MSG_DEBUG("__MmsParseDCFInfo : contentType is invalid\n");
+       if (pFile == NULL || szBuff == NULL || bufLen == 0 || bufLen > gMmsDecodeMaxLen)
                goto __CATCH;
-       }
-       gCurMmsDecodeBuffPos--;
-       pDrmInfo->szContentURI = MsgResolveContentURI(szContentURI);
 
+       memset(szBuff, 0, bufLen);
 
-       if (szContentType) {
-               free(szContentType);
-               szContentType = NULL;
+       if (length < bufLen) {
+               if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                          gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+                       MSG_DEBUG("fail to load to buffer");
+                       goto __CATCH;
+               }
        }
 
-       if (szContentURI) {
-               free(szContentURI);
-               szContentURI = NULL;
+       for (i = 0; i < bufLen - 1; i++) {
+               szBuff[i] = gpCurMmsDecodeBuff[gCurMmsDecodeBuffPos++];
        }
-       return true;
 
+       gCurMmsDecodeBuffPos++; //NULL
 
-__CATCH:
-
-       if (szContentType) {
-               free(szContentType);
-               szContentType = NULL;
-       }
+       return true;
 
-       if (szContentURI) {
-               free(szContentURI);
-               szContentURI = NULL;
-       }
+__CATCH:
        return false;
-
 }
 
-
-bool __MmsParseDCFHdr(FILE *pFile, MsgDRMInfo *pDrmInfo, UINT32 headerLen, int totalLength)
+bool __MmsBinaryDecodeGetLongBytes(FILE *pFile, char *szBuff, int bufLen, int totalLength)
 {
-       char *szDCFHdr = NULL;
-       MsgType partType;
-       ULONG nRead = 0;
-       int offset = 0;
-
-       /* add to parse DCF header such as,
-        *  Right-Issuer, Content-Name, and Content-Description.
-        */
+       int iPos = 0;
 
-       szDCFHdr = (char *)malloc(headerLen + 1);
-       if (szDCFHdr == NULL) {
-               MSG_DEBUG("__MmsParseDCFHdr: szDCFHdr alloc fail\n");
+       if (pFile == NULL || szBuff == NULL || bufLen == 0)
                goto __CATCH;
-       }
-       memset(szDCFHdr, 0, headerLen + 1);
-
-       offset = _MmsGetDecodeOffset();
-       if (offset >= totalLength)
-               goto __RETURN;
 
-       if (MsgFseek(pFile, offset, SEEK_SET) < 0)
-               goto __CATCH;
+       memset(szBuff, 0, bufLen);
 
-       if ((nRead = MsgReadFile(szDCFHdr, sizeof(char), headerLen, pFile)) == 0){
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                  gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+               MSG_DEBUG("fail to load to buffer");
                goto __CATCH;
        }
-       szDCFHdr[nRead] = '\0';
-
-       _MsgInitMsgType(&partType);
-       _MsgParsePartHeader(&partType, szDCFHdr, headerLen);
 
-       pDrmInfo->szContentName = partType.drmInfo.szContentName;
-       pDrmInfo->szContentVendor = partType.drmInfo.szContentVendor;
-       pDrmInfo->szContentDescription = partType.drmInfo.szContentDescription;
-       pDrmInfo->szRightIssuer = partType.drmInfo.szRightIssuer;
+       while ((bufLen - iPos) >= gMmsDecodeMaxLen) {
+               if (__MmsBinaryDecodeGetBytes(pFile, szBuff + iPos, gMmsDecodeMaxLen, totalLength) == false) {
+                       MSG_DEBUG("__MmsBinaryDecodeGetBytes fail");
+                       goto __CATCH;
+               }
 
-       if (MmsBinaryDecodeMovePointer(pFile, offset + headerLen, totalLength) == false)
-               goto __CATCH;
+               iPos += gMmsDecodeMaxLen;
+       }
 
-__RETURN:
+       if ((bufLen - iPos) > 0) {
+               if (__MmsBinaryDecodeGetBytes(pFile, szBuff + iPos, (bufLen - iPos), totalLength) == false) {
+                       MSG_DEBUG("__MmsBinaryDecodeGetBytes fail");
+                       goto __CATCH;
+               }
 
-       if (szDCFHdr) {
-               free(szDCFHdr);
-               szDCFHdr = NULL;
+               iPos += (bufLen - iPos);
        }
 
        return true;
 
 __CATCH:
-
-       if (szDCFHdr) {
-               free(szDCFHdr);
-               szDCFHdr = NULL;
-       }
-
        return false;
 }
 
+/**
+ * Decode uintvar to 32bit unsigned integer
+ *
+ * @param      pEncodedData    [in] encoded data
+ * @param      pUintVar                [out] Decode uintvar (32bit unsigned integer)
+ * @return     The length of uintvar (-1, if cannot be converted to a uintvar)
+ *
+ * 0 XXXXXXX -> 0-bit: continue bit & 1~7bit: integer value
+ * - -------
+ */
+static const UINT32 uintvarDecodeTable[] = { 0x00000001, 0x00000080, 0x00004000, 0x00100000, 0x08000000 };
 
-bool MmsBinaryDecodeDRMContent(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, unsigned int bodyLength, int totalLength)
+static int __MmsBinaryDecodeUintvar(FILE *pFile, UINT32 *pUintVar, int totalLength)
 {
-       int offset = 0;
-       char szTempFilePath[MSG_FILEPATH_LEN_MAX] = MSG_DATA_PATH"drm.dcf";
-       char *pRawData = NULL;
-       bool isFileCreated = false;
-
-       MSG_DEBUG("bodyLength: %d\n", bodyLength);
-
-       offset = _MmsGetDecodeOffset();
+       UINT8 count = 0;
+       UINT8 oneByte = 0;
+       UINT32 decodedUintvar = 0;
+       UINT8 iBuff[5] = {0};
+       int length = MSG_MMS_DECODE_BUFFER_MAX - gCurMmsDecodeBuffPos;
 
-       if (offset >= totalLength)
-               goto __RETURN;
 
-       if (szFilePath != NULL)
-               strncpy(pMsgBody->szOrgFilePath, szFilePath, strlen(szFilePath));
-       if (szFilePath != NULL)
-               strncpy(pMsgType->szOrgFilePath, szFilePath, strlen(szFilePath));
+       if (pFile == NULL || pUintVar == NULL)
+               return -1;
 
-       pRawData = (char *)malloc(bodyLength);
-       if (pRawData == NULL) {
-               MSG_DEBUG("pRawData alloc FAIL \n");
-               goto __CATCH;
+       if (length < 5) {
+               if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                          gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+                       MSG_DEBUG("fail to load to buffer");
+                       goto __CATCH;
+               }
        }
 
-       if (MsgFseek(pFile, offset, SEEK_SET) < 0) {
-               MSG_DEBUG("MsgFseek() returns -1 \n");
-               goto __CATCH;
-       }
-       if (MsgReadFile(pRawData, sizeof(char), bodyLength, pFile) != (size_t)bodyLength) {
-               MSG_DEBUG("FmReadFile() returns false \n");
-               goto __CATCH;
-       }
-       if (MsgOpenCreateAndOverwriteFile(szTempFilePath, pRawData, bodyLength) == false) {
-               MSG_DEBUG("MsgOpenCreateAndOverwriteFile() returns false \n");
-               goto __CATCH;
-       }
+       while (true) {
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false)
+                       goto __CATCH;
 
-       isFileCreated = true;
-       MSG_DEBUG("MmsDrm2GetConvertState() [%d]", MmsDrm2GetConvertState());
+               if (oneByte > 0x7f)     {
+                       iBuff[count++] = oneByte;
+               } else {
+                       iBuff[count++] = oneByte;
+                       break;
+               }
 
-       if (pMsgType->type == MIME_APPLICATION_VND_OMA_DRM_MESSAGE && (MmsDrm2GetConvertState() != MMS_DRM2_CONVERT_FINISH)) {
-               MmsDrm2SetConvertState(MMS_DRM2_CONVERT_REQUIRED);
-       } else {
-               if (MsgDRM2GetDRMInfo(szTempFilePath, pMsgType) == false) {
-                       MSG_DEBUG("MsgDRM2GetDRMInfo() returns false \n");
+               if (count > 4) {
+                       MSG_DEBUG("legnth is too long");
                        goto __CATCH;
                }
        }
 
-       remove(szTempFilePath);
-       isFileCreated = false;
-
-       if (MmsBinaryDecodeMovePointer(pFile, offset + bodyLength, totalLength) == false)
-               goto __CATCH;
-
-__RETURN:
+       for (int i = 0; i < count; i++)
+               decodedUintvar += (uintvarDecodeTable[i] * (iBuff[count-(i+1)]&0x7f));
 
-       if (pRawData) {
-               free(pRawData);
-               pRawData = NULL;
-       }
+       *pUintVar = decodedUintvar;
 
-       return true;
+       return count;
 
 __CATCH:
-       if (isFileCreated)
-               remove(szTempFilePath);
-
-       if (pRawData) {
-               free(pRawData);
-               pRawData = NULL;
-       }
-
-       return false;
+       gCurMmsDecodeBuffPos -= count;
+       return -1;
 }
 
-
-bool MmsBinaryDecodeDRMMessage(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, unsigned int fullBodyLength, int totalLength)
+/**
+ * Decode uintvar to 32bit unsigned integer by uintvar length
+ *
+ * @param      pEncodedData [in] uintvar encoded data
+ * @param      length           [in] length of integer value
+ * @return     unsigned integer value
+ */
+static UINT32 __MmsHeaderDecodeIntegerByLength(FILE *pFile, UINT32 length, int totalLength)
 {
-       int offset = 0;
-       char szTempFilePath[MSG_FILEPATH_LEN_MAX] = "/User/Msg/Mms/Temp/drm.dm";
-       char *pRawData = NULL;
-       bool isFileCreated = false;
+       UINT32 i = 0;
+       UINT8 oneByte = 0;
+       char *pData = NULL;
+       union {
+               UINT32  integer;
+               UINT8   seg[4];
+       } returner;
 
-       offset = _MmsGetDecodeOffset();
-       if (offset >= totalLength)
-               goto __RETURN;
+       returner.integer = 0;
 
-       if (szFilePath != NULL)
-               strncpy(pMsgBody->szOrgFilePath, szFilePath, strlen(szFilePath));
-       if (szFilePath != NULL)
-               strncpy(pMsgType->szOrgFilePath, szFilePath, strlen(szFilePath));
+       if (length > 4)
+               length = 4;
 
-       pRawData = (char *)malloc(fullBodyLength);
-       if (pRawData == NULL) {
-               MSG_DEBUG("pRawData alloc FAIL \n");
-               goto __CATCH;
-       }
+       if (length == 1)
+       {
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                       MSG_DEBUG("_MmsBinaryDecodeGetOneByte fail");
+                       return oneByte;
+               }
 
-       if (MsgFseek(pFile, offset,  SEEK_SET) < 0) {
-               MSG_DEBUG("MsgFseek() returns -1 \n");
-               goto __CATCH;
+               if (oneByte > 0x7f) {
+                       return (oneByte & 0x7f);
+               } else {
+                       return oneByte;
+               }
        }
 
-       if (MsgReadFile(pRawData, sizeof(char), fullBodyLength, pFile)!= (size_t)fullBodyLength) {
-               MSG_DEBUG("FmReadFile() returns false \n");
+       if (length == 0)
+               return 0;
+
+       pData = (char *)calloc(1, length + 1);
+       if (pData == NULL) {
+               MSG_DEBUG("pData alloc fail");
                goto __CATCH;
        }
+       memset(pData, 0, length + 1);
 
-       if (MsgOpenCreateAndOverwriteFile(szTempFilePath, pRawData, fullBodyLength) == false) {
-               MSG_DEBUG("MsgOpenCreateAndOverwriteFile() returns false \n");
+       if (__MmsBinaryDecodeGetBytes(pFile, pData, length + 1, totalLength) == false) {
+               MSG_DEBUG("_MmsBinaryDecodeGetOneByte fail");
                goto __CATCH;
        }
-       isFileCreated = true;
 
-       if (strstr(szTempFilePath, ".dm")) {
-               char szConvertedFilePath[MSG_FILEPATH_LEN_MAX] = {0,};
+       gCurMmsDecodeBuffPos--; // - NULL
 
-               if (MsgDrmConvertDmtoDcfType(szTempFilePath, szConvertedFilePath)) {
-                       remove(szTempFilePath);
-                       memset(szTempFilePath, 0, MSG_FILEPATH_LEN_MAX);
-                       strncpy(szTempFilePath, szConvertedFilePath, MSG_FILEPATH_LEN_MAX-1);
-               }
+       for (i= 0; i < length; i++)
+               returner.seg[length - (i+1)] = pData[i];
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
        }
 
-       if (MsgDRM2GetDRMInfo(szTempFilePath, pMsgType) == false) {
-               MSG_DEBUG("MsgDRM2GetDRMInfo() returns false \n");
-               goto __CATCH;
-       }
-
-       remove(szTempFilePath);
-       isFileCreated = false;
-
-       if (MmsBinaryDecodeMovePointer(pFile, offset + fullBodyLength, totalLength) == false)
-               goto __CATCH;
-
-__RETURN:
-
-       if (pRawData) {
-               free(pRawData);
-               pRawData = NULL;
-       }
-       return true;
+       return returner.integer;
 
 __CATCH:
-       if (isFileCreated)
-               remove(szTempFilePath);
-
-       if (pRawData) {
-               free(pRawData);
-               pRawData = NULL;
-       }
-       return false;
-}
-
-static int __MmsDrm2BinaryEncodeUintvarLen(UINT32 integer)
-{
-       UINT32 length   = 0;
 
-       /* Find encoded unitvar length */
-       if (integer  <= MMS_UINTVAR_LENGTH_1) {
-               length = 1;
-       } else {
-               if (integer <= MMS_UINTVAR_LENGTH_2) {
-                       length = 2;
-               } else {
-                       if (integer <= MMS_UINTVAR_LENGTH_3) {
-                               length = 3;
-                       } else {
-                               length = 4;
-                       }
-               }
+       if (pData) {
+               free(pData);
+               pData = NULL;
        }
 
-       return length;
+       return returner.integer;
 }
 
-
-static bool __MmsDrm2BinaryEncodeUintvar(UINT32 integer, int length, char *pszOutput)
+/**
+ * Decode uintvar to 32bit unsigned integer by uintvar length
+ *
+ * @param      pEncodedData    [in]  uintvar encoded data
+ * @param      pInteger                [out] Decode integer value (long/short)
+ * @return     unsigned integer value (-1, if cannot be converted to unsigned integer value)
+ */
+static bool __MmsBinaryDecodeInteger(FILE *pFile, UINT32 *pInteger, int *pIntLen, int totalLength)
 {
-       const char ZERO = 0x00;
-       int i = 2;
-       char szReverse[MSG_STDSTR_LONG] = {0, };
-
+       UINT8 oneByte   = 0;
+       char *pData     = NULL;
        union {
-               UINT32 integer;
-               char bytes[4];
-       } source;
-       source.integer = integer;
-       memset(szReverse, 0, MSG_STDSTR_LONG);
-
-       /* Seperate integer to 4 1 byte integer */
-       szReverse[3] = source.bytes[3] & 0x0f;
-       szReverse[0] = source.bytes[0];
-       szReverse[0] = szReverse[0] & 0x7f;
-
-       while (length >= i) {// initially, i = 2
-               /* Move integer bit to proper position */
-               source.integer = source.integer << 1;
-               source.integer = source.integer >> 8;
-               source.bytes[3] = ZERO;
-
-               /* Retrive 1 encode uintvar */
-               szReverse[i-1] = source.bytes[0];
-               szReverse[i-1] = szReverse[i-1] | 0x80;
-               i++;
-       }
-
-       for (i=0; i < length; i++)
-               pszOutput[i] = szReverse[length - i - 1];
+               UINT32  integer;
+               UINT8   seg[4];
+       } returner;
 
-       return true;
-}
 
+       if (pInteger == NULL)
+               return false;
 
-static int __MmsDrm2GetEntriesValueLength(FILE *pFile, int orgOffset)
-{
-       char szEntries[5] = {0, };
-       UINT8 oneByte   = 0;
-       int j = 0;                      //j is the length of nEntries value
+       returner.integer = 0;
+       *pIntLen                 = 0;
 
-       if (MsgReadFile(szEntries, sizeof(char), 4, pFile) != (size_t)4) {
-               MSG_DEBUG("__MmsDrm2GetEntriesValueLength: FmReadFile() returns false \n");
+       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+               MSG_DEBUG("GetOneByte fail");
                return false;
        }
 
-       while (true) {
-               oneByte = szEntries[j++];
+       if (oneByte < 0x1F)                             /* long integer : WAP-230-WSP-20010118-p, Proposed Version 18 January 2001 (pp.86) */
+       {
+               pData = (char *)calloc(1, oneByte + 1);
+               if (pData == NULL) {
+                       MSG_DEBUG("pData mecalloc fail");
+                       goto __CATCH;
+               }
+               memset(pData, 0, oneByte + 1);
 
-               if (oneByte <= 0x7f)
-                       break;
-       }
+               // Even NULL is copied in the _MmsBinaryDecodeGetBytes
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, oneByte + 1, totalLength) == false) {
+                       MSG_DEBUG("GetBytes fail");
+                       goto __CATCH;
+               }
 
-       //move file pointer to point nEntries
-       if (MsgFseek(pFile, orgOffset, SEEK_SET) < 0) {
-               MSG_DEBUG("__MmsDrm2GetEntriesValueLength: fail to seek file pointer\n");
-               return false;
-       }
+               gCurMmsDecodeBuffPos--; // - NULL
 
-       return j;
-}
+               int             length  = 0;
+               if (oneByte > 4) {
+                       length = 4;
+               } else {
+                       length = oneByte;
+               }
 
+               int             i = 0;
+               for (i = 0; i < length; i++)
+                       returner.seg[length - (i+1)] = pData[i];
 
-static bool __MmsDrm2WriteDataToConvertedFile(FILE *pSrcFile, FILE *pDestinationFile, char *pszMmsLoadTempBuf, int length, int bufLen)
-{
-       int loadLen = 0, totalLoadLen = 0, nRead = 0;
+               *pInteger = returner.integer;
+               *pIntLen  = oneByte + 1;
+       } else if (oneByte >= 0x80)     {
+               /* short integer : WAP-230-WSP-20010118-p, Proposed Version 18 January 2001 (pp.86) */
+               *pInteger = oneByte & 0x7f;
+               *pIntLen  = 1;
+       } else {
+               goto __CATCH;
+       }
 
-       for (int i=0; i<(length/bufLen)+1; i++) {
-               loadLen = (length-totalLoadLen < bufLen) ? length-totalLoadLen : bufLen;
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
 
-               memset(pszMmsLoadTempBuf, 0, MMS_DRM2_CONVERT_BUFFER_MAX + 1);
+       return true;
 
-               if (MsgReadFile(pszMmsLoadTempBuf, sizeof(char), loadLen, pSrcFile) != (size_t)loadLen) {
-                       MSG_DEBUG("__MmsDrm2WriteDataToConvertedFile: FmReadFile() returns false \n");
-                       return false;
-               }
+__CATCH:
 
-               if (MsgWriteFile(pszMmsLoadTempBuf, sizeof(char), loadLen, pDestinationFile) != (size_t)loadLen) {
-                       MSG_DEBUG("__MmsDrm2WriteDataToConvertedFile: File Writing is failed.\n");
-                       return false;
-               }
+       gCurMmsDecodeBuffPos--;
 
-               totalLoadLen += nRead;
+       if (pData) {
+               free(pData);
+               pData = NULL;
        }
 
-       return true;
+       return false;
 }
 
-
-/*************************************************************************
- * description : make new message file converting CD & FL part of original message file to SD type
- * argument : void
- * return value
-    - bool :  result of converting
-**************************************************************************/
-bool MmsDrm2ConvertMsgBody(char *szOriginFilePath)
+/**
+ * Decode uintvar to 32bit unsigned integer by uintvar length
+ *
+ * @return     1  : Success
+ *                     0  : This is not Value Length type data
+ *                     -1 : Requires System error report
+ */
+static int __MmsDecodeValueLength(FILE *pFile, UINT32 *pValueLength, int totalLength)
 {
-       FILE *pFile = NULL;
-       FILE *hConvertedFile = NULL;
-       FILE *hTempFile = NULL;
-       FILE *hFile = NULL;
-       MsgMultipart *pMultipart = NULL;
-       char szTempFilePath[MSG_FILEPATH_LEN_MAX] = MSG_DATA_PATH"Drm_Convert";
-       char szTempFile[MSG_FILEPATH_LEN_MAX] = MSG_DATA_PATH"temp.dm";
-       char *pszMmsLoadTempBuf = NULL;
-       char *pszOrgData = NULL;
        int length = 0;
-       int bufLen = MMS_DRM2_CONVERT_BUFFER_MAX;
-       int curOffset = 0;
+       UINT32 uintvar = 0;
+       UINT8 oneByte = 0;
 
-       MSG_DEBUG("start convert~~~~~~\n");
 
-       pFile = MsgOpenFile(szOriginFilePath, "rb");
-       if (pFile == NULL) {
-               MSG_DEBUG("Open decode temporary file fail\n");
-               goto __CATCH;
-       }
+       /*
+        * value-length = short-length | (Length-quote Length)
+        *                              = 0~30             | 31 + Uintvar-length
+        */
 
-       hConvertedFile = MsgOpenFile(MMS_DECODE_DRM_CONVERTED_TEMP_FILE, "wb+");
-       if (hConvertedFile == NULL) {
-               MSG_DEBUG("Open decode temporary file fail\n");
+       if (pFile == NULL || pValueLength == NULL)
                goto __CATCH;
-       }
 
-       pszMmsLoadTempBuf = (char*)malloc(MMS_DRM2_CONVERT_BUFFER_MAX + 1);
-       if (pszMmsLoadTempBuf == NULL) {
-               MSG_DEBUG("malloc for pszMmsLoadTempBuf failed\n");
-               goto __CATCH;
-       }
-       memset(pszMmsLoadTempBuf, 0, MMS_DRM2_CONVERT_BUFFER_MAX + 1);
+       *pValueLength = 0;
 
-       // MMS Header  copy
-       length = mmsHeader.msgBody.offset;
-       if (__MmsDrm2WriteDataToConvertedFile(pFile, hConvertedFile, pszMmsLoadTempBuf, length, bufLen) == false) {
-               MSG_DEBUG("Write header data fail\n");
+       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+               gCurMmsDecodeBuffPos--;
                goto __CATCH;
        }
 
-       curOffset += length;    //change offset
+       if (0x00 < oneByte && oneByte < 0x1F) {
+               /* short-length */
 
-       // MMS Body copy
-       if (MsgIsMultipart(mmsHeader.msgType.type) == true)
-       {
-               // nEntries copy
-               length = __MmsDrm2GetEntriesValueLength(pFile, curOffset);      // getting nEntries value's length
+               *pValueLength = oneByte;
+               length = 1;
+       } else if (oneByte == 0x1F) {
+               /* Length-quote = 0x1F */
 
-               if (__MmsDrm2WriteDataToConvertedFile(pFile, hConvertedFile, pszMmsLoadTempBuf, length, bufLen) == false) {
-                       MSG_DEBUG("Write nEntries fail\n");
+               length = __MmsBinaryDecodeUintvar(pFile, &uintvar, totalLength);
+               if (length == -1) {
+                       MSG_DEBUG(" __MmsBinaryDecodeUintvar fail..");
                        goto __CATCH;
                }
+               length ++;                                      // + length-quote
+               *pValueLength = uintvar;
+       } else {
+               MSG_DEBUG("not a value length type data");
+               gCurMmsDecodeBuffPos--;
+               return 0;
+       }
 
-               curOffset += length;    //change offset
+       return length;
 
-               // each Multipart entry copy
-               pMultipart = mmsHeader.msgBody.body.pMultipart;
+__CATCH:
+       MSG_DEBUG("getting data fail");
+       return -1;
+}
 
-               while (pMultipart) {
-                       if (pMultipart->type.type == MIME_APPLICATION_VND_OMA_DRM_MESSAGE) {
-                               int orgDataLen = pMultipart->pBody->size;
-                               int nSize = 0;
+/**
+ * Decode uintvar to 32bit unsigned integer by uintvar length
+ *
+ * @return     1  : Success
+ *                     0  : This is not Value Length type data
+ *                     -1 : Requires System error report
+ * @ defference : if there is not length-quote, consider it as short length.
+ */
+static int __MmsDecodeValueLength2(FILE *pFile, UINT32 *pValueLength, int totalLength)
+{
+       int length      = 0;
+       UINT32 uintvar = 0;
+       UINT8 oneByte = 0;
 
-                               MSG_DEBUG("Write MIME_APPLICATION_VND_OMA_DRM_MESSAGE multipart data(orgDataLen = %d).\n", orgDataLen);
 
-                               pszOrgData = (char *)malloc(orgDataLen + 1);
-                               if (pszOrgData == NULL) {
-                                       MSG_DEBUG("pszOrgData is NULL \n");
-                                       goto __CATCH;
-                               }
-                               memset(pszOrgData, 0, orgDataLen + 1);
+       /*
+        * value-length = short-length | (Length-quote Length)
+        *                              = 0~30             | 31 + Uintvar-length
+        */
 
-                               // move file pointer to data
-                               if (MsgFseek(pFile, pMultipart->pBody->offset, SEEK_SET) < 0) {
-                                       MSG_DEBUG("fail to seek file pointer 1\n");
-                                       goto __CATCH;
-                               }
+       if (pFile == NULL || pValueLength == NULL)
+               goto __CATCH;
 
-                               if (MsgReadFile(pszOrgData, sizeof(char), orgDataLen, pFile) != (size_t)orgDataLen) {
-                                       MSG_DEBUG("FmReadFile() returns false for orgData\n");
-                                       goto __CATCH;
-                               }
+       *pValueLength = 0;
 
-                               if((hFile = MsgOpenFile(szTempFile, "wb+")) == NULL) {
-                                       MSG_DEBUG("file open failed [%s]", szTempFile);
-                                       goto __CATCH;
-                               }
+       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+               gCurMmsDecodeBuffPos--;
+               goto __CATCH;
+       }
 
-                               if (MsgWriteFile(pszOrgData, sizeof(char), orgDataLen, hFile) != (size_t)orgDataLen) {
-                                       MSG_DEBUG("File write error");
-                                       goto __CATCH;
-                               }
+       if (0x00 < oneByte && oneByte < 0x1F) {
+               /* short-length */
 
-                               MsgFflush(hFile);
-                               MsgCloseFile(hFile);
+               *pValueLength = oneByte;
+               length = 1;
+       } else if (oneByte == 0x1F) {
+               /* Length-quote = 0x1F */
 
-                               hFile = NULL;
+               length = __MmsBinaryDecodeUintvar(pFile, &uintvar, totalLength);
+               if (length == -1) {
+                       MSG_DEBUG("__MmsBinaryDecodeUintvar fail..");
+                       goto __CATCH;
+               }
+               length ++;                                      // + length-quote
+               *pValueLength = uintvar;
+       } else {
+               MSG_DEBUG("there is not length-quote, consider it as short length.");
+               *pValueLength = oneByte;
+               length = 1;
+       }
 
-                               // --> invoking drm agent api, converting data part start
-                               MSG_DEBUG("start data part convert by callling drm agent api\n");
+       return length;
 
-                               int ret = 0;
-                               ret = MsgDrmConvertDmtoDcfType(szTempFile, szTempFilePath);
-                               MSG_DEBUG("MsgDrmConvertDmtoDcfType returned %s", ret ? "true": "false");
+__CATCH:
+       MSG_DEBUG("getting data fail");
+       return -1;
+}
 
-                               if (MsgGetFileSize(szTempFilePath, &nSize) == false) {
-                                       MSG_DEBUG("MsgGetFileSize error");
-                                       goto __CATCH;
-                               }
-                               MSG_DEBUG("end data part convert(converted data len = %d)\n", nSize);
+/**
+ * Decode QuotedString
+ *
+ * @param      pEncodedData    [in] QuotedString encoded data
+ * @param      szBuff                  [out] Decoded quoted string
+ * @param      bufLen                  [out] Buffer length
+ * @return     length of quoted string
+ */
+static int __MmsBinaryDecodeQuotedString(FILE *pFile, char *szBuff, int bufLen, int totalLength)
+{
+       int iPos = 0;
+       int length = 0;
+       int readBytes = 0;
+       char *pData = NULL;
+       int returnLength = 0;
 
-                               // move file pointer to the head of multipart
-                               if (MsgFseek(pFile, curOffset, SEEK_SET) < 0) {
-                                       MSG_DEBUG("fail to seek file pointer 2\n");
-                                       goto __CATCH;
-                               }
+       /*
+        * Quoted-string = <Octet 34> *TEXT End-of-string
+        * The TEXT encodes an RFC2616 Quoted-string with the enclosing quotation-marks <"> removed
+        */
 
-                               // read headerLen, dataLen
-                               length = pMultipart->type.offset - curOffset;
-                               memset(pszMmsLoadTempBuf, 0, MMS_DRM2_CONVERT_BUFFER_MAX + 1);
-                               if (MsgReadFile(pszMmsLoadTempBuf, sizeof(char), length, pFile) != (size_t)length) {
-                                       MSG_DEBUG("FmReadFile() returns false for headerLen, dataLen\n");
-                                       goto __CATCH;
-                               }
+       if (pFile == NULL || szBuff == NULL || bufLen <= 0)
+               return -1;
 
-                               curOffset += length;
+       memset(szBuff, 0, bufLen);
 
-                               // change dataLen based on converted data
-                               {
-                                       UINT8   oneByte = 0;
-                                       int             j = 0;
-                                       int             encodeLen = 0;
-                                       char    szOutput[MSG_STDSTR_LONG] = {0, };
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                        gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+               MSG_DEBUG("fail to load to buffer");
+               goto __CATCH;
+       }
 
-                                       while (true) {
-                                               oneByte = pszMmsLoadTempBuf[j++];
+       length = strlen(gpCurMmsDecodeBuff) + 1;        // + NULL
 
-                                               if (oneByte <= 0x7f)
-                                                       break;
-                                       }
+       if (length == 0)
+               goto __RETURN;
 
-                                       encodeLen = __MmsDrm2BinaryEncodeUintvarLen((UINT32)nSize);
-                                       __MmsDrm2BinaryEncodeUintvar((UINT32)nSize, encodeLen, szOutput);
+       while (length > gMmsDecodeBufLen) {
+               if (gMmsDecodeBufLen <= 0) {
+                       MSG_DEBUG("gMmsDecodeBufLen <= 0");
+                       MSG_DEBUG("%x %x %x %x %x",
+                                                                               gpCurMmsDecodeBuff[0], gpCurMmsDecodeBuff[1], gpCurMmsDecodeBuff[2],
+                                                                               gpCurMmsDecodeBuff[3], gpCurMmsDecodeBuff[4]);
+                       MSG_DEBUG("%x %x %x %x %x",
+                                                                               gpCurMmsDecodeBuff[5], gpCurMmsDecodeBuff[6], gpCurMmsDecodeBuff[7],
+                                                                               gpCurMmsDecodeBuff[8], gpCurMmsDecodeBuff[9]);
+                       MSG_DEBUG("%x %x %x %x %x",
+                                                                               gpCurMmsDecodeBuff[10], gpCurMmsDecodeBuff[11], gpCurMmsDecodeBuff[12],
+                                                                               gpCurMmsDecodeBuff[13], gpCurMmsDecodeBuff[14]);
+                       MSG_DEBUG("%x %x %x %x %x",
+                                                                               gpCurMmsDecodeBuff[15], gpCurMmsDecodeBuff[16], gpCurMmsDecodeBuff[17],
+                                                                               gpCurMmsDecodeBuff[18], gpCurMmsDecodeBuff[19]);
+                       goto __CATCH;
+               }
 
-                                       strncpy(&(pszMmsLoadTempBuf[j]), szOutput, encodeLen);
-                                       pszMmsLoadTempBuf[j+encodeLen] = '\0';
+               pData = (char *)calloc(1, gMmsDecodeBufLen + 1);
+               if (pData == NULL)
+                       goto __CATCH;
 
-                                       if (MsgWriteFile(pszMmsLoadTempBuf, sizeof(char), length, hConvertedFile) != (size_t)length) {
-                                               MSG_DEBUG("Drm2WriteConvertData: FmWriteFile() returns false for dateLen\n");
-                                               goto __CATCH;
-                                       }
-                               }
-
-
-                               length = pMultipart->pBody->offset - pMultipart->type.offset;
-
-                               if (__MmsDrm2WriteDataToConvertedFile(pFile, hConvertedFile, pszMmsLoadTempBuf, length, bufLen) == false) {
-                                       MSG_DEBUG("Drm2WriteConvertData: Write content type, headers fail\n");
-                                       goto __CATCH;
-                               }
+               memset(pData, 0, gMmsDecodeBufLen + 1);
 
-                               curOffset += length;
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, gMmsDecodeBufLen, totalLength) == false)
+                       goto __CATCH;
 
-                               // write converted data
-                               hTempFile = MsgOpenFile(szTempFilePath, "rb");
-                               if (hTempFile == NULL) {
-                                       MSG_DEBUG("Open decode temporary file fail\n");
-                                       goto __CATCH;
-                               }
+               returnLength += gMmsDecodeBufLen;
 
-                               length = nSize;
+               if ((bufLen - iPos) > 0) {
+                       readBytes = (gMmsDecodeBufLen < (bufLen - iPos)) ? gMmsDecodeBufLen : (bufLen - iPos);
+                       if (iPos == 0 && (pData[0] == MARK)) {
+                               /* MARK: check first time only */
 
-                               if (__MmsDrm2WriteDataToConvertedFile(hTempFile, hConvertedFile, pszMmsLoadTempBuf, length, bufLen) == false) {
-                                       MSG_DEBUG("Write converted data fail\n");
-                                       goto __CATCH;
-                               }
+                               strncpy(szBuff + iPos, (char*)pData + 1, readBytes - 1);
+                               iPos += (readBytes - 1);
+                       } else {
+                               strncpy(szBuff + iPos, (char*)pData, readBytes);
+                               iPos += readBytes;
+                       }
+               }
 
-                               if (hTempFile != NULL) {
-                                       MsgCloseFile(hTempFile);
-                                       hTempFile = NULL;
-                               }
+               if (pData) {
+                       free(pData);
+                       pData = NULL;
+               }
 
-                               curOffset += pMultipart->pBody->size;
+               if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                               gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+                       MSG_DEBUG("fail to load to buffer");
+                       goto __CATCH;
+               }
+               length = strlen(gpCurMmsDecodeBuff) + 1;        // + NULL
+       }       /* while */
 
-                               // move file pointer to the head of multipart
-                               if (MsgFseek(pFile, curOffset, SEEK_SET) < 0) {
-                                       MSG_DEBUG("fail to seek file pointer \n");
-                                       goto __CATCH;
-                               }
-                       } else {        // it doesn't need to convert if it is not CD or FL
-                               MSG_DEBUG("Write normal multipart data\n");
+       if (length > 0) {
+               pData = (char *)calloc(1, length);
+               if (pData == NULL)
+                       goto __CATCH;
 
-                               length = pMultipart->pBody->offset + pMultipart->pBody->size - curOffset;
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, length, totalLength) == false)
+                       goto __CATCH;
 
-                               if (__MmsDrm2WriteDataToConvertedFile(pFile, hConvertedFile, pszMmsLoadTempBuf, length, bufLen) == false) {
-                                       MSG_DEBUG("Write multipart data fail \n");
-                                       goto __CATCH;
-                               }
+               returnLength += length;
 
-                               curOffset += length;
+               if ((bufLen - iPos) > 0) {
+                       /* read until NULL from raw data, and copy only string */
+                       readBytes = (length < (bufLen - iPos)) ? length : (bufLen - iPos);
+                       if (iPos == 0 && (pData[0] == MARK)) {
+                               /* MARK: check first time only */
+                               strncpy(szBuff + iPos, (char*)pData + 1, readBytes - 1);
+                               iPos += (readBytes - 1);
+                       } else {
+                               strncpy(szBuff + iPos, (char*)pData, readBytes - 1);    // + NULL
+                               iPos += readBytes;
                        }
+               }
 
-                       pMultipart = pMultipart->pNext;
+               if (pData) {
+                       free(pData);
+                       pData = NULL;
                }
        }
 
-       MSG_DEBUG("end convert~~~~~~\n");
+       szBuff[bufLen - 1] = '\0';
 
-       if (pFile != NULL) {
-               MsgCloseFile(pFile);
-               pFile = NULL;
-       }
+       return returnLength;
 
-       if (hConvertedFile != NULL) {
-               MsgCloseFile(hConvertedFile);
-               hConvertedFile = NULL;
-       }
+__RETURN:
 
-       if (hTempFile != NULL) {
-               MsgCloseFile(hTempFile);
-               hTempFile = NULL;
-       }
+       return length;
 
-       if (pszMmsLoadTempBuf) {
-               free(pszMmsLoadTempBuf);
-               pszMmsLoadTempBuf = NULL;
-       }
+__CATCH:
 
-       if (pszOrgData) {
-               free(pszOrgData);
-               pszOrgData = NULL;
+       if (pData) {
+               free(pData);
+               pData = NULL;
        }
 
-       if (hFile != NULL) {
-               MsgCloseFile(hFile);
-               hFile = NULL;
-       }
+       return -1;
+}
 
-       remove(szTempFile);
-       remove(szTempFilePath);
+/**
+ * Decode Text
+ *
+ * @param      pEncodedData    [in] QuotedString encoded data
+ * @param      szBuff                  [out] Decoded quoted string
+ * @param      bufLen                  [out] Buffer length
+ * @return     length of decode text string
+ */
+static int __MmsBinaryDecodeText(FILE *pFile, char *szBuff, int bufLen, int totalLength)
+{
+       int length = 0;
+       int readBytes = 0;
+       int iPos = 0;
+       int returnLength = 0;
+       char *pData = NULL;
+       bool bQuote = false;
+       int offset = 0;
 
-       return true;
+       /*
+        * Text-String = [QUOTE]*TEXT end_of_string
+        *                               [QUOTE]*(128~255)\0
+        *                               *(32~126)\0
+        */
 
-__CATCH:
+       if (pFile == NULL || szBuff == NULL || bufLen <= 0)
+               return -1;
 
-       if (pFile != NULL) {
-               MsgCloseFile(pFile);
-               pFile = NULL;
-       }
+       offset = __MmsGetDecodeOffset();
+       if (offset >= totalLength)
+               goto __RETURN;
 
-       if (hConvertedFile != NULL) {
-               MsgCloseFile(hConvertedFile);
-               hConvertedFile = NULL;
-       }
+       memset(szBuff, 0, bufLen);
 
-       if (hTempFile != NULL) {
-               MsgCloseFile(hTempFile);
-               hTempFile = NULL;
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                       gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+               MSG_DEBUG("fail to load to buffer");
+               goto __CATCH;
        }
 
-       if (pszMmsLoadTempBuf) {
-               free(pszMmsLoadTempBuf);
-               pszMmsLoadTempBuf = NULL;
-       }
+       length = strlen(gpCurMmsDecodeBuff) + 1;        // + NULL
 
-       if (pszOrgData) {
-               free(pszOrgData);
-               pszOrgData = NULL;
-       }
+       if (length == 0)
+               goto __RETURN;
 
-       if (hFile != NULL)
-       {
-               MsgCloseFile(hFile);
-               hFile = NULL;
-       }
+       while (length > gMmsDecodeBufLen) {
+               if (gMmsDecodeBufLen <= 0) {
+                       MSG_DEBUG("gMmsDecodeBufLen <= 0");
+                       MSG_DEBUG("%x %x %x %x %x", gpCurMmsDecodeBuff[0], gpCurMmsDecodeBuff[1], gpCurMmsDecodeBuff[2],
+                                                                               gpCurMmsDecodeBuff[3], gpCurMmsDecodeBuff[4]);
+                       MSG_DEBUG("%x %x %x %x %x", gpCurMmsDecodeBuff[5], gpCurMmsDecodeBuff[6], gpCurMmsDecodeBuff[7],
+                                                                               gpCurMmsDecodeBuff[8], gpCurMmsDecodeBuff[9]);
+                       MSG_DEBUG("%x %x %x %x %x", gpCurMmsDecodeBuff[10], gpCurMmsDecodeBuff[11], gpCurMmsDecodeBuff[12],
+                                                                               gpCurMmsDecodeBuff[13], gpCurMmsDecodeBuff[14]);
+                       MSG_DEBUG("%x %x %x %x %x", gpCurMmsDecodeBuff[15], gpCurMmsDecodeBuff[16], gpCurMmsDecodeBuff[17],
+                                                                               gpCurMmsDecodeBuff[18], gpCurMmsDecodeBuff[19]);
+                       goto __CATCH;
+               }
 
-       remove(szTempFile);
-       remove(szTempFilePath);
-       remove(MMS_DECODE_DRM_CONVERTED_TEMP_FILE);     //remove convertin result if it goes to __CATCH
+               pData = (char *)calloc(1, gMmsDecodeBufLen + 1);
+               if (pData == NULL)
+                       goto __CATCH;
 
-       return false;
-}
+               memset(pData, 0, gMmsDecodeBufLen + 1);
 
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, gMmsDecodeBufLen, totalLength) == false)
+                       goto __CATCH;
 
-/*************************************************************************
- * description : Function for decoding a converted file
- * argument : void
- * return value
-    - bool :  result of converting
-**************************************************************************/
-bool MmsDrm2DecodeConvertedMsg(int msgID, char *pszFullPath)
-{
-       FILE *hConvertedFile = NULL;
-       int     nSize = 0;
+               if ((bufLen - iPos) > 0) {
+                       readBytes = (gMmsDecodeBufLen < (bufLen - iPos)) ? gMmsDecodeBufLen : (bufLen - iPos);
+                       if (iPos == 0 && (pData[0] == QUOTE) && (bQuote == false)) {
+                               /* QUOTE: check first time only */
 
-       MSG_DEBUG("MmsDrm2DecodeConvertedMsg: start re-decoding~~~~~~\n");
+                               strncpy(szBuff + iPos, (char*)pData + 1, readBytes - 1);
+                               iPos += (readBytes - 1);
+                               bQuote = true;
+                       } else {
+                               strncpy(szBuff + iPos, (char*)pData, readBytes);
+                               iPos += readBytes;
+                       }
+               }
 
-       // free
-       _MsgFreeDRMInfo(&mmsHeader.msgType.drmInfo);
-       _MsgFreeBody(&mmsHeader.msgBody, mmsHeader.msgType.type);
+               if (pData) {
+                       free(pData);
+                       pData = NULL;
+               }
 
-       _MmsInitHeader();
-       _MmsUnregisterDecodeBuffer();
+               returnLength += gMmsDecodeBufLen;
 
-       // start decoding
-       _MmsRegisterDecodeBuffer(gszMmsLoadBuf1, gszMmsLoadBuf2, MSG_MMS_DECODE_BUFFER_MAX);
+               if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                          gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+                       MSG_DEBUG("fail to load to buffer");
+                       goto __CATCH;
+               }
+               length = strlen(gpCurMmsDecodeBuff) + 1;        // + NULL
+       }       /* while */
 
-       // open converted file
-       if ((hConvertedFile = MsgOpenFile(MMS_DECODE_DRM_CONVERTED_TEMP_FILE, "rb")) == NULL) {
-               MSG_DEBUG("MmsDrm2ReDecodeMsg: opening temporary file failed\n");
-               goto __CATCH;
-       }
+       if (length > 0) {
+               pData = (char *)calloc(1, length);
+               if (pData == NULL)
+                       goto __CATCH;
 
-       if (MsgGetFileSize(MMS_DECODE_DRM_CONVERTED_TEMP_FILE, &nSize) == false) {
-               MSG_DEBUG("MsgGetFileSize: failed\n");
-               goto __CATCH;
-       }
+               memset(pData, 0, length);
 
-       if (!MmsBinaryDecodeMsgHeader(hConvertedFile, nSize)) {
-               MSG_DEBUG("MmsDrm2ReDecodeMsg: decoding header(binary mode) failed\n");
-               goto __CATCH;
-       }
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, length, totalLength) == false)
+                       goto __CATCH;
 
-       if (!MmsBinaryDecodeMsgBody(hConvertedFile, pszFullPath, nSize)) {
-               MSG_DEBUG("MmsDrm2ReDecodeMsg: decoding body failed\n");
-               goto __CATCH;
-       }
+               if ((bufLen - iPos) > 0) {
+                       readBytes = (length < (bufLen - iPos)) ? length : (bufLen - iPos);
+                       if (iPos == 0 && (pData[0] == QUOTE) && (bQuote == false)) {
+                               /* QUOTE: check first time only */
+
+                               strncpy(szBuff + iPos, (char*)pData + 1, readBytes - 1);
+                               iPos += (readBytes - 1);
+                               bQuote = true;
+                       } else {
+                               strncpy(szBuff + iPos, (char*)pData, readBytes - 1);    // + NULL
+                               iPos += readBytes;
+                       }
+               }
 
-       if (hConvertedFile != NULL) {
-               MsgCloseFile(hConvertedFile);
-               hConvertedFile = NULL;
+               if (pData) {
+                       free(pData);
+                       pData = NULL;
+               }
+
+               returnLength += length;         // + NULL
        }
 
-       return true;
+       szBuff[bufLen - 1] = '\0';
 
-__CATCH:
+       return returnLength;
 
-       if (hConvertedFile != NULL) {
-               MsgCloseFile(hConvertedFile);
-               remove(MMS_DECODE_DRM_CONVERTED_TEMP_FILE);
-               hConvertedFile = NULL;
-       }
+__RETURN:
 
-       return false;
-}
+       szBuff[0] = '\0';
+       length = 0;
 
+       __MmsBinaryDecodeMovePointer(pFile, offset, totalLength);
 
-bool MmsDrm2ReadMsgConvertedBody(MSG_MESSAGE_INFO_S *pMsg, bool bSavePartsAsTempFiles, bool bRetrieved, char *retrievedPath)
-{
-       MmsMsg *pMmsMsg;
-       MmsPluginStorage::instance()->getMmsMessage(&pMmsMsg);
-       _MmsUnregisterDecodeBuffer();
-#ifdef __SUPPORT_DRM__
-       _MsgFreeDRMInfo(&pMmsMsg->msgType.drmInfo);
-#endif
-       _MsgFreeBody(&pMmsMsg->msgBody, pMmsMsg->msgType.type);
+       return length;
 
-       if (_MmsReadMsgBody(pMsg->msgId, bSavePartsAsTempFiles, bRetrieved, retrievedPath) == false) {
-               MSG_DEBUG("MmsDrm2ReadMsgConvertedBody: _MmsReadMsgBody with converted file is failed\n");
-               return false;
+__CATCH:
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
        }
 
-       return true;
+       return -1;
 }
 
-#endif
-
-/* --------------------------------------------------------------------
- *
- *     B  I  N  A  R  Y       D  E  C  D  E      U  T  I  L  I  T  Y
- *
- * --------------------------------------------------------------------*/
-
-bool _MmsBinaryDecodeGetOneByte(FILE *pFile, UINT8 *pOneByte, int totalLength)
+static char* __MmsBinaryDecodeText2(FILE *pFile, int totalLength, int *pLength)
 {
-       int length = gMmsDecodeMaxLen - gCurMmsDecodeBuffPos;
+       int length = 0;
+       int curLen = 0;
+       char *pData = NULL;
+       char *szBuff = NULL;
+       char *szTempPtr = NULL;
+       bool bQuote = false;
+       int offset = 0;
 
-       if (pFile == NULL || pOneByte == NULL)
-       {
-               MSG_DEBUG("_MmsBinaryDecodeGetOneByte: invalid file or buffer\n");
+       /*
+        * Text-String = [QUOTE]*TEXT end_of_string
+        *                               [QUOTE]*(128~255)\0
+        *                               *(32~126)\0
+        */
+
+       if (pFile == NULL || pLength == NULL)
                goto __CATCH;
-       }
 
-       if (length < 1) {
-               if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
-                                                                          gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-                       MSG_DEBUG("_MmsBinaryDecodeGetOneByte: fail to load to buffer \n");
-                       goto __CATCH;
-               }
+       *pLength = 0;
+       offset = __MmsGetDecodeOffset();
+       if (offset >= totalLength)
+               goto __RETURN;
+
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                  gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+               MSG_DEBUG("fail to load to buffer");
+               goto __CATCH;
        }
 
-       *pOneByte = gpCurMmsDecodeBuff[gCurMmsDecodeBuffPos++];
+       length = strlen(gpCurMmsDecodeBuff) + 1;
 
-       return true;
+       if (length == 0)
+               goto __CATCH;
 
-__CATCH:
-       return false;
-}
-
-
-/*
- * @remark: bufLen < gMmsDecodeMaxLen
- */
-bool _MmsBinaryDecodeGetBytes(FILE *pFile, char *szBuff, int bufLen, int totalLength)
-{
-       int length = gMmsDecodeMaxLen - gCurMmsDecodeBuffPos;
-       int i = 0;
-
-
-       if (pFile == NULL || szBuff == NULL || bufLen == 0 || bufLen > gMmsDecodeMaxLen)
-               goto __CATCH;
-
-       memset(szBuff, 0, bufLen);
-
-       if (length < bufLen) {
-               if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
-                                                                          gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-                       MSG_DEBUG("_MmsBinaryDecodeGetBytes: fail to load to buffer \n");
+       while (length > gMmsDecodeBufLen) {
+               if (gMmsDecodeBufLen <= 0) {
+                       MSG_DEBUG("gMmsDecodeBufLen <= 0");
+                       MSG_DEBUG("%x %x %x %x %x",
+                                                                               gpCurMmsDecodeBuff[0], gpCurMmsDecodeBuff[1], gpCurMmsDecodeBuff[2],
+                                                                               gpCurMmsDecodeBuff[3], gpCurMmsDecodeBuff[4]);
+                       MSG_DEBUG("%x %x %x %x %x",
+                                                                               gpCurMmsDecodeBuff[5], gpCurMmsDecodeBuff[6], gpCurMmsDecodeBuff[7],
+                                                                               gpCurMmsDecodeBuff[8], gpCurMmsDecodeBuff[9]);
+                       MSG_DEBUG("%x %x %x %x %x",
+                                                                               gpCurMmsDecodeBuff[10], gpCurMmsDecodeBuff[11], gpCurMmsDecodeBuff[12],
+                                                                               gpCurMmsDecodeBuff[13], gpCurMmsDecodeBuff[14]);
+                       MSG_DEBUG("%x %x %x %x %x\n",
+                                                                               gpCurMmsDecodeBuff[15], gpCurMmsDecodeBuff[16], gpCurMmsDecodeBuff[17],
+                                                                               gpCurMmsDecodeBuff[18], gpCurMmsDecodeBuff[19]);
                        goto __CATCH;
                }
-       }
-
-       for (i = 0; i < bufLen - 1; i++)
-               szBuff[i] = gpCurMmsDecodeBuff[gCurMmsDecodeBuffPos++];
-
 
-       gCurMmsDecodeBuffPos++; //NULL
-
-       return true;
+               pData = (char *)calloc(1, gMmsDecodeBufLen + 1);
+               if (pData == NULL)
+                       goto __CATCH;
 
-__CATCH:
-       return false;
-}
+               memset(pData, 0, gMmsDecodeBufLen + 1);
 
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, gMmsDecodeBufLen, totalLength) == false)
+                       goto __CATCH;
 
+               if (szBuff == NULL)     {
+                       szBuff = (char *)calloc(1, gMmsDecodeBufLen + 1);
+               } else {
+                       szTempPtr = (char *)realloc(szBuff, curLen + gMmsDecodeBufLen + 1);
 
-bool _MmsBinaryDecodeGetLongBytes(FILE *pFile, char *szBuff, int bufLen, int totalLength)
-{
-       int iPos = 0;
+                       //NULL pointer check for realloc
+                       if (szTempPtr == NULL) {
+                               goto __CATCH;
+                       } else {
+                               szBuff = szTempPtr;
+                       }
+               }
+               if (szBuff == NULL)
+                       goto __CATCH;
 
-       if (pFile == NULL || szBuff == NULL || bufLen == 0)
-               goto __CATCH;
+               memset(szBuff + curLen, 0, gMmsDecodeBufLen + 1);
 
-       memset(szBuff, 0, bufLen);
+               if (curLen == 0 && (pData[0] == QUOTE) && (bQuote == false)) {
+                       /* QUOTE: check first time only */
 
-       if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
-                                                                  gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-               MSG_DEBUG("_MmsBinaryDecodeGetLongBytes: fail to load to buffer \n");
-               goto __CATCH;
-       }
+                       strncpy(szBuff + curLen, (char*)pData + 1, gMmsDecodeBufLen - 1);
+                       curLen += (gMmsDecodeBufLen - 1);
+                       bQuote = true;
+               } else {
+                       strncpy(szBuff + curLen, (char*)pData, gMmsDecodeBufLen);
+                       curLen += gMmsDecodeBufLen;
+               }
 
-       while ((bufLen - iPos) >= gMmsDecodeMaxLen) {
-               if (_MmsBinaryDecodeGetBytes(pFile, szBuff + iPos, gMmsDecodeMaxLen, totalLength) == false) {
-                       MSG_DEBUG("_MmsBinaryDecodeGetLongBytes: 1. _MmsBinaryDecodeGetBytes fail \n");
-                       goto __CATCH;
+               if (pData) {
+                       free(pData);
+                       pData = NULL;
                }
 
-               iPos += gMmsDecodeMaxLen;
-       }
+               *pLength += gMmsDecodeBufLen;
 
-       if ((bufLen - iPos) > 0) {
-               if (_MmsBinaryDecodeGetBytes(pFile, szBuff + iPos, (bufLen - iPos), totalLength) == false) {
-                       MSG_DEBUG("_MmsBinaryDecodeGetLongBytes: 2. _MmsBinaryDecodeGetBytes fail \n");
+               if (__MsgLoadDataToDecodeBuffer(pFile,
+                                                          &gpCurMmsDecodeBuff,
+                                                          &gCurMmsDecodeBuffPos,
+                                                          &gMmsDecodeCurOffset,
+                                                          gpMmsDecodeBuf1,
+                                                          gpMmsDecodeBuf2,
+                                                          gMmsDecodeMaxLen,
+                                                          &gMmsDecodeBufLen,
+                                                          totalLength) == false)
+               {
+                       MSG_DEBUG("fail to load to buffer");
                        goto __CATCH;
                }
+               length = strlen(gpCurMmsDecodeBuff) + 1;
+       }       /* while */
 
-               iPos += (bufLen - iPos);
-       }
-
-       return true;
-
-__CATCH:
-       return false;
-}
-
-
-/**
- * Decode uintvar to 32bit unsigned integer
- *
- * @param      pEncodedData    [in] encoded data
- * @param      pUintVar                [out] Decode uintvar (32bit unsigned integer)
- * @return     The length of uintvar (-1, if cannot be converted to a uintvar)
- *
- * 0 XXXXXXX -> 0-bit: continue bit & 1~7bit: integer value
- * - -------
- */
-static const UINT32 uintvarDecodeTable[] = { 0x00000001, 0x00000080, 0x00004000, 0x00100000, 0x08000000 };
-
-static int __MmsBinaryDecodeUintvar(FILE *pFile, UINT32 *pUintVar, int totalLength)
-{
-       UINT8 count = 0;
-       UINT8 oneByte = 0;
-       UINT32 decodedUintvar = 0;
-       UINT8 iBuff[5] = {0};
-       int length = MSG_MMS_DECODE_BUFFER_MAX - gCurMmsDecodeBuffPos;
-
-
-       if (pFile == NULL || pUintVar == NULL)
-               return -1;
-
-       if (length < 5) {
-               if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
-                                                                          gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-                       MSG_DEBUG("__MmsBinaryDecodeUintvar: fail to load to buffer \n");
+       if (length > 0) {
+               pData = (char *)calloc(1, length);
+               if (pData == NULL) {
                        goto __CATCH;
                }
-       }
 
-       while (true) {
-               if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false)
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, length, totalLength) == false) {
                        goto __CATCH;
+               }
 
-               if (oneByte > 0x7f)     {
-                       iBuff[count++] = oneByte;
+               if (szBuff == NULL) {
+                       szBuff = (char *)calloc(1, length);
                } else {
-                       iBuff[count++] = oneByte;
-                       break;
+                       szTempPtr = (char *)realloc(szBuff, curLen + length);
+
+                       //NULL pointer check for realloc
+                       if (szTempPtr == NULL)
+                               goto __CATCH;
+                       else
+                               szBuff = szTempPtr;
                }
 
-               if (count > 5) {
-                       MSG_DEBUG("__MmsBinaryDecodeUintvar : legnth is too long\n");
+               if (szBuff == NULL) {
                        goto __CATCH;
                }
-       }
-
-       for (int i = 0; i < count; i++)
-               decodedUintvar += (uintvarDecodeTable[i] * (iBuff[count-(i+1)]&0x7f));
-
-       *pUintVar = decodedUintvar;
-
-       return count;
-
-__CATCH:
-       gCurMmsDecodeBuffPos -= count;
-       return -1;
-}
-
 
-/**
- * Decode uintvar to 32bit unsigned integer by uintvar length
- *
- * @param      pEncodedData [in] uintvar encoded data
- * @param      length           [in] length of integer value
- * @return     unsigned integer value
- */
-static UINT32 __MmsHeaderDecodeIntegerByLength(FILE *pFile, UINT32 length, int totalLength)
-{
-       UINT32 i = 0;
-       UINT8 oneByte = 0;
-       char *pData = NULL;
-       union {
-               UINT32  integer;
-               UINT8   seg[4];
-       } returner;
-
-       returner.integer = 0;
-
-       if (length > 4)
-               length = 4;
+               memset(szBuff + curLen, 0, length);
 
-       if (length == 1)
-       {
-               if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-                       MSG_DEBUG("__MmsHeaderDecodeIntegerByLength: _MmsBinaryDecodeGetOneByte fail\n");
-                       return oneByte;
-               }
+               if (curLen == 0 && (pData[0] == QUOTE)  && (bQuote == false)) {
+                       /* QUOTE: check first time only */
 
-               if (oneByte > 0x7f) {
-                       return (oneByte & 0x7f);
+                       strncpy(szBuff + curLen, (char*)pData + 1, length - 2);
+                       curLen += (length - 1);
+                       bQuote = true;
                } else {
-                       return oneByte;
+                       strncpy(szBuff + curLen, (char*)pData, length - 1);
+                       curLen += length;
                }
-       }
 
-       if (length == 0)
-               return 0;
+               if (pData) {
+                       free(pData);
+                       pData = NULL;
+               }
 
-       pData = (char *)malloc(length + 1);
-       if (pData == NULL) {
-               MSG_DEBUG("__MmsHeaderDecodeIntegerByLength: pData alloc fail\n");
-               goto __CATCH;
+               *pLength += length;             // + NULL
        }
-       memset(pData, 0, length + 1);
 
-       if (_MmsBinaryDecodeGetBytes(pFile, pData, length + 1, totalLength) == false) {
-               MSG_DEBUG("__MmsHeaderDecodeIntegerByLength: _MmsBinaryDecodeGetOneByte fail\n");
-               goto __CATCH;
-       }
+       return szBuff;
 
-       gCurMmsDecodeBuffPos--; // - NULL
+__RETURN:
 
-       for (i= 0; i < length; i++)
-               returner.seg[length - (i+1)] = pData[i];
+       *pLength = 1;
 
-       if (pData) {
-               free(pData);
-               pData = NULL;
-       }
+       __MmsBinaryDecodeMovePointer(pFile, offset, totalLength);
 
-       return returner.integer;
+       return szBuff;
 
 __CATCH:
 
+       if (szBuff) {
+               free(szBuff);
+               szBuff = NULL;
+       }
+
        if (pData) {
                free(pData);
                pData = NULL;
        }
 
-       return returner.integer;
+       return NULL;
 }
 
-
 /**
- * Decode uintvar to 32bit unsigned integer by uintvar length
+ * Decode Charset
  *
- * @param      pEncodedData    [in]  uintvar encoded data
- * @param      pInteger                [out] Decode integer value (long/short)
- * @return     unsigned integer value (-1, if cannot be converted to unsigned integer value)
+ * @param      pEncodedData    [in] QuotedString encoded data
+ * @param      nCharSet                [out] Decoded character set
+ * @return     length of charset value
  */
-static bool __MmsBinaryDecodeInteger(FILE *pFile, UINT32 *pInteger, int *pIntLen, int totalLength)
+static bool __MmsBinaryDecodeCharset(FILE *pFile, UINT32 *nCharSet, int *pCharSetLen, int totalLength)
 {
-       UINT8 oneByte   = 0;
-       char *pData     = NULL;
-       union {
-               UINT32  integer;
-               UINT8   seg[4];
-       } returner;
+       UINT32 integer = 0;
 
+       /*
+        * Charset v1.1 0x01 Well-known-charset
+        *                                       Well-known-charset = Any-charset | Integer-value
+        *                                              ; Both are encoded using values from
+        *                                                Character Set Assignments table in Assigned Numbers
+        *                                       Any-charset = <Octet 128>
+        *                                              ; Equivalent to the special RFC2616 charset value ��*��
+        */
 
-       if (pInteger == NULL)
+       if (pFile == NULL || nCharSet == NULL || pCharSetLen == NULL)
                return false;
 
-       returner.integer = 0;
-       *pIntLen                 = 0;
+       if (__MmsBinaryDecodeInteger(pFile, &integer, pCharSetLen, totalLength) == false) {
+               MSG_DEBUG("__MmsBinaryDecodeInteger fail...");
+               goto __CATCH;
+       }
 
-       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-               MSG_DEBUG("__MmsBinaryDecodeInteger: GetOneByte fail\n");
-               return false;
+       if (integer == 0) {
+               /* AnyCharSet : return MSG_CHARSET_UTF8 */
+               *nCharSet = MSG_CHARSET_UTF8;
+               return true;
        }
 
-       if (oneByte < 0x1F)                             /* long integer : WAP-230-WSP-20010118-p, Proposed Version 18 January 2001 (pp.86) */
-       {
-               pData = (char *)malloc(oneByte + 1);
-               if (pData == NULL) {
-                       MSG_DEBUG("__MmsBinaryDecodeInteger: pData memalloc fail\n");
+       *nCharSet = MmsGetBinaryType(MmsCodeCharSet, (UINT16)integer);
+       MSG_DEBUG("Decoded charset MIBenum = [%d], charset enum = [%d]", integer, *nCharSet);
+       if (*nCharSet == MIME_UNKNOWN) {
+               MSG_DEBUG("MmsGetBinaryType fail..");
+               *nCharSet = MSG_CHARSET_UNKNOWN;
+       }
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+/**
+ * Decode EncodedString
+ *
+ * @param      pEncodedData    [in] QuotedString encoded data
+ * @param      szBuff                  [out] Decoded string buffer
+ * @param      bufLen                  [in]  Decoded buffer length
+ * @return     length of decoded string length
+ */
+static bool __MmsBinaryDecodeEncodedString(FILE *pFile, char *szBuff, int bufLen, int totalLength)
+{
+       UINT32 valueLength = 0;
+       UINT32 charSet = 0;
+       int charSetLen = 0;
+       int nTemp = 0;
+       char *pData = NULL;
+
+       MSG_DEBUG(" decode string..");
+
+       if (pFile == NULL || szBuff == NULL || bufLen <= 0) {
+               MSG_DEBUG("invalid file or buffer");
+               goto __CATCH;
+       }
+
+       /*
+        * Encoded_string_value = Text-string | Value-length Char-set Text-String
+        *                                                Text-string    = [Quote]*TEXT End-of-string
+        *                                                Value-length   = 0 ~ 31
+        */
+
+       memset(szBuff, 0, bufLen);
+
+       switch (__MmsDecodeValueLength(pFile, &valueLength, totalLength)) {
+       case -1:
+               goto __CATCH;
+
+       case 0:
+
+               /* Text-string = [Quote]*TEXT End-of-string */
+
+               if (__MmsBinaryDecodeText(pFile, szBuff, bufLen, totalLength) < 0) {
+                       MSG_DEBUG("__MmsBinaryDecodeText fail.");
                        goto __CATCH;
                }
-               memset(pData, 0, oneByte + 1);
+               break;
 
-               // Even NULL is copied in the _MmsBinaryDecodeGetBytes
-               if (_MmsBinaryDecodeGetBytes(pFile, pData, oneByte + 1, totalLength) == false) {
-                       MSG_DEBUG("__MmsBinaryDecodeInteger: GetBytes fail\n");
-                       goto __CATCH;
+       default:
+
+               /* Value-length Charset Text_string */
+
+               if (__MmsBinaryDecodeCharset(pFile, &charSet, &charSetLen, totalLength) == false) {
+                       MSG_DEBUG(" __MmsBinaryDecodeCharset error");
+                       goto __CATCH;                   /* (valueLength + valueLengthLen) */
                }
 
-               gCurMmsDecodeBuffPos--; // - NULL
+               nTemp = __MmsBinaryDecodeText(pFile, szBuff, bufLen, totalLength);
 
-               int             length  = 0;
-               if (oneByte > 4) {
-                       length = 4;
-               } else {
-                       length = oneByte;
+               if (nTemp < 0) {
+                       /* There can be some error in data - no NULL -> try again with value length */
+
+                       pData = (char *)calloc(1, valueLength - charSetLen);
+                       if (pData == NULL) {
+                               MSG_DEBUG("pData alloc fail.");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeGetLongBytes(pFile, pData, valueLength - charSetLen, totalLength) == false) {
+                               MSG_DEBUG("_MmsBinaryDecodeGetLongBytes fail.");
+                               goto __CATCH;
+                       }
+
+                       strncpy(szBuff, pData, bufLen - 1);
                }
 
-               int             i = 0;
-               for (i = 0; i < length; i++)
-                       returner.seg[length - (i+1)] = pData[i];
+               {//temp brace
 
-               *pInteger = returner.integer;
-               *pIntLen  = oneByte + 1;
-       } else if (oneByte >= 0x80)     {
-               /* short integer : WAP-230-WSP-20010118-p, Proposed Version 18 January 2001 (pp.86) */
-               *pInteger = oneByte & 0x7f;
-               *pIntLen  = 1;
-       } else {
-               goto __CATCH;
+                       nTemp = strlen(szBuff);
+
+                       const char *pToCharSet = "UTF-8";
+
+                       UINT16 charset_code =  MmsGetBinaryValue(MmsCodeCharSet, charSet);
+
+                       const char *pFromCharSet = MmsPluginTextConvertGetCharSet(charset_code);
+                       if (pFromCharSet == NULL || !strcmp(pFromCharSet, pToCharSet)) {
+                               if (pData) {
+                                       free(pData);
+                                       pData = NULL;
+                               }
+                               return true;
+                       }
+
+                       char *pDest = NULL;
+                       int destLen = 0;
+
+                       if (MmsPluginTextConvert(pToCharSet, pFromCharSet, szBuff, nTemp, &pDest, &destLen) == false) {
+                               MSG_DEBUG("MmsPluginTextConvert Fail");
+
+                       } else {
+                               memset(szBuff, 0x00, bufLen);
+                               snprintf(szBuff, destLen+1, "%s", pDest);
+                       }
+
+                       if (pDest) {
+                               free(pDest);
+                               pDest = NULL;
+                       }
+               }
+               break;
        }
 
        if (pData) {
@@ -3579,8 +3439,6 @@ static bool __MmsBinaryDecodeInteger(FILE *pFile, UINT32 *pInteger, int *pIntLen
 
 __CATCH:
 
-       gCurMmsDecodeBuffPos--;
-
        if (pData) {
                free(pData);
                pData = NULL;
@@ -3590,3943 +3448,1796 @@ __CATCH:
 }
 
 
+
 /**
- * Decode uintvar to 32bit unsigned integer by uintvar length
+ * Decode Encoded Addresses
  *
- * @return     1  : Success
- *                     0  : This is not Value Length type data
- *                     -1 : Requires System error report
+ * @param      pEncodedData    [in] QuotedString encoded data
+ * @param      pAddrLength             [out] Decoded address length
+ * @return     Decoded address list
  */
-static int __MmsDecodeValueLength(FILE *pFile, UINT32 *pValueLength, int totalLength)
+MsgHeaderAddress *__MmsDecodeEncodedAddress(FILE *pFile, int totalLength)
 {
-       int length = 0;
-       UINT32 uintvar = 0;
-       UINT8 oneByte = 0;
+       UINT32 valueLength      = 0;
+       UINT32 charSet          = 0;
+       int charSetLen  = 0;
+       int textLength  = 0;
+       char *pAddrStr  = NULL;
+       MsgHeaderAddress *pAddr = NULL;
+
+       MSG_DEBUG("decoding address..");
 
+       if (pFile == NULL) {
+               MSG_DEBUG("invalid file or buffer");
+               goto __CATCH;
+       }
 
        /*
-        * value-length = short-length | (Length-quote Length)
-        *                              = 0~30             | 31 + Uintvar-length
+        * Encoded_string_value = Text-string | Value-length Char-set Text-String
+        *                                                Text-string    = [Quote]*TEXT End-of-string
+        *                                                Value-length   = 0 ~ 31
         */
 
-       if (pFile == NULL || pValueLength == NULL)
+       switch (__MmsDecodeValueLength(pFile, &valueLength, totalLength)) {
+       case -1:
                goto __CATCH;
 
-       *pValueLength = 0;
+       case 0:
 
-       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-               gCurMmsDecodeBuffPos--;
-               goto __CATCH;
-       }
+               /* Text-string = [Quote]*TEXT End-of-string */
 
-       if (0x00 < oneByte && oneByte < 0x1F) {
-               /* short-length */
+               textLength = 0;
+               pAddrStr   = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+               if (pAddrStr == NULL) {
+                       MSG_DEBUG(" __MmsBinaryDecodeText2 fail.");
+                       goto __CATCH;
+               }
+               break;
 
-               *pValueLength = oneByte;
-               length = 1;
-       } else if (oneByte == 0x1F) {
-               /* Length-quote = 0x1F */
+       default:
 
-               length = __MmsBinaryDecodeUintvar(pFile, &uintvar, totalLength);
-               if (length == -1) {
-                       MSG_DEBUG("__MmsDecodeValueLength: __MmsBinaryDecodeUintvar fail..\n");
+               /* Value-length Charset Text_string */
+
+               if (__MmsBinaryDecodeCharset(pFile, &charSet, &charSetLen, totalLength) == false) {
+                       MSG_DEBUG(" __MmsBinaryDecodeCharset error");
                        goto __CATCH;
                }
-               length ++;                                      // + length-quote
-               *pValueLength = uintvar;
-       } else {
-               MSG_DEBUG("__MmsDecodeValueLength: not a value length type data\n");
-               gCurMmsDecodeBuffPos--;
-               return 0;
+
+               textLength = 0;
+               pAddrStr   = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+               if (pAddrStr == NULL) {
+                       /* There can be some error in data - no NULL -> try again with value length */
+
+                       pAddrStr = (char *)calloc(1, valueLength - charSetLen);
+                       if (pAddrStr == NULL) {
+                               MSG_DEBUG("pData alloc fail.");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeGetLongBytes(pFile, pAddrStr, valueLength - charSetLen, totalLength) == false) {
+                               MSG_DEBUG(" _MmsBinaryDecodeGetLongBytes fail.");
+                               goto __CATCH;
+                       }
+               }
+
+               /* fixme: charset transformation */
+
+               break;
        }
 
-       return length;
+       pAddr = (MsgHeaderAddress *)calloc(1, sizeof(MsgHeaderAddress));
+       if (pAddr == NULL)
+               goto __CATCH;
+
+       memset(pAddr, 0, sizeof(MsgHeaderAddress));
+       pAddr->szAddr = pAddrStr;
+
+       return pAddr;
 
 __CATCH:
-       MSG_DEBUG("__MmsDecodeValueLength: getting data fail\n");
-       return -1;
-}
 
+       if (pAddrStr) {
+               free(pAddrStr);
+               pAddrStr = NULL;
+       }
+
+       return NULL;
+}
 
 
 /**
- * Decode uintvar to 32bit unsigned integer by uintvar length
+ * Decode Encoded Pointer String
  *
- * @return     1  : Success
- *                     0  : This is not Value Length type data
- *                     -1 : Requires System error report
- * @ defference : if there is not length-quote, consider it as short length.
+ * @param      pEncodedData    [in] Long integer encoded data
+ * @param      pLongInteger    [out] Decoded long integer
+ * @return     Decoded address list
  */
-static int __MmsDecodeValueLength2(FILE *pFile, UINT32 *pValueLength, int totalLength)
+static bool __MmsDecodeLongInteger(FILE *pFile, UINT32 *pLongInteger, int totalLength)
 {
-       int length      = 0;
-       UINT32 uintvar = 0;
        UINT8 oneByte = 0;
 
-
        /*
-        * value-length = short-length | (Length-quote Length)
-        *                              = 0~30             | 31 + Uintvar-length
+        * Long-integer = Short-length Multi-octet-integer
+        *                                Short-length = 0~30
+        *                                Multi-octet-integer
         */
 
-       if (pFile == NULL || pValueLength == NULL)
-               goto __CATCH;
+       if (pFile == NULL || pLongInteger == NULL)
+               return false;
 
-       *pValueLength = 0;
+       *pLongInteger = 0;
 
-       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
-               gCurMmsDecodeBuffPos--;
+       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false)
                goto __CATCH;
-       }
 
-       if (0x00 < oneByte && oneByte < 0x1F) {
-               /* short-length */
+       if (oneByte > 31)
+               goto __CATCH;
 
-               *pValueLength = oneByte;
-               length = 1;
-       } else if (oneByte == 0x1F) {
-               /* Length-quote = 0x1F */
+       *pLongInteger = __MmsHeaderDecodeIntegerByLength(pFile, oneByte, totalLength);
 
-               length = __MmsBinaryDecodeUintvar(pFile, &uintvar, totalLength);
-               if (length == -1) {
-                       MSG_DEBUG("__MmsDecodeValueLength2: __MmsBinaryDecodeUintvar fail..\n");
-                       goto __CATCH;
-               }
-               length ++;                                      // + length-quote
-               *pValueLength = uintvar;
-       } else {
-               MSG_DEBUG("__MmsDecodeValueLength2: there is not length-quote, consider it as short length.\n");
-               *pValueLength = oneByte;
-               length = 1;
-       }
-
-       return length;
+       return true;
 
 __CATCH:
-       MSG_DEBUG("__MmsDecodeValueLength2: getting data fail\n");
-       return -1;
+       return false;
 }
 
 
-
-/**
- * Decode QuotedString
- *
- * @param      pEncodedData    [in] QuotedString encoded data
- * @param      szBuff                  [out] Decoded quoted string
- * @param      bufLen                  [out] Buffer length
- * @return     length of quoted string
+/*
+ * @param      pEncodedData    [in] filename encoded data
+ * @param      szBuff                  [out] filename output buffer
+ * @param      fullLength              [in] full filename length
+ * @param      bufLen                  [in] buffer length
+ * CAUTION: bufLen - 1
  */
-static int __MmsBinaryDecodeQuotedString(FILE *pFile, char *szBuff, int bufLen, int totalLength)
+static int __MmsDecodeGetFilename(FILE *pFile, char *szBuff, int bufLen, int totalLength)
 {
-       int iPos = 0;
+       char *pUTF8Buff = NULL;
+       char *pLatinBuff = NULL;
+       char *pExt = NULL;
+       char *szSrc = NULL;
+       char *szSrc2 = NULL;
        int length = 0;
-       int readBytes = 0;
-       char *pData = NULL;
-       int returnLength = 0;
-
-       /*
-        * Quoted-string = <Octet 34> *TEXT End-of-string
-        * The TEXT encodes an RFC2616 Quoted-string with the enclosing quotation-marks <"> removed
-        */
-
-       if (pFile == NULL || szBuff == NULL || bufLen <= 0)
-               return -1;
-
-       memset(szBuff, 0, bufLen);
+       int textLength = 0;
 
-       if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
-                                                                        gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-               MSG_DEBUG("__MmsBinaryDecodeQuotedString: 1. fail to load to buffer \n");
-               goto __CATCH;
-       }
+       char *pTmpBuff = NULL;
 
-       length = strlen(gpCurMmsDecodeBuff) + 1;        // + NULL
+       memset (szBuff, 0, bufLen);
 
-       if (length == 0)
-               goto __RETURN;
+       textLength = 0;
+       pLatinBuff  = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
 
-       while (length > gMmsDecodeBufLen) {
-               if (gMmsDecodeBufLen <= 0) {
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: gMmsDecodeBufLen <= 0 \n");
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n",
-                                                                               gpCurMmsDecodeBuff[0], gpCurMmsDecodeBuff[1], gpCurMmsDecodeBuff[2],
-                                                                               gpCurMmsDecodeBuff[3], gpCurMmsDecodeBuff[4]);
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n",
-                                                                               gpCurMmsDecodeBuff[5], gpCurMmsDecodeBuff[6], gpCurMmsDecodeBuff[7],
-                                                                               gpCurMmsDecodeBuff[8], gpCurMmsDecodeBuff[9]);
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n",
-                                                                               gpCurMmsDecodeBuff[10], gpCurMmsDecodeBuff[11], gpCurMmsDecodeBuff[12],
-                                                                               gpCurMmsDecodeBuff[13], gpCurMmsDecodeBuff[14]);
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n",
-                                                                               gpCurMmsDecodeBuff[15], gpCurMmsDecodeBuff[16], gpCurMmsDecodeBuff[17],
-                                                                               gpCurMmsDecodeBuff[18], gpCurMmsDecodeBuff[19]);
-                       goto __CATCH;
+       //remove ""
+       if (pLatinBuff) {
+               szSrc = MsgRemoveQuoteFromFilename(pLatinBuff);
+               if (szSrc) {
+                       strncpy(pLatinBuff, szSrc, textLength);
+                       free(szSrc);
+                       szSrc = NULL;
                }
 
-               pData = (char *)malloc(gMmsDecodeBufLen + 1);
-               if (pData == NULL)
-                       goto __CATCH;
-
-               memset(pData, 0, gMmsDecodeBufLen + 1);
+               szSrc2 = MsgChangeHexString(pLatinBuff);
+               if (szSrc2) {
+                       strncpy(pLatinBuff, szSrc2, textLength);
+                       free(szSrc2);
+                       szSrc2 = NULL;
+               }
 
-               if (_MmsBinaryDecodeGetBytes(pFile, pData, gMmsDecodeBufLen, totalLength) == false)
-                       goto __CATCH;
+               if (MmsIsUtf8String((unsigned char*)pLatinBuff, strlen(pLatinBuff)) == false) {
+                       length = strlen(pLatinBuff);
 
-               returnLength += gMmsDecodeBufLen;
+                       int             utf8BufSize = 0;
+                       utf8BufSize = __MsgGetLatin2UTFCodeSize((unsigned char*)pLatinBuff, length);
+                       if (utf8BufSize < 3)
+                               utf8BufSize = 3;//min value
 
-               if ((bufLen - iPos) > 0) {
-                       readBytes = (gMmsDecodeBufLen < (bufLen - iPos)) ? gMmsDecodeBufLen : (bufLen - iPos);
-                       if (iPos == 0 && (pData[0] == MARK)) {
-                               /* MARK: check first time only */
+                       pUTF8Buff = (char *)calloc(1, utf8BufSize + 1);
+                       if (pUTF8Buff == NULL) {
+                               MSG_DEBUG("pUTF8Buff alloc fail");
+                               goto __CATCH;
+                       }
 
-                               strncpy(szBuff + iPos, (char*)pData + 1, readBytes - 1);
-                               iPos += (readBytes - 1);
-                       } else {
-                               strncpy(szBuff + iPos, (char*)pData, readBytes);
-                               iPos += readBytes;
+                       if (__MsgLatin2UTF ((unsigned char*)pUTF8Buff, utf8BufSize + 1, (unsigned char*)pLatinBuff, length) < 0) {
+                               MSG_DEBUG("MsgLatin2UTF fail");
+                               goto __CATCH;
                        }
+                       free(pLatinBuff);
+                       pLatinBuff = NULL;
+               } else {
+                       pTmpBuff = MsgDecodeText(pLatinBuff);
+                       pUTF8Buff = pTmpBuff;
+                       free (pLatinBuff);
+                       pLatinBuff = NULL;
                }
+       }
 
-               if (pData) {
-                       free(pData);
-                       pData = NULL;
-               }
+       if (pUTF8Buff) {
+               /*
+                * keeping extension
+                * it should be kept extention even if the file name is shorten
+                */
 
-               if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
-                                                                               gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-                       MSG_DEBUG("__MmsBinaryDecodeText: 2. fail to load to buffer \n");
-                       goto __CATCH;
+               length = strlen(pUTF8Buff);
+               if ((pExt = strrchr(pUTF8Buff, '.')) != NULL) {
+                       int nameLength = 0;
+                       nameLength = (length < bufLen) ? (length - strlen(pExt)) : (bufLen - strlen(pExt));
+                       strncpy(szBuff, pUTF8Buff, nameLength);
+                       g_strlcat(szBuff, pExt,(gsize)bufLen);
+
+               } else {
+                       strncpy(szBuff, pUTF8Buff, bufLen - 1);
                }
-               length = strlen(gpCurMmsDecodeBuff) + 1;        // + NULL
-       }       /* while */
 
-       if (length > 0) {
-               pData = (char *)malloc(length);
-               if (pData == NULL)
-                       goto __CATCH;
+               free(pUTF8Buff);
+               pUTF8Buff = NULL;
 
-               if (_MmsBinaryDecodeGetBytes(pFile, pData, length, totalLength) == false)
-                       goto __CATCH;
+               return textLength;
+       }
 
-               returnLength += length;
+__CATCH:
 
-               if ((bufLen - iPos) > 0) {
-                       /* read until NULL from raw data, and copy only string */
-                       readBytes = (length < (bufLen - iPos)) ? length : (bufLen - iPos);
-                       if (iPos == 0 && (pData[0] == MARK)) {
-                               /* MARK: check first time only */
-                               strncpy(szBuff + iPos, (char*)pData + 1, readBytes - 1);
-                               iPos += (readBytes - 1);
-                       } else {
-                               strncpy(szBuff + iPos, (char*)pData, readBytes - 1);    // + NULL
-                               iPos += readBytes;
-                       }
-               }
+       if (pLatinBuff) {
+               free(pLatinBuff);
+               pLatinBuff = NULL;
+       }
 
-               if (pData) {
-                       free(pData);
-                       pData = NULL;
-               }
+       if (pUTF8Buff) {
+               free(pUTF8Buff);
+               pUTF8Buff = NULL;
        }
 
-       szBuff[bufLen - 1] = '\0';
+       return -1;
+}
 
-       return returnLength;
+/* ==========================================================
 
-__RETURN:
+          M  M  S        D  E  C  O  D  I  N  G
 
-       if (pData) {
-               free(pData);
-               pData = NULL;
-       }
+   ==========================================================*/
 
-       return length;
+//  to get message body this function should be modified from message raw file.
+bool MmsReadMsgBody(msg_message_id_t msgID, bool bSavePartsAsTempFiles, bool bRetrieved, char *retrievedPath)
+{
+       FILE *pFile     = NULL;
+       MmsMsg *pMsg = NULL;
+       MsgMultipart *pMultipart = NULL;
+       int nSize = 0;
+       char szFullPath[MSG_FILEPATH_LEN_MAX] = {0, };
+       char szTempMediaDir[MSG_FILEPATH_LEN_MAX] = {0, };
 
-__CATCH:
+       MSG_BEGIN();
 
-       if (pData) {
-               free(pData);
-               pData = NULL;
+       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+       memset(pMsg, 0, sizeof(MmsMsg));
+
+       MmsInitHeader();
+
+       if (bRetrieved && (retrievedPath != NULL)) {
+               strncpy(szFullPath, retrievedPath, (strlen(retrievedPath) > MSG_FILEPATH_LEN_MAX ? MSG_FILEPATH_LEN_MAX:strlen(retrievedPath)));
+       } else {
+               MmsPluginStorage::instance()->getMmsRawFilePath(msgID, szFullPath, sizeof(szFullPath));
        }
 
-       return -1;
-}
+       pMsg->msgID = msgID;
 
+       /*      read from MMS raw file  */
+       strncpy(pMsg->szFileName, szFullPath + strlen(MSG_DATA_PATH), strlen(szFullPath + strlen(MSG_DATA_PATH)));
 
-/**
- * Decode Text
- *
- * @param      pEncodedData    [in] QuotedString encoded data
- * @param      szBuff                  [out] Decoded quoted string
- * @param      bufLen                  [out] Buffer length
- * @return     length of decode text string
- */
-static int __MmsBinaryDecodeText(FILE *pFile, char *szBuff, int bufLen, int totalLength)
-{
-       int length = 0;
-       int readBytes = 0;
-       int iPos = 0;
-       int returnLength = 0;
-       char *pData = NULL;
-       bool bQuote = false;
-       int offset = 0;
+       MSG_SEC_DEBUG("msg_id = [%d]", msgID);
+       MSG_SEC_DEBUG("raw file path = [%s]", szFullPath);
 
-       /*
-        * Text-String = [QUOTE]*TEXT end_of_string
-        *                               [QUOTE]*(128~255)\0
-        *                               *(32~126)\0
-        */
+       if (MsgGetFileSize(szFullPath, &nSize) == false) {
+               MSG_FATAL("Fail MsgGetFileSize");
+               goto __CATCH;
+       }
 
-       if (pFile == NULL || szBuff == NULL || bufLen <= 0)
-               return -1;
+       pFile = MsgOpenFile(szFullPath, "rb");
+       if (pFile == NULL) {
+               MSG_SEC_DEBUG("Fail MsgOpenFile [%s]", szFullPath);
+               goto __CATCH;
+       }
 
-       offset = _MmsGetDecodeOffset();
-       if (offset >= totalLength)
-               goto __RETURN;
+       MmsRegisterDecodeBuffer();
 
-       memset(szBuff, 0, bufLen);
+       if (MmsBinaryDecodeMsgHeader(pFile, nSize) == false) {
+               MSG_FATAL("Fail to MmsBinaryDecodeMsgHeader");
+               goto __CATCH;
+       }
 
-       if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
-                                                                       gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-               MSG_DEBUG("__MmsBinaryDecodeText: 1. fail to load to buffer \n");
+       if (MmsBinaryDecodeMsgBody(pFile, szFullPath, nSize) == false) {
+               MSG_FATAL("Fail to MmsBinaryDecodeMsgBody");
                goto __CATCH;
        }
 
-       length = strlen(gpCurMmsDecodeBuff) + 1;        // + NULL
+       /* Set mmsHeader.msgType & msgBody to pMsg ----------- */
 
-       if (length == 0)
-               goto __RETURN;
+       memcpy(&(pMsg->msgType), &(mmsHeader.msgType), sizeof(MsgType));
+       memcpy(&(pMsg->msgBody), &(mmsHeader.msgBody), sizeof(MsgBody));
 
-       while (length > gMmsDecodeBufLen) {
-               if (gMmsDecodeBufLen <= 0) {
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: gMmsDecodeBufLen <= 0 \n");
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n", gpCurMmsDecodeBuff[0], gpCurMmsDecodeBuff[1], gpCurMmsDecodeBuff[2],
-                                                                               gpCurMmsDecodeBuff[3], gpCurMmsDecodeBuff[4]);
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n", gpCurMmsDecodeBuff[5], gpCurMmsDecodeBuff[6], gpCurMmsDecodeBuff[7],
-                                                                               gpCurMmsDecodeBuff[8], gpCurMmsDecodeBuff[9]);
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n", gpCurMmsDecodeBuff[10], gpCurMmsDecodeBuff[11], gpCurMmsDecodeBuff[12],
-                                                                               gpCurMmsDecodeBuff[13], gpCurMmsDecodeBuff[14]);
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n", gpCurMmsDecodeBuff[15], gpCurMmsDecodeBuff[16], gpCurMmsDecodeBuff[17],
-                                                                               gpCurMmsDecodeBuff[18], gpCurMmsDecodeBuff[19]);
-                       goto __CATCH;
-               }
+{//attribute convert mmsHeader -> mmsAttribute
 
-               pData = (char *)malloc(gMmsDecodeBufLen + 1);
-               if (pData == NULL)
-                       goto __CATCH;
+       pMsg->mmsAttrib.contentType = (MimeType)mmsHeader.msgType.type;
 
-               memset(pData, 0, gMmsDecodeBufLen + 1);
+       pMsg->mmsAttrib.date = mmsHeader.date;
 
-               if (_MmsBinaryDecodeGetBytes(pFile, pData, gMmsDecodeBufLen, totalLength) == false)
-                       goto __CATCH;
+       if (mmsHeader.deliveryReport == MMS_REPORT_YES) {
+               pMsg->mmsAttrib.bAskDeliveryReport = true;
+       }
 
-               if ((bufLen - iPos) > 0) {
-                       readBytes = (gMmsDecodeBufLen < (bufLen - iPos)) ? gMmsDecodeBufLen : (bufLen - iPos);
-                       if (iPos == 0 && (pData[0] == QUOTE) && (bQuote == false)) {
-                               /* QUOTE: check first time only */
+       memcpy(&pMsg->mmsAttrib.deliveryTime, &mmsHeader.deliveryTime, sizeof(MmsTimeStruct));
 
-                               strncpy(szBuff + iPos, (char*)pData + 1, readBytes - 1);
-                               iPos += (readBytes - 1);
-                               bQuote = true;
-                       } else {
-                               strncpy(szBuff + iPos, (char*)pData, readBytes);
-                               iPos += readBytes;
-                       }
-               }
-
-               if (pData) {
-                       free(pData);
-                       pData = NULL;
-               }
-
-               returnLength += gMmsDecodeBufLen;
-
-               if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
-                                                                          gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-                       MSG_DEBUG("__MmsBinaryDecodeText: 2. fail to load to buffer \n");
-                       goto __CATCH;
-               }
-               length = strlen(gpCurMmsDecodeBuff) + 1;        // + NULL
-       }       /* while */
-
-       if (length > 0) {
-               pData = (char *)malloc(length);
-               if (pData == NULL)
-                       goto __CATCH;
-
-               memset(pData, 0, length);
-
-               if (_MmsBinaryDecodeGetBytes(pFile, pData, length, totalLength) == false)
-                       goto __CATCH;
-
-               if ((bufLen - iPos) > 0) {
-                       readBytes = (length < (bufLen - iPos)) ? length : (bufLen - iPos);
-                       if (iPos == 0 && (pData[0] == QUOTE) && (bQuote == false)) {
-                               /* QUOTE: check first time only */
+       memcpy(&pMsg->mmsAttrib.expiryTime, &mmsHeader.expiryTime, sizeof(MmsTimeStruct));
 
-                               strncpy(szBuff + iPos, (char*)pData + 1, readBytes - 1);
-                               iPos += (readBytes - 1);
-                               bQuote = true;
-                       } else {
-                               strncpy(szBuff + iPos, (char*)pData, readBytes - 1);    // + NULL
-                               iPos += readBytes;
-                       }
-               }
+       pMsg->mmsAttrib.msgClass = mmsHeader.msgClass;
 
-               if (pData) {
-                       free(pData);
-                       pData = NULL;
-               }
+       snprintf(pMsg->szMsgID, sizeof(pMsg->szMsgID), "%s", mmsHeader.szMsgID);
 
-               returnLength += length;         // + NULL
-       }
+       pMsg->mmsAttrib.msgType = mmsHeader.type;
 
-       szBuff[bufLen - 1] = '\0';
+       pMsg->mmsAttrib.version = mmsHeader.version;
 
-       return returnLength;
+       pMsg->mmsAttrib.msgSize = mmsHeader.msgSize;
 
-__RETURN:
+       pMsg->mmsAttrib.priority = mmsHeader.priority;
 
-       if (pData) {
-               free(pData);
-               pData = NULL;
+       if (mmsHeader.readReply == MMS_REPORT_YES) {
+               pMsg->mmsAttrib.bAskReadReply = true;
        }
 
-       szBuff[0] = '\0';
-       length = 0;
-
-       MmsBinaryDecodeMovePointer(pFile, offset, totalLength);
-
-       return length;
+       snprintf(pMsg->mmsAttrib.szSubject, sizeof(pMsg->mmsAttrib.szSubject), "%s", mmsHeader.szSubject);
 
-__CATCH:
+       snprintf(pMsg->szTrID, sizeof(pMsg->szTrID), "%s", mmsHeader.szTrID);
 
-       if (pData) {
-               free(pData);
-               pData = NULL;
-       }
+       pMsg->mmsAttrib.retrieveStatus = mmsHeader.retrieveStatus;
 
-       return -1;
+       //FIXME:: mmsHeader will release after delete global mmsHeader
+       //memset(&(mmsHeader.msgBody), 0x00, sizeof(MsgBody));//After copy to MmsMsg
 }
+       if (pMsg->msgBody.pPresentationBody) {
+               if(MsgFseek(pFile, pMsg->msgBody.pPresentationBody->offset, SEEK_SET) < 0)
+                       goto __CATCH;
 
+               pMsg->msgBody.pPresentationBody->body.pText = (char *)calloc(1, pMsg->msgBody.pPresentationBody->size + 1);
+               if (pMsg->msgBody.pPresentationBody->body.pText == NULL)
+                       goto __CATCH;
 
-static char* __MmsBinaryDecodeText2(FILE *pFile, int totalLength, int *pLength)
-{
-       int length = 0;
-       int curLen = 0;
-       char *pData = NULL;
-       char *szBuff = NULL;
-       char *szTempPtr = NULL;
-       bool bQuote = false;
-       int offset = 0;
-
-       /*
-        * Text-String = [QUOTE]*TEXT end_of_string
-        *                               [QUOTE]*(128~255)\0
-        *                               *(32~126)\0
-        */
-
-       if (pFile == NULL || pLength == NULL)
-               goto __CATCH;
+               memset(pMsg->msgBody.pPresentationBody->body.pText, 0, pMsg->msgBody.pPresentationBody->size + 1);
 
-       *pLength = 0;
-       offset = _MmsGetDecodeOffset();
-       if (offset >= totalLength)
-               goto __RETURN;
+               ULONG nRead = 0;
+               nRead = MsgReadFile(pMsg->msgBody.pPresentationBody->body.pText, sizeof(char), pMsg->msgBody.pPresentationBody->size, pFile);
+               if (nRead == 0)
+                       goto __CATCH;
 
-       if (MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
-                                                                  gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
-               MSG_DEBUG("__MmsBinaryDecodeTextLen: 1. fail to load to buffer \n");
-               goto __CATCH;
        }
 
-       length = strlen(gpCurMmsDecodeBuff) + 1;
-
-       if (length == 0)
-               goto __CATCH;
+       MsgCloseFile(pFile);
+       pFile = NULL;
+       /* nPartCount */
+       pMsg->nPartCount = 0;
 
-       while (length > gMmsDecodeBufLen) {
-               if (gMmsDecodeBufLen <= 0) {
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: gMmsDecodeBufLen <= 0 \n");
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n",
-                                                                               gpCurMmsDecodeBuff[0], gpCurMmsDecodeBuff[1], gpCurMmsDecodeBuff[2],
-                                                                               gpCurMmsDecodeBuff[3], gpCurMmsDecodeBuff[4]);
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n",
-                                                                               gpCurMmsDecodeBuff[5], gpCurMmsDecodeBuff[6], gpCurMmsDecodeBuff[7],
-                                                                               gpCurMmsDecodeBuff[8], gpCurMmsDecodeBuff[9]);
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n",
-                                                                               gpCurMmsDecodeBuff[10], gpCurMmsDecodeBuff[11], gpCurMmsDecodeBuff[12],
-                                                                               gpCurMmsDecodeBuff[13], gpCurMmsDecodeBuff[14]);
-                       MSG_DEBUG("__MmsBinaryDecodeQuotedString: %x %x %x %x %x\n",
-                                                                               gpCurMmsDecodeBuff[15], gpCurMmsDecodeBuff[16], gpCurMmsDecodeBuff[17],
-                                                                               gpCurMmsDecodeBuff[18], gpCurMmsDecodeBuff[19]);
-                       goto __CATCH;
+       if (MsgIsMultipart(mmsHeader.msgType.type) == true) {
+               pMultipart = pMsg->msgBody.body.pMultipart;
+               while (pMultipart) {
+                       pMsg->nPartCount++;
+                       pMultipart = pMultipart->pNext;
                }
+       } else {
+               if (pMsg->msgBody.size > 0)
+                       pMsg->nPartCount++;
+       }
 
-               pData = (char *)malloc(gMmsDecodeBufLen + 1);
-               if (pData == NULL)
-                       goto __CATCH;
-
-               memset(pData, 0, gMmsDecodeBufLen + 1);
-
-               if (_MmsBinaryDecodeGetBytes(pFile, pData, gMmsDecodeBufLen, totalLength) == false)
-                       goto __CATCH;
+       /*      make temporary  */
+       snprintf(szTempMediaDir, MSG_FILEPATH_LEN_MAX, "%s%s.dir", MSG_DATA_PATH, pMsg->szFileName);
 
-               if (szBuff == NULL)     {
-                       szBuff = (char *)malloc(gMmsDecodeBufLen + 1);
-               } else {
-                       szTempPtr = (char *)realloc(szBuff, curLen + gMmsDecodeBufLen + 1);
+       if (MsgIsMultipart(pMsg->msgType.type) == true) {
+               int partIndex = 0;
+               pMultipart = pMsg->msgBody.body.pMultipart;
 
-                       //NULL pointer check for realloc
-                       if (szTempPtr == NULL) {
-                               goto __CATCH;
+               if (bSavePartsAsTempFiles) {
+                       if (mkdir(szTempMediaDir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
+                               if (errno == EEXIST) {
+                                       MSG_SEC_DEBUG("exist dir : [%s]", szTempMediaDir);
+                               } else {
+                                       MSG_SEC_DEBUG("Fail to Create Dir [%s]", szTempMediaDir);
+                                       goto __CATCH;
+                               }
                        } else {
-                               szBuff = szTempPtr;
+                               MSG_SEC_DEBUG("make dir : [%s]", szTempMediaDir);
                        }
                }
-               if (szBuff == NULL)
-                       goto __CATCH;
-
-               memset(szBuff + curLen, 0, gMmsDecodeBufLen + 1);
-
-               if (curLen == 0 && (pData[0] == QUOTE) && (bQuote == false)) {
-                       /* QUOTE: check first time only */
 
-                       strncpy(szBuff + curLen, (char*)pData + 1, gMmsDecodeBufLen - 1);
-                       curLen += (gMmsDecodeBufLen - 1);
-                       bQuote = true;
-               } else {
-                       strncpy(szBuff + curLen, (char*)pData, gMmsDecodeBufLen);
-                       curLen += gMmsDecodeBufLen;
+               if (pMsg->msgBody.pPresentationBody) {
+                       if (__MmsMultipartSaveAsTempFile(&pMsg->msgBody.presentationType, pMsg->msgBody.pPresentationBody,
+                                                                                               (char*)MSG_DATA_PATH, pMsg->szFileName, 0, bSavePartsAsTempFiles) == false)
+                               goto __CATCH;
                }
 
-               if (pData) {
-                       free(pData);
-                       pData = NULL;
-               }
+               while (pMultipart) {
 
-               *pLength += gMmsDecodeBufLen;
+                       if (__MmsMultipartSaveAsTempFile(&pMultipart->type, pMultipart->pBody,
+                                                                                       (char*)MSG_DATA_PATH, pMsg->szFileName, partIndex, bSavePartsAsTempFiles) == false)
+                               goto __CATCH;
 
-               if (MsgLoadDataToDecodeBuffer(pFile,
-                                                          &gpCurMmsDecodeBuff,
-                                                          &gCurMmsDecodeBuffPos,
-                                                          &gMmsDecodeCurOffset,
-                                                          gpMmsDecodeBuf1,
-                                                          gpMmsDecodeBuf2,
-                                                          gMmsDecodeMaxLen,
-                                                          &gMmsDecodeBufLen,
-                                                          totalLength) == false)
-               {
-                       MSG_DEBUG("__MmsBinaryDecodeText: 2. fail to load to buffer \n");
-                       goto __CATCH;
-               }
-               length = strlen(gpCurMmsDecodeBuff) + 1;
-       }       /* while */
+                       MmsPrintMulitpart(pMultipart, partIndex);
 
-       if (length > 0) {
-               pData = (char *)malloc(length);
-               if (pData == NULL) {
-                       goto __CATCH;
+                       pMultipart = pMultipart->pNext;
+                       partIndex ++;
                }
 
-               if (_MmsBinaryDecodeGetBytes(pFile, pData, length, totalLength) == false) {
-                       goto __CATCH;
-               }
+       } else { //single part
+               if (pMsg->nPartCount > 0) {
 
-               if (szBuff == NULL) {
-                       szBuff = (char *)malloc(length);
-               } else {
-                       szTempPtr = (char *)realloc(szBuff, curLen + length);
+                       if (bSavePartsAsTempFiles) {
+                               if (mkdir(szTempMediaDir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
+                                       if (errno == EEXIST) {
+                                               MSG_DEBUG("exist dir : [%s]", szTempMediaDir);
+                                       } else {
+                                               MSG_DEBUG("Fail to Create Dir [%s]", szTempMediaDir);
+                                               goto __CATCH;
+                                       }
+                               } else {
+                                       MSG_DEBUG("make dir : [%s]", szTempMediaDir);
+                               }
+                       }
 
-                       //NULL pointer check for realloc
-                       if (szTempPtr == NULL)
+                       if (__MmsMultipartSaveAsTempFile(&pMsg->msgType, &pMsg->msgBody,
+                                                                                       (char*)MSG_DATA_PATH, pMsg->szFileName, 0, bSavePartsAsTempFiles) == false)
                                goto __CATCH;
-                       else
-                               szBuff = szTempPtr;
-               }
-
-               if (szBuff == NULL) {
-                       goto __CATCH;
                }
+       }
+       MSG_DEBUG("### Success ###");
+       MSG_END();
+       return true;
 
-               memset(szBuff + curLen, 0, length);
-
-               if (curLen == 0 && (pData[0] == QUOTE)  && (bQuote == false)) {
-                       /* QUOTE: check first time only */
-
-                       strncpy(szBuff + curLen, (char*)pData + 1, length - 2);
-                       curLen += (length - 1);
-                       bQuote = true;
-               } else {
-                       strncpy(szBuff + curLen, (char*)pData, length - 1);
-                       curLen += length;
-               }
+__CATCH:
 
-               if (pData) {
-                       free(pData);
-                       pData = NULL;
-               }
+       MmsInitHeader();
+       MmsUnregisterDecodeBuffer();
 
-               *pLength += length;             // + NULL
+       if (pFile != NULL) {
+               MsgCloseFile(pFile);
+               pFile = NULL;
        }
 
-       return szBuff;
 
-__RETURN:
-       if (pData) {
-               free(pData);
-               pData = NULL;
-       }
+       MmsReleaseMsgDRMInfo(&pMsg->msgType.drmInfo);
 
-       *pLength = 1;
+       MmsReleaseMsgBody(&pMsg->msgBody, pMsg->msgType.type);
 
-       MmsBinaryDecodeMovePointer(pFile, offset, totalLength);
+       MSG_DEBUG("### Fail ###");
+       MSG_END();
+       return false;
+}
 
-       return szBuff;
+static bool __MsgFreeHeaderAddress(MsgHeaderAddress *pAddr)
+{
+       MsgHeaderAddress *pTempAddr = NULL;
 
-__CATCH:
+       while (pAddr != NULL) {
+               pTempAddr = pAddr;
+               pAddr = pAddr->pNext;
 
-       if (szBuff) {
-               free(szBuff);
-               szBuff = NULL;
-       }
+               if (pTempAddr->szAddr) {
+                       free(pTempAddr->szAddr);
+                       pTempAddr->szAddr = NULL;
+               }
 
-       if (pData) {
-               free(pData);
-               pData = NULL;
+               free(pTempAddr);
+               pTempAddr = NULL;
        }
 
-       return NULL;
+       return true;
 }
 
-
-/**
- * Decode Charset
- *
- * @param      pEncodedData    [in] QuotedString encoded data
- * @param      nCharSet                [out] Decoded character set
- * @return     length of charset value
- */
-static bool __MmsBinaryDecodeCharset(FILE *pFile, UINT32 *nCharSet, int *pCharSetLen, int totalLength)
+static bool __MsgCheckFileNameHasInvalidChar(char *szName)
 {
-       UINT32 integer = 0;
-
-       /*
-        * Charset v1.1 0x01 Well-known-charset
-        *                                       Well-known-charset = Any-charset | Integer-value
-        *                                              ; Both are encoded using values from
-        *                                                Character Set Assignments table in Assigned Numbers
-        *                                       Any-charset = <Octet 128>
-        *                                              ; Equivalent to the special RFC2616 charset value ¡°*¡±
-        */
+       int     strLen = 0;
+       int i = 0;
 
-       if (pFile == NULL || nCharSet == NULL || pCharSetLen == NULL)
-               return false;
+       strLen = strlen(szName);
 
-       if (__MmsBinaryDecodeInteger(pFile, &integer, pCharSetLen, totalLength) == false) {
-               MSG_DEBUG("__MmsBinaryDecodeCharset : __MmsBinaryDecodeInteger fail...\n");
-               goto __CATCH;
+       for (i=0; i<strLen; i++) {
+               if (__MsgIsInvalidFileNameChar(szName[i]))
+                       return true;
        }
 
-       if (integer == 0) {
-               /* AnyCharSet : return MSG_CHARSET_UTF8 */
-               *nCharSet = MSG_CHARSET_UTF8;
-               return true;
-       }
+       return false;
+}
 
-       *nCharSet = _MmsGetBinaryType(MmsCodeCharSet, (UINT16)integer);
+static bool __MsgReplaceInvalidFileNameChar(char *szInText, char replaceChar)
+{
+       int nCount = 0;
+       int totalLength = 0;
 
-       if (*nCharSet == MIME_UNKNOWN) {
-               MSG_DEBUG("__MmsBinaryDecodeCharset : _MmsGetBinaryType fail..\n");
-               *nCharSet = MSG_CHARSET_UNKNOWN;
+       totalLength = strlen(szInText);
+
+       while ((*(szInText+nCount) != '\0') && (nCount < totalLength)) {
+               if (0x0001 <= *(szInText+nCount) && *(szInText+nCount) <= 0x007F) {
+                       if (__MsgIsInvalidFileNameChar(szInText[nCount]))
+                               *(szInText+nCount) = replaceChar;
+
+                       nCount += 1;
+               } else {
+                       nCount += 2;
+               }
        }
 
        return true;
-
-__CATCH:
-       return false;
 }
 
-
-
-/**
- * Decode EncodedString
- *
- * @param      pEncodedData    [in] QuotedString encoded data
- * @param      szBuff                  [out] Decoded string buffer
- * @param      bufLen                  [in]  Decoded buffer length
- * @return     length of decoded string length
- */
-static bool __MmsBinaryDecodeEncodedString(FILE *pFile, char *szBuff, int bufLen, int totalLength)
+static char *__MsgGetStringUntilDelimiter(char *pszString, char delimiter)
 {
-       UINT32 valueLength = 0;
-       UINT32 charSet = 0;
-       int charSetLen = 0;
-       int nChar = 0;
-       int nRead2 = 0;
-       int nByte = 0;
-       int nTemp = 0;
-       char *pData = NULL;
-       char *pTempData = NULL;
-       unsigned short *mszTempStr = NULL;
-       char *pConvertedStr = NULL;
-       char *pNewData = NULL;
-
+       char *pszBuffer = NULL;
+       char *pszStrDelimiter = NULL;
+       int     bufLength = 0;
 
-       MSG_DEBUG("__MmsBinaryDecodeEncodedString: decode string..\n");
+       if (!pszString) {
+               MSG_DEBUG("pszString == NULL");
+               return NULL;
+       }
 
-       if (pFile == NULL || szBuff == NULL || bufLen <= 0) {
-               MSG_DEBUG("__MmsBinaryDecodeEncodedString: invalid file or buffer\n");
-               goto __CATCH;
+       if ((pszStrDelimiter = strchr(pszString, delimiter)) == NULL) {
+               MSG_DEBUG("There is no %c in %s. \n", delimiter, pszString);
+               return NULL;
        }
 
-       /*
-        * Encoded_string_value = Text-string | Value-length Char-set Text-String
-        *                                                Text-string    = [Quote]*TEXT End-of-string
-        *                                                Value-length   = 0 ~ 31
-        */
+       bufLength = pszStrDelimiter - pszString;
 
-       memset(szBuff, 0, bufLen);
+       if ((pszBuffer = (char*)calloc (1, bufLength + 1)) == NULL) {
+               MSG_DEBUG("calloc is failed");
+               return NULL;
+       }
+       memset(pszBuffer, 0, bufLength + 1) ;
 
-       switch (__MmsDecodeValueLength(pFile, &valueLength, totalLength)) {
-       case -1:
-               goto __CATCH;
+       strncat(pszBuffer, pszString, bufLength);
 
-       case 0:
+       return pszBuffer;
+}
 
-               /* Text-string = [Quote]*TEXT End-of-string */
+char *MsgChangeHexString(char *pOrg)
+{
+       char *pNew = NULL;
+       char szBuf[10] = {0,};
+       char OneChar;
+       int cLen = 0;
+       int cIndex =0;
+       int index = 0;
 
-               if (__MmsBinaryDecodeText(pFile, szBuff, bufLen, totalLength) < 0) {
-                       MSG_DEBUG("__MmsBinaryDecodeEncodedString : 1. __MmsBinaryDecodeText fail.\n");
-                       goto __CATCH;
-               }
-               break;
+       if (pOrg == NULL)
+               return false;
 
-       default:
+       cLen = strlen(pOrg);
 
-               /* Value-length Charset Text_string */
+       pNew = (char *)calloc(1, cLen + 1);
+       if (pNew == NULL)
+               return NULL;
 
-               if (__MmsBinaryDecodeCharset(pFile, &charSet, &charSetLen, totalLength) == false) {
-                       MSG_DEBUG("__MmsBinaryDecodeEncodedString : __MmsBinaryDecodeCharset error\n");
-                       goto __CATCH;                   /* (valueLength + valueLengthLen) */
-               }
+       memset(pNew, 0, cLen + 1);
 
-               nTemp = __MmsBinaryDecodeText(pFile, szBuff, bufLen, totalLength);
-               if (nTemp < 0) {
-                       /* There can be some error in data - no NULL -> try again with value length */
+       for (cIndex = 0; cIndex< cLen ; cIndex++) {
+               if (pOrg[cIndex] == '%') {
+                       if (pOrg[cIndex+1] != 0 && pOrg[cIndex+2] != 0)         {
+                               snprintf(szBuf, sizeof(szBuf), "%c%c", pOrg[cIndex+1], pOrg[cIndex+2]); // read two chars after '%'
 
-                       pData = (char *)malloc(valueLength - charSetLen);
-                       if (pData == NULL) {
-                               MSG_DEBUG("__MmsBinaryDecodeEncodedString : pData alloc fail.\n");
-                               goto __CATCH;
-                       }
+                               if (__MsgIsHexChar(szBuf) == true) { // check the two character is between  0 ~ F
+                                       OneChar = __MsgConvertHexValue(szBuf);
 
-                       if (_MmsBinaryDecodeGetLongBytes(pFile, pData, valueLength - charSetLen, totalLength) == false) {
-                               MSG_DEBUG("__MmsBinaryDecodeEncodedString : _MmsBinaryDecodeGetLongBytes fail.\n");
-                               goto __CATCH;
+                                       pNew[index] = OneChar;
+                                       index++;
+                                       cIndex+= 2;
+                                       continue;
+                               }
                        }
+               }
+               pNew[index++] = pOrg[cIndex];
+       }
+       return pNew;
+}
 
-                       strncpy(szBuff, pData, bufLen - 1);
+static bool __MsgParseParameter(MsgType *pType, char *pSrc)
+{
+       char *pName = NULL;
+       char *pValue = NULL;
+       char *pDec = NULL;
+       char *pTest = NULL;
+       char *pNextParam = NULL;
+       char *pExt = NULL;
+       int nameLen = 0;
+       int count;
+       char *pTempNextParam = NULL;
+       char *pCh = NULL;
+       char *szSrc = NULL;
+       char *pUTF8Buff = NULL;
+
+       while (pSrc != NULL) {
+               pSrc = __MsgSkipWS(pSrc);
+               if (pSrc == NULL) {
+                       /* End of parse parameter */
+                       return true;
                }
 
-               switch (charSet) {
-               case MSG_CHARSET_UTF16:
-               case MSG_CHARSET_USC2:
+               pNextParam = NULL;
+               pTempNextParam = strchr(pSrc, MSG_CH_SEMICOLON);
+               pCh = pSrc;
 
-                       MSG_DEBUG("__MmsBinaryDecodeEncodedString: MSG_CHARSET_USC2 \n");
+               if (*pCh == MSG_CH_QUOT) {
+                       count = 1;
+               } else {
+                       count = 0;
+               }
 
-                       nTemp = strlen(szBuff);
-                       pTempData = (char *)malloc(nTemp + 1);
-                       if (pTempData == NULL) {
-                               MSG_DEBUG("__MmsBinaryDecodeEncodedString: Memory Full \n");
-                               goto __CATCH;
-                       }
+               pCh++;
+               for (; pCh<=pTempNextParam ; pCh++) {
+                       if (*pCh == MSG_CH_QUOT)
+                               if (*(pCh - 1) != '\\')
+                                       count++;
+               }
 
-                       memset(pTempData, 0, nTemp + 1);
-                       memcpy(pTempData, szBuff, nTemp + 1);
+               if (count%2 == 0)
+                       pNextParam = pTempNextParam;
 
-                       if (((UINT8)pTempData[0]) == 0xFF && ((UINT8)pTempData[1]) == 0xFE) {
-                               if ((nChar = (nTemp / 2 - 1)) <= 0)     {
-                                       MSG_DEBUG("__MmsBinaryDecodeEncodedString(%d) : nChar is invalid value (%d), charset(%d)\n", __LINE__, nChar, charSet);
-                                       goto __CATCH ;
-                               }
+               if (pNextParam)
+                       *pNextParam++ = MSG_CH_NULL;
 
-                               mszTempStr = (unsigned short*) malloc(nChar * sizeof(unsigned short));
-                               if (mszTempStr == NULL) {
-                                       MSG_DEBUG("MmsGetMediaPartData : 1. Memory Full !!! \n");
-                                       goto __CATCH;
-                               }
+               if ((pName = strchr(pSrc, MSG_CH_EQUAL)) != NULL) {
+                       *pName++ = MSG_CH_NULL;
 
-                               memcpy(mszTempStr, ((unsigned short*)pTempData + 1), nChar * sizeof(unsigned short));
+                       if ((pValue = strchr(pName, MSG_CH_QUOT))!= NULL) {
+                               *pValue++ = MSG_CH_NULL;
 
-                               nByte = MsgGetUnicode2UTFCodeSize(((unsigned short*)pTempData + 1), nChar);
+                               if ((pTest = strchr(pValue, MSG_CH_QUOT)) != NULL)
+                                       *pTest = MSG_CH_NULL;
 
-                               pConvertedStr = (char *)malloc(nByte + 1);
-                               if (pConvertedStr)
-                                       MsgUnicode2UTF ((unsigned char*)pConvertedStr, nByte + 1, mszTempStr, nChar);
+                               pDec = MsgDecodeText(pValue);           // Api is to long, consider Add to another file (MsgMIMECodec.c)
                        } else {
-                               if ((nChar = (nTemp / 2)) <= 0) {
-                                       MSG_DEBUG("__MmsBinaryDecodeEncodedString(%d) : nChar is invalid value (%d), charset(%d)\n", __LINE__, nChar, charSet);
-                                       goto __CATCH ;
-                               }
+                               pDec = MsgDecodeText(pName);
+                       }
 
-                               mszTempStr = (unsigned short*) malloc(nChar * sizeof(unsigned short));
-                               if (mszTempStr == NULL) {
-                                       MSG_DEBUG("__MmsBinaryDecodeEncodedString: 2. Memory Full !!! \n");
-                                       goto __CATCH;
-                               }
+                       if (pDec) {
+                               switch (MmsGetTextType(MmsCodeParameterCode, pSrc)) {
+                               case MSG_PARAM_BOUNDARY:
 
-                               memcpy(mszTempStr, ((unsigned short*)pTempData), nChar * sizeof(unsigned short));
+                                       /* RFC 822: boundary := 0*69<bchars> bcharsnospace */
 
-                               nByte = MsgGetUnicode2UTFCodeSize(((unsigned short*)pTempData), nChar);
+                                       memset (pType->param.szBoundary, 0, MSG_BOUNDARY_LEN + 1);
+                                       strncpy(pType->param.szBoundary, pDec, MSG_BOUNDARY_LEN);
+                                       MSG_SEC_INFO("szBoundary = [%s]", pType->param.szBoundary);
+                                       break;
 
-                               pConvertedStr = (char *)malloc(nByte + 1);
-                               if (pConvertedStr != NULL)
-                                       MsgUnicode2UTF ((unsigned char*)pConvertedStr, nByte + 1, mszTempStr, nChar);
-                       }
+                               case MSG_PARAM_CHARSET:
+                                       if (pDec != NULL) {
+                                               pType->param.charset = MmsGetTextType(MmsCodeParameterCode, pDec);
 
-                       if (pConvertedStr != NULL) {
-                               pNewData = pConvertedStr;
-                               nRead2 = nByte;
+                                               if (pType->param.charset == -1)
+                                                       pType->param.charset = MSG_CHARSET_UNKNOWN;
+                                       } else {
+                                               pType->param.charset = MSG_CHARSET_UNKNOWN;
+                                       }
+                                       MSG_SEC_INFO("type = %d    [charset] = %d", pType->type, pType->param.charset);
+                                       break;
 
-                               strncpy(szBuff, pNewData, bufLen - 1);
-                       }
+                               case MSG_PARAM_NAME:
 
-                       break;
+                                       memset (pType->param.szName, 0, MSG_LOCALE_FILENAME_LEN_MAX + 1);
 
-               case MSG_CHARSET_US_ASCII:
+                                       pUTF8Buff = __MsgConvertLatin2UTF8FileName(pDec);
 
-                       MSG_DEBUG("__MmsBinaryDecodeEncodedString: MSG_CHARSET_US_ASCII \n");
+                                       if (pUTF8Buff) {
+                                               if ((pExt = strrchr(pUTF8Buff, '.')) != NULL) {
+                                                       if ((MSG_LOCALE_FILENAME_LEN_MAX-1) < strlen(pUTF8Buff)) {
+                                                               nameLen = (MSG_LOCALE_FILENAME_LEN_MAX-1) - strlen(pExt);
+                                                       } else {
+                                                               nameLen = strlen(pUTF8Buff) - strlen(pExt);
+                                                       }
 
-               case MSG_CHARSET_UTF8:
+                                                       strncpy(pType->param.szName, pUTF8Buff, nameLen);
+                                                       g_strlcat(pType->param.szName, pExt, sizeof(pType->param.szName));
+                                               } else {
+                                                       strncpy(pType->param.szName, pUTF8Buff, (MSG_LOCALE_FILENAME_LEN_MAX-1));
+                                               }
+                                               free(pUTF8Buff);
+                                               pUTF8Buff = NULL;
 
-                       MSG_DEBUG("__MmsBinaryDecodeEncodedString: MSG_CHARSET_UTF8 or Others \n");
+                                               if (__MsgChangeSpace(pType->param.szName, &szSrc) == true) {
+                                                       if (szSrc)
+                                                               strncpy(pType->param.szName, szSrc , strlen(szSrc));
+                                               }
 
-                       pNewData = pTempData;
-                       nRead2 = nTemp;
+                                               if (szSrc) {
+                                                       free(szSrc);
+                                                       szSrc = NULL;
+                                               }
 
-                       break;
+                                               // Remvoe '/', ex) Content-Type: image/gif; name="images/vf7.gif"
+                                               __MsgRemoveFilePath(pType->param.szName);
+                                       } else {
+                                               MSG_SEC_DEBUG("MsgConvertLatin2UTF8FileName(%s) return NULL", pDec);
+                                       }
 
-               case MSG_CHARSET_ISO_8859_7: /* Greek */
+                                       MSG_SEC_INFO("szName = %s", pType->param.szName);
+                                       break;
 
-                       MSG_DEBUG("__MmsBinaryDecodeEncodedString: MSG_CHARSET_ISO_8859_7 \n");
+                               case MSG_PARAM_FILENAME:
 
-                       nTemp = strlen(szBuff);
-                       pTempData = (char *)malloc(nTemp + 1);
-                       if (pTempData == NULL)
-                       {
-                               MSG_DEBUG("__MmsBinaryDecodeEncodedString: Memory Full \n");
-                               goto __CATCH;
-                       }
+                                       memset (pType->param.szFileName, 0, MSG_FILENAME_LEN_MAX+1);
 
-                       memset(pTempData, 0 , nTemp + 1);
-                       memcpy(pTempData, szBuff, nTemp + 1);
+                                       pUTF8Buff = __MsgConvertLatin2UTF8FileName(pDec);
 
-                       nByte = MsgGetLatin72UTFCodeSize((unsigned char*)pTempData, nTemp);
-                       pConvertedStr = (char *)malloc(nByte + 1);
+                                       if (pUTF8Buff) {
+                                               if ((pExt = strrchr(pUTF8Buff, '.')) != NULL) {
+                                                       if ((MSG_FILENAME_LEN_MAX-1) < strlen(pUTF8Buff)) {
+                                                               nameLen = (MSG_FILENAME_LEN_MAX-1) - strlen(pExt);
+                                                       } else {
+                                                               nameLen = strlen(pUTF8Buff) - strlen(pExt);
+                                                       }
 
-                       if (pConvertedStr != NULL) {
-                               MsgLatin7code2UTF((unsigned char*)pConvertedStr, nByte + 1, (unsigned char*)pTempData, nTemp);
+                                                       strncpy(pType->param.szFileName, pUTF8Buff, nameLen);
+                                                       g_strlcat (pType->param.szFileName, pExt, sizeof(pType->param.szFileName));
+                                               } else {
+                                                       strncpy(pType->param.szFileName, pUTF8Buff, (MSG_FILENAME_LEN_MAX-1));
+                                               }
+                                               free(pUTF8Buff);
+                                               pUTF8Buff = NULL;
 
-                               pNewData = pConvertedStr;
-                               nRead2 = nByte;
+                                               if (__MsgChangeSpace(pType->param.szFileName, &szSrc) == true) {
+                                                       snprintf(pType->param.szFileName, sizeof(pType->param.szFileName), "%s", szSrc);
+                                               }
 
-                               strncpy(szBuff, pNewData, bufLen - 1);
-                       }
+                                               if (szSrc) {
+                                                       free(szSrc);
+                                                       szSrc = NULL;
+                                               }
 
-                       break;
+                                               // Remvoe '/', ex) Content-Type: image/gif; name="images/vf7.gif"
+                                               __MsgRemoveFilePath(pType->param.szFileName);
+                                       } else {
+                                               MSG_SEC_DEBUG("MsgConvertLatin2UTF8FileName(%s) return NULL", pDec);
+                                       }
 
-               case MSG_CHARSET_ISO_8859_9: /* Turkish */
+                                       MSG_SEC_INFO("szFileName = %s", pType->param.szFileName);
 
-                       MSG_DEBUG("__MmsBinaryDecodeEncodedString: MSG_CHARSET_ISO_8859_9 \n");
+                                       break;
 
-                       nTemp = strlen(szBuff);
-                       pTempData = (char *)malloc(nTemp + 1);
-                       if (pTempData == NULL) {
-                               MSG_DEBUG("__MmsBinaryDecodeEncodedString: Memory Full \n");
-                               goto __CATCH;
-                       }
+                               case MSG_PARAM_TYPE:
 
-                       memset(pTempData, 0 , nTemp + 1);
-                       memcpy(pTempData, szBuff, nTemp + 1);
+                                       /* type/subtype of root. Only if content-type is multipart/related */
 
-                       nByte = MsgGetLatin52UTFCodeSize((unsigned char*)pTempData, nTemp);
-                       pConvertedStr = (char *)malloc(nByte + 1);
+                                       pType->param.type = MimeGetMimeIntFromMimeString(pDec);
+                                       MSG_SEC_INFO("type = %d", pType->param.type);
 
-                       if (pConvertedStr != NULL) {
-                               MsgLatin5code2UTF((unsigned char*)pConvertedStr, nByte + 1, (unsigned char*)pTempData, nTemp);
+                                       break;
 
-                               pNewData = pConvertedStr;
-                               nRead2 = nByte;
+                               case MSG_PARAM_START:
 
-                               strncpy(szBuff, pNewData, bufLen - 1);
-                       }
+                                       /* Content-id. Only if content-type is multipart/related */
 
-                       break;
+                                       memset (pType->param.szStart, 0, MSG_MSG_ID_LEN + 1);
+                                       strncpy(pType->param.szStart, pDec, MSG_MSG_ID_LEN);
 
-               default:
+                                       MSG_SEC_INFO("szStart = %s", pType->param.szStart);
 
-                       MSG_DEBUG("__MmsBinaryDecodeEncodedString: Other charsets \n");
+                                       break;
 
-                       nTemp = strlen(szBuff);
-                       pTempData = (char *)malloc(nTemp + 1);
-                       if (pTempData == NULL) {
-                               MSG_DEBUG("__MmsBinaryDecodeEncodedString: Memory Full \n");
-                               goto __CATCH;
-                       }
+                               case MSG_PARAM_START_INFO :
 
-                       memset(pTempData, 0, nTemp + 1);
-                       memcpy(pTempData, szBuff, nTemp + 1);
+                                       /* Only if content-type is multipart/related */
 
-                       nByte = MsgGetLatin2UTFCodeSize((unsigned char*)pTempData, nTemp);
-                       pConvertedStr = (char *)malloc(nByte + 1);
+                                       memset (pType->param.szStartInfo, 0, MSG_MSG_ID_LEN + 1);
+                                       strncpy(pType->param.szStartInfo, pDec, MSG_MSG_ID_LEN);
 
-                       if (pConvertedStr != NULL) {
-                               MsgLatin2UTF((unsigned char*)pConvertedStr, nByte + 1, (unsigned char*)pTempData, nTemp);
+                                       MSG_SEC_INFO("szStartInfo = %s", pType->param.szStartInfo);
 
-                               pNewData = pConvertedStr;
-                               nRead2 = nByte;
+                                       break;
 
-                               strncpy(szBuff, pNewData, bufLen - 1);
-                       }
+                               case MSG_PARAM_REPORT_TYPE :
 
-                       break;
+                                       //  only used as parameter of Content-Type: multipart/report; report-type=delivery-status;
 
-               } //switch (charset)
-
-       } //switch (__MmsDecodeValueLength....)
+                                       if (pDec != NULL && strcasecmp(pDec, "delivery-status") == 0) {
+                                               pType->param.reportType = MSG_PARAM_REPORT_TYPE_DELIVERY_STATUS;
+                                       } else {
+                                               pType->param.reportType = MSG_PARAM_REPORT_TYPE_UNKNOWN;
+                                       }
 
-       if (pData) {
-               free(pData);
-               pData = NULL;
-       }
+                                       MSG_SEC_INFO("reportType = %s", pDec);
+                                       break;
 
-       if (pTempData) {
-               free(pTempData);
-               pTempData = NULL;
-       }
+                               default:
 
-       if (mszTempStr) {
-               free(mszTempStr);
-               mszTempStr = NULL;
-       }
+                                       MSG_DEBUG("Unknown paremeter (%s)", pDec);
+                                       break;
+                               }
 
-       if (pConvertedStr) {
-               free(pConvertedStr);
-               pConvertedStr = NULL;
+                               free(pDec);
+                               pDec = NULL;
+                       }
+               }
+               pSrc = pNextParam;
        }
-
-
        return true;
+}
 
-__CATCH:
-
-       if (pData) {
-               free(pData);
-               pData = NULL;
-       }
-
-       if (pTempData) {
-               free(pTempData);
-               pTempData = NULL;
+static char *__MsgSkipWS(char *s)
+{
+       while (true) {
+               if ((*s == MSG_CH_CR) || (*s == MSG_CH_LF) || (*s == MSG_CH_SP) || (*s == MSG_CH_TAB)) {
+                       ++s;
+               } else if ((*s != '(') || (__MsgSkipComment(s,(long)NULL)==NULL)) {
+                       return s;
+               }
        }
+}
 
-       if (mszTempStr) {
-               free(mszTempStr);
-               mszTempStr = NULL;
-       }
+static char *__MsgSkipComment (char *s,long trim)
+{
 
-       if (pConvertedStr) {
-               free(pConvertedStr);
-               pConvertedStr = NULL;
-       }
+       char *ret;
+       char *s1 = s;
+       char *t = NULL;
 
-       return false;
-}
+       // ignore empty space
+       for (ret = ++s1; *ret == ' '; ret++)
+               ;
 
+       // handle '(', ')', '\',  '\0'
+       do {
+               switch (*s1) {
+               case '(':
+                       if (!__MsgSkipComment (s1,(long)NULL))
+                               goto __NULL_RETURN;
+                       t = --s1;
+                       break;
+               case ')':
+                       s = ++s1;
+                       if (trim) {
+                               if (t) {
+                                       t[1] = '\0';
+                               } else {
+                                       *ret = '\0';
+                               }
+                       }
+                       return ret;
+               case '\\':
+                       if (*++s1)
+                               break;
+               case '\0':
+                       *s = '\0';
+                       goto __NULL_RETURN;
+               case ' ':
+                       break;
+               default:
+                       t = s1;
+                       break;
+               }
+       } while (s1++);
 
+__NULL_RETURN:
+       return NULL;
+}
 
-/**
- * Decode Encoded Addresses
- *
- * @param      pEncodedData    [in] QuotedString encoded data
- * @param      pAddrLength             [out] Decoded address length
- * @return     Decoded address list
- */
-MsgHeaderAddress *__MmsDecodeEncodedAddress(FILE *pFile, int totalLength)
+static char *__MsgConvertLatin2UTF8FileName(char *pSrc)
 {
-       UINT32 valueLength      = 0;
-       UINT32 charSet          = 0;
-       int charSetLen  = 0;
-       int textLength  = 0;
-       char *pAddrStr  = NULL;
-       MsgHeaderAddress *pAddr = NULL;
-
-       MSG_DEBUG("__MmsDecodeEncodedAddress: decoding address..\n");
-
-       if (pFile == NULL) {
-               MSG_DEBUG("__MmsDecodeEncodedAddress: invalid file or buffer\n");
-               goto __CATCH;
-       }
+       char *pUTF8Buff  = NULL;
+//     char *pData = NULL;
 
-       /*
-        * Encoded_string_value = Text-string | Value-length Char-set Text-String
-        *                                                Text-string    = [Quote]*TEXT End-of-string
-        *                                                Value-length   = 0 ~ 31
-        */
 
-       switch (__MmsDecodeValueLength(pFile, &valueLength, totalLength)) {
-       case -1:
-               goto __CATCH;
+       //convert utf8 string
+       if (MmsIsUtf8String((unsigned char*)pSrc, strlen(pSrc)) == false) {
+               int length  = 0;
+               int utf8BufSize = 0;
 
-       case 0:
+               length = strlen(pSrc);
+               utf8BufSize = __MsgGetLatin2UTFCodeSize((unsigned char*)pSrc, length);
+               if (utf8BufSize < 3)
+                       utf8BufSize = 3; //min value
 
-               /* Text-string = [Quote]*TEXT End-of-string */
+               pUTF8Buff = (char *)calloc(1, utf8BufSize + 1);
 
-               textLength = 0;
-               pAddrStr   = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
-               if (pAddrStr == NULL) {
-                       MSG_DEBUG("__MmsDecodeEncodedAddress : 1. __MmsBinaryDecodeText2 fail.\n");
+               if (pUTF8Buff == NULL) {
+                       MSG_DEBUG("pUTF8Buff alloc fail");
                        goto __CATCH;
                }
-               break;
-
-       default:
-
-               /* Value-length Charset Text_string */
 
-               if (__MmsBinaryDecodeCharset(pFile, &charSet, &charSetLen, totalLength) == false) {
-                       MSG_DEBUG("__MmsDecodeEncodedAddress : __MmsBinaryDecodeCharset error\n");
+               if (__MsgLatin2UTF ((unsigned char*)pUTF8Buff, utf8BufSize + 1, (unsigned char*)pSrc, length) < 0) {
+                       MSG_DEBUG("MsgLatin2UTF fail");
                        goto __CATCH;
                }
+       } else {
+               int length = strlen(pSrc);
+               pUTF8Buff = (char *)calloc(1, length+1);
 
-               textLength = 0;
-               pAddrStr   = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
-               if (pAddrStr == NULL) {
-                       /* There can be some error in data - no NULL -> try again with value length */
-
-                       pAddrStr = (char *)malloc(valueLength - charSetLen);
-                       if (pAddrStr == NULL) {
-                               MSG_DEBUG("__MmsDecodeEncodedAddress : pData alloc fail.\n");
-                               goto __CATCH;
-                       }
-
-                       if (_MmsBinaryDecodeGetLongBytes(pFile, pAddrStr, valueLength - charSetLen, totalLength) == false) {
-                               MSG_DEBUG("__MmsDecodeEncodedAddress : _MmsBinaryDecodeGetLongBytes fail.\n");
-                               goto __CATCH;
-                       }
+               if (pUTF8Buff == NULL) {
+                       MSG_DEBUG("pUTF8Buff alloc fail");
+                       goto __CATCH;
                }
 
-               break;
+               memcpy(pUTF8Buff, pSrc, length);
        }
 
-       pAddr = (MsgHeaderAddress *)malloc(sizeof(MsgHeaderAddress));
-       if (pAddr == NULL)
-               goto __CATCH;
-
-       memset(pAddr, 0, sizeof(MsgHeaderAddress));
-       pAddr->szAddr = pAddrStr;
+       //convert hex string
+//     if (__MsgIsPercentSign(pUTF8Buff) == true) {
+//             pData = MsgChangeHexString(pUTF8Buff);
+//             if (pData) {
+//                     free(pUTF8Buff);
+//                     pUTF8Buff = pData;
+//             }
+//     }
 
-       return pAddr;
+       return pUTF8Buff;
 
 __CATCH:
 
-       if (pAddrStr) {
-               free(pAddrStr);
-               pAddrStr = NULL;
+       if (pUTF8Buff) {
+               free(pUTF8Buff);
+               pUTF8Buff = NULL;
        }
 
        return NULL;
 }
 
-
-/**
- * Decode Encoded Pointer String
- *
- * @param      pEncodedData    [in] Long integer encoded data
- * @param      pLongInteger    [out] Decoded long integer
- * @return     Decoded address list
- */
-static bool __MmsDecodeLongInteger(FILE *pFile, UINT32 *pLongInteger, int totalLength)
+static bool __MsgChangeSpace(char *pOrg, char **ppNew)
 {
-       UINT8 oneByte = 0;
-
-       /*
-        * Long-integer = Short-length Multi-octet-integer
-        *                                Short-length = 0~30
-        *                                Multi-octet-integer
-        */
+       char *pNew = NULL;
+       int cLen = 0;
+       int cIndex =0;
+       int index = 0;
 
-       if (pFile == NULL || pLongInteger == NULL)
+       if (pOrg == NULL)
                return false;
 
-       *pLongInteger = 0;
+       cLen = strlen(pOrg);
 
-       if (_MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false)
-               goto __CATCH;
+       pNew = (char *)calloc(1, cLen + 1);
+       if (pNew == NULL)
+               return false;
 
-       if (oneByte > 31)
-               goto __CATCH;
+       memset(pNew, 0, cLen + 1);
 
-       *pLongInteger = __MmsHeaderDecodeIntegerByLength(pFile, oneByte, totalLength);
+       for (cIndex=0; cIndex<cLen;cIndex++) {
+               if (pOrg[cIndex] == '%' && pOrg[cIndex+1] == '2' && pOrg[cIndex+2] == '0') {
+                       pNew[index] = ' ';
+                       index++;
+                       cIndex+= 2;
+                       continue;
+               }
+               pNew[index++] = pOrg[cIndex];
+       }
 
-       return true;
+       *ppNew = pNew;
 
-__CATCH:
-       return false;
+       return true;
 }
 
-
-/*
- * @param      pEncodedData    [in] filename encoded data
- * @param      szBuff                  [out] filename output buffer
- * @param      fullLength              [in] full filename length
- * @param      bufLen                  [in] buffer length
- * CAUTION: bufLen - 1
- */
-static int __MmsDecodeGetFilename(FILE *pFile, char *szBuff, int bufLen, int totalLength)
+static void __MsgRemoveFilePath(char *pSrc)
 {
-       char *pUTF8Buff = NULL;
-       char *pLatinBuff = NULL;
-       char *pExt = NULL;
-       char *szSrc = NULL;
-       char *szSrc2 = NULL;
-       int length = 0;
-       int textLength = 0;
+       // Remvoe '/', ex) Content-Type: image/gif; name="images/vf7.gif"
+       char *pTemp = NULL;
+       char *tmp_name = NULL;
 
-       char *pTmpBuff = NULL;
+       tmp_name = MsgGetFileName(pSrc);
+       if (tmp_name) {
+               snprintf(pSrc, strlen(tmp_name), "%s", tmp_name);
+               g_free(tmp_name);
+               tmp_name = NULL;
+       }
 
-       memset (szBuff, 0, bufLen);
+       // Remove additional file information
+       // ex) Content-type: application/octet-stream; name="060728gibson_210.jpg?size=s"
+       // if "?size=" exist, insert NULL char.
+       {
+               pTemp = strcasestr(pSrc, "?size=");
+               if (pTemp != NULL)
+                       *pTemp = '\0';
+       }
+}
 
-       textLength = 0;
-       pLatinBuff  = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+#if 0
+static bool __MsgIsPercentSign(char *pSrc)
+{
+       char *pCh = NULL;
+       bool bRet = false;
 
-       //remove ""
-       if (pLatinBuff) {
-               szSrc = MsgRemoveQuoteFromFilename(pLatinBuff);
-               if (szSrc) {
-                       strcpy(pLatinBuff, szSrc);
-                       free(szSrc);
-                       szSrc = NULL;
-               }
+       pCh = strchr(pSrc , '%');
 
-               szSrc2 = MsgChangeHexString(pLatinBuff);
-               if (szSrc2) {
-                       strcpy(pLatinBuff, szSrc2);
-                       free(szSrc2);
-                       szSrc2 = NULL;
-               }
+       if (pCh != NULL) {
+               bRet = true;
+       } else {
+               bRet = false;
+       }
 
-               if (MsgIsUTF8String((unsigned char*)pLatinBuff, strlen(pLatinBuff)) == false) {
-                       length = strlen(pLatinBuff);
+       return bRet;
+}
+#endif
 
-                       int             utf8BufSize = 0;
-                       utf8BufSize = MsgGetLatin2UTFCodeSize((unsigned char*)pLatinBuff, length);
-                       pUTF8Buff = (char *)malloc(utf8BufSize + 1);
-                       if (pUTF8Buff == NULL) {
-                               MSG_DEBUG("__MmsDecodeGetFilename: pUTF8Buff alloc fail \n");
-                               goto __CATCH;
-                       }
+static MsgPresentationFactor __MsgIsPresentationEx(MsgType *multipartType, char* szStart, MimeType typeParam)
+{
+       char szTmpStart[MSG_MSG_ID_LEN + 3] = { 0, };
+       char szTmpContentID[MSG_MSG_ID_LEN + 3] = { 0, };
+       char szTmpContentLO[MSG_MSG_ID_LEN + 3] = { 0, };
+       int strLen = 0;
 
-                       if (MsgLatin2UTF ((unsigned char*)pUTF8Buff, utf8BufSize + 1, (unsigned char*)pLatinBuff, length) < 0) {
-                               MSG_DEBUG("__MmsDecodeGetFilename: MsgLatin2UTF fail \n");
-                               goto __CATCH;
-                       }
-                       free(pLatinBuff);
-                       pLatinBuff = NULL;
+       // remove '<' and '>' in Start Param : contentID ex] <0_1.jpg> or <1233445>
+       if (szStart && szStart[0]) {
+               int startLen = 0;
+               startLen = strlen(szStart);
+               if (szStart[0] == '<' && szStart[startLen - 1] == '>') {
+                       strncpy(szTmpStart, &szStart[1], startLen - 2);
                } else {
-                       pTmpBuff = _MsgDecodeText(pLatinBuff);
-                       pUTF8Buff = pTmpBuff;
-                       free (pLatinBuff);
-                       pLatinBuff = NULL;
+                       strncpy(szTmpStart, szStart, startLen);
                }
        }
 
-       if (pUTF8Buff) {
-               /*
-                * keeping extension
-                * it should be kept extention even if the file name is shorten
-                */
-
-               length = strlen(pUTF8Buff);
-               if ((pExt = strrchr(pUTF8Buff, '.')) != NULL) {
-                       int nameLength  = 0;
-                       nameLength = (length < bufLen) ? (length - strlen(pExt)) : (bufLen - strlen(pExt));
-                       strncpy(szBuff, pUTF8Buff, nameLength);
-                       strcat (szBuff, pExt);
+       // remove '<' and '>' in ContentID : contentID ex] <0_1.jpg> or <1233445>
+       if (multipartType->szContentID[0])      {
+               strLen = strlen(multipartType->szContentID);
+               if (multipartType->szContentID[0] == '<' && multipartType->szContentID[strLen - 1] == '>') {
+                       strncpy(szTmpContentID, &(multipartType->szContentID[1]), strLen - 2);
                } else {
-                       strncpy(szBuff, pUTF8Buff, bufLen - 1);
+                       strncpy(szTmpContentID, multipartType->szContentID, strLen);
                }
-               free(pUTF8Buff);
-               pUTF8Buff = NULL;
-
-               return textLength;
-       }
-
-__CATCH:
-
-       if (pLatinBuff) {
-               free(pLatinBuff);
-               pLatinBuff = NULL;
        }
 
-       if (pUTF8Buff) {
-               free(pUTF8Buff);
-               pUTF8Buff = NULL;
+       // remove '<' and '>' in ContentLocation : contentID ex] <0_1.jpg> or <1233445>
+       if (multipartType->szContentLocation[0]) {
+               strLen = strlen(multipartType->szContentLocation);
+               if (multipartType->szContentLocation[0] == '<' && multipartType->szContentLocation[strLen - 1] == '>') {
+                       strncpy(szTmpContentLO, &multipartType->szContentLocation[1], strLen - 2);
+               } else {
+                       strncpy(szTmpContentLO, multipartType->szContentLocation, strLen);
+               }
        }
 
-       return -1;
-}
-
-
-/* ==========================================================
-
-          T  E  X  T         D  E  C  O  D  I  N  G
-
-   ==========================================================*/
-
-
-bool MmsTextDecodeMsgBody(FILE *pFile)
-{
-       MSG_DEBUG("MmsTextDecodeMsgBody: \n");
-       return false;
-}
-
-bool __MmsTextDecodeMsgHeader(FILE *pFile)
-{
-       return true;
-}
-
-
-/* ==========================================================
-
-          M  M  S        D  E  C  O  D  I  N  G
-
-   ==========================================================*/
-
-//  to get message body this function should be modified from message raw file.
-bool _MmsReadMsgBody(msg_message_id_t msgID, bool bSavePartsAsTempFiles, bool bRetrieved, char *retrievedPath)
-{
-       FILE *pFile     = NULL;
-       MmsMsg *pMsg = NULL;
-       MsgMultipart *pMultipart = NULL;
-       int nSize = 0;
-       char szFullPath[MSG_FILEPATH_LEN_MAX] = {0, };
-       char szTempMediaDir[MSG_FILEPATH_LEN_MAX] = {0, };
-       int attachmax = MSG_ATTACH_MAX;
-
-       MSG_DEBUG("_MmsReadMsgBody: start read msg(msgID=%d)\n", msgID);
-
-       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
-       memset(pMsg, 0, sizeof(MmsMsg));
-
-       _MmsInitHeader();
+       if ((szTmpContentID[0] == '\0') && (szTmpContentLO[0] == '\0') && (multipartType->type == MIME_UNKNOWN))
+               return  MSG_PRESENTATION_NONE;
 
-       if (bRetrieved && (retrievedPath != NULL)) {
-               strncpy(szFullPath, retrievedPath, (strlen(retrievedPath) > MSG_FILEPATH_LEN_MAX ? MSG_FILEPATH_LEN_MAX:strlen(retrievedPath)));
+       // exception handling
+       if (szTmpStart[0] != '\0') {
+               // presentation part : 1.compare with contentID 2.compare with content Location 3. compare with type
+               if (strcmp(szTmpStart, szTmpContentID) == 0) {
+                       return MSG_PRESENTATION_ID;
+               } else if (strcmp(szTmpStart, szTmpContentLO) == 0) {
+                       return   MSG_PRESENTATION_LOCATION;
+               } else if (multipartType->type == typeParam) {
+                       return   MSG_PRESENTATION_TYPE_BASE;
+               } else {
+                       return   MSG_PRESENTATION_NONE;
+               }
        } else {
-               MmsPluginStorage::instance()->getMmsRawFilePath(msgID, szFullPath);
-       }
-
-       pMsg->msgID = msgID;
-
-       /*      read from MMS raw file  */
-       if (szFullPath != NULL)
-               strncpy(pMsg->szFileName, szFullPath + strlen(MSG_DATA_PATH), strlen(szFullPath + strlen(MSG_DATA_PATH)));
-
-       MSG_DEBUG("szFullPath = (%s)", szFullPath);
-
-       if (MsgGetFileSize(szFullPath, &nSize) == false) {
-               MSG_DEBUG("MsgGetFileSize: failed");
-               goto __CATCH;
-       }
-
-       pFile = MsgOpenFile(szFullPath, "rb");
-
-       if (pFile == NULL) {
-               MSG_DEBUG("_MmsReadMsgBody: invalid mailbox\n");
-               goto __CATCH;
-       }
-
-       _MmsRegisterDecodeBuffer(gszMmsLoadBuf1, gszMmsLoadBuf2, MSG_MMS_DECODE_BUFFER_MAX);
-
-       if (MmsBinaryDecodeMsgHeader(pFile, nSize) == false) {
-               MSG_DEBUG("_MmsReadMsgBody: MmsBinaryDecodeMsgHeader fail...\n");
-               goto __CATCH;
-       }
-
-#ifdef __SUPPORT_DRM__
-       if (MmsDrm2GetConvertState() != MMS_DRM2_CONVERT_FINISH)
-               MmsDrm2SetConvertState(MMS_DRM2_CONVERT_NONE);  //initialize convertState
-#endif
-
-       if (MmsBinaryDecodeMsgBody(pFile, szFullPath, nSize) == false) {
-               MSG_DEBUG("_MmsReadMsgBody: MmsBinaryDecodeMsgBody fail\n");
-               goto __CATCH;
-       }
-
-#ifdef __SUPPORT_DRM__
-       if (MmsDrm2GetConvertState() == MMS_DRM2_CONVERT_REQUIRED) {
-               MSG_DEBUG("_MmsReadMsgBody: MmsDrm2GetConvertState returns MMS_DRM2_CONVERT_REQUIRED.\n");
-               goto RETURN;
+               if (multipartType->type == typeParam && typeParam != MIME_UNKNOWN) {
+                       return   MSG_PRESENTATION_TYPE_BASE;
+               } else {
+                       return   MSG_PRESENTATION_NONE;
+               }
        }
-#endif
-
-       /* Set mmsHeader.msgType & msgBody to pMsg ----------- */
-
-       pMsg->mmsAttrib.contentType = (MsgContentType)mmsHeader.msgType.type;
-
-       memcpy(&(pMsg->msgType), &(mmsHeader.msgType), sizeof(MsgType));
-       memcpy(&(pMsg->msgBody), &(mmsHeader.msgBody), sizeof(MsgBody));
-
-       if (pMsg->msgBody.pPresentationBody) {
-               if(MsgFseek(pFile, pMsg->msgBody.pPresentationBody->offset, SEEK_SET) < 0)
-                       goto __CATCH;
-
-               pMsg->msgBody.pPresentationBody->body.pText = (char *)malloc(pMsg->msgBody.pPresentationBody->size + 1);
-               if (pMsg->msgBody.pPresentationBody->body.pText == NULL)
-                       goto __CATCH;
-
-               memset(pMsg->msgBody.pPresentationBody->body.pText, 0, pMsg->msgBody.pPresentationBody->size + 1);
+}
 
-               ULONG nRead = 0;
-               nRead = MsgReadFile(pMsg->msgBody.pPresentationBody->body.pText, sizeof(char), pMsg->msgBody.pPresentationBody->size, pFile);
-               if (nRead == 0)
-                       goto __CATCH;
+static void __MsgConfirmPresentationPart(MsgType *pMsgType, MsgBody *pMsgBody, MsgPresentaionInfo *pPresentationInfo)
+{
+       MSG_BEGIN();
+       MsgMultipart *pNextPart = NULL;
+       MsgMultipart *pRemovePart = NULL;
 
-       }
+       if (__MsgIsMultipartRelated(pMsgType->type)) {
+               // assign the multipart to presentation part
+               // remove the multipart(pCurPresentation) which is presentation part from the linked list.
+               // if there is no presentation part -> assign first multipart to presentation part by force.
+               if (pPresentationInfo->pCurPresentation == NULL) {
+                       pPresentationInfo->pCurPresentation     = pMsgBody->body.pMultipart;
+                       pPresentationInfo->pPrevPart            = NULL;
+                       pPresentationInfo->factor                       = MSG_PRESENTATION_NONE;
+               }
 
-       MsgCloseFile(pFile);
-       pFile = NULL;
+               if (pPresentationInfo->pCurPresentation != NULL && __MsgIsPresentablePart(pPresentationInfo->pCurPresentation->type.type)) {
+                       /* Presentable Part is some MARK-UP page, such as SMIL, HTML, WML, XHTML.
+                        * In this case, COPY the Presentation part and leave other multiparts.
+                        */
+                       memcpy(&pMsgBody->presentationType, &pPresentationInfo->pCurPresentation->type, sizeof(MsgType));
+                       pMsgBody->pPresentationBody = pPresentationInfo->pCurPresentation->pBody;
 
-       /* nPartCount */
-       pMsg->nPartCount = 0;
+                       // remove pCurPresentation from multipart linked list
+                       if ((pPresentationInfo->factor == MSG_PRESENTATION_NONE)||(pPresentationInfo->pPrevPart == NULL)) {
+                               // first part
+                               pMsgBody->body.pMultipart = pPresentationInfo->pCurPresentation->pNext;
+                               pMsgType->contentSize -= pPresentationInfo->pCurPresentation->pBody->size;
+                               pMsgBody->size -= pPresentationInfo->pCurPresentation->pBody->size;
+                               if (pPresentationInfo->pCurPresentation) {
 
-       if (MsgIsMultipart(mmsHeader.msgType.type) == true) {
-               pMultipart = pMsg->msgBody.body.pMultipart;
-               while (pMultipart) {
-                       pMsg->nPartCount++;
+                                       MmsReleaseMsgDRMInfo(&pPresentationInfo->pCurPresentation->type.drmInfo);
 
-                       if (pMultipart->type.type == MIME_TEXT_PLAIN)
-                               attachmax++;
+                                       free(pPresentationInfo->pCurPresentation);
+                                       pPresentationInfo->pCurPresentation = NULL;
+                               }
+                       } else {
+                               // not a first part
+                               pPresentationInfo->pPrevPart->pNext = pPresentationInfo->pCurPresentation->pNext;
+                               pMsgType->contentSize -= pPresentationInfo->pCurPresentation->pBody->size;
+                               pMsgBody->size -= pPresentationInfo->pCurPresentation->pBody->size;
+                               if (pPresentationInfo->pCurPresentation) {
+                                       free(pPresentationInfo->pCurPresentation);
+                                       pPresentationInfo->pCurPresentation = NULL;
+                               }
+                       }
+               } else if (pPresentationInfo->pCurPresentation != NULL && MmsIsTextType(pPresentationInfo->pCurPresentation->type.type)) {
+                       /* NON-Presentable Part is some PLAIN part such as, text/plain, multipart/alternative.
+                        * In this case, leave the Presentation part as a multipart and remove other multiparts.
+                        */
 
-                       if ((mmsHeader.msgType.type == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED)||(mmsHeader.msgType.type == MIME_MULTIPART_MIXED)) {
-                               if ((pMsg->nPartCount >= attachmax)&&(pMultipart->pNext != NULL)) {
-                                       _MsgFreeBody(pMultipart->pNext->pBody, pMultipart->pNext->type.type);
+                       // Backup the multipart link information
+                       pNextPart = pMsgBody->body.pMultipart;
 
-                                       free(pMultipart->pNext->pBody);
-                                       pMultipart->pNext->pBody= NULL;
+                       // Copy presentation part as a main part
+                       memcpy(pMsgType, &pPresentationInfo->pCurPresentation->type, sizeof(MsgType));
+                       memcpy(pMsgBody, pPresentationInfo->pCurPresentation->pBody, sizeof(MsgBody));
 
-                                       free(pMultipart->pNext);
+                       // Remove multipart linked list
+                       while (pNextPart) {
+                               pRemovePart = pNextPart;
+                               pNextPart = pNextPart->pNext;
 
-                                       pMultipart->pNext = NULL;
-                                       break;
+                               if (pRemovePart->pBody) {
+                                       MmsReleaseMsgBody(pRemovePart->pBody, pRemovePart->type.type);
+                                       free(pRemovePart->pBody);
+                                       pRemovePart->pBody = NULL;
                                }
-                       }
-                       pMultipart = pMultipart->pNext;
-               }
-       } else {
-               if (pMsg->msgBody.size > 0)
-                       pMsg->nPartCount++;
-       }
-
-       /*      make temporary  */
-       snprintf(szTempMediaDir, MSG_FILEPATH_LEN_MAX, MSG_DATA_PATH"%s.dir", pMsg->szFileName);
 
-       ///////////////////////////////////////////////
-       // call before processing urgent event.
-       //_MmsInitHeader();
-       //_MmsUnregisterDecodeBuffer();
-       ///////////////////////////////////////////////
+                               free(pRemovePart);
+                               pRemovePart = NULL;
+                       }
+               } else {
 
-       if (MsgIsMultipart(pMsg->msgType.type) == true) {
-               int partIndex = 0;
-               pMultipart = pMsg->msgBody.body.pMultipart;
-
-               if (bSavePartsAsTempFiles) {
-                       if (mkdir(szTempMediaDir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
-                               if (errno == EEXIST) {
-                                       MSG_DEBUG("The %s already exists", szTempMediaDir);
-                               } else {
-                                       MSG_DEBUG("Fail to Create Dir [%s]", szTempMediaDir);
-                                       goto __CATCH;
-                               }
-                       }
-               }
-
-               while (pMultipart) {
-
-                       if (_MmsMultipartSaveAsTempFile(&pMultipart->type, pMultipart->pBody,
-                                                                                       (char*)MSG_DATA_PATH, pMsg->szFileName, partIndex, bSavePartsAsTempFiles) == false)
-                               goto __CATCH;
-
-                       pMultipart = pMultipart->pNext;
-                       partIndex ++;
-               }
-
-       } else { //single part
-               if (pMsg->nPartCount > 0) {
-
-                       if (bSavePartsAsTempFiles) {
-                               if (mkdir(szTempMediaDir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
-                                       if (errno == EEXIST) {
-                                               MSG_DEBUG("The %s already exists", szTempMediaDir);
-                                       } else {
-                                               MSG_DEBUG("Fail to Create Dir [%s]", szTempMediaDir);
-                                               goto __CATCH;
-                                       }
-                               }
-                       }
-
-                       if (_MmsMultipartSaveAsTempFile( &pMsg->msgType, &pMsg->msgBody,
-                                                                                       (char*)MSG_DATA_PATH, pMsg->szFileName, 0, bSavePartsAsTempFiles) == false)
-                               goto __CATCH;
-               }
-       }
-       MSG_DEBUG("****   _MmsReadMsgBody:  E  N  D   (Success)  ***\n");
-       return true;
-
-#ifdef __SUPPORT_DRM__
-
-RETURN:
-
-       if (pFile != NULL) {
-               MsgCloseFile(pFile);
-               pFile = NULL;
-       }
-
-       return false;
-
-#endif
-
-__CATCH:
-
-       _MmsInitHeader();
-       _MmsUnregisterDecodeBuffer();
-
-       if (pFile != NULL) {
-               MsgCloseFile(pFile);
-               pFile = NULL;
-       }
-
-#ifdef __SUPPORT_DRM__
-       _MsgFreeDRMInfo(&pMsg->msgType.drmInfo);
-#endif
-
-       _MsgFreeBody(&pMsg->msgBody, pMsg->msgType.type);
-       MSG_DEBUG("_MmsReadMsgBody:    E  N  D    (fail)    ******************** \n");
-
-       return false;
-}
-
-
-bool MsgFreeHeaderAddress(MsgHeaderAddress *pAddr)
-{
-       MsgHeaderAddress *pTempAddr = NULL;
-
-       while (pAddr != NULL) {
-               pTempAddr = pAddr;
-               pAddr = pAddr->pNext;
-
-               if (pTempAddr->szAddr) {
-                       free(pTempAddr->szAddr);
-                       pTempAddr->szAddr = NULL;
-               }
-
-               free(pTempAddr);
-               pTempAddr = NULL;
-       }
-
-       return true;
-}
-
-bool MsgCheckFileNameHasInvalidChar(char *szName)
-{
-       int     strLen = 0;
-       int i = 0;
-
-       strLen = strlen(szName);
-
-       for (i=0; i<strLen; i++) {
-               if (__MsgIsInvalidFileNameChar(szName[i]))
-                       return true;
-       }
-
-       return false;
-}
-
-bool _MsgReplaceInvalidFileNameChar(char *szInText, char replaceChar)
-{
-       int nCount = 0;
-       int totalLength = 0;
-
-       totalLength = strlen(szInText);
-
-       while ((*(szInText+nCount) != '\0') && (nCount < totalLength)) {
-               if (0x0001 <= *(szInText+nCount) && *(szInText+nCount) <= 0x007F) {
-                       if (__MsgIsInvalidFileNameChar(szInText[nCount]))
-                               *(szInText+nCount) = replaceChar;
-
-                       nCount += 1;
-               } else {
-                       nCount += 2;
-               }
-       }
-
-       return true;
-}
-
-char *_MsgGetStringUntilDelimiter(char *pszString, char delimiter)
-{
-       char *pszBuffer = NULL;
-       char *pszStrDelimiter = NULL;
-       int     bufLength = 0;
-
-       if (!pszString) {
-               MSG_DEBUG("_MsgGetStringUntilDelimiter: pszString == NULL \n");
-               return NULL;
-       }
-
-       if ((pszStrDelimiter = strchr(pszString, delimiter)) == NULL) {
-               MSG_DEBUG("_MsgGetStringUntilDelimiter: There is no %c in %s. \n", delimiter, pszString);
-               return NULL;
-       }
-
-       bufLength = pszStrDelimiter - pszString;
-
-       if ((pszBuffer = (char*)malloc (bufLength + 1)) == NULL) {
-               MSG_DEBUG("malloc is failed");
-               return NULL;
-       }
-       memset(pszBuffer, 0, bufLength + 1) ;
-
-       strncat(pszBuffer, pszString, bufLength);
-
-       return pszBuffer;
-}
-
-char *MsgChangeHexString(char *pOrg)
-{
-       char *pNew = NULL;
-       char szBuf[10] = {0,};
-       char OneChar;
-       int cLen = 0;
-       int cIndex =0;
-       int index = 0;
-
-       if (pOrg == NULL)
-               return false;
-
-       cLen = strlen(pOrg);
-
-       pNew = (char *)malloc(cLen + 1);
-       if (pNew == NULL)
-               return NULL;
-
-       memset(pNew, 0, cLen + 1);
-
-       for (cIndex = 0; cIndex< cLen ; cIndex++) {
-               if (pOrg[cIndex] == '%') {
-                       if (pOrg[cIndex+1] != 0 && pOrg[cIndex+2] != 0)         {
-                               snprintf(szBuf, sizeof(szBuf), "%c%c", pOrg[cIndex+1], pOrg[cIndex+2]); // read two chars after '%'
-
-                               if (MsgIsHexChar(szBuf) == true) { // check the two character is between  0 ~ F
-                                       OneChar = _MsgConvertHexValue(szBuf);
-
-                                       pNew[index] = OneChar;
-                                       index++;
-                                       cIndex+= 2;
-                                       continue;
-                               }
-                       }
-               }
-               pNew[index++] = pOrg[cIndex];
-       }
-       return pNew;
-}
-
-bool _MsgParseParameter(MsgType *pType, char *pSrc)
-{
-       char *pName = NULL;
-       char *pValue = NULL;
-       char *pDec = NULL;
-       char *pTest = NULL;
-       char *pNextParam = NULL;
-       char *pExt = NULL;
-       int nameLen = 0;
-       int count;
-       char *pTempNextParam = NULL;
-       char *pCh = NULL;
-       char *szSrc = NULL;
-       char *pUTF8Buff = NULL;
-
-       while (pSrc != NULL) {
-               pSrc = _MsgSkipWS(pSrc);
-               if (pSrc == NULL) {
-                       /* End of parse parameter */
-                       return true;
-               }
-
-               pNextParam = NULL;
-               pTempNextParam = strchr(pSrc, MSG_CH_SEMICOLON);
-               pCh = pSrc;
-
-               if (*pCh == MSG_CH_QUOT) {
-                       count = 1;
-               } else {
-                       count = 0;
-               }
-
-               pCh++;
-               for (; pCh<=pTempNextParam ; pCh++) {
-                       if (*pCh == MSG_CH_QUOT)
-                               if (*(pCh - 1) != '\\')
-                                       count++;
-               }
-
-               if (count%2 == 0)
-                       pNextParam = pTempNextParam;
-
-               if (pNextParam)
-                       *pNextParam++ = MSG_CH_NULL;
-
-               if ((pName = strchr(pSrc, MSG_CH_EQUAL)) != NULL) {
-                       *pName++ = MSG_CH_NULL;
-
-                       if ((pValue = strchr(pName, MSG_CH_QUOT))!= NULL) {
-                               *pValue++ = MSG_CH_NULL;
-
-                               if ((pTest = strchr(pValue, MSG_CH_QUOT)) != NULL)
-                                       *pTest = MSG_CH_NULL;
-
-                               pDec = _MsgDecodeText(pValue);          // Api is to long, consider Add to another file (MsgMIMECodec.c)
-                       } else {
-                               pDec = _MsgDecodeText(pName);
-                       }
-
-                       switch (_MsgGetCode(MSG_PARAM, pSrc)) {
-                       case MSG_PARAM_BOUNDARY:
-
-                               /* RFC 822: boundary := 0*69<bchars> bcharsnospace */
-
-                               memset (pType->param.szBoundary, 0, MSG_BOUNDARY_LEN + 1);
-                               strncpy(pType->param.szBoundary, pDec, MSG_BOUNDARY_LEN);
-                               MSG_DEBUG("_MsgParseParameter: szBoundary = %s \n", pType->param.szBoundary);
-                               break;
-
-                       case MSG_PARAM_CHARSET:
-                               pType->param.charset = _MsgGetCode(MSG_CHARSET, pDec);
-
-                               if (pType->param.charset == INVALID_HOBJ)
-                                       pType->param.charset = MSG_CHARSET_UNKNOWN;
-
-                               MSG_DEBUG("_MsgParseParameter: type = %d    [charset] = %d \n", pType->type, pType->param.charset);
-                               break;
-
-                       case MSG_PARAM_NAME:
-
-                               memset (pType->param.szName, 0, MSG_LOCALE_FILENAME_LEN_MAX + 1);
-
-                               pUTF8Buff = MsgConvertLatin2UTF8FileName(pDec);
-
-                               if (pUTF8Buff) {
-                                       if ((pExt = strrchr(pUTF8Buff, '.')) != NULL) {
-                                               if ((MSG_FILENAME_LEN_MAX-1) < strlen(pUTF8Buff)) {
-                                                       nameLen = (MSG_FILENAME_LEN_MAX-1) - strlen(pExt);
-                                               } else {
-                                                       nameLen = strlen(pUTF8Buff) - strlen(pExt);
-                                               }
-
-                                               strncpy(pType->param.szName, pUTF8Buff, nameLen);
-                                               strcat (pType->param.szName, pExt);
-                                       } else {
-                                               strncpy(pType->param.szName, pUTF8Buff, (MSG_FILENAME_LEN_MAX-1));
-                                       }
-                                       free(pUTF8Buff);
-                                       pUTF8Buff = NULL;
-
-                                       if (_MsgChangeSpace(pType->param.szName, &szSrc) == true) {
-                                               if (szSrc)
-                                                       strncpy(pType->param.szName, szSrc , strlen(szSrc));
-                                       }
-
-                                       if (szSrc) {
-                                               free(szSrc);
-                                               szSrc = NULL;
-                                       }
-
-                                       // Remvoe '/', ex) Content-Type: image/gif; name="images/vf7.gif"
-                                       _MsgRemoveFilePath(pType->param.szName);
-                               } else {
-                                       MSG_DEBUG("_MsgParseParameter: MsgConvertLatin2UTF8FileName(%s) return NULL\n", pDec);
-                               }
-
-                               MSG_DEBUG("_MsgParseParameter: szName = %s \n", pType->param.szName);
-                               break;
-
-                       case MSG_PARAM_FILENAME:
-
-                               memset (pType->param.szFileName, 0, MSG_FILENAME_LEN_MAX+1);
-
-                               pUTF8Buff = MsgConvertLatin2UTF8FileName(pDec);
-
-                               if (pUTF8Buff) {
-                                       if ((pExt = strrchr(pUTF8Buff, '.')) != NULL) {
-                                               if ((MSG_FILENAME_LEN_MAX-1) < strlen(pUTF8Buff)) {
-                                                       nameLen = (MSG_FILENAME_LEN_MAX-1) - strlen(pExt);
-                                               } else {
-                                                       nameLen = strlen(pUTF8Buff) - strlen(pExt);
-                                               }
-
-                                               strncpy(pType->param.szFileName, pUTF8Buff, nameLen);
-                                               strcat (pType->param.szFileName, pExt);
-                                       } else {
-                                               strncpy(pType->param.szFileName, pUTF8Buff, (MSG_FILENAME_LEN_MAX-1));
-                                       }
-                                       free(pUTF8Buff);
-                                       pUTF8Buff = NULL;
-
-                                       if (_MsgChangeSpace(pType->param.szFileName, &szSrc) == true)
-                                               strcpy(pType->param.szFileName, szSrc);
-
-                                       if (szSrc) {
-                                               free(szSrc);
-                                               szSrc = NULL;
-                                       }
-
-                                       // Remvoe '/', ex) Content-Type: image/gif; name="images/vf7.gif"
-                                       _MsgRemoveFilePath(pType->param.szFileName);
-                               } else {
-                                       MSG_DEBUG("_MsgParseParameter: MsgConvertLatin2UTF8FileName(%s) return NULL\n", pDec);
-                               }
-
-                               MSG_DEBUG("_MsgParseParameter: szFileName = %s \n", pType->param.szFileName);
-
-                               break;
-
-                       case MSG_PARAM_TYPE:
-
-                               /* type/subtype of root. Only if content-type is multipart/related */
-
-                               pType->param.type = _MsgGetCode(MSG_TYPE, pDec);
-                               MSG_DEBUG("_MsgParseParameter: type = %d \n", pType->param.type);
-
-                               break;
-
-                       case MSG_PARAM_START:
-
-                               /* Content-id. Only if content-type is multipart/related */
-
-                               memset (pType->param.szStart, 0, MSG_MSG_ID_LEN + 1);
-                               strncpy(pType->param.szStart, pDec, MSG_MSG_ID_LEN);
-
-                               MSG_DEBUG("_MsgParseParameter: szStart = %s \n", pType->param.szStart);
-
-                               break;
-
-                       case MSG_PARAM_START_INFO :
-
-                               /* Only if content-type is multipart/related */
-
-                               memset (pType->param.szStartInfo, 0, MSG_MSG_ID_LEN + 1);
-                               strncpy(pType->param.szStartInfo, pDec, MSG_MSG_ID_LEN);
-
-                               MSG_DEBUG("_MsgParseParameter: szStartInfo = %s \n", pType->param.szStartInfo);
-
-                               break;
-
-                       case MSG_PARAM_REPORT_TYPE :
-
-                               //  only used as parameter of Content-Type: multipart/report; report-type=delivery-status;
-
-                               if (pDec != NULL && strcasecmp(pDec, "delivery-status") == 0) {
-                                       pType->param.reportType = MSG_PARAM_REPORT_TYPE_DELIVERY_STATUS;
-                               } else {
-                                       pType->param.reportType = MSG_PARAM_REPORT_TYPE_UNKNOWN;
-                               }
-
-                               MSG_DEBUG("_MsgParseParameter: reportType = %s \n", pDec);
-                               break;
-
-                       default:
-
-                               MSG_DEBUG("_MsgParseParameter: Unknown paremeter (%s)\n", pDec);
-                               break;
-                       }
-
-                       if (pDec) {
-                               free(pDec);
-                               pDec = NULL;
-                       }
-               }
-               pSrc = pNextParam;
-       }
-       return true;
-}
-
-char *_MsgSkipWS(char *s)
-{
-       while (true) {
-               if ((*s == MSG_CH_CR) || (*s == MSG_CH_LF) || (*s == MSG_CH_SP) || (*s == MSG_CH_TAB)) {
-                       ++s;
-               } else if ((*s != '(') || (__MsgSkipComment(s,(long)NULL)==NULL)) {
-                       return s;
-               }
-       }
-}
-
-char *__MsgSkipComment (char *s,long trim)
-{
-
-       char *ret;
-       char *s1 = s;
-       char *t = NULL;
-
-       // ignore empty space
-       for (ret = ++s1; *ret == ' '; ret++)
-               ;
-
-       // handle '(', ')', '\',  '\0'
-       do {
-               switch (*s1) {
-               case '(':
-                       if (!__MsgSkipComment (s1,(long)NULL))
-                               return NULL;
-                       t = --s1;
-                       break;
-               case ')':
-                       s = ++s1;
-                       if (trim) {
-                               if (t) {
-                                       t[1] = '\0';
-                               } else {
-                                       *ret = '\0';
-                               }
-                       }
-                       return ret;
-               case '\\':
-                       if (*++s1)
-                               break;
-               case '\0':
-                       *s = '\0';
-                       return NULL;
-               case ' ':
-                       break;
-               default:
-                       t = s1;
-                       break;
-               }
-       }while (s1++);
-
-       return NULL;
-}
-
-char *MsgConvertLatin2UTF8FileName(char *pSrc)
-{
-       char *pUTF8Buff  = NULL;
-       char *pData = NULL;
-
-
-       //convert utf8 string
-       if (MsgIsUTF8String((unsigned char*)pSrc, strlen(pSrc)) == false) {
-               int length  = 0;
-               int utf8BufSize = 0;
-
-               length = strlen(pSrc);
-               utf8BufSize = MsgGetLatin2UTFCodeSize((unsigned char*)pSrc, length);
-               pUTF8Buff = (char *)malloc(utf8BufSize + 1);
-
-               if (pUTF8Buff == NULL) {
-                       MSG_DEBUG("MsgConvertLatin2UTF8FileName: pUTF8Buff alloc fail \n");
-                       goto __CATCH;
-               }
-
-               if (MsgLatin2UTF ((unsigned char*)pUTF8Buff, utf8BufSize + 1, (unsigned char*)pSrc, length) < 0) {
-                       MSG_DEBUG("MsgConvertLatin2UTF8FileName: MsgLatin2UTF fail \n");
-                       goto __CATCH;
-               }
-       } else {
-               int length = strlen(pSrc);
-               pUTF8Buff = (char *)calloc(1, length+1);
-
-               if (pUTF8Buff == NULL) {
-                       MSG_DEBUG("MsgConvertLatin2UTF8FileName: pUTF8Buff alloc fail \n");
-                       goto __CATCH;
-               }
-
-               memcpy(pUTF8Buff, pSrc, length);
-       }
-
-       //convert hex string
-       if (MsgIsPercentSign(pUTF8Buff) == true) {
-               pData = MsgChangeHexString(pUTF8Buff);
-               if (pData) {
-                       strcpy(pUTF8Buff, pData);
-                       free(pData);
-                       pData = NULL;
-               }
-       }
-
-       return pUTF8Buff;
-
-__CATCH:
-
-       if (pUTF8Buff) {
-               free(pUTF8Buff);
-               pUTF8Buff = NULL;
-       }
-       if (pData) {
-               free(pData);
-               pData = NULL;
-       }
-       return NULL;
-}
-
-bool _MsgChangeSpace(char *pOrg, char **ppNew)
-{
-       char *pNew = NULL;
-       int cLen = 0;
-       int cIndex =0;
-       int index = 0;
-
-       if (pOrg == NULL)
-               return false;
-
-       cLen = strlen(pOrg);
-
-       pNew = (char *)malloc(cLen + 1);
-       if (pNew == NULL)
-               return false;
-
-       memset(pNew, 0, cLen + 1);
-
-       for (cIndex=0; cIndex<cLen;cIndex++) {
-               if (pOrg[cIndex] == '%' && pOrg[cIndex+1] == '2' && pOrg[cIndex+2] == '0') {
-                       pNew[index] = ' ';
-                       index++;
-                       cIndex+= 2;
-                       continue;
-               }
-               pNew[index++] = pOrg[cIndex];
-       }
-
-       *ppNew = pNew;
-
-       return true;
-}
-
-void _MsgRemoveFilePath(char *pSrc)
-{
-       // Remvoe '/', ex) Content-Type: image/gif; name="images/vf7.gif"
-       char *pPath = NULL;
-       char *pTemp = NULL;
-       char szFileName[MSG_FILENAME_LEN_MAX] = {0};
-
-       if (pSrc == NULL)
-               return;
-
-       pTemp = pSrc;
-       while ((pTemp = strchr(pTemp, '/')) != NULL) {
-               // Find the last  '/'
-               pPath = pTemp;
-               pTemp++;
-       }
-
-       if (pPath) {
-               MSG_DEBUG("_MsgRemoveFilePath: filename(%s)\n", pSrc);
-
-               // case : images/vf7.gif -> vf7.gif
-               if (pPath != NULL && *(pPath+1) != '\0') {
-                       strncpy(szFileName, pPath+1, strlen(pPath+1));
-                       strncpy(pSrc, szFileName , strlen(szFileName));
-               }
-       }
-       // Remove additional file information
-       // ex) Content-type: application/octet-stream; name="060728gibson_210.jpg?size=s"
-       // if "?size=" exist, insert NULL char.
-       {
-               pTemp = strcasestr(pSrc, "?size=");
-               if (pTemp != NULL)
-                       *pTemp = '\0';
-       }
-}
-
-bool MsgIsUTF8String(unsigned char *szSrc, int nChar)
-{
-       MSG_DEBUG("MsgIsUTF8String: --------------- \n");
-
-       if (szSrc == NULL) {
-               MSG_DEBUG("MsgIsUTF8String: szSrc is NULL !!!! --------------- \n");
-               return true;
-       }
-
-       while (nChar > 0 && (*szSrc != '\0')) {
-               if (*szSrc < 0x80) {
-                       szSrc++;
-                       nChar--;
-               } else if ((0xC0 <= *szSrc) && (*szSrc < 0xE0)) {
-                       if (*(szSrc + 1) >= 0x80) {
-                               szSrc += 2;
-                               nChar -= 2;
-                       } else {
-                               MSG_DEBUG("MsgIsUTF8String: 1. NOT utf8 range!\n");
-                               goto __CATCH;
-                       }
-               } else if (*szSrc >= 0xE0) {
-                       if (*(szSrc + 1) >= 0x80) {
-                               if (*(szSrc + 2) >= 0x80) {
-                                       szSrc += 3;
-                                       nChar -= 3;
-                               } else {
-                                       MSG_DEBUG("MsgIsUTF8String: 2. NOT utf8 range!\n");
-                                       goto __CATCH;
-                               }
-                       } else {
-                               MSG_DEBUG("MsgIsUTF8String: 3. NOT utf8 range!\n");
-                               goto __CATCH;
-                       }
-               } else {
-                       MSG_DEBUG("MsgIsUTF8String: 4. NOT utf8 range!\n");
-                       goto __CATCH;
-               }
-       }
-
-       return true;
-
-__CATCH:
-       return false;
-}
-
-bool MsgIsPercentSign(char *pSrc)
-{
-       char *pCh = NULL;
-       bool bRet = false;
-
-       pCh = strchr(pSrc , '%');
-
-       if (pCh != NULL) {
-               bRet = true;
-       } else {
-               bRet = false;
-       }
-
-       return bRet;
-}
-
-MsgMultipart *MsgAllocMultipart(void)
-{
-       MsgMultipart *pMultipart = NULL;
-
-       MSG_DEBUG("MsgAllocMultipart: --------- \n");
-
-       pMultipart = (MsgMultipart*)malloc(sizeof(MsgMultipart));
-       if (pMultipart == NULL) {
-               MSG_DEBUG("MsgAllocMultipart: pMultipart malloc Fail \n");
-               goto __CATCH;
-       }
-
-       pMultipart->pBody = (MsgBody*)malloc(sizeof(MsgBody));
-       if (pMultipart->pBody == NULL) {
-               MSG_DEBUG("MsgAllocMultipart: pMultipart->pBody malloc Fail \n");
-               goto __CATCH;
-       }
-
-       _MsgInitMsgType(&pMultipart->type);
-       _MsgInitMsgBody(pMultipart->pBody);
-
-       pMultipart->pNext = NULL;
-
-       return pMultipart;
-
-__CATCH:
-
-       if (pMultipart) {
-               if (pMultipart->pBody) {
-                       free(pMultipart->pBody);
-                       pMultipart->pBody = NULL;
-               }
-
-               free(pMultipart);
-               pMultipart = NULL;
-       }
-
-       return NULL;
-}
-
-bool _MsgInitMsgType(MsgType *pMsgType)
-{
-       pMsgType->offset = 0;
-       pMsgType->size = 0;
-       pMsgType->contentSize = 0;
-       pMsgType->disposition = 0;
-       pMsgType->encoding = 0;
-       pMsgType->type = MIME_UNKNOWN;
-#ifdef FEATURE_JAVA_MMS_MIME
-       pMsgType->szMimeString[0] ='\0';
-#endif
-       pMsgType->section = 0;
-
-       pMsgType->szOrgFilePath[0] = '\0';
-       pMsgType->szContentID[0] = '\0';
-       pMsgType->szContentLocation[0] = '\0';
-
-       pMsgType->szContentRepPos[0] = '\0';
-       pMsgType->szContentRepSize[0] = '\0';
-       pMsgType->szContentRepIndex[0] = '\0';
-
-       __MsgInitMsgContentParam(&pMsgType->param);
-#ifdef __SUPPORT_DRM__
-       __MsgInitMsgDRMInfo(&pMsgType->drmInfo);
-#endif
-
-       return true;
-}
-
-
-bool __MsgInitMsgContentParam(MsgContentParam *pMsgContentParam)
-{
-       pMsgContentParam->charset = MSG_CHARSET_UNKNOWN;
-       pMsgContentParam->type = MIME_UNKNOWN;
-       pMsgContentParam->szBoundary[0] = '\0';
-       pMsgContentParam->szFileName[0] = '\0';
-       pMsgContentParam->szName[0] = '\0';
-#ifdef FEATURE_JAVA_MMS
-       pMsgContentParam->szApplicationID = NULL;
-       pMsgContentParam->szReplyToApplicationID = NULL;
-#endif
-       pMsgContentParam->szStart[0] = '\0';
-       pMsgContentParam->szStartInfo[0] = '\0';
-       pMsgContentParam->pPresentation = NULL;
-
-       pMsgContentParam->reportType = MSG_PARAM_REPORT_TYPE_UNKNOWN; //  add only used as parameter of Content-Type: multipart/report; report-type
-
-       return true;
-}
-
-
-bool _MsgInitMsgBody(MsgBody *pMsgBody)
-{
-       pMsgBody->offset = 0;
-       pMsgBody->size = 0;
-       pMsgBody->body.pText = NULL;
-       pMsgBody->szOrgFilePath[0] = '\0';
-
-       _MsgInitMsgType(&pMsgBody->presentationType);
-       pMsgBody->pPresentationBody = NULL;
-
-       memset(pMsgBody->szOrgFilePath, 0, MSG_FILEPATH_LEN_MAX);
-
-       return true;
-}
-
-
-MsgPresentationFactor MsgIsPresentationEx(MsgType *multipartType, char* szStart, MsgContentType typeParam)
-{
-       char szTmpStart[MSG_MSG_ID_LEN + 3] = { 0, };
-       char szTmpContentID[MSG_MSG_ID_LEN + 3] = { 0, };
-       char szTmpContentLO[MSG_MSG_ID_LEN + 3] = { 0, };
-       int strLen = 0;
-
-       // remove '<' and '>' in Start Param : contentID ex] <0_1.jpg> or <1233445>
-       if (szStart && szStart[0]) {
-               int startLen = 0;
-               startLen = strlen(szStart);
-               if (szStart[0] == '<' && szStart[startLen - 1] == '>') {
-                       strncpy(szTmpStart, &szStart[1], startLen - 2);
-               } else {
-                       strncpy(szTmpStart, szStart, startLen);
-               }
-       }
-
-       // remove '<' and '>' in ContentID : contentID ex] <0_1.jpg> or <1233445>
-       if (multipartType->szContentID[0])      {
-               strLen = strlen(multipartType->szContentID);
-               if (multipartType->szContentID[0] == '<' && multipartType->szContentID[strLen - 1] == '>') {
-                       strncpy(szTmpContentID, &(multipartType->szContentID[1]), strLen - 2);
-               } else {
-                       strncpy(szTmpContentID, multipartType->szContentID, strLen);
-               }
-       }
-
-       // remove '<' and '>' in ContentLocation : contentID ex] <0_1.jpg> or <1233445>
-       if (multipartType->szContentLocation[0]) {
-               strLen = strlen(multipartType->szContentLocation);
-               if (multipartType->szContentLocation[0] == '<' && multipartType->szContentLocation[strLen - 1] == '>') {
-                       strncpy(szTmpContentLO, &multipartType->szContentLocation[1], strLen - 2);
-               } else {
-                       strncpy(szTmpContentLO, multipartType->szContentLocation, strLen);
-               }
-       }
-
-       if ((szTmpContentID[0] == '\0') && (szTmpContentLO[0] == '\0') && (multipartType->type == MIME_UNKNOWN))
-               return  MSG_PRESENTATION_NONE;
-
-       // exception handling
-       if (szTmpStart[0] != '\0') {
-               // presentation part : 1.compare with contentID 2.compare with content Location 3. compare with type
-               if (strcmp(szTmpStart, szTmpContentID) == 0) {
-                       return MSG_PRESENTATION_ID;
-               } else if (strcmp(szTmpStart, szTmpContentLO) == 0) {
-                       return   MSG_PRESENTATION_LOCATION;
-               } else if (multipartType->type == typeParam) {
-                       return   MSG_PRESENTATION_TYPE_BASE;
-               } else {
-                       return   MSG_PRESENTATION_NONE;
-               }
-       } else {
-               if (multipartType->type == typeParam && typeParam != MIME_UNKNOWN) {
-                       return   MSG_PRESENTATION_TYPE_BASE;
-               } else {
-                       return   MSG_PRESENTATION_NONE;
-               }
-       }
-}
-
-void MsgConfirmPresentationPart(MsgType *pMsgType, MsgBody *pMsgBody, MsgPresentaionInfo *pPresentationInfo)
-{
-       MSG_BEGIN();
-       MsgMultipart *pNextPart = NULL;
-       MsgMultipart *pRemovePart = NULL;
-
-       if (MsgIsMultipartRelated(pMsgType->type)) {
-               // assign the multipart to presentation part
-               // remove the multipart(pCurPresentation) which is presentation part from the linked list.
-               // if there is no presentation part -> assign first multipart to presentation part by force.
-               if (pPresentationInfo->pCurPresentation == NULL) {
-                       pPresentationInfo->pCurPresentation     = pMsgBody->body.pMultipart;
-                       pPresentationInfo->pPrevPart            = NULL;
-                       pPresentationInfo->factor                       = MSG_PRESENTATION_NONE;
-               }
-
-               if (pPresentationInfo->pCurPresentation != NULL && MsgIsPresentablePart(pPresentationInfo->pCurPresentation->type.type)) {
-                       /* Presentable Part is some MARK-UP page, such as SMIL, HTML, WML, XHTML.
-                        * In this case, COPY the Presentation part and leave other multiparts.
-                        */
-                       memcpy(&pMsgBody->presentationType, &pPresentationInfo->pCurPresentation->type, sizeof(MsgType));
-                       pMsgBody->pPresentationBody = pPresentationInfo->pCurPresentation->pBody;
-
-                       // remove pCurPresentation from multipart linked list
-                       if ((pPresentationInfo->factor == MSG_PRESENTATION_NONE)||(pPresentationInfo->pPrevPart == NULL)) {
-                               // first part
-                               pMsgBody->body.pMultipart = pPresentationInfo->pCurPresentation->pNext;
-                               pMsgType->contentSize -= pPresentationInfo->pCurPresentation->pBody->size;
-                               pMsgBody->size -= pPresentationInfo->pCurPresentation->pBody->size;
-                               if (pPresentationInfo->pCurPresentation) {
-#ifdef __SUPPORT_DRM__
-                                       _MsgFreeDRMInfo(&pPresentationInfo->pCurPresentation->type.drmInfo);
-#endif
-                                       free(pPresentationInfo->pCurPresentation);
-                                       pPresentationInfo->pCurPresentation = NULL;
-                               }
-                       } else {
-                               // not a first part
-                               pPresentationInfo->pPrevPart->pNext = pPresentationInfo->pCurPresentation->pNext;
-                               pMsgType->contentSize -= pPresentationInfo->pCurPresentation->pBody->size;
-                               pMsgBody->size -= pPresentationInfo->pCurPresentation->pBody->size;
-                               if (pPresentationInfo->pCurPresentation) {
-                                       free(pPresentationInfo->pCurPresentation);
-                                       pPresentationInfo->pCurPresentation = NULL;
-                               }
-                       }
-               } else if (pPresentationInfo->pCurPresentation != NULL && MsgIsText(pPresentationInfo->pCurPresentation->type.type)) {
-                       /* NON-Presentable Part is some PLAIN part such as, text/plain, multipart/alternative.
-                        * In this case, leave the Presentation part as a multipart and remove other multiparts.
-                        */
-
-                       // Backup the multipart link information
-                       pNextPart = pMsgBody->body.pMultipart;
-
-                       // Copy presentation part as a main part
-                       memcpy(pMsgType, &pPresentationInfo->pCurPresentation->type, sizeof(MsgType));
-                       memcpy(pMsgBody, pPresentationInfo->pCurPresentation->pBody, sizeof(MsgBody));
-
-                       // Remove multipart linked list
-                       while (pNextPart) {
-                               pRemovePart = pNextPart;
-                               pNextPart = pNextPart->pNext;
-
-                               if (pRemovePart->pBody) {
-                                       _MsgFreeBody(pRemovePart->pBody, pRemovePart->type.type);
-                                       free(pRemovePart->pBody);
-                                       pRemovePart->pBody = NULL;
-                               }
-
-                               free(pRemovePart);
-                               pRemovePart = NULL;
-                       }
-               } else {
-#ifdef __SUPPORT_DRM__
-                       _MsgFreeDRMInfo(&pMsgBody->presentationType.drmInfo);
-#endif
-                       _MsgInitMsgType(&pMsgBody->presentationType);
-                       pMsgBody->pPresentationBody = NULL;
-               }
-       }
-       MSG_END();
-}
-
-bool MsgIsMultipartRelated(int type)
-{
-       if (type == MIME_MULTIPART_RELATED || type == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
-               return true;
-       } else {
-               return false;
-       }
-}
-
-bool MsgIsPresentablePart(int type)
-{
-       if (type == MIME_TEXT_HTML || type == MIME_TEXT_VND_WAP_WML || type == MIME_APPLICATION_SMIL) {
-               return true;
-       } else {
-               return false;
-       }
-}
-
-#ifdef __SUPPORT_DRM__
-void _MsgFreeDRMInfo(MsgDRMInfo *pDrmInfo)
-{
-       MSG_DEBUG("_MsgFreeDRMInfo: S T A R T  !!! \n");
-
-       if (pDrmInfo == NULL) {
-               MSG_DEBUG("pDrmInfo is NULL");
-               return;
-       }
-
-       if (pDrmInfo->szContentDescription) {
-               free(pDrmInfo->szContentDescription);
-               pDrmInfo->szContentDescription = NULL;
-       }
-
-       if (pDrmInfo->szContentVendor) {
-               free(pDrmInfo->szContentVendor);
-               pDrmInfo->szContentVendor = NULL;
-       }
-
-       if (pDrmInfo->szContentName) {
-               free(pDrmInfo->szContentName);
-               pDrmInfo->szContentName = NULL;
-       }
-
-       if (pDrmInfo->szContentURI) {
-               free(pDrmInfo->szContentURI);
-               pDrmInfo->szContentURI = NULL;
-       }
-
-       if (pDrmInfo->szRightIssuer) {
-               free(pDrmInfo->szRightIssuer);
-               pDrmInfo->szRightIssuer = NULL;
-       }
-
-       if (pDrmInfo->szDrm2FullPath) {
-               free(pDrmInfo->szDrm2FullPath);
-               pDrmInfo->szDrm2FullPath = NULL;
-       }
-
-#if MMS_ENABLE_EXTEND_CFM
-       // DRM (Extended)CFM
-       if (pDrmInfo->pszContentType) {
-               free(pDrmInfo->pszContentType);
-               pDrmInfo->pszContentType = NULL;
-       }
-#endif
-
-       pDrmInfo->contentType = MIME_UNKNOWN;
-       pDrmInfo->drmType = MSG_DRM_TYPE_NONE;
-}
-
-bool MsgCopyDrmInfo(MsgType *pPartType)
-{
-       char *pExt = NULL;
-       char *pTmpBuf = NULL;
-
-       //convert application/vnd.oma.drm.content to media type
-       pPartType->type = pPartType->drmInfo.contentType;
-
-       // fix wrong file name presentation on save media screen.
-       if (pPartType->szContentID[0] == '\0' && pPartType->drmInfo.szContentURI)
-               strncpy(pPartType->szContentID, pPartType->drmInfo.szContentURI, MSG_MSG_ID_LEN);
-
-       /* set title name (content name) */
-       if (pPartType->param.szName[0] == '\0') {
-               /*      szName is vitual name, real filename is *.dcf or *.dm   */
-               if (pPartType->drmInfo.szContentName && pPartType->drmInfo.szContentName[0] != '\0') {
-                       /* In case of szContentName retrieved from DRM agent is exist. */
-                       pTmpBuf = pPartType->drmInfo.szContentName;
-               } else if (pPartType->szContentLocation[0] != '\0')     {
-                       /* In case of szContentLocation parsed from MMS header */
-                       pTmpBuf = strrchr(pPartType->szContentLocation, '/');
-                       if (pTmpBuf == NULL)
-                               pTmpBuf = pPartType->szContentLocation;
-               } else {
-                       /* use another name */
-                       /* possible NULL pointer assignment*/
-                       pTmpBuf = strdup("untitled");
-               }
-
-               if ((pExt = strrchr(pTmpBuf, '.')) != NULL) {
-                       int extLen = 0;
-                       int fileNameLen = 0;
-                       int tmpLen = 0;
-
-                       extLen = strlen(pExt);
-                       tmpLen = strlen(pTmpBuf);
-                       fileNameLen = (tmpLen - extLen < MSG_LOCALE_FILENAME_LEN_MAX - extLen)?(tmpLen - extLen):(MSG_LOCALE_FILENAME_LEN_MAX - extLen);
-                       strncpy(pPartType->param.szName, pTmpBuf, fileNameLen);
-                       strcpy (pPartType->param.szName + fileNameLen, pExt);
-               } else {
-                       strncpy(pPartType->param.szName, pTmpBuf, MSG_LOCALE_FILENAME_LEN_MAX);
-                       MsgMakeFileName(pPartType->type, pPartType->param.szName, MSG_DRM_TYPE_NONE, 0);
-               }
-       }
-
-       return true;
-}
-
-#endif
-
-bool MsgIsText(int type)
-{
-       if (type == MIME_TEXT_PLAIN || type == MIME_TEXT_HTML || type == MIME_TEXT_VND_WAP_WML ||
-               type == MIME_TEXT_X_VNOTE || type == MIME_APPLICATION_SMIL || type == MIME_TEXT_X_IMELODY) {
-               return true;
-       } else {
-               return false;
-       }
-}
-
-bool MsgFreeAttrib(MmsAttrib *pAttrib)
-{
-       MSG_BEGIN();
-
-       if (pAttrib == NULL) {
-               MSG_DEBUG("pAttrib is NULL");
-               return false;
-       }
-
-       if (pAttrib->szTo) {
-               free(pAttrib->szTo);
-               pAttrib->szTo = NULL;
-       }
-
-       if (pAttrib->szCc) {
-               free(pAttrib->szCc);
-               pAttrib->szCc = NULL;
-       }
-
-       if (pAttrib->szBcc) {
-               free(pAttrib->szBcc);
-               pAttrib->szBcc = NULL;
-       }
-
-       //check if pMultiStatus should be freed or not, because pMultiStatus is not allocated
-       if (pAttrib->pMultiStatus) {
-               MmsMsgMultiStatus *pMultiStatus = pAttrib->pMultiStatus;
-               MmsMsgMultiStatus *pCurStatus = NULL;
-
-               while (pMultiStatus != NULL ) {
-                       pCurStatus = pMultiStatus;
-                       pMultiStatus = pMultiStatus->pNext;
-
-                       if (pCurStatus) {
-                               free(pCurStatus);
-                               pCurStatus = NULL;
-                       }
-               }
-
-               pAttrib->pMultiStatus = NULL;
-       }
-
-
-       MSG_END();
-
-       return true;
-}
-
-bool _MsgFreeBody(MsgBody *pBody, int type)
-{
-       MSG_DEBUG("_MsgFreeBody: S T A R T  !!! \n") ;
-
-       if (pBody == NULL) {
-               MSG_DEBUG("_MsgFreeBody: pBody == NULL \n" );
-               MSG_DEBUG("_MsgFreeBody: E  N  D   (End)!!! \n") ;
-
-               return false;
-       }
-
-       switch (type) {
-       case MIME_MULTIPART_REPORT:
-       case MIME_APPLICATION_VND_OMA_DRM_MESSAGE:
-       case MIME_APPLICATION_VND_WAP_MULTIPART_MIXED:
-       case MIME_APPLICATION_VND_WAP_MULTIPART_RELATED:
-       case MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC:
-       case MIME_MULTIPART_MIXED:
-       case MIME_MULTIPART_RELATED:
-       case MIME_MULTIPART_ALTERNATIVE:
-       case MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE:
-               {
-                       MsgMultipart *pMulti = pBody->body.pMultipart;
-                       MsgMultipart *pCurrPart = NULL;
-                       MsgBody *pPresentation = pBody->pPresentationBody;
-                       while (pMulti != NULL) {
-                               pCurrPart = pMulti;
-
-                               pMulti = pMulti->pNext;
-
-                               if (pCurrPart) {
-#ifdef __SUPPORT_DRM__
-                                       _MsgFreeDRMInfo(&pCurrPart->type.drmInfo);
-#endif
-
-                                       if (pCurrPart->pBody) {
-                                               if (pCurrPart->pBody->body.pBinary) {
-                                                       free(pCurrPart->pBody->body.pBinary);
-                                                       pCurrPart->pBody->body.pBinary = NULL;
-                                               }
-                                               free(pCurrPart->pBody);
-                                               pCurrPart->pBody = NULL;
-                                       }
-                                       free(pCurrPart);
-                                       pCurrPart = NULL;
-                               }
-                       }
-
-                       pBody->body.pMultipart = NULL;
-
-                       if (pPresentation) {
-                               if (pPresentation->body.pText) {
-                                       free(pPresentation->body.pText);
-                                       pPresentation->body.pText = NULL;
-                               }
-                               free(pPresentation);
-                               pBody->pPresentationBody = NULL;
-                       }
-
-                       _MsgInitMsgType(&pBody->presentationType);
-
-                       break;
-               }
-
-       default:
-               /* Any single part */
-
-               if (pBody->body.pBinary) {
-                       free(pBody->body.pBinary);
-                       pBody->body.pBinary = NULL;
-               }
-
-               break;
-       }
-
-       MSG_DEBUG("_MsgFreeBody: E  N  D  (Successfully) !!! \n") ;
-
-       return true;
-
-}
-
-bool MsgResolveNestedMultipart(MsgType *pPartType, MsgBody *pPartBody)
-{
-       MSG_BEGIN();
-       MsgMultipart *pTmpMultipart = NULL;
-       MsgMultipart *pSelectedPart = NULL;
-       MsgMultipart *pPrevPart = NULL;
-       MsgMultipart *pFirstPart = NULL;
-       MsgMultipart *pLastPart = NULL;
-       MsgMultipart *pRemoveList = NULL;
-       MsgMultipart *pNextRemovePart = NULL;
-
-       switch (pPartType->type) {
-       case MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE:
-       case MIME_MULTIPART_ALTERNATIVE:
-
-               /*
-                * Policy: multipart/alternative
-                * multipart/alternative message has only several parts of media.
-                * You should choose one of them and make the alternative part
-                * to the selected media part.
-                */
-
-               MSG_DEBUG("MsgResolveNestedMultipart : MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE\n");
-
-               pSelectedPart = pPartBody->body.pMultipart;
-
-               // NULL Pointer check!!
-               if (pSelectedPart == NULL) {
-                       MSG_DEBUG("MsgResolveNestedMultipart : multipart(ALTERNATIVE) does not exist\n");
-                       break;
-               }
-
-               pTmpMultipart = pPartBody->body.pMultipart->pNext;
-
-               while (pTmpMultipart) {
-                       if (pSelectedPart->type.type <= pTmpMultipart->type.type)
-                               pSelectedPart = pTmpMultipart;
-
-                       pTmpMultipart = pTmpMultipart->pNext;
-               }
-
-               pTmpMultipart = pPartBody->body.pMultipart;
-               pPrevPart = NULL;
-
-               while (pTmpMultipart) {
-                       if (pSelectedPart == pTmpMultipart)
-                               break;
-
-                       pPrevPart = pTmpMultipart;
-                       pTmpMultipart = pTmpMultipart->pNext;
-               }
-
-               if (pPrevPart == NULL) {
-                       /* selected part is the first part */
-                       pRemoveList = pSelectedPart->pNext;
-               } else {
-                       pPrevPart->pNext = pSelectedPart->pNext;
-                       pRemoveList = pPartBody->body.pMultipart;
-                       pPartBody->body.pMultipart = pSelectedPart;
-               }
-
-               pSelectedPart->pNext = NULL;
-
-               if (pRemoveList) {
-#ifdef __SUPPORT_DRM__
-                       _MsgFreeDRMInfo(&pRemoveList->type.drmInfo);
-#endif
-                       _MsgFreeBody(pRemoveList->pBody, pRemoveList->type.type);
-
-                       free(pRemoveList->pBody);
-                       free(pRemoveList);
-               }
-
-               if (MsgCopyNestedMsgType(pPartType, &(pSelectedPart->type)) == false) {
-                       MSG_DEBUG("MsgResolveNestedMultipart : MsgPriorityCopyMsgType failed \n");
-                       goto __CATCH;
-               }
-
-               if (pSelectedPart->pBody != NULL)
-                       memcpy(pPartBody, pSelectedPart->pBody, sizeof(MsgBody));
-
-               if (pSelectedPart != NULL) {
-#ifdef __SUPPORT_DRM__
-                       _MsgFreeDRMInfo(&pSelectedPart->type.drmInfo);
-#endif
-
-                       if (pSelectedPart->pBody != NULL) {
-                               free(pSelectedPart->pBody);
-                               pSelectedPart->pBody = NULL;
-                       }
-                       free(pSelectedPart);
-                       pSelectedPart = NULL;
-               }
-
-               break;
-
-       case MIME_APPLICATION_VND_WAP_MULTIPART_RELATED:
-       case MIME_MULTIPART_RELATED:
-
-               MSG_DEBUG("MsgResolveNestedMultipart : MIME_APPLICATION_VND_WAP_MULTIPART_RELATED\n");
-
-               pSelectedPart = pPartBody->body.pMultipart;
-
-               while (pSelectedPart) {
-                       if (MsgIsMultipartMixed(pSelectedPart->type.type)) {
-
-                               if (pSelectedPart->pBody == NULL) {
-                                       MSG_DEBUG("MsgResolveNestedMultipart :pSelectedPart->pBody(1) is NULL\n");
-                                       break;
-                               }
-
-                               pFirstPart = pSelectedPart->pBody->body.pMultipart;
-
-                               if (pFirstPart == NULL) {
-                                       MSG_DEBUG("MsgResolveNestedMultipart : multipart(RELATED) does not exist\n");
-                                       break;
-                               }
-
-                               if (pFirstPart->pNext) {
-                                       pLastPart = pFirstPart->pNext;
-                                       while (pLastPart->pNext)
-                                               pLastPart = pLastPart->pNext;
-                               } else {
-                                       pLastPart = pFirstPart;
-                               }
-
-                               if (pPrevPart == NULL) {
-                                       /* the first part */
-                                       pTmpMultipart = pPartBody->body.pMultipart->pNext;
-                                       pPartBody->body.pMultipart = pFirstPart;
-                                       pLastPart->pNext = pTmpMultipart;
-                               } else {
-                                       pTmpMultipart = pSelectedPart->pNext;
-                                       pPrevPart->pNext = pFirstPart;
-                                       pLastPart->pNext = pTmpMultipart;
-                               }
-
-                               if (pSelectedPart) {
-#ifdef __SUPPORT_DRM__
-                                       _MsgFreeDRMInfo(&pSelectedPart->type.drmInfo);
-#endif
-                                       free(pSelectedPart->pBody);
-                                       free(pSelectedPart);
-                               }
-                               pSelectedPart = pTmpMultipart;
-                       } else if (MsgIsMultipartRelated(pSelectedPart->type.type) && pPrevPart != NULL) {
-                               pPrevPart->pNext = pTmpMultipart = pSelectedPart->pNext;
-                               _MsgFreeBody(pSelectedPart->pBody, pSelectedPart->type.type);
-
-                               free(pSelectedPart->pBody);
-                               free(pSelectedPart);
-                               pSelectedPart = pTmpMultipart;
-                       } else {
-                               pPrevPart = pSelectedPart;
-                               pSelectedPart = pSelectedPart->pNext;
-                       }
-               }
-
-               break;
-
-
-       case MIME_APPLICATION_VND_WAP_MULTIPART_MIXED:
-       case MIME_MULTIPART_MIXED:
-
-               MSG_DEBUG("MsgResolveNestedMultipart : MIME_APPLICATION_VND_WAP_MULTIPART_MIXED\n");
-
-               pPrevPart = NULL;
-               pSelectedPart = pPartBody->body.pMultipart;
-
-               while (pSelectedPart) {
-                       if (MsgIsMultipart(pSelectedPart->type.type)) {
-                               if (pSelectedPart->pBody == NULL) {
-                                       MSG_DEBUG("MsgResolveNestedMultipart :pSelectedPart->pBody(2) is NULL\n");
-                                       break;
-                               }
-
-                               pFirstPart = pSelectedPart->pBody->body.pMultipart;
-
-                               // NULL Pointer check!!
-                               if (pFirstPart == NULL) {
-                                       MSG_DEBUG("MsgResolveNestedMultipart : multipart does not exist\n");
-                                       break;
-                               }
-
-                               if (pFirstPart->pNext) {
-                                       pLastPart = pFirstPart->pNext;
-                                       while (pLastPart->pNext)
-                                               pLastPart = pLastPart->pNext;
-                               } else {
-                                       pLastPart = pFirstPart;
-                               }
-
-                               if (pPrevPart == NULL) {
-                                       /* the first part */
-                                       pTmpMultipart = pPartBody->body.pMultipart->pNext;
-                                       pPartBody->body.pMultipart = pFirstPart;
-                                       pLastPart->pNext = pTmpMultipart;
-                               } else {
-                                       pTmpMultipart = pSelectedPart->pNext;
-                                       pPrevPart->pNext = pFirstPart;
-                                       pLastPart->pNext = pTmpMultipart;
-                               }
-
-                               if (pSelectedPart->pBody->pPresentationBody)
-                                       pPartBody->pPresentationBody = pSelectedPart->pBody->pPresentationBody;
-
-                               memcpy(&pPartBody->presentationType,
-                                                 &pSelectedPart->pBody->presentationType, sizeof(MsgType));
-
-                               pPartType->type = pSelectedPart->type.type;
-
-#ifdef __SUPPORT_DRM__
-                               _MsgFreeDRMInfo(&pSelectedPart->type.drmInfo);
-#endif
-                               free(pSelectedPart->pBody);
-                               free(pSelectedPart);
-
-                               pSelectedPart = pTmpMultipart;
-                       } else {
-                               pPrevPart = pSelectedPart;
-                               pSelectedPart = pSelectedPart->pNext;
-                       }
-               }
-
-               break;
-
-       case MIME_MULTIPART_REPORT:
-
-               MSG_DEBUG("MsgResolveNestedMultipart : MIME_MULTIPART_REPORT \n");
-
-               pTmpMultipart = pPartBody->body.pMultipart;
-               pPrevPart = NULL;
-
-               if (pTmpMultipart == NULL) {
-                       MSG_DEBUG("MsgResolveNestedMultipart : pTmpMultipart == NULL \n");
-                       return false;
-               }
-
-               while (pTmpMultipart) {
-                       if (pTmpMultipart->type.type == MIME_TEXT_PLAIN) {
-                               pSelectedPart = pTmpMultipart;
-                               break;
-                       }
-
-                       pPrevPart = pTmpMultipart;
-                       pTmpMultipart = pTmpMultipart->pNext;
-               }
-
-               if (pSelectedPart == NULL) {
-                       MSG_DEBUG("MsgResolveNestedMultipart : MIME_MULTIPART_REPORT [no selected part]\n");
-                       MSG_DEBUG("MsgResolveNestedMultipart : MIME_MULTIPART_REPORT [no selected part]\n");
-
-                       pRemoveList = pPartBody->body.pMultipart->pNext;
-                       pSelectedPart = pPartBody->body.pMultipart;
-                       pSelectedPart->pNext = NULL;
-               } else {
-                       if (pPrevPart == NULL) {
-                               // first part is selected
-                               pRemoveList = pPartBody->body.pMultipart->pNext;
-                       } else {
-                               pRemoveList = pPartBody->body.pMultipart->pNext;
-                               pPrevPart->pNext = pSelectedPart->pNext;
-                       }
-
-                       pSelectedPart->pNext = NULL;
-                       pPartBody->body.pMultipart = pSelectedPart;
-               }
-
-               pTmpMultipart = pRemoveList;
-
-               while (pTmpMultipart) {
-#ifdef __SUPPORT_DRM__
-                       _MsgFreeDRMInfo(&pTmpMultipart->type.drmInfo);
-#endif
-                       _MsgFreeBody(pTmpMultipart->pBody, pTmpMultipart->type.type);
-                       pNextRemovePart = pTmpMultipart->pNext;
-
-                       free(pTmpMultipart->pBody);
-                       free(pTmpMultipart);
-                       pTmpMultipart = pNextRemovePart;
-               }
-
-               if (MsgCopyNestedMsgType(pPartType, &(pSelectedPart->type)) == false) {
-                       MSG_DEBUG("MsgResolveNestedMultipart : MsgPriorityCopyMsgType failed \n");
-                       goto __CATCH;
-               }
-
-               if (pSelectedPart->pBody != NULL)
-                       memcpy(pPartBody, pSelectedPart->pBody, sizeof(MsgBody));
-
-               if (pSelectedPart != NULL) {
-#ifdef __SUPPORT_DRM__
-                       _MsgFreeDRMInfo(&pSelectedPart->type.drmInfo);
-#endif
-                       if (pSelectedPart->pBody != NULL) {
-                               free(pSelectedPart->pBody);
-                               pSelectedPart->pBody = NULL;
-                       }
-                       free(pSelectedPart);
-                       pSelectedPart = NULL;
-               }
-
-               break;
-
-       default:
-               break;
-       }
-       MSG_END();
-
-       return true;
-
-__CATCH:
-       return false;
-
-}
-
-char *MsgResolveContentURI(char *szSrc)
-{
-       char *szTemp = NULL;
-       char *szReturn = NULL;
-       int length = 0;
-
-       if (szSrc == NULL) {
-               goto __CATCH;
-       }
-
-       if (szSrc[0] == '\0')
-               goto __CATCH;
-
-
-       if (!strncasecmp(szSrc, "cid:", 4)) {
-               length = strlen(szSrc) - 3;
-               szSrc += 4;
-       } else {
-               length = strlen(szSrc) + 1;
-       }
-
-       szTemp = (char *)malloc(length);
-       if (szTemp == NULL) {
-               MSG_DEBUG("MsgResolveContentURI: memory full\n");
-               goto __CATCH;
-       }
-
-       memset(szTemp, 0, length);
-       strcpy(szTemp, szSrc);
-
-       szReturn = MsgChangeHexString(szTemp);
-
-       if (szTemp) {
-               free(szTemp);
-               szTemp = NULL;
-       }
-
-       return szReturn;
-
-__CATCH:
-       if (szTemp) {
-               free(szTemp);
-               szTemp = NULL;
-       }
-
-       return NULL;
-}
-
-bool _MsgParsePartHeader(MsgType *pType, const char *pRawData, int nRawData)
-{
-       char ch = '\0';
-       int cRaw = nRawData;
-       char *pFieldLine = NULL;
-       char *pFieldValue = NULL;
-       char *szFieldValue = NULL;
-       char *szSrc = NULL;
-       int nLen = 0;
-       char fieldLine[MSG_LINE_LEN] = {0, }; //temporary line buffer
-       int length = 0;
-
-       char szTempBuf[MSG_LOCAL_TEMP_BUF_SIZE];
-
-       while ((cRaw > 0) && *pRawData != MSG_CH_LF) {
-               memset(fieldLine, 0, MSG_LINE_LEN);
-               pFieldLine = fieldLine;
-
-               ch = MSG_CH_SP; //remember previous character.
-
-               while (ch) {
-                       switch (ch = *pRawData++) {
-                       case MSG_CH_CR: //'\r'
-                               if (*pRawData == MSG_CH_LF)
-                                       break;
-
-                       case MSG_CH_LF: //'\n'
-                               if (*pRawData != MSG_CH_SP && *pRawData != MSG_CH_TAB) {
-                                       ch = MSG_CH_NULL;
-                                       *pFieldLine = ch;
-                                       pFieldLine++;
-                               }
-                               break;
-
-                       case MSG_CH_TAB: //'\t'
-                               *pFieldLine = MSG_CH_SP;
-                               pFieldLine++;
-                               break;
-
-                       default:
-                               *pFieldLine = ch;
-                               pFieldLine++;
-                               break;
-                       }
-
-                       if (--cRaw <= 0) {  //If is the last character of header
-                               *pFieldLine = MSG_CH_NULL;
-                               pFieldLine++;
-                       }
-               }
-
-
-               if ((pFieldValue =  strchr(fieldLine, MSG_CH_COLON)) != NULL) {
-                       char*   pTemp = pFieldValue;
-                       char*   pValue = NULL;
-
-                       *pFieldValue++ = MSG_CH_NULL; //remove ':'
-
-                       while (*pFieldValue == MSG_CH_SP) //remove space ' '
-                               pFieldValue++;
-
-                       while ((fieldLine < pTemp--) && (*pTemp == MSG_CH_SP))
-                               *pTemp = MSG_CH_NULL;
-
-                       nLen = strlen(pFieldValue);
-
-                       if (nLen >= MSG_LOCAL_TEMP_BUF_SIZE) {
-                               szFieldValue = (char *)malloc(nLen + 1);
-                               memset(szFieldValue, 0 , nLen + 1);
-                               memcpy(szFieldValue, pFieldValue, nLen + 1);
-                       } else {
-                               memset(szTempBuf, 0, MSG_LOCAL_TEMP_BUF_SIZE);
-                               strcpy(szTempBuf, pFieldValue);
-                               szFieldValue = szTempBuf;
-                       }
-
-                       if (MsgStrcpyWithoutCRLF(szFieldValue, &szSrc) == true) {
-                               if (szSrc != NULL)
-                                       strncpy(szFieldValue, szSrc, strlen(szSrc));
-                       }
-                       if (szSrc) {
-                               free(szSrc);
-                               szSrc = NULL;
-                       }
-
-                       switch (_MsgGetCode(MSG_FIELD, fieldLine)) {
-                       case MSG_FIELD_CONTENT_ID:
-                               if ((pTemp = strchr(szFieldValue, MSG_CH_SEMICOLON)) != NULL)
-                                       *pTemp++ = MSG_CH_NULL;
-
-                               pValue = _MsgDecodeText(szFieldValue);
-                               memset (pType->szContentID, 0, MSG_MSG_ID_LEN + 1);
-
-                               if (pValue) {
-                                       // support CD & SD
-                                       length = MsgStrlen(pValue);
-                                       if (pValue[0] == '<' && pValue[length-1] == '>') {
-                                               strncpy(pType->szContentID, pValue + 1, length - 2);
-                                       } else {
-                                               strncpy(pType->szContentID, pValue, MSG_MSG_ID_LEN);
-                                       }
-
-                                       MSG_DEBUG("_MsgParsePartHeader: Content-ID = %s     %s\n", pFieldValue, pType->szContentID);
-
-                                       if (pTemp != NULL)
-                                               _MsgParseParameter(pType, pTemp);
-
-                                       free(pValue);
-                                       pValue = NULL;
-                               }
-
-                               break;
-
-                       case MSG_FIELD_CONTENT_LOCATION:
-                               if ((pTemp = strchr(szFieldValue, MSG_CH_SEMICOLON)) != NULL)
-                                       *pTemp++ = MSG_CH_NULL;
-
-                               pValue = _MsgDecodeText(szFieldValue);
-                               memset (pType->szContentLocation, 0, MSG_MSG_ID_LEN + 1);
-
-                               if (pValue) {
-                                       strncpy(pType->szContentLocation, pValue, MSG_MSG_ID_LEN);
-
-                                       MSG_DEBUG("_MsgParsePartHeader: Content-Location = %s     %s\n", pFieldValue, pType->szContentLocation);
-
-                                       if (pTemp != NULL)
-                                               _MsgParseParameter(pType, pTemp);
-
-                                       free(pValue);
-                                       pValue = NULL;
-                               }
-
-                               break;
-
-                       case MSG_FIELD_CONTENT_TYPE:
-                               if ((pTemp = strchr(szFieldValue, MSG_CH_SEMICOLON)) == NULL) {
-                                       if ((pTemp = strchr(szFieldValue, MSG_CH_SP)) != NULL)
-                                               *pTemp++ = MSG_CH_NULL;
-                               } else {
-                                       *pTemp++ = MSG_CH_NULL;
-                               }
-
-                               pType->type = _MsgGetCode(MSG_TYPE, szFieldValue);
-
-                               MSG_DEBUG("_MsgParsePartHeader: Content-Type = %s     %d\n", pFieldValue, pType->type);
-
-                               if (pType->type == INVALID_HOBJ)
-                                       pType->type = MIME_UNKNOWN;
-
-                               if (pTemp != NULL)
-                                       _MsgParseParameter(pType, pTemp);
-
-                               break;
-
-                       case MSG_FIELD_CONTENT_TRANSFER_ENCODING:
-                               if ((pTemp = strchr(szFieldValue, MSG_CH_SEMICOLON)) == NULL) {
-                                       if ((pTemp = strchr(szFieldValue, MSG_CH_SP)) != NULL)
-                                               *pTemp++ = MSG_CH_NULL;
-                               } else {
-                                       *pTemp++ = MSG_CH_NULL;
-                               }
-
-                               pType->encoding = _MsgGetCode(MSG_ENCODING, szFieldValue);
-
-                               MSG_DEBUG("_MsgParsePartHeader: Content-Encoding = %s     %d\n", pFieldValue, pType->encoding);
-
-                               if (pTemp != NULL)
-                                       _MsgParseParameter(pType, pTemp);
-
-                               break;
-
-                       case MSG_FIELD_CONTENT_DISPOSITION:
-                               if ((pTemp = strchr(szFieldValue, MSG_CH_SEMICOLON)) == NULL) {
-                                       if ((pTemp = strchr(szFieldValue, MSG_CH_SP)) != NULL)
-                                               *pTemp++ = MSG_CH_NULL;
-                               } else {
-                                       *pTemp++ = MSG_CH_NULL;
-                               }
-
-                               pType->disposition = _MsgGetCode(MSG_DISPOSITION, szFieldValue);
-
-                               MSG_DEBUG("_MsgParsePartHeader: Content-Disposition = %s     %d\n", pFieldValue, pType->disposition);
-
-                               if (pTemp != NULL)
-                                       _MsgParseParameter(pType, pTemp);
-
-                               break;
-
-#ifdef __SUPPORT_DRM__
-
-                       case MSG_FIELD_CONTENT_NAME:
-                               /* add to parse DCF header such as,
-                                * Right-Issuer, Content-Name, and Content-Description.
-                                */
-                               MsgMIMERemoveQuote(szFieldValue);
-                               pType->drmInfo.szContentName = MsgStrCopy(szFieldValue);
-                               break;
-
-                       case MSG_FIELD_CONTENT_DESCRIPTION:
-                               MsgMIMERemoveQuote(szFieldValue);
-                               pType->drmInfo.szContentDescription = MsgStrCopy(szFieldValue);
-                               break;
-
-                       case MSG_FIELD_CONTENT_VENDOR:
-                               MsgMIMERemoveQuote(szFieldValue);
-                               pType->drmInfo.szContentVendor = MsgStrCopy(szFieldValue);
-                               break;
-
-                       case MSG_FIELD_RIGHT_ISSUER:
-                               MsgMIMERemoveQuote(szFieldValue);
-                               pType->drmInfo.szRightIssuer = MsgStrCopy(szFieldValue);
-                               break;
-
-
-                       case MSG_FIELD_DRM_CONVERTED:
-                               MsgMIMERemoveQuote(szFieldValue);
-                               pType->nDrmConvertedStatus = atoi(szFieldValue);
-                               break;
-
-#endif
-                       case MSG_FILED_CONTENT_REPLACE_POS:
-                               MsgMIMERemoveQuote(szFieldValue);
-                               strncpy(pType->szContentRepPos, szFieldValue, sizeof(pType->szContentRepPos));
-                               break;
-
-                       case MSG_FILED_CONTENT_REPLACE_SIZE:
-                               MsgMIMERemoveQuote(szFieldValue);
-                               strncpy(pType->szContentRepSize, szFieldValue, sizeof(pType->szContentRepSize));
-                               break;
-
-                       case MSG_FILED_CONTENT_REPLACE_INDEX:
-                               MsgMIMERemoveQuote(szFieldValue);
-                               strncpy(pType->szContentRepIndex, szFieldValue, sizeof(pType->szContentRepIndex));
-                               break;
-
-                       default:
-                               MSG_DEBUG("_MsgParsePartHeader: Unhandled field \n");
-                               break;
-                       }
-               }
-
-               if (szFieldValue != NULL && szFieldValue != szTempBuf) {
-                       free(szFieldValue);
-                       szFieldValue = NULL;
-               }
-
-       }
-
-       return true;
-}
-
-char *MsgRemoveQuoteFromFilename(char *pSrc)
-{
-       int cLen = 0;   // length of pBuff
-       char *pBuff = NULL;
-
-       if (pSrc == NULL) {
-               MSG_DEBUG("MsgRemoveQuoteFromFilename: pSrc is Null\n");
-               return NULL;
-       }
-
-       cLen = strlen(pSrc);
-
-       pBuff = (char *)malloc(cLen + 1);
-
-       if (pBuff == NULL) {
-               MSG_DEBUG("MsgRemoveQuoteFromFilename: pBuff mem alloc fail!\n");
-               return NULL;
-       }
-       memset(pBuff, 0 , sizeof(char)*(cLen + 1));
-
-       // remove front quote
-       if (pSrc[0] == MSG_CH_QUOT) {
-               cLen--;
-               strncpy(pBuff, &pSrc[1], cLen);
-               pBuff[cLen] = '\0';
-       }
-
-       if (pSrc[0] == MSG_CH_LF) {
-               cLen--;
-               strncpy(pBuff, &pSrc[1], cLen);
-       } else {
-               strcpy(pBuff, pSrc);
-       }
-
-       // remove last qoute
-       if (pBuff[cLen-1] == MSG_CH_QUOT) {
-               pBuff[cLen-1] = '\0';
-       }
-
-       return pBuff;
-}
-
-bool MsgIsMultipart(int type)
-{
-       if (type == MIME_MULTIPART_RELATED || type == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED ||
-               type == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED || type == MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC ||
-               type == MIME_MULTIPART_MIXED || type == MIME_MULTIPART_REPORT) {
-               return true;
-       } else {
-               return false;
-       }
-}
-
-
-bool MsgIsHexChar(char *pSrc)
-{
-       int cIndex = 0;
-       int cLen = 0;
-       bool bRet = false;
-
-       cLen = strlen(pSrc);
-
-       for (cIndex = 0; cIndex < cLen ; cIndex++) {
-               if ((pSrc[cIndex] >= '0' && pSrc[cIndex] <= '9') || (pSrc[cIndex] >= 'A'&& pSrc[cIndex] <= 'F') ||
-                       (pSrc[cIndex] >= 'a' && pSrc[cIndex] <= 'f')) {
-                       bRet = true;
-               } else {
-                       return false;
-               }
-       }
-
-       return bRet;
-}
-
-char _MsgConvertHexValue(char *pSrc)
-{
-       int ch = 0;
-       int cIndex = 0;
-       int cLen = 0;
-       char ResultChar;
-       unsigned char uCh[2] = {0,};
-
-       cLen = strlen(pSrc);
-
-       for (cIndex = 0; cIndex < cLen ; cIndex += 2) {
-               uCh[0] = __MsgConvertCharToInt(pSrc[cIndex]);
-               uCh[1] = __MsgConvertCharToInt(pSrc[cIndex+1]);
-               ch = (int)uCh[0]<<4|uCh[1];
-       }
 
-       ResultChar = (char)ch;
+                       MmsReleaseMsgDRMInfo(&pMsgBody->presentationType.drmInfo);
 
-       return ResultChar;
+                       MmsInitMsgType(&pMsgBody->presentationType);
+                       pMsgBody->pPresentationBody = NULL;
+               }
+       }
+       MSG_END();
 }
 
-int __MsgConvertCharToInt(char ch)
+static bool __MsgIsMultipartRelated(int type)
 {
-       if (ch>='0' && ch<='9') {
-               return ch - '0';
-       } else if (ch>='a'&& ch <='f') {
-               return ch -'a'+10;
-       } else if (ch>='A'&& ch <='F') {
-               return ch -'A'+10;
+       if (type == MIME_MULTIPART_RELATED || type == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
+               return true;
        } else {
-               return 0;
+               return false;
        }
 }
 
-bool MsgCopyNestedMsgType(MsgType *pMsgType1, MsgType *pMsgType2)
+static bool __MsgIsPresentablePart(int type)
 {
-       if (pMsgType1->section == INVALID_HOBJ)
-               pMsgType1->section = pMsgType2->section;
-
-#ifdef __SUPPORT_DRM__
-       int             length = 0;
-
-       if (pMsgType1->drmInfo.drmType == MSG_DRM_TYPE_NONE)
-               pMsgType1->drmInfo.drmType = pMsgType2->drmInfo.drmType;
-
-
-       if (pMsgType1->szContentID[0] == '\0') {
-               strcpy(pMsgType1->szContentID, pMsgType2->szContentID);
-
-               if (pMsgType2->szContentID[0]) {
-                       length = MsgStrlen(pMsgType2->szContentID);
-                       if (pMsgType2->szContentID[0] == '<' && pMsgType2->szContentID[length - 1] == '>') {
-                               pMsgType1->drmInfo.szContentURI = MsgStrNCopy(pMsgType2->szContentID + 1, length - 2);
-                       } else {
-                               pMsgType1->drmInfo.szContentURI = MsgStrCopy(pMsgType2->szContentID);
-                       }
-               }
+       if (type == MIME_TEXT_HTML || type == MIME_TEXT_VND_WAP_WML || type == MIME_APPLICATION_SMIL) {
+               return true;
        } else {
-               length = MsgStrlen(pMsgType1->szContentID);
-               if (pMsgType1->szContentID[0] == '<' && pMsgType1->szContentID[length - 1] == '>') {
-                       pMsgType1->drmInfo.szContentURI = MsgStrNCopy(pMsgType1->szContentID + 1, length - 2);
-               } else {
-                       pMsgType1->drmInfo.szContentURI = MsgStrCopy(pMsgType1->szContentID);
-               }
+               return false;
        }
-#endif
-
-       if (pMsgType1->szContentLocation[0] == '\0')
-               strcpy(pMsgType1->szContentLocation, pMsgType2->szContentLocation);
-
-       /* Copy informations - we shoud open the pMsgType2's orgFile
-        * concerning its offset and size.
-        */
-       if (pMsgType2->szOrgFilePath[0] != '\0')
-               strcpy(pMsgType1->szOrgFilePath, pMsgType2->szOrgFilePath);
-
-       if (pMsgType2->disposition != INVALID_HOBJ)
-               pMsgType1->disposition = pMsgType2->disposition;
+}
 
-       if ((pMsgType1->type != MIME_APPLICATION_VND_OMA_DRM_MESSAGE && pMsgType1->type != MIME_APPLICATION_VND_OMA_DRM_CONTENT) &&
-                pMsgType2->encoding != INVALID_HOBJ)
-               pMsgType1->encoding = pMsgType2->encoding;
+static bool __MsgResolveNestedMultipart(MsgType *pPartType, MsgBody *pPartBody)
+{
+       MSG_BEGIN();
+       MsgMultipart *pTmpMultipart = NULL;
+       MsgMultipart *pSelectedPart = NULL;
+       MsgMultipart *pPrevPart = NULL;
+       MsgMultipart *pFirstPart = NULL;
+       MsgMultipart *pLastPart = NULL;
+       MsgMultipart *pRemoveList = NULL;
+       MsgMultipart *pNextRemovePart = NULL;
 
-       pMsgType1->contentSize = pMsgType2->contentSize;
-       pMsgType1->offset = pMsgType2->offset;
-       pMsgType1->size = pMsgType2->size;
-       pMsgType1->type = pMsgType2->type;
+       switch (pPartType->type) {
+       case MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE:
+       case MIME_MULTIPART_ALTERNATIVE:
 
-       MsgCopyNestedMsgParam(&(pMsgType1->param), &(pMsgType2->param));
+               /* fixme:
+                * Policy: multipart/alternative
+                * multipart/alternative message has only several parts of media.
+                * You should choose one of them and make the alternative part
+                * to the selected media part.
+                */
 
-       if (pMsgType1->param.szName[0]) {
-#ifdef __SUPPORT_DRM__
-               pMsgType1->drmInfo.szContentName = MsgStrCopy(pMsgType2->param.szName);
-#endif
-       }
+               MSG_DEBUG("MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE");
 
-       return true;
-}
+               pSelectedPart = pPartBody->body.pMultipart;
 
+               // NULL Pointer check!!
+               if (pSelectedPart == NULL) {
+                       MSG_DEBUG("multipart(ALTERNATIVE) does not exist");
+                       break;
+               }
 
-bool MsgCopyNestedMsgParam(MsgContentParam *pParam1, MsgContentParam *pParam2)
-{
-       if (pParam1->charset == MSG_CHARSET_UNKNOWN)
-               pParam1->charset = pParam2->charset;
+               pTmpMultipart = pPartBody->body.pMultipart->pNext;
 
-       if (pParam1->type == MIME_UNKNOWN)
-               pParam1->type = pParam2->type;
+               while (pTmpMultipart) {
+                       if (pSelectedPart->type.type <= pTmpMultipart->type.type)
+                               pSelectedPart = pTmpMultipart;
 
-       /* Don't copy pParam2->pPresentation */
+                       pTmpMultipart = pTmpMultipart->pNext;
+               }
 
-       /* For alternative: copy the boundary string */
-       if (pParam2->szBoundary[0] !='\0')
-               strcpy(pParam1->szBoundary, pParam2->szBoundary);
+               pTmpMultipart = pPartBody->body.pMultipart;
+               pPrevPart = NULL;
 
-       if (pParam1->szFileName[0] =='\0')
-               strcpy(pParam1->szFileName, pParam2->szFileName);
+               while (pTmpMultipart) {
+                       if (pSelectedPart == pTmpMultipart)
+                               break;
 
-       if (pParam1->szName[0] =='\0')
-               strcpy(pParam1->szName, pParam2->szName);
+                       pPrevPart = pTmpMultipart;
+                       pTmpMultipart = pTmpMultipart->pNext;
+               }
 
-       if (pParam1->szStart[0] =='\0')
-               strcpy(pParam1->szStart, pParam2->szStart);
+               if (pPrevPart == NULL) {
+                       /* selected part is the first part */
+                       pRemoveList = pSelectedPart->pNext;
+               } else {
+                       pPrevPart->pNext = pSelectedPart->pNext;
+                       pRemoveList = pPartBody->body.pMultipart;
+                       pPartBody->body.pMultipart = pSelectedPart;
+               }
 
-       if (pParam1->szStartInfo[0] =='\0')
-               strcpy(pParam1->szStartInfo, pParam2->szStartInfo);
+               pSelectedPart->pNext = NULL;
 
-       return true;
-}
+               if (pRemoveList) {
 
-bool MsgIsMultipartMixed(int type)
-{
-       if (type == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED || type == MIME_MULTIPART_MIXED) {
-               return true;
-       } else {
-               return false;
-       }
-}
+                       MmsReleaseMsgDRMInfo(&pRemoveList->type.drmInfo);
 
-bool MsgStrcpyWithoutCRLF(char *pOrg, char **ppNew)
-{
-       int nLen = 0;
-       int     i = 0;
-       int index = 0;
-       char*   pDest = NULL;
+                       MmsReleaseMsgBody(pRemoveList->pBody, pRemoveList->type.type);
 
+                       free(pRemoveList->pBody);
+                       free(pRemoveList);
+               }
 
-       nLen = strlen(pOrg);
+               if (__MsgCopyNestedMsgType(pPartType, &(pSelectedPart->type)) == false) {
+                       MSG_DEBUG("MsgPriorityCopyMsgType failed");
+                       goto __CATCH;
+               }
 
-       pDest = (char *)malloc(nLen + 1);
+               if (pSelectedPart->pBody != NULL)
+                       memcpy(pPartBody, pSelectedPart->pBody, sizeof(MsgBody));
 
-       if (pDest == NULL) {
-               MSG_DEBUG("MsgStrcpyWithoutCRLF: malloc is failed\n");
-               return false;
-       }
+               if (pSelectedPart != NULL) {
 
-       memset(pDest, 0 , (nLen + 1));
+                       MmsReleaseMsgDRMInfo(&pSelectedPart->type.drmInfo);
 
-       for (i = 0; i < nLen ; i++) {
-               if (i < nLen - 2) {
-                       if ((pOrg[i] == MSG_CH_CR && pOrg[i+1] == MSG_CH_LF && pOrg[i+2] == MSG_CH_TAB) ||
-                               (pOrg[i] == MSG_CH_CR && pOrg[i+1] == MSG_CH_LF && pOrg[i+2] == MSG_CH_SP)) {
-                               i+=2;
-                               continue;
+                       if (pSelectedPart->pBody != NULL) {
+                               free(pSelectedPart->pBody);
+                               pSelectedPart->pBody = NULL;
                        }
+                       free(pSelectedPart);
+                       pSelectedPart = NULL;
                }
-               pDest[index++] = pOrg[i];
-       }
-       *ppNew = pDest;
 
-       return true;
-}
-
-bool MmsGetMsgAttrib(MmsMsgID msgID, MmsAttrib* pAttrib)
-{
-       MmsMsg *pMsg = NULL;
+               break;
 
-       memset(pAttrib, 0, sizeof(MmsAttrib));
-       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
-       memcpy(pAttrib, &(pMsg->mmsAttrib), sizeof(MmsAttrib));
+       case MIME_APPLICATION_VND_WAP_MULTIPART_RELATED:
+       case MIME_MULTIPART_RELATED:
 
-       MSG_DEBUG("MmsGetMsgAttrib: msgID = %lu ---------------------\n", msgID);
+               MSG_DEBUG("MIME_APPLICATION_VND_WAP_MULTIPART_RELATED");
 
-       if ('\0' != pMsg->szTrID[0])
-               MSG_DEBUG("szTrID = %s \n", pMsg->szTrID);
+               pSelectedPart = pPartBody->body.pMultipart;
 
-       MSG_END();
-       return true;
-}
+               while (pSelectedPart) {
+                       if (__MsgIsMultipartMixed(pSelectedPart->type.type)) {
 
-bool __MsgIsInvalidFileNameChar(char ch)
-{
-       if ((ch == 0x5C /* \ */) ||
-               (ch == 0x2F /* / */) ||
-               (ch == 0x3A /* : */) ||
-               (ch == 0x2A /* * */) ||
-               (ch == 0x3F /* ? */) ||
-               (ch == 0x22 /* " */) ||
-               (ch == 0x3C /* < */) ||
-               (ch == 0x3E /* > */) ||
-               (ch == 0x7C /* | */))
-               return true;
+                               if (pSelectedPart->pBody == NULL) {
+                                       MSG_DEBUG("pSelectedPart->pBody(1) is NULL");
+                                       break;
+                               }
 
-       return false;
-}
+                               pFirstPart = pSelectedPart->pBody->body.pMultipart;
 
-bool _MmsDataUpdateLastStatus(MmsMsg *pMsg)
-{
-       MmsMsgMultiStatus*      pStatus = NULL;
+                               if (pFirstPart == NULL) {
+                                       MSG_DEBUG("multipart(RELATED) does not exist");
+                                       break;
+                               }
 
-       pStatus = pMsg->mmsAttrib.pMultiStatus;
+                               if (pFirstPart->pNext) {
+                                       pLastPart = pFirstPart->pNext;
+                                       while (pLastPart->pNext)
+                                               pLastPart = pLastPart->pNext;
+                               } else {
+                                       pLastPart = pFirstPart;
+                               }
 
-       while (pStatus != NULL) {
-               pStatus->bDeliveyrReportIsLast = false;
-               pStatus->bReadReplyIsLast = false;
-               pStatus = pStatus->pNext;
-       }
+                               if (pPrevPart == NULL) {
+                                       /* the first part */
+                                       pTmpMultipart = pPartBody->body.pMultipart->pNext;
+                                       pPartBody->body.pMultipart = pFirstPart;
+                                       pLastPart->pNext = pTmpMultipart;
+                               } else {
+                                       pTmpMultipart = pSelectedPart->pNext;
+                                       pPrevPart->pNext = pFirstPart;
+                                       pLastPart->pNext = pTmpMultipart;
+                               }
 
-       return true;
-}
+                               if (pSelectedPart) {
 
+                                       MmsReleaseMsgDRMInfo(&pSelectedPart->type.drmInfo);
 
-bool MmsAddrUtilCompareAddr(char *pszAddr1, char *pszAddr2)
-{
-       int len1;
-       int len2;
-       char *p;
+                                       free(pSelectedPart->pBody);
+                                       free(pSelectedPart);
+                               }
+                               pSelectedPart = pTmpMultipart;
+                       } else if (__MsgIsMultipartRelated(pSelectedPart->type.type) && pPrevPart != NULL) {
+                               pPrevPart->pNext = pTmpMultipart = pSelectedPart->pNext;
+                               MmsReleaseMsgBody(pSelectedPart->pBody, pSelectedPart->type.type);
 
-       MmsAddrUtilRemovePlmnString(pszAddr1);
-       MmsAddrUtilRemovePlmnString(pszAddr2);
+                               free(pSelectedPart->pBody);
+                               free(pSelectedPart);
+                               pSelectedPart = pTmpMultipart;
+                       } else {
+                               pPrevPart = pSelectedPart;
+                               pSelectedPart = pSelectedPart->pNext;
+                       }
+               }
 
-       MSG_DEBUG("##### pszAddr1 = %s #####", pszAddr1);
-       MSG_DEBUG("##### pszAddr2 = %s #####", pszAddr2);
-       if (!strcmp(pszAddr1, pszAddr2))
-               return true;
+               break;
 
-       len1 = strlen(pszAddr1);
-       len2 = strlen(pszAddr2);
 
-       if (len1 > len2) {
-               p = strstr(pszAddr1, pszAddr2);
-       } else {
-               p = strstr(pszAddr2, pszAddr1);
-       }
+       case MIME_APPLICATION_VND_WAP_MULTIPART_MIXED:
+       case MIME_MULTIPART_MIXED:
 
-       if (p)
-               return true;
+               MSG_DEBUG("MIME_APPLICATION_VND_WAP_MULTIPART_MIXED");
 
-       return false;
-}
+               pPrevPart = NULL;
+               pSelectedPart = pPartBody->body.pMultipart;
 
-int MsgGetLatin2UTFCodeSize(unsigned char *szSrc, int nChar)
-{
-       int nCount = 0;
+               while (pSelectedPart) {
+                       if (MsgIsMultipart(pSelectedPart->type.type)) {
+                               if (pSelectedPart->pBody == NULL) {
+                                       MSG_DEBUG("pSelectedPart->pBody(2) is NULL");
+                                       break;
+                               }
 
-       MSG_DEBUG("MsgGetLatin2UTFCodeSize: --------------- \n");
+                               pFirstPart = pSelectedPart->pBody->body.pMultipart;
 
-       if ((szSrc == NULL) || (nChar <= 0)) {
-               MSG_DEBUG("MsgGetLatin2UTFCodeSize: szSrc is NULL !!!! --------------- \n");
-               return 0;
-       }
+                               // NULL Pointer check!!
+                               if (pFirstPart == NULL) {
+                                       MSG_DEBUG("multipart does not exist");
+                                       break;
+                               }
 
-       while ((nChar > 0) && (*szSrc != '\0')) {
-               if (0x01 <= *szSrc && *szSrc <= 0x7F) {
-                       nCount += 1;
-                       szSrc++;
-                       nChar--;
-               } else {
-                       nCount += 2;
-                       szSrc++;
-                       nChar--;
-               }
-       }
+                               if (pFirstPart->pNext) {
+                                       pLastPart = pFirstPart->pNext;
+                                       while (pLastPart->pNext)
+                                               pLastPart = pLastPart->pNext;
+                               } else {
+                                       pLastPart = pFirstPart;
+                               }
 
-       return nCount;
-}
+                               if (pPrevPart == NULL) {
+                                       /* the first part */
+                                       pTmpMultipart = pPartBody->body.pMultipart->pNext;
+                                       pPartBody->body.pMultipart = pFirstPart;
+                                       pLastPart->pNext = pTmpMultipart;
+                               } else {
+                                       pTmpMultipart = pSelectedPart->pNext;
+                                       pPrevPart->pNext = pFirstPart;
+                                       pLastPart->pNext = pTmpMultipart;
+                               }
 
-int MsgLatin5code2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar)
-{
-       unsigned char *org;
-       unsigned char t1;
-       unsigned char t2;
-       unsigned short temp = 0;
+                               if (pSelectedPart->pBody->pPresentationBody)
+                                       pPartBody->pPresentationBody = pSelectedPart->pBody->pPresentationBody;
 
-       org = des;
-       outBufSize--;   //Null Character
+                               memcpy(&pPartBody->presentationType,
+                                                 &pSelectedPart->pBody->presentationType, sizeof(MsgType));
 
-       while ((nChar > 0) && (*szSrc != '\0')) {
+                               pPartType->type = pSelectedPart->type.type;
 
-               if (*szSrc >= 0x01 && *szSrc <= 0x7F) { //basic common
-                       temp = (unsigned short)(*szSrc);
+                               MmsReleaseMsgDRMInfo(&pSelectedPart->type.drmInfo);
 
-                       outBufSize --;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+                               free(pSelectedPart->pBody);
+                               free(pSelectedPart);
 
-                       *des = (unsigned char) ((*szSrc) & 0x007F);
+                               pSelectedPart = pTmpMultipart;
+                       } else {
+                               pPrevPart = pSelectedPart;
+                               pSelectedPart = pSelectedPart->pNext;
+                       }
+               }
 
-                       des++;
-                       szSrc++;
-                       nChar--;
-               } else if ((*szSrc == 0x00) || (*szSrc >= 0x80 && *szSrc <= 0x9F) ||
-                                       (*szSrc >= 0xA0 && *szSrc <= 0xCF) || (*szSrc >= 0xD1 && *szSrc <= 0xDC) ||
-                                       (*szSrc >= 0xDF && *szSrc <= 0xEF) || (*szSrc >= 0xF1 && *szSrc <= 0xFC) ||
-                                       (*szSrc == 0xFF)) {//uni 0x00A0 ~ 0x00CF
+               break;
 
-                       temp = (unsigned short)(*szSrc);
+       case MIME_MULTIPART_REPORT:
 
-                       outBufSize -= 2;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+               MSG_DEBUG("MIME_MULTIPART_REPORT");
 
-                       t2 = (unsigned char) (temp & 0x003F);                           //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0x07C0) >> 6);            //      right most 5 bit
+               pTmpMultipart = pPartBody->body.pMultipart;
+               pPrevPart = NULL;
 
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
+               if (pTmpMultipart == NULL) {
+                       MSG_DEBUG("pTmpMultipart == NULL");
+                       return false;
+               }
 
-                       des += 2;
-                       szSrc += 1;
-                       nChar -= 1;
-               } else if (*szSrc == 0xD0) {//empty section OR vendor specific codes.
+               while (pTmpMultipart) {
+                       if (pTmpMultipart->type.type == MIME_TEXT_PLAIN) {
+                               pSelectedPart = pTmpMultipart;
+                               break;
+                       }
 
-                       temp = 0x011E;
+                       pPrevPart = pTmpMultipart;
+                       pTmpMultipart = pTmpMultipart->pNext;
+               }
 
-                       outBufSize -= 2;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+               if (pSelectedPart == NULL) {
+                       MSG_DEBUG("MIME_MULTIPART_REPORT [no selected part]");
 
-                       t2 = (unsigned char) (temp & 0x003F);                           //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0x07C0) >> 6);            //      right most 5 bit
+                       pRemoveList = pPartBody->body.pMultipart->pNext;
+                       if (pPartBody->body.pMultipart != NULL) {
+                               pSelectedPart = pPartBody->body.pMultipart;
+                               pSelectedPart->pNext = NULL;
+                       }
+               } else {
+                       if (pPrevPart == NULL) {
+                               // first part is selected
+                               pRemoveList = pPartBody->body.pMultipart->pNext;
+                       } else {
+                               pRemoveList = pPartBody->body.pMultipart->pNext;
+                               pPrevPart->pNext = pSelectedPart->pNext;
+                       }
 
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
+                       pSelectedPart->pNext = NULL;
+                       pPartBody->body.pMultipart = pSelectedPart;
+               }
 
-                       des += 2;
-                       szSrc += 1;
-                       nChar -= 1;
-               } else if (*szSrc == 0xDD) {
-                       temp = 0x0130;
+               pTmpMultipart = pRemoveList;
 
-                       outBufSize -= 2;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+               while (pTmpMultipart) {
 
-                       t2 = (unsigned char) (temp & 0x003F);                           //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0x07C0) >> 6);            //      right most 5 bit
+                       MmsReleaseMsgDRMInfo(&pTmpMultipart->type.drmInfo);
 
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
+                       MmsReleaseMsgBody(pTmpMultipart->pBody, pTmpMultipart->type.type);
+                       pNextRemovePart = pTmpMultipart->pNext;
 
-                       des += 2;
-                       szSrc += 1;
-                       nChar -= 1;
-               } else if (*szSrc == 0xDE) {
-                       temp = 0x015E;
+                       free(pTmpMultipart->pBody);
+                       free(pTmpMultipart);
+                       pTmpMultipart = pNextRemovePart;
+               }
 
-                       outBufSize -= 2;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+               if (__MsgCopyNestedMsgType(pPartType, &(pSelectedPart->type)) == false) {
+                       MSG_DEBUG("MsgPriorityCopyMsgType failed");
+                       goto __CATCH;
+               }
 
-                       t2 = (unsigned char) (temp & 0x003F);                           //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0x07C0) >> 6);            //      right most 5 bit
+               if (pSelectedPart != NULL) {
 
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
+                       if (pSelectedPart->pBody != NULL)
+                               memcpy(pPartBody, pSelectedPart->pBody, sizeof(MsgBody));
 
-                       des += 2;
-                       szSrc += 1;
-                       nChar -= 1;
-               } else if (*szSrc == 0xF0) {
-                       temp = 0x011F;
-                               outBufSize -= 2;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+                       MmsReleaseMsgDRMInfo(&pSelectedPart->type.drmInfo);
 
-                       t2 = (unsigned char) (temp & 0x003F);                           //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0x07C0) >> 6);            //      right most 5 bit
+                       if (pSelectedPart->pBody != NULL) {
+                               free(pSelectedPart->pBody);
+                               pSelectedPart->pBody = NULL;
+                       }
+                       free(pSelectedPart);
+                       pSelectedPart = NULL;
+               }
 
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
+               break;
 
-                       des += 2;
-                       szSrc += 1;
-                       nChar -= 1;
-               } else if (*szSrc == 0xFD) {
-                       temp = 0x0131;
+       default:
+               break;
+       }
+       MSG_END();
 
-                       outBufSize -= 2;
+       return true;
 
-                       if (outBufSize < 0)
-                               goto __RETURN;
+__CATCH:
+       return false;
 
-                       t2 = (unsigned char) (temp & 0x003F);                           //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0x07C0) >> 6);            //      right most 5 bit
+}
 
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
+char *MsgResolveContentURI(char *szSrc)
+{
+       char *szTemp = NULL;
+       char *szReturn = NULL;
+       int length = 0;
 
-                       des += 2;
-                       szSrc += 1;
-                       nChar -= 1;
-               } else if (*szSrc == 0xFE) {
-                       temp = 0x015F;
+       if (szSrc == NULL) {
+               goto __CATCH;
+       }
 
-                       outBufSize -= 2;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+       if (szSrc[0] == '\0')
+               goto __CATCH;
 
-                       t2 = (unsigned char) (temp & 0x003F);                           //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0x07C0) >> 6);            //      right most 5 bit
 
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
+       if (!strncasecmp(szSrc, "cid:", 4)) {
+               length = strlen(szSrc) - 3;
+               szSrc += 4;
+       } else {
+               length = strlen(szSrc) + 1;
+       }
 
-                       des += 2;
-                       szSrc += 1;
-                       nChar -= 1;
-               } else {
-                       return -1;
-               }
+       szTemp = (char *)calloc(1, length);
+       if (szTemp == NULL) {
+               MSG_DEBUG("memory full");
+               goto __CATCH;
        }
-__RETURN:
-       *des = 0;
-       return(des-org);
-}
 
-int MsgGetLatin52UTFCodeSize(unsigned char *szSrc, int nChar)
-{
-       int nCount = 0;
+       memset(szTemp, 0, length);
 
-       MSG_DEBUG("MsgGetLatin52UTFCodeSize: --------------- \n");
+       strncpy(szTemp, szSrc, length - 1);
 
-       if ((szSrc == NULL) || (nChar <= 0))
-               return 0;
+       szReturn = MsgChangeHexString(szTemp);
 
-       while ((nChar > 0) && (*szSrc != '\0')) {
-               if (*szSrc >= 0x01 && *szSrc <= 0x7F) {
-                       nCount += 1;
-                       szSrc++;
-                       nChar--;
-               } else if (*szSrc == 0x00 || (*szSrc >= 0x80 && *szSrc <= 0x9F) ||
-                                       (*szSrc >= 0xA0 && *szSrc <= 0xCF) || (*szSrc >= 0xD1 && *szSrc <= 0xDC) |
-                                       (*szSrc >= 0xDF && *szSrc <= 0xEF) || (*szSrc >= 0xF1 && *szSrc <= 0xFC) ||
-                                       *szSrc == 0xD0 || *szSrc == 0xDD || *szSrc == 0xDE || *szSrc == 0xF0 ||
-                                       *szSrc == 0xFD || *szSrc == 0xFE        || *szSrc == 0xFF) { //uni 0x00A0 ~ 0x00CF
-                       nCount += 2;
-                       szSrc++;
-                       nChar--;
-               } else {
-                       return -1;
-               }
+       if (szTemp) {
+               free(szTemp);
+               szTemp = NULL;
        }
-       return nCount;
-}
-
-int MsgLatin2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar)
-{
-       unsigned char*  org;
-       unsigned char   t1, t2;
 
-       MSG_DEBUG("MsgLatin2UTF: --------------- \n");
+       return szReturn;
 
-       org = des;
-       outBufSize--;                   // NULL character
+__CATCH:
 
-       while ((nChar > 0) && (*szSrc != '\0')) {
-               if (0x01 <= *szSrc && *szSrc <= 0x7F) {
-                       /* check outbuffer's room for this UTF8 character */
+       return NULL;
+}
 
-                       outBufSize --;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+char *MsgRemoveQuoteFromFilename(char *pSrc)
+{
+       int cLen = 0;   // length of pBuff
+       char *pBuff = NULL;
 
-                       *des = (unsigned char) (*szSrc & 0x007F);
+       if (pSrc == NULL) {
+               MSG_DEBUG("pSrc is Null");
+               return NULL;
+       }
 
-                       des++;
-                       szSrc++;
-                       nChar--;
-               } else {
-                       /* check outbuffer's room for this UTF8 character */
+       cLen = strlen(pSrc);
 
-                       outBufSize -= 2;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+       pBuff = (char *)calloc(1, cLen + 1);
 
-                       t2 = (unsigned char) (*szSrc & 0x003F);                         //      right most 6 bit
-                       t1 = (unsigned char) ((*szSrc & 0xC0) >> 6);            //      right most 2 bit
+       if (pBuff == NULL) {
+               MSG_DEBUG("pBuff mem alloc fail!");
+               return NULL;
+       }
+       memset(pBuff, 0 , sizeof(char)*(cLen + 1));
 
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des + 1) = 0x80 | (t2 & 0x3F);
+       // remove front quote
+       if (pSrc[0] == MSG_CH_QUOT) {
+               cLen--;
+               strncpy(pBuff, &pSrc[1], cLen);
+               pBuff[cLen] = '\0';
+       }
 
-                       des += 2;
-                       szSrc += 1;
-                       nChar -= 1;
-               }
+       if (pSrc[0] == MSG_CH_LF) {
+               cLen--;
+               strncpy(pBuff, &pSrc[1], cLen);
+       } else {
+               strncpy(pBuff, pSrc, cLen);
        }
 
-__RETURN:
+       // remove last qoute
+       if (pBuff[cLen-1] == MSG_CH_QUOT) {
+               pBuff[cLen-1] = '\0';
+       }
 
-       *des = 0;
-       return (des - org);
+       return pBuff;
 }
 
-
-int MsgLatin7code2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar)
+bool MsgIsMultipart(int type)
 {
-       unsigned char *org;
-       unsigned char t1;
-       unsigned char t2;
-       unsigned char t3;
-       unsigned short temp = 0;
-
-       MSG_DEBUG("MsgUnicode2UTF: --------------- \n");
-
-       org = des;
-       outBufSize--;   //Null Character
-
-       while ((nChar > 0) && (*szSrc != '\0')) {
-               if (*szSrc >= 0x01 && *szSrc <= 0x7F) {
-                       temp = (unsigned short)(*szSrc);
-
-                       outBufSize --;
-                       if (outBufSize < 0)
-                               goto __RETURN;
-
-                       *des = (unsigned char) (temp & 0x007F);
-
-                       des++;
-                       szSrc++;
-                       nChar--;
+       if (type == MIME_MULTIPART_RELATED || type == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED ||
+               type == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED || type == MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC ||
+               type == MIME_MULTIPART_MIXED || type == MIME_MULTIPART_REPORT) {
+               return true;
+       } else {
+               return false;
+       }
+}
 
-               } else if ((*szSrc == 0x00) || (*szSrc >= 0x80 && *szSrc <= 0x9F) ||
-                                       (*szSrc >= 0xA3 && *szSrc <= 0xAD) || (*szSrc == 0xBB)) { // consider 0xA4, 0xA5
 
-                       temp = (unsigned short)(*szSrc);
+static bool __MsgIsHexChar(char *pSrc)
+{
+       int cIndex = 0;
+       int cLen = 0;
+       bool bRet = false;
 
-                       outBufSize -= 2;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+       cLen = strlen(pSrc);
 
-                       t2 = (unsigned char) (temp & 0x003F);                           //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0xC0) >> 6);              //      right most 2 bit
+       for (cIndex = 0; cIndex < cLen ; cIndex++) {
+               if ((pSrc[cIndex] >= '0' && pSrc[cIndex] <= '9') || (pSrc[cIndex] >= 'A'&& pSrc[cIndex] <= 'F') ||
+                       (pSrc[cIndex] >= 'a' && pSrc[cIndex] <= 'f')) {
+                       bRet = true;
+               } else {
+                       return false;
+               }
+       }
 
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des + 1) = 0x80 | (t2 & 0x3F);
+       return bRet;
+}
 
-                       des += 2;
-                       szSrc += 1;
-                       nChar -= 1;
-               } else if (*szSrc == 0xA0) {
-                       temp = 0x0020;
-                       //*des = temp to utf-8
-                       outBufSize--;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+static char __MsgConvertHexValue(char *pSrc)
+{
+       int ch = 0;
+       int cIndex = 0;
+       int cLen = 0;
+       char ResultChar;
+       unsigned char uCh[2] = {0,};
 
-                       *des = (unsigned char) (temp & 0x007F);
+       cLen = strlen(pSrc);
 
-                       des++;
-                       szSrc++;
-                       nChar--;
+       for (cIndex = 0; cIndex < cLen ; cIndex += 2) {
+               uCh[0] = __MsgConvertCharToInt(pSrc[cIndex]);
+               uCh[1] = __MsgConvertCharToInt(pSrc[cIndex+1]);
+               ch = (int)uCh[0]<<4|uCh[1];
+       }
 
-               } else if (*szSrc == 0xA1) {
-                       temp = 0x2018;
+       ResultChar = (char)ch;
 
-                       outBufSize -= 3;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+       return ResultChar;
+}
 
-                       t3 = (unsigned char) (temp & 0x003F);                                   //      right most 6 bit
-                       t2 = (unsigned char) ((temp & 0x0FC0) >> 6);                    //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0xF000) >> 12);                   //      right most 4 bit
+static int __MsgConvertCharToInt(char ch)
+{
+       if (ch>='0' && ch<='9') {
+               return ch - '0';
+       } else if (ch>='a'&& ch <='f') {
+               return ch -'a'+10;
+       } else if (ch>='A'&& ch <='F') {
+               return ch -'A'+10;
+       } else {
+               return 0;
+       }
+}
 
-                       *des = 0xE0 | (t1 & 0x0F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
-                       *(des+2) = 0x80 | (t3 & 0x3F);
+static bool __MsgCopyNestedMsgType(MsgType *pMsgType1, MsgType *pMsgType2)
+{
+       if(!pMsgType1 || !pMsgType2)
+               return false;
 
-                       des += 3;
-                       szSrc += 1;
-                       nChar -= 1;
+       //if (pMsgType1->section == INVALID_HOBJ)
+               pMsgType1->section = pMsgType2->section;
 
-               } else if (*szSrc == 0xA2) {
-                       temp = 0x2019;
+       int length = 0;
 
-                       outBufSize -= 3;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+       if (pMsgType1->drmInfo.drmType == MSG_DRM_TYPE_NONE)
+               pMsgType1->drmInfo.drmType = pMsgType2->drmInfo.drmType;
 
-                       t3 = (unsigned char) (temp & 0x003F);                                   //      right most 6 bit
-                       t2 = (unsigned char) ((temp & 0x0FC0) >> 6);                    //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0xF000) >> 12);                   //      right most 4 bit
 
-                       *des = 0xE0 | (t1 & 0x0F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
-                       *(des+2) = 0x80 | (t3 & 0x3F);
+       if (pMsgType1->szContentID[0] == '\0') {
+               snprintf(pMsgType1->szContentID, sizeof(pMsgType1->szContentID), "%s", pMsgType2->szContentID);
+       }
 
-                       des += 3;
-                       szSrc += 1;
-                       nChar -= 1;
+       if (pMsgType1->szContentID[0] != '\0') {
 
-               } else if (*szSrc == 0xAF) {
-                       temp = 0x2015;
+               length = strlen(pMsgType1->szContentID);
+               if (pMsgType1->szContentID[0] == '<' && pMsgType1->szContentID[length - 1] == '>') {
+                       char szTempString[MSG_MSG_ID_LEN + 1];
+                       MmsRemoveLessGreaterChar(pMsgType1->szContentID, szTempString, sizeof(szTempString));
+                       pMsgType1->drmInfo.szContentURI = g_strdup(szTempString);
+               } else {
+                       pMsgType1->drmInfo.szContentURI = g_strdup(pMsgType1->szContentID);
+               }
+       }
 
-                       outBufSize -= 3;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+       if (pMsgType1->szContentLocation[0] == '\0') {
+               strncpy(pMsgType1->szContentLocation, pMsgType2->szContentLocation, MSG_MSG_ID_LEN);
+       }
 
-                       t3 = (unsigned char) (temp & 0x003F);                                   //      right most 6 bit
-                       t2 = (unsigned char) ((temp & 0x0FC0) >> 6);                    //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0xF000) >> 12);                   //      right most 4 bit
+       /* Copy informations - we shoud open the pMsgType2's orgFile
+        * concerning its offset and size.
+        */
+       if (pMsgType2->szOrgFilePath[0] != '\0') {
+               strncpy(pMsgType1->szOrgFilePath, pMsgType2->szOrgFilePath, MSG_FILEPATH_LEN_MAX-1);
+       }
 
-                       *des = 0xE0 | (t1 & 0x0F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
-                       *(des+2) = 0x80 | (t3 & 0x3F);
+       if (pMsgType2->disposition != -1)
+               pMsgType1->disposition = pMsgType2->disposition;
 
-                       des += 3;
-                       szSrc += 1;
-                       nChar -= 1;
+       if ((pMsgType1->type != MIME_APPLICATION_VND_OMA_DRM_MESSAGE && pMsgType1->type != MIME_APPLICATION_VND_OMA_DRM_CONTENT) &&
+                pMsgType2->encoding != -1)
+               pMsgType1->encoding = pMsgType2->encoding;
 
-               } else if (0xB0 <= *szSrc && *szSrc <= 0xB4) { //0x00B0 ~ 0x00B4
+       pMsgType1->contentSize = pMsgType2->contentSize;
+       pMsgType1->offset = pMsgType2->offset;
+       pMsgType1->size = pMsgType2->size;
+       pMsgType1->type = pMsgType2->type;
 
-                       temp = (unsigned short)(*szSrc);
+       __MsgCopyNestedMsgParam(&(pMsgType1->param), &(pMsgType2->param));
 
-                       outBufSize -= 2;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+       if (pMsgType1->param.szName[0]) {
+               pMsgType1->drmInfo.szContentName = g_strdup(pMsgType2->param.szName);
+       }
 
-                       t2 = (unsigned char) (temp & 0x003F);                           //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0x07C0) >> 6);            //      right most 5 bit
+       return true;
+}
 
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
+static bool __MsgCopyNestedMsgParam(MsgContentParam *pParam1, MsgContentParam *pParam2)
+{
+       if (pParam1->charset == MSG_CHARSET_UNKNOWN)
+               pParam1->charset = pParam2->charset;
 
-                       des += 2;
-                       szSrc += 1;
-                       nChar -= 1;
+       if (pParam1->type == MIME_UNKNOWN)
+               pParam1->type = pParam2->type;
 
-               } else if ((0xB5 <= *szSrc &&  *szSrc <= 0xBA) ||
-                               (0xBC <= *szSrc && *szSrc <= 0xD1) ||
-                               (0xD3 <= *szSrc && *szSrc <= 0xFE)) {
-                       temp= (unsigned short)(*szSrc + 0x02D0);
+       /* Don't copy pParam2->pPresentation */
 
-                       outBufSize -= 2;
-                       if (outBufSize < 0)
-                               goto __RETURN;
+       /* For alternative: copy the boundary string */
+       if (pParam2->szBoundary[0] !='\0') {
+               strncpy(pParam1->szBoundary, pParam2->szBoundary, MSG_BOUNDARY_LEN);
+       }
 
-                       t2 = (unsigned char) (temp & 0x003F);                           //      right most 6 bit
-                       t1 = (unsigned char) ((temp & 0x07C0) >> 6);            //      right most 5 bit
+       if (pParam1->szFileName[0] =='\0') {
+               strncpy(pParam1->szFileName, pParam2->szFileName, MSG_FILENAME_LEN_MAX);
+       }
 
-                       *des = 0xC0 | (t1 & 0x1F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
+       if (pParam1->szName[0] =='\0') {
+               strncpy(pParam1->szName, pParam2->szName, MSG_LOCALE_FILENAME_LEN_MAX);
+       }
 
-                       des += 2;
-                       szSrc += 1;
-                       nChar -= 1;
+       if (pParam1->szStart[0] =='\0') {
+               strncpy(pParam1->szStart, pParam2->szStart, MSG_MSG_ID_LEN);
+       }
 
-               } else {
-                       return -1;
-               }
+       if (pParam1->szStartInfo[0] =='\0') {
+               strncpy(pParam1->szStartInfo, pParam2->szStartInfo, MSG_MSG_ID_LEN);
+       }
+       return true;
+}
 
+static bool __MsgIsMultipartMixed(int type)
+{
+       if (type == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED || type == MIME_MULTIPART_MIXED) {
+               return true;
+       } else {
+               return false;
        }
+}
 
-__RETURN:
-       *des = 0;
-       return(des - org);
+static bool __MsgIsInvalidFileNameChar(char ch)
+{
+       if ((ch == 0x5C /* \ */) ||
+               (ch == 0x2F /* / */) ||
+               (ch == 0x3A /* : */) ||
+               (ch == 0x2A /* * */) ||
+               (ch == 0x3F /* ? */) ||
+               (ch == 0x22 /* " */) ||
+               (ch == 0x3C /* < */) ||
+               (ch == 0x3E /* > */) ||
+               (ch == 0x7C /* | */))
+               return true;
+
+       return false;
 }
 
-int MsgGetLatin72UTFCodeSize(unsigned char *szSrc, int nChar)
+static int __MsgGetLatin2UTFCodeSize(unsigned char *szSrc, int nChar)
 {
        int nCount = 0;
 
-       MSG_DEBUG("MsgGetLatin72UTFCodeSize: --------------- \n");
+       MSG_DEBUG("---------------");
 
-       if ((szSrc == NULL) || (nChar <= 0))
+       if ((szSrc == NULL) || (nChar <= 0)) {
+               MSG_DEBUG("szSrc is NULL !!!! ---------------");
                return 0;
+       }
 
        while ((nChar > 0) && (*szSrc != '\0')) {
-
-               if ((*szSrc >= 0x01 && *szSrc <= 0x7F) || (*szSrc == 0xA0)) {
+               if (0x01 <= *szSrc && *szSrc <= 0x7F) {
                        nCount += 1;
                        szSrc++;
                        nChar--;
-               } else if (*szSrc == 0x00 || (0x80 <= *szSrc && *szSrc <= 0x9F) || (0xA3 <= *szSrc && *szSrc <= 0xAD) ||
-                                       (0xB0 <= *szSrc && *szSrc <= 0xB4) || (0xB5 <= *szSrc && *szSrc <= 0xFE)) {
+               } else {
                        nCount += 2;
                        szSrc++;
                        nChar--;
-               } else if (*szSrc == 0xA1 ||*szSrc == 0xA2 || *szSrc == 0xAF) {
-                       nCount += 3;
-                       szSrc += 1;
-                       nChar -= 1;
-
-               } else {
-                       return -1;
                }
        }
+
        return nCount;
 }
 
-int MsgUnicode2UTF(unsigned char *des, int outBufSize, unsigned short *szSrc, int nChar)
+static int __MsgLatin2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar)
 {
-       unsigned char *org;
-       unsigned char t1;
-       unsigned char t2;
-       unsigned char t3;
+       unsigned char*  org;
+       unsigned char   t1, t2;
 
-       MSG_DEBUG("MsgUnicode2UTF: --------------- \n");
+       MSG_DEBUG("---------------");
 
        org = des;
        outBufSize--;                   // NULL character
 
        while ((nChar > 0) && (*szSrc != '\0')) {
-               if (0x0001 <= *szSrc && *szSrc <= 0x007F) {
+               if (0x01 <= *szSrc && *szSrc <= 0x7F) {
                        /* check outbuffer's room for this UTF8 character */
 
                        outBufSize --;
@@ -7538,7 +5249,7 @@ int MsgUnicode2UTF(unsigned char *des, int outBufSize, unsigned short *szSrc, in
                        des++;
                        szSrc++;
                        nChar--;
-               } else if  ((*szSrc == 0x0000) || (0x0080 <= *szSrc && *szSrc <= 0x07FF)) {
+               } else {
                        /* check outbuffer's room for this UTF8 character */
 
                        outBufSize -= 2;
@@ -7546,32 +5257,14 @@ int MsgUnicode2UTF(unsigned char *des, int outBufSize, unsigned short *szSrc, in
                                goto __RETURN;
 
                        t2 = (unsigned char) (*szSrc & 0x003F);                         //      right most 6 bit
-                       t1 = (unsigned char) ((*szSrc & 0x07C0) >> 6);          //      right most 5 bit
+                       t1 = (unsigned char) ((*szSrc & 0xC0) >> 6);            //      right most 2 bit
 
                        *des = 0xC0 | (t1 & 0x1F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
+                       *(des + 1) = 0x80 | (t2 & 0x3F);
 
                        des += 2;
                        szSrc += 1;
                        nChar -= 1;
-               } else {
-                       /* check outbuffer's room for this UTF8 character */
-
-                       outBufSize -= 3;
-                       if (outBufSize < 0)
-                               goto __RETURN;
-
-                       t3 = (unsigned char) (*szSrc & 0x003F);                                 //      right most 6 bit
-                       t2 = (unsigned char) ((*szSrc & 0x0FC0) >> 6);                  //      right most 6 bit
-                       t1 = (unsigned char) ((*szSrc & 0xF000) >> 12);                 //      right most 4 bit
-
-                       *des = 0xE0 | (t1 & 0x0F);
-                       *(des+1) = 0x80 | (t2 & 0x3F);
-                       *(des+2) = 0x80 | (t3 & 0x3F);
-
-                       des += 3;
-                       szSrc += 1;
-                       nChar -= 1;
                }
        }
 
@@ -7581,36 +5274,6 @@ __RETURN:
        return (des - org);
 }
 
-int MsgGetUnicode2UTFCodeSize(unsigned short *szSrc, int nChar)
-{
-       int nCount = 0;
-
-       MSG_DEBUG("MsgGetUnicode2UTFCodeSize: --------------- \n");
-
-       if ((szSrc == NULL) || (nChar <= 0)) {
-               MSG_DEBUG("MsgGetUnicode2UTFCodeSize: szSrc is NULL !!!! --------------- \n");
-               return 0;
-       }
-
-       while ((nChar > 0) && (*szSrc != '\0')) {
-               if (0x0001 <= *szSrc && *szSrc <= 0x007F) {
-                       nCount += 1;
-                       szSrc++;
-                       nChar--;
-               } else if  ((*szSrc == 0x0000) || (0x0080 <= *szSrc && *szSrc <= 0x07FF)) {
-                       nCount += 2;
-                       szSrc++;
-                       nChar--;
-               } else {
-                       nCount += 3;
-                       szSrc++;
-                       nChar--;
-               }
-       }
-
-       return nCount;
-}
-
 bool MmsAddrUtilCheckEmailAddress(char *pszAddr)
 {
        if (!pszAddr || pszAddr[0] == 0)
@@ -7630,7 +5293,7 @@ bool MmsAddrUtilRemovePlmnString(char *pszAddr)
        int strLen = 0;
 
        if ((!pszAddr) || (pszAddr[0] == 0)) {
-               MSG_DEBUG("MmsAddrUtilRemovePlmnString: pszAddr is null or zero\n");
+               MSG_DEBUG("pszAddr is null or zero");
                return false;
        }
 
@@ -7638,19 +5301,18 @@ bool MmsAddrUtilRemovePlmnString(char *pszAddr)
 
        pszAddrCopy = (char*)calloc(1,strLen + 1);
        if (!pszAddrCopy) {
-               MSG_DEBUG("MmsAddrUtilRemovePlmnString: pszAddrCopy is NULL, mem alloc failed\n");
+               MSG_DEBUG("pszAddrCopy is NULL, mem alloc failed");
                return false;
        }
 
-       strcpy(pszAddrCopy, pszAddr);
-
+       strncpy(pszAddrCopy, pszAddr, strLen);
 
        pszAddr[0] = 0;
        pszStrStart = pszAddrCopy;
 
        while (true) {
                char*   pszStrEnd = NULL;
-               int             addressLen = 0;
+               int     addressLen = 0;
 
                if (MmsAddrUtilCheckEmailAddress(pszAddrCopy))
                        pszStrEnd = strstr(pszStrStart, "/TYPE=PLMN");
@@ -7658,6 +5320,8 @@ bool MmsAddrUtilRemovePlmnString(char *pszAddr)
                        pszStrEnd = strstr(pszStrStart, "/");
 
                if (!pszStrEnd) {
+                       char *pszStart = NULL;
+                       char *pszEnd = NULL;
                        // "/TYPE=PLMN" not found
 
                        int remainedLen = strlen(pszStrStart);
@@ -7665,8 +5329,21 @@ bool MmsAddrUtilRemovePlmnString(char *pszAddr)
                        if (remainedLen <= 0)
                                break;
 
-                       strcat(pszAddr, pszStrStart);
+                       //Email address can occur with Sender Name<email-address> format
+                       //remove the Sender name and only retain the email address.
+                       pszStart = strstr(pszStrStart, "<");
+                       if (pszStart) {
+                               pszEnd = strstr(pszStrStart, ">");
+
+                               if (pszEnd) {
+                                       pszStart++; //skip "<"
+                                       g_strlcat(pszAddr, pszStart, pszEnd - pszStart + 1);
+                                       break;
+                               }
+                       }
 
+                       //strcat(pszAddr, pszStrStart);
+                       g_strlcat(pszAddr, pszStrStart, strLen + 1);
                        break;
                }
 
@@ -7691,23 +5368,23 @@ bool MmsAddrUtilRemovePlmnString(char *pszAddr)
                        break;
 
 
-               strcat(pszAddr, MSG_MMS_STR_ADDR_DELIMETER);    // add ';'
+               g_strlcat(pszAddr, MSG_MMS_STR_ADDR_DELIMETER, strLen + 1);     // add ';'
                pszStrStart++;  // remove ';'
        }
 
        if (pszAddr[0] == 0)
-               strcpy(pszAddr, pszAddrCopy);
+               strncpy(pszAddr, pszAddrCopy, strLen);
 
        free(pszAddrCopy);
 
        return true;
 }
 
-int MsgCutUTFString(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar)
+static int __MsgCutUTFString(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar)
 {
        unsigned char *org;
 
-       MSG_DEBUG("MsgCutUTFString: --------------- \n");
+       MSG_DEBUG("---------------");
 
        org = des;
        outBufSize--;                   // NULL character
@@ -7750,7 +5427,7 @@ int MsgCutUTFString(unsigned char *des, int outBufSize, unsigned char *szSrc, in
                        *des = *szSrc;
                        des++;
                        szSrc++;
-                       MSG_DEBUG("MsgCutUTFString: utf8 incorrect range!\n");
+                       MSG_DEBUG("utf8 incorrect range!");
                }
 
                nChar--;
@@ -7762,11 +5439,11 @@ __RETURN:
        return (des - org);
 }
 
-void MsgMIMERemoveQuote(char *szSrc)
+static void __MsgMIMERemoveQuote(char *szSrc)
 {
-       int             length = 0;
+       int length = 0;
 
-       length = MsgStrlen(szSrc);
+       length = strlen(szSrc);
        if (szSrc[0] == MSG_CH_QUOT && szSrc[length-1] == MSG_CH_QUOT) {
                int index = 0;
 
@@ -7776,14 +5453,12 @@ void MsgMIMERemoveQuote(char *szSrc)
        }
 }
 
-bool MsgLoadDataToDecodeBuffer(FILE *pFile, char **ppBuf, int *pPtr, int *pOffset, char *pInBuf1, char *pInBuf2, int maxLen, int *pBufLen, int endOfFile)
+static bool __MsgLoadDataToDecodeBuffer(FILE *pFile, char **ppBuf, int *pPtr, int *pOffset, char *pInBuf1, char *pInBuf2, int maxLen, int *pBufLen, int endOfFile)
 {
        MSG_BEGIN();
        int nRead = 0;
        int length= 0;
 
-       MSG_DEBUG("MsgLoadDataToDecodeBuffer: \n");
-
        if (pFile == NULL) {
                MSG_DEBUG("Error");
 
@@ -7843,77 +5518,15 @@ bool MsgLoadDataToDecodeBuffer(FILE *pFile, char **ppBuf, int *pPtr, int *pOffse
        }
 
        if ((*pOffset = MsgFtell(pFile)) == -1L) {
-               MSG_DEBUG("MsgFtell Error");
-               return false;
-       }
-
-       MSG_END();
-
-       return true;
-}
-
-
-bool MsgGetTypeByFileName(int *type, char *szFileName)
-{
-       char *pExt   = NULL;
-       AvCodecType AvType = AV_CODEC_NONE;
-
-       pExt = strrchr(szFileName, '.');
-       if (pExt == NULL || pExt[0] == '\0')
-               goto __CATCH;
-
-       pExt++;
-
-       if (strcasecmp(pExt, "mp4") == 0 ||strcasecmp(pExt, "mpeg4") == 0 ||strcasecmp(pExt, "3gp") == 0 ||strcasecmp(pExt, "3gpp") == 0) {
-
-               if (szFileName[0] != '/')
-                       goto __CATCH;
-
-               AvType = AvGetFileCodecType(szFileName);
-               MSG_DEBUG("MsgGetTypeByFileName:AvType(0x%x)\n", AvType);
-
-               switch (AvType) {
-               case AV_DEC_AUDIO_MPEG4:
-                       *type = MIME_AUDIO_MP4;
-                       break;
-
-               case AV_DEC_VIDEO_MPEG4:
-                       *type = MIME_VIDEO_MP4;
-                       break;
-
-               default:
-                       *type = MIME_VIDEO_3GPP;
-                       break;
-               }
-               return true;
-       }
-
-       if (strcasecmp(pExt, "amr") == 0) {
-               *type = MIME_AUDIO_AMR;
-               return true;
-       } else if ((strcasecmp(pExt, "mid") == 0) || (strcasecmp(pExt, "midi") == 0)) {
-               *type = MIME_AUDIO_MIDI;
-               return true;
-       } else if (strcasecmp(pExt, "imy") == 0) {
-               *type = MIME_TEXT_X_IMELODY;
-               return true;
-       }
-
-       *type = MimeGetMimeFromExtInt((const char*)pExt);
-       MSG_DEBUG("MsgGetTypeByFileName: szFileName = %s     type = %d \n", szFileName, type);
-       return true;
-
-
-__CATCH:
-
-       *type = MIME_UNKNOWN;
-       MSG_DEBUG("MsgGetTypeByFileName: szFileName = %s     type = %d \n", szFileName, type);
+               MSG_DEBUG("MsgFtell Error");
+               return false;
+       }
 
-       return false;
+       MSG_END();
 
+       return true;
 }
 
-
 /*
  *     This function write media data from raw data to file.
  *     @param  pMsg
@@ -7923,72 +5536,142 @@ __CATCH:
  *     @param  index                   : used for file naming
  *     @param  bSave                   : if true, file will be save otherwise just filename will be stored.
  */
-bool _MmsMultipartSaveAsTempFile(MsgType *pPartType, MsgBody *pPartBody, char *pszMailboxPath, char *pszMsgFilename, int index, bool bSave)
+static bool __MmsMultipartSaveAsTempFile(MsgType *pPartType, MsgBody *pPartBody, char *pszMailboxPath, char *pszMsgFilename, int index, bool bSave)
 {
        FILE *pFile = NULL;
-       char *pExt = NULL;
        char szFileName[MSG_FILENAME_LEN_MAX+1] = {0, };        // file name of temp file
        char szFullPath[MSG_FILEPATH_LEN_MAX] = {0, }; // full absolute path of temp file.
-
-       MSG_DEBUG("****   _MmsSaveMediaData:  [Multi part]  START  ***\n");
+       bool bFileExist = false;
+       MSG_BEGIN();
 
        if (!pPartType) {
-               MSG_DEBUG("pPartType is NULL\n");
-               return true; // why true value is retured ??? ; false;
+               MSG_DEBUG("pPartType is NULL");
+               return false;
        }
 
-       if (pPartType->param.szName[0] == '\0' && pPartType->param.szFileName[0] == '\0')
-               strcpy(pPartType->param.szName, pPartType->param.szFileName);
-
-       if (pPartType->param.szName) {
-               strcpy(szFileName, pPartType->param.szName);
+       if (pPartType->type == MIME_APPLICATION_SMIL) {
+               snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%s", "smil.txt");
        } else {
-               snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%lu", (unsigned long)index);
-       }
-
 
-#ifndef __SUPPORT_DRM__
-       MsgMakeFileName(pPartType->type, szFileName, 0);        //FL & CD -> extension(.dm) SD -> extension(.dcf)
-#else
-       MsgMakeFileName(pPartType->type, szFileName, pPartType->drmInfo.drmType, 0);    //FL & CD -> extension(.dm) SD -> extension(.dcf)
-       if (MsgDRMIsForwardLockType(pPartType->drmInfo.drmType))
-               MsgChangeDrm2FileName(szFileName);
-#endif
+               if (pPartType->param.szName[0] != '\0') {
+                       snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%s", pPartType->param.szName);
+               } else if (pPartType->param.szFileName[0] != '\0') {
+                       snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%s", pPartType->param.szFileName);
+               } else if (pPartType->szContentLocation[0] != '\0') {
+                       snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%s", pPartType->szContentLocation);
+               } else {
+                       snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%lu", (unsigned long)index);
+               }
+       }
 
+       // make full path for save
+       __MsgMakeFileName(pPartType->type, szFileName, pPartType->drmInfo.drmType, 0, szFileName, sizeof(szFileName));  //FL & CD -> extension(.dm) SD -> extension(.dcf)
 
        snprintf(szFullPath, MSG_FILEPATH_LEN_MAX, "%s%s.dir/%s", pszMailboxPath, pszMsgFilename, szFileName);  // get absolute path of each temp file of each part
-       snprintf(pPartType->param.szFileName, MSG_FILENAME_LEN_MAX+1, "%s.dir/%s", pszMsgFilename, szFileName);         // store relative path of each temp file of each part including sub folder.
 
        if (pPartType->type == MIME_APPLICATION_OCTET_STREAM)
-               MsgGetTypeByFileName(&pPartType->type, szFullPath);
+               MmsGetMimeTypeFromFileName(MIME_MAINTYPE_UNKNOWN, szFullPath, (MimeType *)&pPartType->type, NULL);
 
        // save file
-       if (bSave) {
+       bFileExist = MsgAccessFile(szFullPath, F_OK);
+
+       MSG_SEC_DEBUG("save flag  [%d],  filepath [%s], file exist [%d]", bSave, szFullPath, bFileExist);
+
+       if (bSave == true && bFileExist == false) {
+
                if ((pFile = MsgOpenFile(szFullPath, "wb+")) == NULL) {
                        MSG_DEBUG("MsgOpenFile failed");
                        goto __CATCH;
                }
 
-               if (MmsGetMediaPartData(pPartType, pPartBody, pFile) == false) {
+               if (__MmsGetMediaPartData(pPartType, pPartBody, pFile) == false) {
                        MSG_DEBUG("MmsGetMediaPartData fail [index:%d]\n", index);
                        goto __CATCH;
                }
 
                MsgCloseFile(pFile);
                pFile = NULL;
+
+               snprintf(pPartBody->szOrgFilePath, sizeof(pPartBody->szOrgFilePath), "%s", szFullPath);
+
+               //IF DRM type Convert to dcf
+               if (pPartType->type == MIME_APPLICATION_VND_OMA_DRM_MESSAGE
+                       || pPartType->type == MIME_APPLICATION_VND_OMA_DRM_CONTENT)
+               {
+                       char destDrmPath[MSG_FILEPATH_LEN_MAX] = {0,};
+
+                       if (MsgDrmConvertDmtoDcfType(pPartBody->szOrgFilePath, destDrmPath) == true) {
+                               MSG_INFO("Success Convert to Dcf");
+
+                               bFileExist = MsgAccessFile(destDrmPath, F_OK);
+
+                               if (bFileExist) {
+                                       snprintf(pPartBody->szOrgFilePath, sizeof(pPartBody->szOrgFilePath), "%s", destDrmPath);
+                                       MsgGetFileName(pPartBody->szOrgFilePath, szFileName, MSG_FILENAME_LEN_MAX);
+                               }
+
+                       } else {
+                               MSG_INFO("Fail Convert to Dcf");
+                       }
+
+                       if (MsgDrmIsDrmFile(pPartBody->szOrgFilePath) == true)
+                               MmsPluginDrmGetInfo(pPartBody->szOrgFilePath, pPartType);
+
+                       MSG_SEC_INFO("Drm File Path [%s] isdrm [%d]", pPartBody->szOrgFilePath, MsgDrmIsDrmFile(pPartBody->szOrgFilePath));
+               }
+
+               pPartBody->offset = 0;
+               pPartBody->size = MsgGetFileSize(pPartBody->szOrgFilePath);
+
                if (pPartType->drmInfo.drmType != MSG_DRM_TYPE_NONE) {
-                       MsgDrmRegisterFile(MSG_MODE_FILE, szFullPath, strlen(szFullPath));
+                       MsgDrmRegisterFile(MSG_MODE_FILE, pPartBody->szOrgFilePath, strlen(pPartBody->szOrgFilePath));
 
                        /* change szDrm2FullPath as current content path*/
                        if (pPartType->drmInfo.szDrm2FullPath) {
                                free(pPartType->drmInfo.szDrm2FullPath);
-                               pPartType->drmInfo.szDrm2FullPath = MsgStrCopy(szFullPath);
+                               pPartType->drmInfo.szDrm2FullPath = g_strdup(pPartBody->szOrgFilePath);
+                       }
+               }
+
+               MSG_SEC_DEBUG("Save Part File to [%s]", pPartBody->szOrgFilePath);
+
+       } else {
+               snprintf(pPartBody->szOrgFilePath, sizeof(pPartBody->szOrgFilePath), "%s", szFullPath);
+
+               //IF DRM type check dcf exist
+               if (pPartType->type == MIME_APPLICATION_VND_OMA_DRM_MESSAGE
+                       || pPartType->type == MIME_APPLICATION_VND_OMA_DRM_CONTENT)
+               {
+                       char destDrmPath[MSG_FILEPATH_LEN_MAX] = {0,};
+
+                       MsgGetFileNameWithoutExtension(destDrmPath, pPartBody->szOrgFilePath);
+                       strncat(destDrmPath, ".dcf", 4);
+
+                       bFileExist = MsgAccessFile(destDrmPath, F_OK);
+
+                       if (bFileExist) {
+                               snprintf(pPartBody->szOrgFilePath, sizeof(pPartBody->szOrgFilePath), "%s", destDrmPath);
+                               MsgGetFileName(pPartBody->szOrgFilePath, szFileName, MSG_FILENAME_LEN_MAX);
                        }
+
+                       if (MsgDrmIsDrmFile(pPartBody->szOrgFilePath) == true)
+                               MmsPluginDrmGetInfo(pPartBody->szOrgFilePath, pPartType);
                }
 
+               pPartBody->offset = 0;
+               pPartBody->size = MsgGetFileSize(pPartBody->szOrgFilePath);
+
+               MSG_SEC_DEBUG("Set Part File to [%s]", pPartBody->szOrgFilePath);
        }
-       MSG_DEBUG("****   MmsGetMediaPartData:  [Multi part]  E  N  D  (Successfully)  ***\n");
 
+       //file name fix
+       if (szFileName[0]  != '\0') {
+               snprintf(pPartType->param.szFileName, MSG_FILENAME_LEN_MAX+1, "%s.dir/%s", pszMsgFilename, szFileName);// store relative path of each temp file of each part including sub folder.
+               snprintf(pPartType->param.szName, MSG_LOCALE_FILENAME_LEN_MAX+1, "%s", szFileName);
+               MSG_SEC_DEBUG("Set Name : %s", pPartType->param.szName);
+       }
+
+       MSG_END();
        return true;
 
 __CATCH:
@@ -7997,13 +5680,11 @@ __CATCH:
                MsgCloseFile(pFile);
                pFile = NULL;
        }
-
+       MSG_END();
        return false;
 }
 
-
-
-bool MmsGetMediaPartData(MsgType *pPartType, MsgBody *pPartBody, FILE* pFile)
+bool __MmsGetMediaPartData(MsgType *pPartType, MsgBody *pPartBody, FILE* pFile)
 {
        int nRead = 0;
        int nRead2 = 0;
@@ -8013,8 +5694,7 @@ bool MmsGetMediaPartData(MsgType *pPartType, MsgBody *pPartBody, FILE* pFile)
        int msgEncodingValue = 0;
        int msgTypeValue = 0;
        int msgCharsetValue     = 0;
-       int cidLen = 0;
-       char *szCid = NULL;
+
        int offset = 0;
        int size = 0;
 
@@ -8022,8 +5702,6 @@ bool MmsGetMediaPartData(MsgType *pPartType, MsgBody *pPartBody, FILE* pFile)
        msgTypeValue = pPartType->type;
        msgCharsetValue = pPartType->param.charset;
 
-       cidLen = MsgStrlen(szCid);
-
        offset = pPartBody->offset;
        size = pPartBody->size;
 
@@ -8031,7 +5709,7 @@ bool MmsGetMediaPartData(MsgType *pPartType, MsgBody *pPartBody, FILE* pFile)
                pTempData = MsgOpenAndReadMmsFile(pPartBody->szOrgFilePath, offset, size, &nRead);
 
                if (pTempData == NULL) {
-                       MSG_DEBUG("MmsGetMediaPartData : pTempData read fail\n");
+                       MSG_DEBUG("pTempData read fail");
                        goto __CATCH;
                }
 
@@ -8042,20 +5720,28 @@ bool MmsGetMediaPartData(MsgType *pPartType, MsgBody *pPartBody, FILE* pFile)
        }
 
        if (pData == NULL) {
-               MSG_DEBUG("MmsGetMediaPartData : there is no data \n");
+               MSG_DEBUG("there is no data");
                goto __RETURN;
        }
 
-       pNewData = MmsGetBinaryUTF8Data(pData, nRead, msgEncodingValue, msgTypeValue, msgCharsetValue, &nRead2);
-       pPartType->encoding = MSG_ENCODING_BINARY;
+       pNewData = __MmsGetBinaryUTF8Data(pData, nRead, msgEncodingValue, msgTypeValue, msgCharsetValue, &nRead2);
 
-       if (MsgIsText(msgTypeValue))
-               pPartType->param.charset = MSG_CHARSET_UTF8;
+       if (pNewData) {
+               pPartType->encoding = MSG_ENCODING_BINARY;
 
-       if (MsgWriteFile(pNewData, sizeof(char), nRead2,  pFile) != (size_t)nRead2) {
-               MSG_DEBUG("MmsGetMediaPartData: file writing fail \n");
+               if (MmsIsTextType(msgTypeValue))
+                       pPartType->param.charset = MSG_CHARSET_UTF8;
 
-               goto __CATCH;
+               if (MsgWriteFile(pNewData, sizeof(char), nRead2,  pFile) != (size_t)nRead2) {
+                       MSG_DEBUG("file writing fail");
+                       goto __CATCH;
+               }
+
+       } else {
+               if (MsgWriteFile(pData, sizeof(char), nRead,  pFile) != (size_t)nRead) {
+                       MSG_DEBUG("file writing fail");
+                       goto __CATCH;
+               }
        }
 
 __RETURN:
@@ -8087,24 +5773,25 @@ __CATCH:
        return false;
 }
 
-char *MmsGetBinaryUTF8Data(char *pData, int nRead, int msgEncodingValue, int msgTypeValue, int msgCharsetValue, int *npRead)
+char *__MmsGetBinaryUTF8Data(char *pData, int nRead, int msgEncodingValue, int msgTypeValue, int msgCharsetValue, int *npRead)
 {
-       int nChar = 0;
        int nByte = 0;
        int nTemp = 0;
        char *pTemp = NULL;
-       unsigned short *mszTempStr = NULL;
+
        char *pConvertedStr     = NULL;
        char *pConvertedData = NULL;
        char *pNewData = NULL;
        char *pReturnData = NULL;
 
+       const char *pToCodeSet = "UTF-8";
+       const char *pFromCodeSet = NULL;
 
        switch (msgEncodingValue) {
        case MSG_ENCODING_BASE64:
 
-               pConvertedData = (char*)_MsgDecodeBase64((UCHAR*)pData, (ULONG)nRead, (ULONG*)&nByte);
-               MSG_DEBUG("MmsGetBinaryUTF8Data : MSG_ENCODING_BASE64     bodyLength = %d \n", nByte);
+               pConvertedData = (char*)MsgDecodeBase64((UCHAR*)pData, (ULONG)nRead, (ULONG*)&nByte);
+               MSG_DEBUG("MSG_ENCODING_BASE64 bodyLength [%d]", nByte);
 
                pTemp = pConvertedData;
                nTemp = nByte;
@@ -8113,8 +5800,8 @@ char *MmsGetBinaryUTF8Data(char *pData, int nRead, int msgEncodingValue, int msg
 
        case MSG_ENCODING_QUOTE_PRINTABLE:
 
-               pConvertedData = (char*)_MsgDecodeQuotePrintable((UCHAR*)pData, (ULONG)nRead, (ULONG*)&nByte);
-               MSG_DEBUG("MmsGetBinaryUTF8Data: MSG_ENCODING_QUOTE_PRINTABLE     bodyLength = %d \n", nByte);
+               pConvertedData = (char*)MsgDecodeQuotePrintable((UCHAR*)pData, (ULONG)nRead, (ULONG*)&nByte);
+               MSG_DEBUG("MSG_ENCODING_QUOTE_PRINTABLE bodyLength [%d]", nByte);
 
                pTemp = pConvertedData;
                nTemp = nByte;
@@ -8123,436 +5810,602 @@ char *MmsGetBinaryUTF8Data(char *pData, int nRead, int msgEncodingValue, int msg
 
        default:
 
-               MSG_DEBUG("MmsGetBinaryUTF8Data: 8bit    OR    Binary   bodyLength = %d \n", nRead);
-
+               MSG_DEBUG("encoding val [%d] bodyLength [%d]", msgEncodingValue, nRead);
                pTemp = pData;
                nTemp = nRead;
 
-               break;
+               break;
+       }
+
+       if (MmsIsTextType(msgTypeValue)) {
+
+               if (msgCharsetValue == MSG_CHARSET_US_ASCII) {
+                       pNewData = pTemp;
+                       *npRead = nTemp;
+               } else if (msgCharsetValue == MSG_CHARSET_UTF8) {
+
+                       // skip BOM (Byte Order Mark) bytes .. (Please refer to the http://www.unicode.org/faq/utf_bom.html#BOM)
+                       if (nTemp >= 3) {
+                               if (((UINT8)pTemp[0]) == 0xEF && ((UINT8)pTemp[1]) == 0xBB && ((UINT8)pTemp[2]) == 0xBF) {
+                                       pTemp += 3;
+                                       nTemp -= 3;
+                               }
+                       }
+
+                       pNewData = pTemp;
+                       *npRead = nTemp;
+               } else {
+
+                       UINT16 MIBenum = MmsGetBinaryValue(MmsCodeCharSet, msgCharsetValue);
+
+                       pFromCodeSet = MmsGetTextByCode(MmsCodeCharSet, MIBenum);
+
+                       MSG_DEBUG("char set enum = [%d], MIBenum = [%d], str = [%s]", msgCharsetValue, MIBenum, pFromCodeSet);
+
+                       if (pFromCodeSet) {
+                               MSG_DEBUG("Convert to UTF-8");
+
+                               if (MmsPluginTextConvert(pToCodeSet, pFromCodeSet, pTemp, nTemp, &pConvertedStr, npRead) == true) {
+                                       pNewData = pConvertedStr;
+                               } else {
+                                       MSG_DEBUG("Failed MmsPluginTextConvert");
+                                       pNewData = pTemp;
+                                       *npRead = nTemp;
+                               }
+
+                       } else {//unsupported charset
+                               MSG_DEBUG("unsupported charset");
+                               pNewData = pTemp;
+                               *npRead = nTemp;
+                       }
+               }
+
+       } else {
+               pNewData = pTemp;
+               *npRead = nTemp;
+       }
+
+       pReturnData = (char *)calloc(1, *npRead);
+       if (pReturnData == NULL) {
+               MSG_DEBUG("pReturnData alloc fail.");
+               goto __CATCH;
+       }
+
+       if (pNewData != NULL) {
+               memset(pReturnData, 0, *npRead);
+               memcpy(pReturnData, pNewData, *npRead);
+       }
+
+       if (pConvertedData) {
+               free(pConvertedData);
+               pConvertedData = NULL;
+       }
+
+       if (pConvertedStr) {
+               free(pConvertedStr);
+               pConvertedStr = NULL;
+       }
+
+       return pReturnData;
+
+__CATCH:
+
+       if (pConvertedData) {
+               free(pConvertedData);
+               pConvertedData = NULL;
+       }
+
+       if (pConvertedStr) {
+               free(pConvertedStr);
+               pConvertedStr = NULL;
+       }
+
+       return NULL;
+}
+
+static bool __MsgMakeFileName(int iMsgType, char *szFileName, MsgDrmType drmType, int nUntitleIndex, char *outBuf, int outBufLen)
+{
+       char szTemp[MSG_FILENAME_LEN_MAX+1]={0,};
+       char szTempFileName[MSG_FILENAME_LEN_MAX+1]={0,};
+       const char *pExt = NULL;
+
+       SECURE_SLOGD("Input : type  [0x%x], drmType [%d], filename [%s]", iMsgType, drmType, szFileName);
+
+       if (szFileName == NULL)
+               return false;
+
+       //Filename
+       int inp_len = strlen(szFileName);
+       if (inp_len > 0) {
+
+               pExt = strrchr(szFileName, '.');
+
+               if (pExt != NULL && *(pExt + 1) != '\0') {
+                       pExt = pExt +1;
+               } else {
+                       pExt = NULL;
+               }
+
+               MsgGetFileNameWithoutExtension(szTempFileName, szFileName);
+       } else {
+               if (nUntitleIndex >= 1) {
+                       snprintf(szTempFileName, sizeof(szTempFileName), "%s_%d", "untitled", nUntitleIndex);
+               } else {
+                       snprintf(szTempFileName, sizeof(szTempFileName), "%s", "untitled");
+               }
+       }
+
+       //extension
+       if (iMsgType == MIME_APPLICATION_VND_OMA_DRM_MESSAGE)
+               pExt = "dm";
+       else if (iMsgType == MIME_APPLICATION_VND_OMA_DRM_CONTENT)
+               pExt = "dcf";
+
+       if (pExt == NULL) { // find ext from content type
+
+               if (iMsgType == MIME_APPLICATION_OCTET_STREAM || iMsgType == MIME_UNKNOWN) {
+                       MSG_DEBUG("unsupported MsgType [%d]", iMsgType);
+                       goto __CATCH;
+               }
+
+               pExt = MimeGetExtFromMimeInt((MimeType)iMsgType);
+       }
+
+       //Filename + extension
+       if (pExt) {
+               snprintf(szTemp, sizeof(szTemp), "%s.%s", szTempFileName, pExt);
+       } else {
+               MSG_DEBUG("Failed to get extension of that mime data file.");
+               goto __CATCH;
+       }
+
+       snprintf(outBuf, outBufLen, "%s", szTemp);
+       SECURE_SLOGD("Result : filename [%s]", outBuf);
+       return true;
+
+__CATCH:
+       return false;
+}
+
+bool MsgGetFileNameWithoutExtension (char *szOutputName, char *szName)
+{
+       char *pszExt = NULL;
+
+       if (szOutputName == NULL) {
+               MSG_DEBUG("szOutputName is NULL");
+               return false;
+       }
+
+       strncpy(szOutputName, szName, strlen(szName));
+
+       if ((pszExt = strrchr(szOutputName, '.'))) {
+               if (pszExt[0] == '.')
+                       pszExt[0] = '\0';
+       }
+
+       return true;
+}
+
+bool MsgGetFileName(char *szFilePath, char *szFileName, int size)
+{
+       char *filename = NULL;
+       if (szFilePath) {
+               filename = strrchr(szFilePath, '/');
+               if (filename != NULL) {
+                       snprintf(szFileName, size, "%s", filename + 1);
+               } else {
+                       snprintf(szFileName, size, "%s", szFilePath);
+               }
+       } else {
+               return false;
+       }
+
+       return true;
+}
+
+bool MmsGetMediaPartHeader(int index, MsgType *pHeader)
+{
+       MmsMsg *pMsg = NULL;
+       MsgMultipart *pPart = NULL;
+
+       if (pHeader == NULL) {
+               MSG_DEBUG("Invalid pHeader input. It's null");
+               return false;
+       }
+
+       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+
+       MmsInitMsgType(pHeader);
+
+
+       /* Requires header of non-presentation */
+       if (MsgIsMultipart(pMsg->msgType.type)) {
+               MSG_DEBUG("Multipart header [index = %d] \n", index);
+
+               pPart = pMsg->msgBody.body.pMultipart;
+
+               while (pPart && index--)
+                       pPart = pPart->pNext;
+
+               if (pPart == NULL) {
+                       MSG_DEBUG("There is no such msg part.");
+                       return false;
+               }
+
+               memcpy(pHeader, &pPart->type, sizeof(MsgType));
+       } else {
+               MSG_DEBUG("Requires singlepart header");
+               memcpy(pHeader, &pMsg->msgType, sizeof(MsgType));
+       }
+
+       return true;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+
+MmsPluginDecoder *MmsPluginDecoder::pInstance = NULL;
+
+MmsPluginDecoder *MmsPluginDecoder::instance()
+{
+       if (!MmsPluginDecoder::pInstance)
+               MmsPluginDecoder::pInstance = new MmsPluginDecoder();
+
+       return MmsPluginDecoder::pInstance;
+}
+
+MmsPluginDecoder::MmsPluginDecoder(){}
+MmsPluginDecoder::~MmsPluginDecoder(){}
+
+void MmsPluginDecoder::decodeMmsPdu(MmsMsg *pMsg, msg_message_id_t msgID, const char *pduFilePath)
+{
+       MSG_BEGIN();
+
+       FILE *pFile     = NULL;
+       MsgMultipart *pMultipart = NULL;
+       int nSize = 0;
+       char szFullPath[MSG_FILEPATH_LEN_MAX] = {0, };
+       char szTempMediaDir[MSG_FILEPATH_LEN_MAX] = {0, };
+
+       MmsInitHeader();
+
+       pMsg->msgID = msgID;
+
+       snprintf(szFullPath, sizeof(szFullPath), "%s", pduFilePath);
+
+       MsgGetFileName(szFullPath, pMsg->szFileName, sizeof(pMsg->szFileName));
+
+       if (MsgGetFileSize(szFullPath, &nSize) == false) {
+               MSG_FATAL("Fail MsgGetFileSize");
+               goto __CATCH;
        }
 
-       if (MsgIsText(msgTypeValue)) {
-               /* charset converting */
+       pFile = MsgOpenFile(szFullPath, "rb");
+       if (pFile == NULL) {
+               MSG_SEC_DEBUG("Fail MsgOpenFile [%s]", szFullPath);
+               goto __CATCH;
+       }
 
-               switch (msgCharsetValue) {
-               case MSG_CHARSET_UTF16:
-               case MSG_CHARSET_USC2:
+       MmsRegisterDecodeBuffer();
 
-                       MSG_DEBUG("MmsGetBinaryUTF8Data: MSG_CHARSET_USC2 \n");
+       if (MmsBinaryDecodeMsgHeader(pFile, nSize) == false) {
+               MSG_FATAL("Fail to MmsBinaryDecodeMsgHeader");
+               goto __CATCH;
+       }
 
-                       if (((UINT8)pTemp[0]) == 0xFF && ((UINT8)pTemp[1]) == 0xFE) {
-                               nChar = (nTemp / 2 - 1);
+       if (MmsBinaryDecodeMsgBody(pFile, szFullPath, nSize) == false) {
+               MSG_FATAL("Fail to MmsBinaryDecodeMsgBody");
+               goto __CATCH;
+       }
 
-                               mszTempStr = (unsigned short*) malloc(nChar * sizeof(unsigned short));
-                               if (mszTempStr == NULL) {
-                                       MSG_DEBUG("MmsGetBinaryUTF8Data : 1. Memory Full !!! \n");
-                                       goto __CATCH;
-                               }
+       /* Set mmsHeader.msgType & msgBody to pMsg ----------- */
 
-                               memcpy(mszTempStr, ((unsigned short*)pTemp + 1), nChar * sizeof(unsigned short));
+       memcpy(&(pMsg->msgType), &(mmsHeader.msgType), sizeof(MsgType));
+       memcpy(&(pMsg->msgBody), &(mmsHeader.msgBody), sizeof(MsgBody));
 
-                               nByte = MsgGetUnicode2UTFCodeSize(((unsigned short*)pTemp + 1), nChar);
+{//attribute convert mmsHeader -> mmsAttribute
 
-                               pConvertedStr = (char *)malloc(nByte + 1);
-                               if (pConvertedStr != NULL)
-                                       MsgUnicode2UTF ((unsigned char*)pConvertedStr, nByte + 1, mszTempStr, nChar);
-                       } else {
-                               nChar = (nTemp / 2);
+       pMsg->mmsAttrib.contentType = (MimeType)mmsHeader.msgType.type;
 
-                               mszTempStr = (unsigned short*) malloc(nChar * sizeof(unsigned short));
-                               if (mszTempStr == NULL) {
-                                       MSG_DEBUG("MmsGetBinaryUTF8Data: 2. Memory Full !!! \n");
-                                       goto __CATCH;
-                               }
+       pMsg->mmsAttrib.date = mmsHeader.date;
 
-                               memcpy(mszTempStr, ((unsigned short*)pTemp), nChar * sizeof(unsigned short));
+       if (mmsHeader.deliveryReport == MMS_REPORT_YES) {
+               pMsg->mmsAttrib.bAskDeliveryReport = true;
+       }
 
-                               nByte = MsgGetUnicode2UTFCodeSize(((unsigned short*)pTemp), nChar);
+       memcpy(&pMsg->mmsAttrib.deliveryTime, &mmsHeader.deliveryTime, sizeof(MmsTimeStruct));
 
-                               pConvertedStr = (char *)malloc(nByte + 1);
-                               if (pConvertedStr)
-                                       MsgUnicode2UTF ((unsigned char*)pConvertedStr, nByte + 1, mszTempStr, nChar);
-                       }
+       memcpy(&pMsg->mmsAttrib.expiryTime, &mmsHeader.expiryTime, sizeof(MmsTimeStruct));
 
-                       if (pConvertedStr != NULL)
-                               pNewData = pConvertedStr;
+       MSG_DEBUG("@@@@@pMsg->mmsAttrib.deliveryTime=[%d]", pMsg->mmsAttrib.deliveryTime);
 
-                       *npRead = nByte + 1;
+       pMsg->mmsAttrib.msgClass = mmsHeader.msgClass;
 
-                       break;
+       snprintf(pMsg->szMsgID, sizeof(pMsg->szMsgID), "%s", mmsHeader.szMsgID);
 
-               case MSG_CHARSET_US_ASCII:
+       pMsg->mmsAttrib.msgType = mmsHeader.type;
 
-                       MSG_DEBUG("MmsGetBinaryUTF8Data: MSG_CHARSET_US_ASCII \n");
+       pMsg->mmsAttrib.version = mmsHeader.version;
 
-                       /* fall through */
+       pMsg->mmsAttrib.msgSize = mmsHeader.msgSize;
 
-               case MSG_CHARSET_UTF8:
+       pMsg->mmsAttrib.priority = mmsHeader.priority;
 
-                       MSG_DEBUG("MmsGetBinaryUTF8Data: MSG_CHARSET_UTF8 or Others \n");
+       if (mmsHeader.readReply == MMS_REPORT_YES) {
+               pMsg->mmsAttrib.bAskReadReply = true;
+       }
 
-                       // skip BOM (Byte Order Mark) bytes .. (Please refer to the http://www.unicode.org/faq/utf_bom.html#BOM)
-                       if (nTemp >= 3) {
-                               if (((UINT8)pTemp[0]) == 0xEF && ((UINT8)pTemp[1]) == 0xBB && ((UINT8)pTemp[2]) == 0xBF) {
-                                       pTemp += 3;
-                                       nTemp -= 3;
-                               }
-                       }
-                       pNewData = pTemp;
-                       *npRead = nTemp;
+       snprintf(pMsg->mmsAttrib.szSubject, sizeof(pMsg->mmsAttrib.szSubject), "%s", mmsHeader.szSubject);
 
-                       break;
+       snprintf(pMsg->szTrID, sizeof(pMsg->szTrID), "%s", mmsHeader.szTrID);
 
-               case MSG_CHARSET_ISO_8859_7:
+       pMsg->mmsAttrib.retrieveStatus = mmsHeader.retrieveStatus;
 
-                       /* Greek */
+       //FIXME:: mmsHeader will release after delete global mmsHeader
+       //memset(&(mmsHeader.msgBody), 0x00, sizeof(MsgBody));//After copy to MmsMsg
+}
+       if (pMsg->msgBody.pPresentationBody) {
+               if(MsgFseek(pFile, pMsg->msgBody.pPresentationBody->offset, SEEK_SET) < 0)
+                       goto __CATCH;
 
-                       MSG_DEBUG("MmsGetBinaryUTF8Data: MSG_CHARSET_ISO_8859_7 \n");
+               pMsg->msgBody.pPresentationBody->body.pText = (char *)calloc(1, pMsg->msgBody.pPresentationBody->size + 1);
+               if (pMsg->msgBody.pPresentationBody->body.pText == NULL)
+                       goto __CATCH;
 
-                       nByte = MsgGetLatin72UTFCodeSize((unsigned char*)pTemp, nTemp);
-                       pConvertedStr = (char *)malloc(nByte + 1);
-                       if (pConvertedStr)
-                               MsgLatin7code2UTF((unsigned char*)pConvertedStr, nByte + 1, (unsigned char*)pTemp, nTemp);
+               memset(pMsg->msgBody.pPresentationBody->body.pText, 0, pMsg->msgBody.pPresentationBody->size + 1);
 
-                       pNewData = pConvertedStr;
-                       *npRead = nByte + 1;
+               ULONG nRead = 0;
+               nRead = MsgReadFile(pMsg->msgBody.pPresentationBody->body.pText, sizeof(char), pMsg->msgBody.pPresentationBody->size, pFile);
+               if (nRead == 0)
+                       goto __CATCH;
 
-                       break;
+       }
 
-               case MSG_CHARSET_ISO_8859_9:
+       MsgCloseFile(pFile);
+       pFile = NULL;
+       /* nPartCount */
+       pMsg->nPartCount = 0;
 
-                       /* Turkish */
-                       MSG_DEBUG("MmsGetBinaryUTF8Data: MSG_CHARSET_ISO_8859_9 \n");
+       if (MsgIsMultipart(mmsHeader.msgType.type) == true) {
+               pMultipart = pMsg->msgBody.body.pMultipart;
+               while (pMultipart) {
+                       pMsg->nPartCount++;
+                       pMultipart = pMultipart->pNext;
+               }
+       } else {
+               if (pMsg->msgBody.size > 0)
+                       pMsg->nPartCount++;
+       }
 
-                       nByte = MsgGetLatin52UTFCodeSize((unsigned char*)pTemp, nTemp);
-                       pConvertedStr = (char *)malloc(nByte + 1);
-                       if (pConvertedStr)
-                                       MsgLatin5code2UTF((unsigned char*)pConvertedStr, nByte + 1, (unsigned char*)pTemp, nTemp);
+       /*      make temporary  */
+       snprintf(szTempMediaDir, MSG_FILEPATH_LEN_MAX, "%s%s.dir", MSG_DATA_PATH, pMsg->szFileName);
 
-                       pNewData = pConvertedStr;
-                       *npRead = nByte + 1;
+       if (MsgIsMultipart(pMsg->msgType.type) == true) {
+               int partIndex = 0;
+               pMultipart = pMsg->msgBody.body.pMultipart;
 
-                       break;
+               //if (bSavePartsAsTempFiles) {
+                       if (mkdir(szTempMediaDir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
+                               if (errno == EEXIST) {
+                                       MSG_SEC_DEBUG("exist dir : [%s]", szTempMediaDir);
+                               } else {
+                                       MSG_SEC_DEBUG("Fail to Create Dir [%s]", szTempMediaDir);
+                                       goto __CATCH;
+                               }
+                       } else {
+                               MSG_SEC_DEBUG("make dir : [%s]", szTempMediaDir);
+                       }
+               //}
 
-               default:
+               if (pMsg->msgBody.pPresentationBody) {
+                       if (__MmsMultipartSaveAsTempFile(&pMsg->msgBody.presentationType, pMsg->msgBody.pPresentationBody,
+                                                                                               (char*)MSG_DATA_PATH, pMsg->szFileName, 0, true) == false)
+                               goto __CATCH;
+               }
 
-                       MSG_DEBUG("MmsGetBinaryUTF8Data: Other charsets \n");
+               while (pMultipart) {
 
-                       nByte = MsgGetLatin2UTFCodeSize((unsigned char*)pTemp, nTemp);
-                       pConvertedStr = (char *)malloc(nByte + 1);
-                       if (pConvertedStr)
-                               MsgLatin2UTF((unsigned char*)pConvertedStr, nByte + 1, (unsigned char*)pTemp, nTemp);
+                       if (__MmsMultipartSaveAsTempFile(&pMultipart->type, pMultipart->pBody,
+                                                                                       (char*)MSG_DATA_PATH, pMsg->szFileName, partIndex, true) == false)
+                               goto __CATCH;
 
-                       pNewData = pConvertedStr;
-                       *npRead = nByte + 1;
+                       MmsPrintMulitpart(pMultipart, partIndex);
 
-                       break;
+                       pMultipart = pMultipart->pNext;
+                       partIndex ++;
                }
-       } else {
-               pNewData = pTemp;
-               *npRead = nTemp;
-       }
 
-       pReturnData = (char *)malloc(*npRead);
-       if (pReturnData == NULL) {
-               MSG_DEBUG("MmsGetBinaryUTF8Data : pReturnData alloc fail. \n");
+       } else { //single part
+               if (pMsg->nPartCount > 0) {
 
-               goto __CATCH;
-       }
+                       //if (bSavePartsAsTempFiles) {
+                               if (mkdir(szTempMediaDir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
+                                       if (errno == EEXIST) {
+                                               MSG_DEBUG("exist dir : [%s]", szTempMediaDir);
+                                       } else {
+                                               MSG_DEBUG("Fail to Create Dir [%s]", szTempMediaDir);
+                                               goto __CATCH;
+                                       }
+                               } else {
+                                       MSG_DEBUG("make dir : [%s]", szTempMediaDir);
+                               }
+                       //}
 
-       if (pNewData != NULL) {
-               memset(pReturnData, 0, *npRead);
-               memcpy(pReturnData, pNewData, *npRead);
+                       if (__MmsMultipartSaveAsTempFile(&pMsg->msgType, &pMsg->msgBody,
+                                                                                       (char*)MSG_DATA_PATH, pMsg->szFileName, 0, true) == false)
+                               goto __CATCH;
+               }
        }
+       MSG_DEBUG("### Success ###");
+       MSG_END();
+       return;
 
-       if (pConvertedData) {
-               free(pConvertedData);
-               pConvertedData = NULL;
-       }
+__CATCH:
 
-       if (pConvertedStr) {
-               free(pConvertedStr);
-               pConvertedStr = NULL;
-       }
+       MmsInitHeader();
+       MmsUnregisterDecodeBuffer();
 
-       if (mszTempStr) {
-               free(mszTempStr);
-               mszTempStr = NULL;
+       if (pFile != NULL) {
+               MsgCloseFile(pFile);
+               pFile = NULL;
        }
 
-       return pReturnData;
-
-__CATCH:
 
-       if (pConvertedData) {
-               free(pConvertedData);
-               pConvertedData = NULL;
-       }
+       MmsReleaseMsgDRMInfo(&pMsg->msgType.drmInfo);
 
-       if (pConvertedStr) {
-               free(pConvertedStr);
-               pConvertedStr = NULL;
-       }
+       MmsReleaseMsgBody(&pMsg->msgBody, pMsg->msgType.type);
 
-       if (mszTempStr) {
-               free(mszTempStr);
-               mszTempStr = NULL;
-       }
+       MSG_DEBUG("### Fail ###");
+       MSG_END();
+       return;
 
-       return NULL;
 }
 
-#ifndef __SUPPORT_DRM__
-bool MsgMakeFileName(int iMsgType, char *szFileName, int nUntitleIndex)
+//CID 41989: Removed function decodeMmsPdu which is unused.
+#if 0
+void MmsPluginDecoder::decodeMmsPdu(MMS_DATA_S *pMmsData, const char *pduFilePath)
 {
-       char szText[MSG_FILENAME_LEN_MAX+1]={0,};
-       char szTemp[MSG_FILENAME_LEN_MAX+1]={0,};
-       char szTempFileName[MSG_FILENAME_LEN_MAX+1]={0,};
-       char *pExt = NULL;
+       MSG_BEGIN();
 
+       FILE *pFile     = NULL;
+       MsgMultipart * iter_multipart = NULL;
+       int nSize = 0;
+       char szFullPath[MSG_FILEPATH_LEN_MAX] = {0, };
 
-       MSG_DEBUG("MsgMakeFileName: iMsgType = %d     szFileName = %s \n", iMsgType, szFileName);
+       MmsInitHeader();
 
-       if (szFileName == NULL)
-               return false;
+       //pMsg->msgID = msgID;
 
-       if (szFileName && (szFileName[0] != '\0')) {
-               MsgGetFileNameWithoutExtension (szTempFileName, szFileName);
+       snprintf(szFullPath, sizeof(szFullPath), "%s", pduFilePath);
 
-               pExt = strrchr(szTempFileName, '.');
-               if (pExt == NULL) {
-                       memset  (szText, 0, MSG_FILENAME_LEN_MAX+1);
-                       strncpy(szText, szTempFileName, MSG_FILEPATH_LEN_MAX - 1);
-                       strcat(szText, ".");                    // add '.'
-               } else {
-                       memset  (szText, 0, MSG_FILENAME_LEN_MAX+1);
-                       strncpy(szText, szTempFileName, pExt+1 - szFileName);   // add '.'
-               }
-       } else {
-               if (nUntitleIndex >= 1) {
-                       snprintf(szText, MSG_FILENAME_LEN_MAX+1, "%s_%d.", "Untitled", nUntitleIndex);
-               } else {
-                       snprintf(szText, MSG_FILENAME_LEN_MAX+1, "%s.", "Untitled");
-               }
-       }
+       //MsgGetFileName(szFullPath, pMsg->szFileName, sizeof(pMsg->szFileName));
 
-       if (iMsgType == MIME_APPLICATION_OCTET_STREAM) {
-               MSG_DEBUG("MsgMakeFileName: unsupported MsgType\n");
+       if (MsgGetFileSize(szFullPath, &nSize) == false) {
+               MSG_FATAL("Fail MsgGetFileSize");
                goto __CATCH;
-       } else {
-               int             nLen = 0;
-               strncpy(szTemp, szText, MSG_FILENAME_LEN_MAX - 5);
-               if (iMsgType == MIME_UNKNOWN || (pExt = MimeGetExtFromMimeInt((MimeType)iMsgType)) == NULL) {
-                       MSG_DEBUG("MsgMakeFileName: Failed to get extension of that mime data file. \n");
-                       goto __CATCH;
-               }
-               nLen = MSG_FILENAME_LEN_MAX - strlen(szTemp);
-               strncat(szTemp, pExt, nLen);
        }
 
+       pFile = MsgOpenFile(szFullPath, "rb");
+       if (pFile == NULL) {
+               MSG_SEC_DEBUG("Fail MsgOpenFile [%s]", szFullPath);
+               goto __CATCH;
+       }
 
-       strcpy(szFileName, szTemp);
-
-       MSG_DEBUG("MsgMakeFileName: made szFileName = %s \n", szFileName);
+       MmsRegisterDecodeBuffer();
 
-       return true;
+       if (MmsBinaryDecodeMsgHeader(pFile, nSize) == false) {
+               MSG_FATAL("Fail to MmsBinaryDecodeMsgHeader");
+               goto __CATCH;
+       }
 
-__CATCH:
-       {
-               char *p = NULL;
-               p = strrchr(szText, '.');
-               if (p != NULL)
-                       *p = 0;
-               snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%s", szText);
+       if (MmsBinaryDecodeMsgBody(pFile, szFullPath, nSize) == false) {
+               MSG_FATAL("Fail to MmsBinaryDecodeMsgBody");
+               goto __CATCH;
+       }
 
-               return false;
+       //set header
+       if (pMmsData->header == NULL) {
+               pMmsData->header = MsgMmsCreateHeader();
        }
-}
-#else
-bool MsgMakeFileName(int iMsgType, char *szFileName, MsgDrmType drmType, int nUntitleIndex)
-{
-       char szText[MSG_FILENAME_LEN_MAX+1]={0,};
-       char szTemp[MSG_FILENAME_LEN_MAX+1]={0,};
-       char szTempFileName[MSG_FILENAME_LEN_MAX+1]={0,};
-       char *pExt = NULL;
 
-       MSG_DEBUG("MsgMakeFileName: iMsgType = 0x%x, drmType = %d, szFileName = %s \n", iMsgType, drmType, szFileName);
+       pMmsData->header->messageType = mmsHeader.type;
 
-       if (szFileName == NULL)
-               return false;
+       pMmsData->header->mmsVersion = mmsHeader.version;
 
-       if (szFileName && (szFileName[0] != '\0')) {
-               MsgGetFileNameWithoutExtension (szTempFileName, szFileName);
+       pMmsData->header->contentType = mmsHeader.msgType.type;
 
-               if (drmType != MSG_DRM_TYPE_NONE) {
-                       pExt = strrchr(szTempFileName, '.');
-                       if (pExt == NULL) {
-                               memset(szText, 0, MSG_FILENAME_LEN_MAX+1);
-                               strncpy(szText, szTempFileName, MSG_FILENAME_LEN_MAX - 1);
-                               strcat(szText, ".");                    // add '.'
-                       } else {
-                               memset(szText, 0, MSG_FILENAME_LEN_MAX+1);
-                               strncpy(szText, szTempFileName, pExt+1 - szFileName);
-                       }
-               } else {
-                       if (strrchr(szTempFileName, '.'))
-                               return true;
+       pMmsData->header->date = mmsHeader.date;
 
-                       memset(szText, 0, MSG_FILENAME_LEN_MAX+1);
-                       strncpy(szText, szTempFileName, MSG_FILENAME_LEN_MAX - 1);
-               //temporary commented to save file as original name.
-                       pExt = strrchr(szFileName, '.');
-               }
-       } else {
-               if (nUntitleIndex >= 1) {
-                       snprintf(szText, MSG_FILENAME_LEN_MAX+1, "%s_%d.", "untitled", nUntitleIndex);
-               } else {
-                       snprintf(szText, MSG_FILENAME_LEN_MAX+1, "%s.", "untitled");
-               }
-       }
+       pMmsData->header->messageSize  = mmsHeader.msgSize;
 
-       if (drmType == MSG_DRM_TYPE_SD) {
-               strncpy(szTemp, szText, MSG_FILENAME_LEN_MAX - 5);
-               strcat(szTemp, "dcf");
-       } else if (MsgDRMIsForwardLockType(drmType)) {
-               strncpy(szTemp, szText, MSG_FILENAME_LEN_MAX - 4);
-               strcat(szTemp, "dm");
-       } else {
-               if (iMsgType == MIME_APPLICATION_OCTET_STREAM) {
-                       MSG_DEBUG("MsgMakeFileName: unsupported MsgType\n");
-                       goto __CATCH;
-               } else {
-                       int             nLen = 0;
-                       strncpy(szTemp, szText, MSG_FILENAME_LEN_MAX - 5);
-                       //temporary commented to save file as original name.
-                       if (pExt == NULL) {
+       pMmsData->header->mmsPriority = mmsHeader.priority;
 
-                               if (iMsgType == MIME_UNKNOWN || (pExt = MimeGetExtFromMimeInt((MimeType)iMsgType)) == NULL) {
-                                       MSG_DEBUG("MsgMakeFileName: Failed to get extension of that mime data file. \n");
-                                       goto __CATCH;
-                               }
-                       }
+       pMmsData->header->messageClass = mmsHeader.msgClass;
 
-                       nLen = MSG_FILENAME_LEN_MAX - strlen(szTemp);
-                       strncat(szTemp, pExt, nLen);
-               }
+       if (mmsHeader.deliveryReport == MMS_REPORT_YES) {
+               pMmsData->header->bDeliveryReport = true;
        }
 
-       strcpy(szFileName, szTemp);
+       if (mmsHeader.readReply == MMS_REPORT_YES) {
+               pMmsData->header->bReadReport = true;
+       }
 
-       MSG_DEBUG("MsgMakeFileName: made szFileName = %s \n", szFileName);
+       memcpy(&pMmsData->header->delivery, &mmsHeader.deliveryTime, sizeof(MmsTimeStruct));
 
-       return true;
+       memcpy(&pMmsData->header->expiry, &mmsHeader.expiryTime, sizeof(MmsTimeStruct));
 
-__CATCH:
-       {
-               char *p = NULL;
-               p = strrchr(szText, '.');
-               if (p != NULL)
-                       *p = 0;
-               snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%s", szText);
 
-               return false;
-       }
-}
-#endif
+       snprintf(pMmsData->header->messageID, sizeof(pMmsData->header->messageID), "%s", mmsHeader.szMsgID);
 
-bool MsgGetFileNameWithoutExtension (char *szOutputName, char *szName)
-{
-       char *pszExt = NULL;
+       snprintf(pMmsData->header->szSubject, sizeof(pMmsData->header->szSubject), "%s", mmsHeader.szSubject);
 
-       if (szOutputName == NULL) {
-               MSG_DEBUG("szOutputName is NULL");
-               return false;
-       }
+       snprintf(pMmsData->header->trID, sizeof(pMmsData->header->trID), "%s", mmsHeader.szTrID);
 
-       strncpy(szOutputName, szName, strlen(szName));
+       //CID 41989: Moving assignment of iter_multipart before its de-referencing.
+       iter_multipart = mmsHeader.msgBody.body.pMultipart;
+       //set multipart
+       if (pMmsData->header->contentType == MIME_MULTIPART_RELATED || pMmsData->header->contentType == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
 
-       if ((pszExt = strrchr(szOutputName, '.'))) {
-               if (pszExt[0] == '.')
-                       pszExt[0] = '\0';
-       }
+               MMS_MULTIPART_DATA_S *pMultipart = MsgMmsCreateMultipart();
 
-       return true;
-}
+               pMultipart->type = MIME_APPLICATION_SMIL;
+               snprintf(pMultipart->szContentType, sizeof(pMultipart->szContentType), "%s", "application/smil");
+               snprintf(pMultipart->szContentID, sizeof(pMultipart->szContentID), "%s", mmsHeader.msgBody.presentationType.szContentID);
+               snprintf(pMultipart->szContentLocation, sizeof(pMultipart->szContentLocation), "%s", mmsHeader.msgBody.presentationType.szContentLocation);
+               snprintf(pMultipart->szFileName, sizeof(pMultipart->szFileName), "%s", mmsHeader.msgBody.presentationType.param.szName);
 
-int MmsGetMediaPartCount(msg_message_id_t msgId)
-{
-       MmsMsg *pMsg;
+               //snprintf(pMultipart->szFilePath, sizeof(pMultipart->szFilePath), MSG_DATA_PATH"%s", mmsHeader.msgBody.presentationType.param.szFileName);
 
-       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+               MsgBody *pBody = iter_multipart->pBody;
+               pMultipart->pMultipartData = MsgOpenAndReadMmsFile(pBody->szOrgFilePath, pBody->offset, pBody->size, (int*)&pMultipart->nMultipartDataLen);
 
-       if (msgId != pMsg->msgID) {
-               MSG_DEBUG("Invalid Message Id");
-               return -1;
+               pMmsData->smil = pMultipart;
        }
 
-       return pMsg->nPartCount;
-}
-
-bool MmsGetMediaPartHeader(int index, MsgType *pHeader)
-{
-       MmsMsg *pMsg = NULL;
-       MsgMultipart *pPart = NULL;
 
-       if (pHeader == NULL) {
-               MSG_DEBUG("MmsGetMediaPartHeader: Invalid pHeader input. It's null \n");
-               return false;
-       }
+       while (iter_multipart) {
 
-       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+               MMS_MULTIPART_DATA_S *pMultipart = MsgMmsCreateMultipart();
 
-       _MsgInitMsgType(pHeader);
+               pMultipart->type = (MimeType)iter_multipart->type.type;
 
+               snprintf(pMultipart->szContentType, sizeof(pMultipart->szContentType), "%s",MimeGetMimeStringFromMimeInt(iter_multipart->type.type));
+               snprintf(pMultipart->szContentID, sizeof(pMultipart->szContentID), "%s", iter_multipart->type.szContentID);
+               snprintf(pMultipart->szContentLocation, sizeof(pMultipart->szContentLocation), "%s", iter_multipart->type.szContentLocation);
+               snprintf(pMultipart->szFileName, sizeof(pMultipart->szFileName), "%s", iter_multipart->type.param.szName);
 
-       /* Requires header of non-presentation */
-       if (MsgIsMultipart(pMsg->msgType.type)) {
-               MSG_DEBUG("MmsGetMediaPartHeader: Multipart header [index = %d] \n", index);
+               //snprintf(pMultipart->szFilePath, sizeof(pMultipart->szFilePath), "%s", iter_multipart->pBody->szOrgFilePath);
 
-               pPart = pMsg->msgBody.body.pMultipart;
+               MsgBody *pBody = iter_multipart->pBody;
+               pMultipart->pMultipartData = MsgOpenAndReadMmsFile(pBody->szOrgFilePath, pBody->offset, pBody->size, (int*)&pMultipart->nMultipartDataLen);
 
-               while (pPart && index--)
-                       pPart = pPart->pNext;
 
-               if (pPart == NULL) {
-                       MSG_DEBUG("MmsGetMediaPartHeader: There is no such msg part.\n");
-                       return false;
+#ifdef __SUPPORT_DRM__
+               if (iter_multipart->type.drmInfo.drmType != MSG_DRM_TYPE_NONE) {
+                       pMultipart->drmType = iter_multipart->type.drmInfo.drmType;
                }
+#endif
 
-               memcpy(pHeader, &pPart->type, sizeof(MsgType));
-       } else {
-               MSG_DEBUG("MmsGetMediaPartHeader: Requires singlepart header \n");
-               memcpy(pHeader, &pMsg->msgType, sizeof(MsgType));
+               pMmsData->multipartlist = g_list_append(pMmsData->multipartlist, pMultipart);
+               iter_multipart = iter_multipart->pNext;
        }
 
-       return true;
-}
 
-bool MmsDebugPrintMulitpartEntry(MsgMultipart *pMultipart, int index)
-{
-       MSG_DEBUG("------------------------------\n");
-       MSG_DEBUG("%dth multipart info\n", index);
-       MSG_DEBUG("header size=%d\n", pMultipart->type.size);
-       MSG_DEBUG("body size=%d\n", pMultipart->type.contentSize);
-       MSG_DEBUG("content type=%s\n", MmsDebugGetMimeType((MimeType)pMultipart->type.type));
-       MSG_DEBUG("content ID=%s\n", pMultipart->type.szContentID);
-       MSG_DEBUG("content location=%s\n", pMultipart->type.szContentLocation);
-
-       if (pMultipart->type.type == MIME_TEXT_PLAIN) {
-               MSG_DEBUG("text info\n");
-               MSG_DEBUG("charset=%d\n", pMultipart->type.param.charset);
-               MSG_DEBUG("text file name=%s\n", pMultipart->type.param.szName);
-       }
-#ifdef __SUPPORT_DRM__
-       if (pMultipart->type.drmInfo.drmType != MSG_DRM_TYPE_NONE) {
-               MSG_DEBUG("drm info\n");
-               MSG_DEBUG("drm type=%d      (0: NONE 1: Fowward Lock, 2:Combined Delivery, 3: Separated Delivery)\n", pMultipart->type.drmInfo.drmType);
-               MSG_DEBUG("drm content type=%s\n", MmsDebugGetMimeType((MimeType)pMultipart->type.drmInfo.contentType));
-               MSG_DEBUG("drm content URI=%s\n", pMultipart->type.drmInfo.szContentURI);
-               MSG_DEBUG("drm2FullPath=%s\n", pMultipart->type.drmInfo.szDrm2FullPath);
+       MSG_DEBUG("### SUCCESS ###");
+       MSG_END();
+       return;
+__CATCH:
+
+       MmsInitHeader();
+       MmsUnregisterDecodeBuffer();
+
+       if (pFile != NULL) {
+               MsgCloseFile(pFile);
+               pFile = NULL;
        }
-#endif
-       MSG_DEBUG("------------------------------\n");
-       return true;
-}
 
+       MSG_DEBUG("### Fail ###");
+       MSG_END();
+       return;
+}
+#endif
index ac0630a..160abdb 100755 (executable)
@@ -1,88 +1,55 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <string.h>
+
+#if MSG_DRM_SUPPORT
 #include <drm_client_types.h>
 #include <drm_client.h>
+#endif
+
+#include "MsgDrmWrapper.h"
 #include "MmsPluginDrm.h"
 #include "MmsPluginCodec.h"
-#include "MsgMmsTypes.h"
-#include "MsgDrmWrapper.h"
-#include "MsgDebug.h"
-
-
-#ifdef __SUPPORT_DRM__
+#include "MmsPluginMIME.h"
+#include "MmsPluginDebug.h"
 
-MmsDrm2ConvertState    mmsDrm2ConvertState;
-
-MsgDrmType MsgGetDRMType(MsgType *pMsgType, MsgBody *pMsgBody)
-{
-       MsgDrmType drmType = MSG_DRM_TYPE_NONE;
-       MsgMultipart *pMultipart = NULL;
-
-       if (MsgIsMultipart(pMsgType->type)) {
-               pMultipart = pMsgBody->body.pMultipart;
-               while (pMultipart) {
-                       if (drmType < pMultipart->type.drmInfo.drmType)
-                               drmType = pMultipart->type.drmInfo.drmType;
-
-                       pMultipart = pMultipart->pNext;
-               }
-       } else {
-               drmType = pMsgType->drmInfo.drmType;
-       }
-
-       return drmType;
-}
-
-void MmsDrm2SetConvertState(MmsDrm2ConvertState newConvertState)
-{
-       mmsDrm2ConvertState = newConvertState;
-       MSG_DEBUG("MmsDrm2SetConvertState: mmsDrm2ConvertState = %d\n", mmsDrm2ConvertState);
-}
-
-MmsDrm2ConvertState MmsDrm2GetConvertState(void)
-{
-       return mmsDrm2ConvertState;
-}
-
-bool MsgDRM2GetDRMInfo(char *szFilePath, MsgType *pMsgType)
+bool MmsPluginDrmGetInfo(const char *szFilePath, MsgType *pMsgType)
 {
+#if MSG_DRM_SUPPORT
        if (szFilePath == NULL || pMsgType == NULL) {
                MSG_DEBUG("Param is NULL szFilePath = %d, pMsgType = %d", szFilePath, pMsgType);
                return false;
        }
 
-       char szMimeType[DRM_MAX_LEN_MIME + 1];
-       char szContentID[DRM_MAX_LEN_CID + 1];
+       char szMimeType[DRM_MAX_LEN_MIME + 1] = {0,};
+       char szContentID[DRM_MAX_LEN_CID + 1] = {0,};
        MSG_DRM_TYPE drmType = MSG_DRM_NONE;
+       int ret = 0;
 
        MsgDrmGetDrmType(szFilePath, &drmType);
        MsgDrmGetMimeTypeEx(szFilePath, szMimeType, sizeof(szMimeType));
        MsgDrmGetContentID(szFilePath, szContentID, sizeof(szContentID));
-       MSG_DEBUG("drmType: %d", drmType);
+
+       MSG_DEBUG("drmType: [%d], mimetype: [%s], contentID: [%s]", drmType, szMimeType, szContentID);
 
        switch (drmType) {
        case MSG_DRM_FORWARD_LOCK:
                pMsgType->drmInfo.drmType = MSG_DRM_TYPE_FL;
-               pMsgType->drmInfo.contentType = (MsgContentType)_MsgGetCode(MSG_TYPE, szMimeType);
-               if (MsgCopyDrmInfo(pMsgType) == false) {
-                       MSG_DEBUG("MsgDRM2GetDRMInfo : MsgCopyDrmInfo failed");
-                       return false;
-               }
+               pMsgType->drmInfo.contentType = MimeGetMimeIntFromMimeString(szMimeType);
                break;
 
        case MSG_DRM_COMBINED_DELIVERY:
@@ -92,20 +59,23 @@ bool MsgDRM2GetDRMInfo(char *szFilePath, MsgType *pMsgType)
 
        case MSG_DRM_SEPARATE_DELIVERY:
                pMsgType->drmInfo.drmType = MSG_DRM_TYPE_SD;
-
-               pMsgType->drmInfo.contentType = (MsgContentType)_MsgGetCode(MSG_TYPE, szMimeType);
+               pMsgType->drmInfo.contentType = MimeGetMimeIntFromMimeString(szMimeType);
 
                drm_content_info_s dcfHdrInfo;
                bzero(&dcfHdrInfo, sizeof(drm_content_info_s));
-               drm_get_content_info(szFilePath, &dcfHdrInfo);
+               ret = drm_get_content_info(szFilePath, &dcfHdrInfo);
+               if (ret != DRM_RETURN_SUCCESS)
+                       MSG_DEBUG("drm_get_content_info is failed, ret=[%d]", ret);
 
                drm_file_info_s fileInfo;
                bzero(&fileInfo, sizeof(drm_file_info_s));
-               drm_get_file_info(szFilePath,&fileInfo);
+               ret = drm_get_file_info(szFilePath, &fileInfo);
+               if (ret != DRM_RETURN_SUCCESS)
+                       MSG_DEBUG("drm_get_file_info is failed, ret=[%d]", ret);
 
                if (fileInfo.oma_info.version == DRM_OMA_DRMV1_RIGHTS) {
                        pMsgType->drmInfo.szContentName = MsgRemoveQuoteFromFilename(dcfHdrInfo.title);
-                       pMsgType->drmInfo.szContentDescription = MsgStrCopy(dcfHdrInfo.description);
+                       pMsgType->drmInfo.szContentDescription = g_strdup(dcfHdrInfo.description);
                }
                break;
 
@@ -114,60 +84,9 @@ bool MsgDRM2GetDRMInfo(char *szFilePath, MsgType *pMsgType)
                break;
        }
 
-       pMsgType->drmInfo.szDrm2FullPath = MsgStrCopy(szFilePath);
+       pMsgType->drmInfo.szDrm2FullPath = g_strdup(szFilePath);
        MSG_DEBUG("pMsgType->drmInfo.szDrm2FullPath: %s", pMsgType->drmInfo.szDrm2FullPath);
 
+#endif
        return true;
 }
-
-bool MsgDRMIsForwardLockType(MsgDrmType        drmType)
-{
-       switch (drmType) {
-       case MSG_DRM_TYPE_FL:
-       case MSG_DRM_TYPE_CD:
-               return true;
-
-       case MSG_DRM_TYPE_NONE:         //SD & plain can be forwarded
-       case MSG_DRM_TYPE_SD:
-       default:
-               return false;
-       }
-}
-
-bool MsgChangeDrm2FileName(char *szFileName)
-{
-       char szTempFileName[MSG_FILENAME_LEN_MAX] = {0,};
-
-       if (szFileName == NULL || szFileName[0] == '\0')
-               return false;
-
-       MsgGetFileNameWithoutExtension(szTempFileName, szFileName);
-
-       if (strrchr(szTempFileName, '.'))
-               return true;
-
-       strcat(szTempFileName, ".dcf");
-       strcpy(szFileName, szTempFileName);
-
-       MSG_DEBUG("MsgChangeDrm2FileName: made szFileName = %s \n", szFileName);
-
-       return true;
-}
-
-bool MsgIsDCFFile(char *szFilePath)
-{
-       int length = 0;
-
-       MSG_DEBUG("MsgIsDCFFile: szFilePath = %s \n", szFilePath);
-
-       length = MsgStrlen(szFilePath);
-       if (szFilePath[length - 4] == '.' &&
-               (szFilePath[length - 3] == 'd' || szFilePath[length - 3] == 'D') &&
-               (szFilePath[length - 2] == 'c' || szFilePath[length - 2] == 'C') &&
-               (szFilePath[length - 1] == 'f' || szFilePath[length - 1] == 'F'))
-               return true;
-
-       return false;
-}
-
-#endif
index ca26649..abf59b1 100755 (executable)
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <time.h>
 #include <stdlib.h>
+#include <stdio.h>
+#include <errno.h>
+#include <sys/stat.h>
 
-#include "MmsPluginMessage.h"
-#include "MmsPluginCodec.h"
-#include "MsgDebug.h"
+#include "MsgCppTypes.h"
 #include "MsgUtilFile.h"
+
+#include "MmsPluginDebug.h"
+#include "MmsPluginEncode.h"
+#include "MmsPluginCodecTypes.h"
+#include "MmsPluginCodecCommon.h"
 #include "MmsPluginMIME.h"
+#include "MmsPluginUtil.h"
 
-gint _g_time_rev_set = 0;
-gint _g_time_rev = 0;
+using namespace std;
 
 /**  Sending message related variables  ------------------------ */
-
 static char gszMmsEncodeBuf[MSG_MMS_ENCODE_BUFFER_MAX] = {0, };
 static int gCurMmsEncodeBuffPos = 0;   /* number of characters on gpMmsEncodeBuf */
 static int     gMmsEncodeMaxLen = 0;
 static int     gMmsEncodeCurOffset = 0;        /* offset in file */
 static char *gpMmsEncodeBuf = NULL;
 
-
 /* Acknowledge.ind & NotifyResp.ind related variables ------------------------ */
-
 static char gszMmsEncodeBuf2[MSG_MMS_ENCODE_BUFFER_MAX] = {0, };
 static int     gCurMmsEncodeBuffPos2 = 0;      /* number of characters on gpMmsEncodeBuf */
 static int     gMmsEncodeMaxLen2 = 0;
 static int     gMmsEncodeCurOffset2 = 0;       /* offset in file */
 static char *gpMmsEncodeBuf2 = NULL;
 
-
-bool _MmsBinaryEncodeSendReqHdr(FILE *pFile, MmsMsg *pMsg);
-bool _MmsBinaryEncodeAckIndHdr(FILE *pFile, char *pTrID, bool bReportAllowed);
-bool _MmsBinaryEncodeNotiRespIndHdr(FILE* pFile, char *pTrID, msg_delivery_report_status_t iStatus, bool bReportAllowed);
-bool _MmsBinaryEncodeForwardReqHdr(FILE *pFile, char *szContentLocation, char *szForwardTo, char *szForwardCc, char *szForwardBcc);
-bool _MmsBinaryEncodeReadReport10Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus);
-bool _MmsBinaryEncodeReadReport11Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus);
-
-static         bool __MmsEncodeSendReq(FILE *pFile, MmsMsg *pMsg, bool bIncludeSendReqHeader);
-static int MmsBinaryEncodeUintvarLen(UINT32 integer);
-static bool MmsBinaryEncodeUintvar(FILE *pFile, UINT32 integer, int length);
-static int MmsBinaryEncodeValueLengthLen(UINT32 integer);
-static bool MmsBinaryEncodeValueLength(FILE *pFile, UINT32 integer, int length);
-static int     MmsBinaryEncodeIntegerLen(UINT32 integer);
-static bool MmsBinaryEncodeInteger(FILE *pFile, UINT32 integer, int length);
-static int     MmsBinaryEncodeLongIntegerLen(UINT32 integer);
-static bool MmsBinaryEncodeLongInteger(FILE *pFile, UINT32 integer, int length);
-static int     MmsBinaryEncodeTextStringLen(UINT8 *source);
-static bool MmsBinaryEncodeTextString(FILE *pFile, UINT8 *source, int length);
-static int     MmsBinaryEncodeQuotedStringLen(UINT8 *pSrc);
-static bool MmsBinaryEncodeQuotedString(FILE *pFile, UINT8 *source, int length);
-static int     MmsBinaryEncodeEncodedStringLen(UINT8 *source);
-static bool MmsBinaryEncodeEncodedString(FILE *pFile, UINT8 *source, int length);
-bool MmsBinaryEncodeSendReqHdrwithinBufRegi(FILE *pFile, MmsMsg *pMsg);
-bool MmsBinaryEncodeSendReqHdrContTypeFildCode(FILE *pFile, int msgID);
-
-static bool __MmsBinaryEncodeFieldCodeAndValue(FILE *pFile, UINT8 fieldCode, UINT8 fieldValue);
+static int __MmsGetEncodeOffset(void);
+static void __MmsRegisterEncodeBuffer2(char *pInBuff, int maxLen);
+static void __MmsUnregisterEncodeBuffer2(void);
+
+static int __MmsBinaryEncodeUintvarLen(UINT32 integer);
+static bool __MmsBinaryEncodeUintvar(FILE *pFile, UINT32 integer, int length);
+static int __MmsBinaryEncodeValueLengthLen(UINT32 integer);
+static bool __MmsBinaryEncodeValueLength(FILE *pFile, UINT32 integer, int length);
+static int     __MmsBinaryEncodeIntegerLen(UINT32 integer);
+static bool __MmsBinaryEncodeInteger(FILE *pFile, UINT32 integer, int length);
+static int     __MmsBinaryEncodeLongIntegerLen(UINT32 integer);
+static bool __MmsBinaryEncodeLongInteger(FILE *pFile, UINT32 integer, int length);
+static int     __MmsBinaryEncodeTextStringLen(UINT8 *source);
+static bool __MmsBinaryEncodeTextString(FILE *pFile, UINT8 *source, int length);
+static int     __MmsBinaryEncodeQuotedStringLen(UINT8 *pSrc);
+static bool __MmsBinaryEncodeQuotedString(FILE *pFile, UINT8 *source, int length);
+static int     __MmsBinaryEncodeEncodedStringLen(UINT8 *source);
+static bool __MmsBinaryEncodeEncodedString(FILE *pFile, UINT8 *source, int length);
+
+static int __MmsBinaryEncodeContentTypeLen(MsgType *pType);
+static bool __MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength);
+static int __MmsBinaryEncodeContentHeaderLen(MimeType contentType, MsgType *pType, bool bMultipart);
+static bool __MmsBinaryEncodeContentHeader(FILE *pFile, MimeType contentType, MsgType *pType, bool bMultipart);
+
+static bool __MmsBinaryEncodeContentBody(FILE *pFile, MsgBody *pBody);
+static bool __MmsBinaryEncodeMsgPart(FILE *pFile, int contentType, MsgType *pType, MsgBody *pBody);
 
 static bool __MmsBinaryEncodeMmsVersion(FILE *pFile);
 static bool __MmsBinaryEncodeTrID(FILE *pFile, char *szTrID, int bufLen);
 static bool __MmsBinaryEncodeMsgID(FILE *pFile, const char *szMsgID);  /** 2005-05-24, added for read-reply PDU 1.2 */
 static bool __MmsBinaryEncodeFrom(FILE *pFile);
 static bool __MmsBinaryEncodeTime(FILE *pFile, MmsFieldCode fieldCode, MmsTimeStruct time);
-static bool __MmsBinaryEncodeDate(FILE *pFile);
+static bool __MmsBinaryEncodeDate(FILE *pFile, time_t inpDateSec);
 static bool __MmsBinaryEncodeOneAddress(FILE *pFile, MmsFieldCode addrType, char *szAddrStr);
 static bool __MmsBinaryEncodeAddress(FILE *pFile, MmsFieldCode addrType, char *szAddr);
 
+static bool __MmsBinaryEncodeFieldCodeAndValue(FILE *pFile, UINT8 fieldCode, UINT8 fieldValue);
+static bool __MmsBinaryEncodeSendReqHdr(FILE *pFile, MmsMsg *pMsg);
+static bool __MmsBinaryEncodeAckIndHdr(FILE *pFile, char *pTrID, bool bReportAllowed);
+static bool __MmsBinaryEncodeNotiRespIndHdr(FILE* pFile, char *pTrID, msg_delivery_report_status_t iStatus, bool bReportAllowed);
+static bool __MmsBinaryEncodeReadReport10Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus);
+static bool __MmsBinaryEncodeReadReport11Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus);
+
+static bool __MmsBinaryEncodeMsgBody(FILE *pFile, MsgType *pType, MsgBody *pBody, int nPartCount, bool bTemplate);//NEW_TEMPLATE
+static bool __MmsEncodeSendReq(FILE *pFile, MmsMsg *pMsg, bool bIncludeSendReqHeader);
 
 /* Functions for Acknowledge.ind & NotifyResp.ind  ------------------------ */
-
-static bool MmsBinaryEncodeTextString2(FILE *pFile, UINT8 *source, int length);
+static bool __MmsBinaryEncodeTextString2(FILE *pFile, UINT8 *source, int length);
 static bool __MmsBinaryEncodeMmsVersion2(FILE *pFile);
 static bool __MmsBinaryEncodeFieldCodeAndValue2(FILE *pFile, UINT8 fieldCode, UINT8 fieldValue);
-extern int MsgProcessUrgentEvent(int iMode);
 
+static char *_MsgSkipWS3(char *s);
 
 /** -----------------------------------------------------------------
  *                                     M   M   S       E   N   C   O   D   E
  * * -----------------------------------------------------------------*/
 
-
 static void __MmsCleanEncodeBuff(void)
 {
        memset(gpMmsEncodeBuf, 0, MSG_MMS_ENCODE_BUFFER_MAX);
@@ -101,7 +110,7 @@ static      void __MmsCleanEncodeBuff(void)
 }
 
 
-void _MmsRegisterEncodeBuffer(char *pInBuff, int maxLen)
+void MmsRegisterEncodeBuffer(char *pInBuff, int maxLen)
 {
        gpMmsEncodeBuf = pInBuff;
        gCurMmsEncodeBuffPos = 0;
@@ -109,7 +118,7 @@ void _MmsRegisterEncodeBuffer(char *pInBuff, int maxLen)
        gMmsEncodeCurOffset = 0;
 }
 
-void _MmsUnregisterEncodeBuffer(void)
+void MmsUnregisterEncodeBuffer(void)
 {
        gpMmsEncodeBuf = NULL;
        gCurMmsEncodeBuffPos = 0;
@@ -117,53 +126,42 @@ void _MmsUnregisterEncodeBuffer(void)
        gMmsEncodeCurOffset = 0;
 }
 
-int _MmsGetEncodeOffset(void)
+static int __MmsGetEncodeOffset(void)
 {
        return (gMmsEncodeCurOffset + gCurMmsEncodeBuffPos);
 }
 
-
-bool _MmsEncodeMsg(void)
-{
-       MSG_DEBUG("_MmsEncodeMsg: Start Binary Encoding now ============= \n");
-       return true;
-}
-
-
-bool _MmsEncodeSendReq(FILE *pFile, MmsMsg *pMsg)
+bool MmsEncodeSendReq(FILE *pFile, MmsMsg *pMsg)
 {
        return __MmsEncodeSendReq(pFile, pMsg, true);
 }
 
-
-bool _MmsEncodeTemplate(FILE *pFile, MmsMsg *pMsg)
+bool MmsEncodeTemplate(FILE *pFile, MmsMsg *pMsg)
 {
        return __MmsEncodeSendReq(pFile, pMsg, false);
 }
 
-
 static bool __MmsEncodeSendReq(FILE* pFile, MmsMsg* pMsg, bool bIncludeSendReqHeader)
 {
-       _MmsRegisterEncodeBuffer(gszMmsEncodeBuf, MSG_MMS_ENCODE_BUFFER_MAX);
+       MmsRegisterEncodeBuffer(gszMmsEncodeBuf, MSG_MMS_ENCODE_BUFFER_MAX);
 
        if (bIncludeSendReqHeader) {
-               if (_MmsBinaryEncodeSendReqHdr(pFile, pMsg) == false) {
-                       _MmsUnregisterEncodeBuffer();
+               if (__MmsBinaryEncodeSendReqHdr(pFile, pMsg) == false) {
+                       MmsUnregisterEncodeBuffer();
                        return false;
                }
        }
 
-       if (MmsBinaryEncodeMsgBody(pFile, &pMsg->msgType, &pMsg->msgBody, pMsg->nPartCount, !bIncludeSendReqHeader) == false) {
-               _MmsUnregisterEncodeBuffer();
+       if (__MmsBinaryEncodeMsgBody(pFile, &pMsg->msgType, &pMsg->msgBody, pMsg->nPartCount, !bIncludeSendReqHeader) == false) {
+               MmsUnregisterEncodeBuffer();
                return false;
        }
 
-       _MmsUnregisterEncodeBuffer();
+       MmsUnregisterEncodeBuffer();
 
        return true;
 }
 
-
 /* Functions for Acknowledge.ind & NotifyResp.ind ------------------------ */
 
 static void __MmsCleanEncodeBuff2(void)
@@ -172,8 +170,7 @@ static      void __MmsCleanEncodeBuff2(void)
        gCurMmsEncodeBuffPos2 = 0;
 }
 
-
-void _MmsRegisterEncodeBuffer2(char *pInBuff, int maxLen)
+static void __MmsRegisterEncodeBuffer2(char *pInBuff, int maxLen)
 {
        gpMmsEncodeBuf2 = pInBuff;
        gCurMmsEncodeBuffPos2 = 0;
@@ -181,7 +178,7 @@ void _MmsRegisterEncodeBuffer2(char *pInBuff, int maxLen)
        gMmsEncodeCurOffset2 = 0;
 }
 
-void _MmsUnregisterEncodeBuffer2(void)
+static void __MmsUnregisterEncodeBuffer2(void)
 {
        gpMmsEncodeBuf2 = NULL;
        gCurMmsEncodeBuffPos2 = 0;
@@ -189,17 +186,14 @@ void _MmsUnregisterEncodeBuffer2(void)
        gMmsEncodeCurOffset2 = 0;
 }
 
-
 /**
  * @param      source [in] originam string
  * @param      length [in] gotten from MmsBinaryEncodeTextStringLen()
  * @param      dest [in] buffer to store quted string
  * @return     changed string length
 */
-static bool MmsBinaryEncodeTextString2(FILE *pFile, UINT8 *source, int length)
+static bool __MmsBinaryEncodeTextString2(FILE *pFile, UINT8 *source, int length)
 {
-       MSG_DEBUG("MmsBinaryEncodeTextString2: \n");
-
        /**
         * make text string
         * Text-string = [Quote] *TEXT End-of-string
@@ -210,14 +204,14 @@ static bool MmsBinaryEncodeTextString2(FILE *pFile, UINT8 *source, int length)
         */
 
        if (pFile == NULL || source == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeTextString2: source == NULL \n");
+               MSG_DEBUG("source == NULL");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen2 - gCurMmsEncodeBuffPos2) < length) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
                                                                                        gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeTextString2: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
@@ -237,24 +231,23 @@ __CATCH:
        return false;
 }
 
-
 static bool __MmsBinaryEncodeFieldCodeAndValue2(FILE *pFile, UINT8 fieldCode, UINT8 fieldValue)
 {
        if ((gMmsEncodeMaxLen2 - gCurMmsEncodeBuffPos2) < 2) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
                                                                                        gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeFieldCodeAndValue: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
        if (fieldCode == 0xff) {
-               MSG_DEBUG("__MmsBinaryEncodeFieldCodeAndValue: invalid fieldCode \n");
+               MSG_DEBUG("invalid fieldCode");
                goto __CATCH;
        }
 
        if (fieldValue == 0xff) {
-               MSG_DEBUG("__MmsBinaryEncodeFieldCodeAndValue: invalid fieldValue \n");
+               MSG_DEBUG("invalid fieldValue");
                return true;
        }
 
@@ -267,33 +260,25 @@ __CATCH:
        return false;
 }
 
-
 static bool __MmsBinaryEncodeMmsVersion2(FILE *pFile)
 {
        UINT8 majorVer = MMS_MAJOR_VERSION;
        UINT8 minorVer = MMS_MINOR_VERSION;
 
-       MSG_DEBUG("__MmsBinaryEncodeMmsVersion2: \n");
-
        if (pFile == NULL) {
-               MSG_DEBUG("__MmsBinaryEncodeMmsVersion2: invalid input file \n");
-               goto __CATCH;
-       }
-
-       if (majorVer < 1) {
-               MSG_DEBUG("__MmsBinaryEncodeMmsVersion2: invalid major version (%d)\n", majorVer);
+               MSG_DEBUG("invalid input file");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen2 - gCurMmsEncodeBuffPos2) < 2) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
                                                                                        gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeMmsVersion2: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
-       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_VERSION) | 0x80;
+       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_VERSION) | 0x80;
        gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2] = (majorVer << 4) | (minorVer & 0x0f) | MSB;
 
        if (gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2] < 0x80) {
@@ -308,73 +293,72 @@ __CATCH:
        return false;
 }
 
-
-bool _MmsBinaryEncodeAckIndHdr(FILE *pFile, char *szTrID, bool bReportAllowed)
+static bool __MmsBinaryEncodeAckIndHdr(FILE *pFile, char *szTrID, bool bReportAllowed)
 {
        int length = 0;
        UINT8 fieldCode = 0xff;
        UINT8 fieldValue = 0xff;
 
-       MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: szTrID = %s\n", szTrID);
-       MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: bReportAllowed = %d\n", bReportAllowed);
+       MSG_DEBUG("szTrID = %s", szTrID);
+       MSG_DEBUG("bReportAllowed = %d", bReportAllowed);
 
        __MmsCleanEncodeBuff2();
 
        /* msgType */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGTYPE) | 0x80;
-       fieldValue = _MmsGetBinaryValue(MmsCodeMsgType, MMS_MSGTYPE_ACKNOWLEDGE_IND) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGTYPE) | 0x80;
+       fieldValue = MmsGetBinaryValue(MmsCodeMsgType, MMS_MSGTYPE_ACKNOWLEDGE_IND) | 0x80;
        if (__MmsBinaryEncodeFieldCodeAndValue2(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: msgType error\n");
+               MSG_DEBUG("msgType error");
                goto __CATCH;
        }
 
        /* trID (other type of message) */
-       length = MmsBinaryEncodeTextStringLen((UINT8*)szTrID);
+       length = __MmsBinaryEncodeTextStringLen((UINT8*)szTrID);
        if (length == -1) {
-               MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: MmsBinaryEncodeTextStringLen fail \n");
+               MSG_DEBUG("MmsBinaryEncodeTextStringLen fail");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen2 - gCurMmsEncodeBuffPos2) < (length + 1)) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
                                                                                        gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
-       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_TRID) | 0x80;
+       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_TRID) | 0x80;
 
-       if (MmsBinaryEncodeTextString2(pFile, (UINT8*)szTrID, length) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: MmsBinaryEncodeTextString fail\n");
+       if (__MmsBinaryEncodeTextString2(pFile, (UINT8*)szTrID, length) == false) {
+               MSG_DEBUG("MmsBinaryEncodeTextString fail");
                goto __CATCH;
        }
 
 
        if (__MmsBinaryEncodeMmsVersion2(pFile) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: __MmsBinaryEncodeMmsVersion error\n");
+               MSG_DEBUG("__MmsBinaryEncodeMmsVersion error");
                goto __CATCH;
        }
 
 
        /* Report Allowed */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPORTALLOWED) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPORTALLOWED) | 0x80;
 
        if (bReportAllowed) {
-               fieldValue = _MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_YES) | 0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_YES) | 0x80;
        } else {
-               fieldValue = _MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_NO) | 0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_NO) | 0x80;
        }
 
        if (__MmsBinaryEncodeFieldCodeAndValue2(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: Report Allowed error\n");
+               MSG_DEBUG("Report Allowed error");
                goto __CATCH;
        }
 
        /* flush remained data on encoding file */
        if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
                                                                                gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: remained data MsgWriteDataFromEncodeBuffer fail \n");
+               MSG_DEBUG("remained data MsgWriteDataFromEncodeBuffer fail");
                goto __CATCH;
        }
 
@@ -385,89 +369,87 @@ __CATCH:
        return false;
 }
 
-
-
-bool _MmsBinaryEncodeNotiRespIndHdr(FILE *pFile, char *szTrID, msg_delivery_report_status_t iStatus, bool bReportAllowed)
+static bool __MmsBinaryEncodeNotiRespIndHdr(FILE *pFile, char *szTrID, msg_delivery_report_status_t iStatus, bool bReportAllowed)
 {
        int length = 0;
        UINT8 fieldCode = 0xff;
        UINT8 fieldValue = 0xff;
 
-       MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: szTrID = %s\n", szTrID);
-       MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: iStatus = %d\n", iStatus);
-       MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: bReportAllowed = %d\n", bReportAllowed);
+       MSG_DEBUG("szTrID = %s", szTrID);
+       MSG_DEBUG("iStatus = %d", iStatus);
+       MSG_DEBUG("bReportAllowed = %d", bReportAllowed);
 
        __MmsCleanEncodeBuff2();
 
        /* msgType */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGTYPE) | 0x80;
-       fieldValue = _MmsGetBinaryValue(MmsCodeMsgType, MMS_MSGTYPE_NOTIFYRESP_IND) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGTYPE) | 0x80;
+       fieldValue = MmsGetBinaryValue(MmsCodeMsgType, MMS_MSGTYPE_NOTIFYRESP_IND) | 0x80;
 
        if (__MmsBinaryEncodeFieldCodeAndValue2(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: msgType error\n");
+               MSG_DEBUG("msgType error");
                goto __CATCH;
        }
 
 
        /* trID (other type of message) */
-       length = MmsBinaryEncodeTextStringLen((UINT8*)szTrID);
+       length = __MmsBinaryEncodeTextStringLen((UINT8*)szTrID);
        if (length == -1) {
-               MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: MmsBinaryEncodeTextStringLen fail \n");
+               MSG_DEBUG("MmsBinaryEncodeTextStringLen fail");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen2 - gCurMmsEncodeBuffPos2) < (length + 1)) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
                                                                                        gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
-       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_TRID) | 0x80;
-       if (MmsBinaryEncodeTextString2(pFile, (UINT8*)szTrID, length) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: MmsBinaryEncodeTextString fail\n");
+       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_TRID) | 0x80;
+       if (__MmsBinaryEncodeTextString2(pFile, (UINT8*)szTrID, length) == false) {
+               MSG_DEBUG("MmsBinaryEncodeTextString fail");
                goto __CATCH;
        }
 
 
        if (__MmsBinaryEncodeMmsVersion2(pFile) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: __MmsBinaryEncodeMmsVersion error\n");
+               MSG_DEBUG("__MmsBinaryEncodeMmsVersion error");
                goto __CATCH;
        }
 
 
        /* MsgStatus */
-       MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: MsgStatus = %d\n", iStatus);
+       MSG_DEBUG("MsgStatus = %d", iStatus);
 
        if (iStatus != MSG_DELIVERY_REPORT_NONE) {
-               fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGSTATUS) | 0x80;
-               fieldValue = _MmsGetBinaryValue(MmsCodeMsgStatus, iStatus) | 0x80;
+               fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGSTATUS) | 0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodeMsgStatus, iStatus) | 0x80;
                if (__MmsBinaryEncodeFieldCodeAndValue2(pFile, fieldCode, fieldValue) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: MsgStatus error\n");
+                       MSG_DEBUG("MsgStatus error");
                        goto __CATCH;
                }
        }
 
 
        /* Report Allowed */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPORTALLOWED) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPORTALLOWED) | 0x80;
 
        if (bReportAllowed) {
-               fieldValue = _MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_YES) | 0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_YES) | 0x80;
        } else {
-               fieldValue = _MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_NO) | 0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_NO) | 0x80;
        }
 
        if (__MmsBinaryEncodeFieldCodeAndValue2(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: Report Allowed error\n");
+               MSG_DEBUG("Report Allowed error");
                goto __CATCH;
        }
 
        /* flush remained data on encoding file */
        if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
                                                                                gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: remained data MsgWriteDataFromEncodeBuffer fail \n");
+               MSG_DEBUG("remained data MsgWriteDataFromEncodeBuffer fail");
                goto __CATCH;
        }
 
@@ -478,44 +460,41 @@ __CATCH:
        return false;
 }
 
-
-bool _MmsEncodeAckInd(FILE *pFile, char *pTrID, bool bReportAllowed)
+bool MmsEncodeAckInd(FILE *pFile, char *pTrID, bool bReportAllowed)
 {
-       _MmsRegisterEncodeBuffer2(gszMmsEncodeBuf2, MSG_MMS_ENCODE_BUFFER_MAX);
+       __MmsRegisterEncodeBuffer2(gszMmsEncodeBuf2, MSG_MMS_ENCODE_BUFFER_MAX);
 
-       MSG_DEBUG("_MmsEncodeAckInd: Start Binary Encoding now ============= \n");
+       MSG_DEBUG("Start Binary Encoding now =============");
 
-       if (_MmsBinaryEncodeAckIndHdr(pFile, pTrID, bReportAllowed) == false) {
-               MSG_DEBUG("_MmsEncodeAckInd: SendReq Binary encoding fail \n");
+       if (__MmsBinaryEncodeAckIndHdr(pFile, pTrID, bReportAllowed) == false) {
+               MSG_DEBUG("SendReq Binary encoding fail");
                goto __CATCH;
        }
 
-       _MmsUnregisterEncodeBuffer2();
+       __MmsUnregisterEncodeBuffer2();
 
        return true;
 
 __CATCH:
 
-       MSG_DEBUG("## _MmsEncodeAckInd: failed");
-       _MmsUnregisterEncodeBuffer2();
+       MSG_DEBUG("Failed");
+       __MmsUnregisterEncodeBuffer2();
 
        return false;
 }
 
-
-
-bool _MmsEncodeNotiRespInd(FILE *pFile, char *pTrID, msg_delivery_report_status_t iStatus, bool bReportAllowed)
+bool MmsEncodeNotiRespInd(FILE *pFile, char *pTrID, msg_delivery_report_status_t iStatus, bool bReportAllowed)
 {
-       _MmsRegisterEncodeBuffer2(gszMmsEncodeBuf2, MSG_MMS_ENCODE_BUFFER_MAX);
+       __MmsRegisterEncodeBuffer2(gszMmsEncodeBuf2, MSG_MMS_ENCODE_BUFFER_MAX);
 
-       MSG_DEBUG("_MmsEncodeNotiRespInd: Start Binary Encoding now ============= \n");
+       MSG_DEBUG("Start Binary Encoding now =============");
 
-       if (_MmsBinaryEncodeNotiRespIndHdr(pFile, pTrID, iStatus, bReportAllowed) == false) {
-               MSG_DEBUG("_MmsEncodeNotiRespInd: SendReq Binary encoding fail \n");
+       if (__MmsBinaryEncodeNotiRespIndHdr(pFile, pTrID, iStatus, bReportAllowed) == false) {
+               MSG_DEBUG("SendReq Binary encoding fail");
                goto __CATCH;
        }
 
-       _MmsUnregisterEncodeBuffer2();
+       __MmsUnregisterEncodeBuffer2();
 
        return true;
 
@@ -524,45 +503,45 @@ __CATCH:
        return false;
 }
 
-
 /* Functions for Acknowledge.ind & NotifyResp.ind  (END) ------------------------ */
-bool _MmsEncodeReadReport10(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
+bool MmsEncodeReadReport10(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
 {
        char *pText = NULL;
        MsgMultipart *pPart = NULL;
        MsgType msgType;
-       MsgBody msgBody;
+
+       MsgBody *msgBody = NULL;
+       unique_ptr<MsgBody*, void(*)(MsgBody**)> buf(&msgBody, unique_ptr_deleter);
+       msgBody = (MsgBody *)new char[sizeof(MsgBody)];
+       memset(msgBody, 0x00, sizeof(MsgBody));
 
        char *pszReportMsg = NULL;
-       int     maxLen = 0;
+       int maxLen = 0;
 
-       struct  tm      *dateTime = NULL;
-       time_t  RawTime = 0;
-       time_t  dateSec = 0;
+       struct tm dateTime;
+       time_t RawTime = 0;
 
-       _MmsRegisterEncodeBuffer(gszMmsEncodeBuf, MSG_MMS_ENCODE_BUFFER_MAX);
+       MmsRegisterEncodeBuffer(gszMmsEncodeBuf, MSG_MMS_ENCODE_BUFFER_MAX);
 
-       MSG_DEBUG("_MmsEncodeMsg: Start Binary Encoding now V1.0============= \n");
+       MSG_DEBUG("Start Binary Encoding now V1.0=============");
 
-       if (_MmsBinaryEncodeReadReport10Hdr(pFile, pMsg, mmsReadStatus) == false) {
-               MSG_DEBUG("_MmsEncodeReadReport10: SendReq Binary encoding fail \n");
+       if (__MmsBinaryEncodeReadReport10Hdr(pFile, pMsg, mmsReadStatus) == false) {
+               MSG_DEBUG("SendReq Binary encoding fail");
                goto __CATCH;
        }
 
        memset(&msgType, 0, sizeof(MsgType));
-       memset(&msgBody, 0, sizeof(MsgBody));
 
-       pText = (char *)malloc(MSG_STDSTR_LONG);
+       pText = (char *)calloc(1, MSG_STDSTR_LONG);
        if (pText == NULL) {
-               MSG_DEBUG("__MmsSendReadReportV10: text body malloc fail \n");
+               MSG_DEBUG("text body calloc fail");
                goto __CATCH;
        }
 
        memset(pText, 0, MSG_STDSTR_LONG);
 
        time(&RawTime);
-       dateTime = localtime(&RawTime);
-       dateSec = mktime(dateTime);
+       localtime_r(&RawTime, &dateTime);
 
        // get report message
        if (mmsReadStatus == MSG_READ_REPORT_IS_DELETED) {
@@ -575,10 +554,10 @@ bool _MmsEncodeReadReport10(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t
        maxLen = strlen (pszReportMsg) +16 /* date string */ + 8 /* enter chars */ ;
 
        if (maxLen > MSG_STDSTR_LONG) {
-               snprintf (pText, MSG_STDSTR_LONG, "%s\n", pszReportMsg);
+               snprintf (pText, MSG_STDSTR_LONG, "%s", pszReportMsg);
        } else {
                snprintf(pText, MSG_STDSTR_LONG, "%s\r\n\r\n%.4d/%.2d/%.2d %.2d:%.2d\r\n",
-                                               pszReportMsg, dateTime->tm_year+1900, dateTime->tm_mon+1, dateTime->tm_mday, dateTime->tm_hour, dateTime->tm_min);
+                                               pszReportMsg, dateTime.tm_year+1900, dateTime.tm_mon+1, dateTime.tm_mday, dateTime.tm_hour, dateTime.tm_min);
        }
 
        // make header
@@ -588,7 +567,7 @@ bool _MmsEncodeReadReport10(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t
 
        // make body
        if ((pPart = MmsAllocMultipart()) == NULL) {
-               MSG_DEBUG("__MmsSendReadReportV10: MsgAllocMultipart Fail \n");
+               MSG_DEBUG("MsgAllocMultipart Fail");
                goto __CATCH;
        }
 
@@ -598,21 +577,21 @@ bool _MmsEncodeReadReport10(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t
        pPart->type.param.charset = MSG_CHARSET_UTF8;
 
        if (pPart->pBody == NULL) {
-               MSG_DEBUG("__MmsSendReadReportV10: pPart->pBody is NULL \n");
+               MSG_DEBUG("pPart->pBody is NULL");
                goto __CATCH;
        }
 
        pPart->pBody->size = strlen(pText);
        pPart->pBody->body.pText = pText;
 
-       msgBody.body.pMultipart = pPart;
+       msgBody->body.pMultipart = pPart;
 
-       if (MmsBinaryEncodeMsgBody(pFile, &msgType, &msgBody, 1, false) == false) {
-               MSG_DEBUG("__MmsSendReadReportV10: MmsBinaryEncodeMsgBody fail \n");
+       if (__MmsBinaryEncodeMsgBody(pFile, &msgType, msgBody, 1, false) == false) {
+               MSG_DEBUG("MmsBinaryEncodeMsgBody fail");
                goto __CATCH;
        }
 
-       MSG_DEBUG("__MmsSendReadReportV10:  Send To RM ReadReport Msg \n");
+       MSG_DEBUG(" Send To RM ReadReport Msg");
 
        if (pText) {
                free(pText);
@@ -628,7 +607,7 @@ bool _MmsEncodeReadReport10(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t
                pPart = NULL;
        }
 
-       _MmsUnregisterEncodeBuffer();
+       MmsUnregisterEncodeBuffer();
 
        return true;
 
@@ -648,35 +627,32 @@ __CATCH:
                pPart = NULL;
        }
 
-       _MmsUnregisterEncodeBuffer();
+       MmsUnregisterEncodeBuffer();
 
        return false;
 }
 
-
-bool _MmsEncodeReadReport11(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
+bool MmsEncodeReadReport11(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
 {
-       _MmsRegisterEncodeBuffer(gszMmsEncodeBuf, MSG_MMS_ENCODE_BUFFER_MAX);
+       MmsRegisterEncodeBuffer(gszMmsEncodeBuf, MSG_MMS_ENCODE_BUFFER_MAX);
 
-       MSG_DEBUG("_MmsEncodeMsg: Start Binary Encoding now V1.1============= \n");
+       MSG_DEBUG("Start Binary Encoding now V1.1=============");
 
-       if (_MmsBinaryEncodeReadReport11Hdr(pFile, pMsg, mmsReadStatus) == false) {
-               MSG_DEBUG("_MmsEncodeMsg: SendReq Binary encoding fail \n");
+       if (__MmsBinaryEncodeReadReport11Hdr(pFile, pMsg, mmsReadStatus) == false) {
+               MSG_DEBUG("SendReq Binary encoding fail");
                goto __CATCH;
        }
 
-       _MmsUnregisterEncodeBuffer();
+       MmsUnregisterEncodeBuffer();
 
        return true;
 
 __CATCH:
-       _MmsUnregisterEncodeBuffer();
+       MmsUnregisterEncodeBuffer();
 
        return false;
 }
 
-
-
 /* ==========================================================
 
                                        B  I  N  A  R  Y         E  N  C  O  D  I  N  G
@@ -715,8 +691,7 @@ __CATCH:
  *                                                                                     |                       Data                    |  | Data Length
  *                                                                                     -----------------------------  -
  */
-
-bool _MmsBinaryEncodeSendReqHdr(FILE *pFile, MmsMsg *pMsg)
+static bool __MmsBinaryEncodeSendReqHdr(FILE *pFile, MmsMsg *pMsg)
 {
        UINT8 fieldCode = 0xff;
        UINT8 fieldValue        = 0xff;
@@ -725,29 +700,29 @@ bool _MmsBinaryEncodeSendReqHdr(FILE *pFile, MmsMsg *pMsg)
        __MmsCleanEncodeBuff();
 
        /* msgType */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGTYPE) | 0x80;
-       fieldValue = _MmsGetBinaryValue(MmsCodeMsgType, MMS_MSGTYPE_SEND_REQ) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGTYPE) | 0x80;
+       fieldValue = MmsGetBinaryValue(MmsCodeMsgType, MMS_MSGTYPE_SEND_REQ) | 0x80;
        if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: msgType error\n");
+               MSG_DEBUG("msgType error");
                goto __CATCH;
        }
 
+       MSG_SEC_INFO("X-Mms-Message-Type = [%s]", MmsDebugGetMsgType(MMS_MSGTYPE_SEND_REQ));
+
        /* trID (other type of message) */
        if (__MmsBinaryEncodeTrID(pFile, pMsg->szTrID, MMS_TR_ID_LEN + 1) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: trID error\n");
+               MSG_DEBUG("trID error");
                goto __CATCH;
        }
 
-       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr:                pMsg->szTrID = %s\n", pMsg->szTrID);
-
        if (__MmsBinaryEncodeMmsVersion(pFile) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: __MmsBinaryEncodeMmsVersion error\n");
+               MSG_DEBUG("__MmsBinaryEncodeMmsVersion error");
                goto __CATCH;
        }
 
        /* From : Insert Token mode */
        if (__MmsBinaryEncodeFrom(pFile) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: __MmsBinaryEncodeFrom fail\n");
+               MSG_DEBUG("__MmsBinaryEncodeFrom fail");
                goto __CATCH;
        }
 
@@ -755,143 +730,145 @@ bool _MmsBinaryEncodeSendReqHdr(FILE *pFile, MmsMsg *pMsg)
        /* To = Encoded-string-value */
        if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_TO, pMsg->mmsAttrib.szTo) == false)
        {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: To __MmsBinaryEncodeAddress fail\n");
+               MSG_DEBUG("To __MmsBinaryEncodeAddress fail");
                goto __CATCH;
        }
 
 
        /* Cc = Encoded-string-value */
        if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_CC, pMsg->mmsAttrib.szCc) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: Cc __MmsBinaryEncodeAddress fail\n");
+               MSG_DEBUG("Cc __MmsBinaryEncodeAddress fail");
                goto __CATCH;
        }
 
 
        /* Bcc = Encoded-string-value */
-
        if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_BCC, pMsg->mmsAttrib.szBcc) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: Bcc __MmsBinaryEncodeAddress fail\n");
+               MSG_DEBUG("Bcc __MmsBinaryEncodeAddress fail");
                goto __CATCH;
        }
 
-
-       MSG_DEBUG("_MmsBinaryEnocdeSendReqHdr() pMsg->mmsAttrib.szSubject =%s\n",pMsg->mmsAttrib.szSubject);
+       MSG_SEC_INFO("Subject = [%s]", pMsg->mmsAttrib.szSubject);
 
        /* Subject = Encoded-string-value */
        if (pMsg->mmsAttrib.szSubject[0]) {
-               length = MmsBinaryEncodeEncodedStringLen((UINT8*)pMsg->mmsAttrib.szSubject);
+               length = __MmsBinaryEncodeEncodedStringLen((UINT8*)pMsg->mmsAttrib.szSubject);
                if (length == -1) {
-                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: subject MmsBinaryEncodeEncodedStringLen fail \n");
+                       MSG_DEBUG("subject MmsBinaryEncodeEncodedStringLen fail");
                        goto __CATCH;
                }
 
                if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length + 1) {
                        if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                                gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: subject MsgWriteDataFromEncodeBuffer fail \n");
+                               MSG_DEBUG("subject MsgWriteDataFromEncodeBuffer fail");
                                goto __CATCH;
                        }
                }
 
-               fieldCode = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_SUBJECT) | 0x80;
+               fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_SUBJECT) | 0x80;
                gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = fieldCode;
-               if (MmsBinaryEncodeEncodedString(pFile, (UINT8*)pMsg->mmsAttrib.szSubject, length) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: subject MmsBinaryEncodeEncodedString fail \n");
+               if (__MmsBinaryEncodeEncodedString(pFile, (UINT8*)pMsg->mmsAttrib.szSubject, length) == false) {
+                       MSG_DEBUG("subject MmsBinaryEncodeEncodedString fail");
                        goto __CATCH;
                }
        }
 
        /* MMS-1.3-con-739 */
        /* Msg class */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGCLASS) | 0x80;
-       fieldValue = _MmsGetBinaryValue(MmsCodeMsgClass,  (int)pMsg->mmsAttrib.msgClass) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGCLASS) | 0x80;
+       fieldValue = MmsGetBinaryValue(MmsCodeMsgClass,  (int)pMsg->mmsAttrib.msgClass) | 0x80;
        if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: msgClass error\n");
+               MSG_DEBUG("msgClass error");
                goto __CATCH;
        }
+
+       MSG_SEC_INFO("X-Mms-Message-Class = [%s]", MmsDebugGetMsgClass(pMsg->mmsAttrib.msgClass));
+
        /* MMS-1.3-con-739 */
        /* MMS-1.3-con-733 */
        /* Date = Long-integer */
-       if (!__MmsBinaryEncodeDate(pFile)) {
-                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: __MmsBinaryEncodeDate error\n");
-                       goto __CATCH;
+       if (!__MmsBinaryEncodeDate(pFile, 0)) {
+               MSG_DEBUG("__MmsBinaryEncodeDate error");
+               goto __CATCH;
        }
        /* MMS-1.3-con-733 */
 
        /* Expiry Time  : Value-length Absolute-token Date-value */
-       if (pMsg->mmsAttrib.bUseExpiryCustomTime == true) {
-               if (__MmsBinaryEncodeTime(pFile, MMS_CODE_EXPIRYTIME, pMsg->mmsAttrib.expiryCustomTime) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: expiryTime __MmsBinaryEncodeTime fail\n");
-                       goto __CATCH;
-               }
-       } else if (pMsg->mmsAttrib.expiryTime.type != MMS_TIMETYPE_NONE) {      // for avoiding the creation of the expiry field in case the user selects the maximum
+       if (pMsg->mmsAttrib.expiryTime.type != MMS_TIMETYPE_NONE) {     // for avoiding the creation of the expiry field in case the user selects the maximum
                if (__MmsBinaryEncodeTime(pFile, MMS_CODE_EXPIRYTIME, pMsg->mmsAttrib.expiryTime) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: expiryTime __MmsBinaryEncodeTime fail\n");
+                       MSG_DEBUG("expiryTime __MmsBinaryEncodeTime fail");
                        goto __CATCH;
                }
+
+               MSG_DEBUG("X-Mms-Expiry : type = [%d], time = [%u]", pMsg->mmsAttrib.expiryTime.type, pMsg->mmsAttrib.expiryTime.time);
        }
 
-       /* Use Custom time for Delivery Time */
-       if (pMsg->mmsAttrib.bUseDeliveryCustomTime == true) {
-               if (__MmsBinaryEncodeTime(pFile, MMS_CODE_DELIVERYTIME, pMsg->mmsAttrib.deliveryCustomTime) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: deliveryTime __MmsBinaryEncodeTime fail\n");
-                       goto __CATCH;
-               }
-       } else {
+       if (pMsg->mmsAttrib.deliveryTime.type != MMS_TIMETYPE_NONE) {
                if (__MmsBinaryEncodeTime(pFile, MMS_CODE_DELIVERYTIME, pMsg->mmsAttrib.deliveryTime) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: deliveryTime __MmsBinaryEncodeTime fail\n");
+                       MSG_DEBUG("deliveryTime __MmsBinaryEncodeTime fail");
                        goto __CATCH;
                }
+
+               MSG_DEBUG("X-Mms-Delivery-Time : type = [%d], time = [%u]", pMsg->mmsAttrib.deliveryTime.type, pMsg->mmsAttrib.deliveryTime.time);
        }
 
        /* Priority */
        if (pMsg->mmsAttrib.priority!= MMS_PRIORITY_ERROR && pMsg->mmsAttrib.priority!= MMS_PRIORITY_NORMAL) {
                /* MMS_PRIORITY_NORMAL is default : don't send optional field */
 
-               fieldCode = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_PRIORITY)|0x80;
-               fieldValue = _MmsGetBinaryValue(MmsCodePriority, pMsg->mmsAttrib.priority)|0x80;
+               fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_PRIORITY)|0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodePriority, pMsg->mmsAttrib.priority)|0x80;
 
                if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: priority error\n");
+                       MSG_DEBUG("priority error");
                        goto __CATCH;
                }
+
+               MSG_SEC_INFO("X-Mms-Priority = [%d]", pMsg->mmsAttrib.priority);
        }
 
        /* Sender Visible (hide | show) */
        if (pMsg->mmsAttrib.bHideAddress == true) {
-               fieldCode = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_SENDERVISIBILLITY) | MSB;
-               fieldValue = _MmsGetBinaryValue(MmsCodeSenderVisibility, MMS_SENDER_HIDE) | 0x80;
+               fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_SENDERVISIBILLITY) | MSB;
+               fieldValue = MmsGetBinaryValue(MmsCodeSenderVisibility, MMS_SENDER_HIDE) | 0x80;
 
                if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: sender visibility error\n");
+                       MSG_DEBUG("sender visibility error");
                        goto __CATCH;
                }
        }
 
+       MSG_SEC_INFO("X-Mms-Sender-Visibility = [%d]", pMsg->mmsAttrib.bHideAddress);
+
        /* Delivery Report (yes | no) */
-       fieldCode = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_DELIVERYREPORT)|0x80;
+       fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_DELIVERYREPORT)|0x80;
 
        if (pMsg->mmsAttrib.bAskDeliveryReport) {
-               fieldValue = _MmsGetBinaryValue(MmsCodeDeliveryReport, MMS_REPORT_YES) | 0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodeDeliveryReport, MMS_REPORT_YES) | 0x80;
        } else {
-               fieldValue = _MmsGetBinaryValue(MmsCodeDeliveryReport, MMS_REPORT_NO) | 0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodeDeliveryReport, MMS_REPORT_NO) | 0x80;
        }
 
+       MSG_SEC_INFO("X-Mms-Delivery-Report = [%d]", pMsg->mmsAttrib.bAskDeliveryReport);
+
        if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: sender visibility error\n");
+               MSG_DEBUG("sender visibility error");
                goto __CATCH;
        }
 
        /* Read Reply (Yes | no) */
-       fieldCode = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_READREPLY)|0x80;
+       fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_READREPLY)|0x80;
        if (pMsg->mmsAttrib.bAskReadReply) {
-               fieldValue = _MmsGetBinaryValue(MmsCodeReadReply, MMS_REPORT_YES)|0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodeReadReply, MMS_REPORT_YES)|0x80;
        } else {
-               fieldValue = _MmsGetBinaryValue(MmsCodeReadReply, MMS_REPORT_NO)|0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodeReadReply, MMS_REPORT_NO)|0x80;
        }
 
+       MSG_SEC_INFO("X-Mms-Read-Report = [%d]", pMsg->mmsAttrib.bAskReadReply);
+
        if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: read reply error\n");
+               MSG_DEBUG("read reply error");
                goto __CATCH;
        }
 
@@ -899,59 +876,62 @@ bool _MmsBinaryEncodeSendReqHdr(FILE *pFile, MmsMsg *pMsg)
                (pMsg->mmsAttrib.replyCharge.chargeType == MMS_REPLY_REQUESTED_TEXT_ONLY)) {
 
                // reply charging
-               fieldCode = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPLYCHARGING)|0x80;
-               fieldValue = _MmsGetBinaryValue(MmsCodeReadReply, pMsg->mmsAttrib.replyCharge.chargeType)|0x80;
+               fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPLYCHARGING)|0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodeReadReply, pMsg->mmsAttrib.replyCharge.chargeType)|0x80;
 
                if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: replyCharging error\n");
+                       MSG_DEBUG("replyCharging error");
                        goto __CATCH;
                }
 
+               /** fixme: Reply-charging-deadline */
                if (pMsg->mmsAttrib.replyCharge.deadLine.time > 0) {
                        if (__MmsBinaryEncodeTime(pFile, MMS_CODE_REPLYCHARGINGDEADLINE, pMsg->mmsAttrib.replyCharge.deadLine) == false) {
-                               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: replyCharging __MmsBinaryEncodeTime fail\n");
+                               MSG_DEBUG("replyCharging __MmsBinaryEncodeTime fail");
                                goto __CATCH;
                        }
                }
 
+               /** fixme: Reply-charging-size */
                if (pMsg->mmsAttrib.replyCharge.chargeSize > 0) {
-                       length = MmsBinaryEncodeIntegerLen(pMsg->mmsAttrib.replyCharge.chargeSize);
+                       length = __MmsBinaryEncodeIntegerLen(pMsg->mmsAttrib.replyCharge.chargeSize);
 
                        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < (length + 1)) {
                                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                                gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: MsgWriteDataFromEncodeBuffer fail \n");
+                                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                                        goto __CATCH;
                                }
                        }
 
-                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPLYCHARGINGSIZE) | 0x80;
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPLYCHARGINGSIZE) | 0x80;
 
-                       if (MmsBinaryEncodeInteger(pFile, pMsg->mmsAttrib.replyCharge.chargeSize, length) == false)     {
-                               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: replyChargingSize MmsBinaryEncodeInteger error\n");
+                       if (__MmsBinaryEncodeInteger(pFile, pMsg->mmsAttrib.replyCharge.chargeSize, length) == false)   {
+                               MSG_DEBUG("replyChargingSize MmsBinaryEncodeInteger error");
                                goto __CATCH;
                        }
                }
 
+               /** fixme: Reply-charging-ID  ----> used only when reply message  */
                if (pMsg->mmsAttrib.replyCharge.szChargeID[0]) {
-                       length = MmsBinaryEncodeTextStringLen((UINT8*)pMsg->mmsAttrib.replyCharge.szChargeID);
+                       length = __MmsBinaryEncodeTextStringLen((UINT8*)pMsg->mmsAttrib.replyCharge.szChargeID);
                        if (length == -1) {
-                               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: szReplyChargingID MmsBinaryEncodeTextStringLen fail\n");
+                               MSG_DEBUG("szReplyChargingID MmsBinaryEncodeTextStringLen fail");
                                goto __CATCH;
                        }
 
                        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < (length + 1)) {
                                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                                gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: MsgWriteDataFromEncodeBuffer fail \n");
+                                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                                        goto __CATCH;
                                }
                        }
 
-                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPLYCHARGINGID) | 0x80;
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPLYCHARGINGID) | 0x80;
 
-                       if (MmsBinaryEncodeTextString(pFile, (UINT8*)pMsg->mmsAttrib.replyCharge.szChargeID, length) == false) {
-                               MSG_DEBUG("_MmsBinaryEncodeForwardReqHdr: szContentLocation MmsBinaryEncodeTextString fail\n");
+                       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)pMsg->mmsAttrib.replyCharge.szChargeID, length) == false) {
+                               MSG_DEBUG("szContentLocation MmsBinaryEncodeTextString fail");
                                goto __CATCH;
                        }
                }
@@ -959,7 +939,7 @@ bool _MmsBinaryEncodeSendReqHdr(FILE *pFile, MmsMsg *pMsg)
 
        /* flush remained data on encoding file */
        if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos, gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: remained data MsgWriteDataFromEncodeBuffer fail \n");
+               MSG_DEBUG("remained data MsgWriteDataFromEncodeBuffer fail");
                goto __CATCH;
        }
 
@@ -967,56 +947,11 @@ bool _MmsBinaryEncodeSendReqHdr(FILE *pFile, MmsMsg *pMsg)
 
 __CATCH:
 
-       MSG_DEBUG("## _MmsBinaryEncodeSendReqHdr: failed");
+       MSG_DEBUG("Failed");
        return false;
 }
 
-bool MmsBinaryEncodeSendReqHdrwithinBufRegi(FILE *pFile, MmsMsg *pMsg)
-{
-       bool ret = false;
-
-       _MmsRegisterEncodeBuffer(gszMmsEncodeBuf, MSG_MMS_ENCODE_BUFFER_MAX);
-       ret = _MmsBinaryEncodeSendReqHdr(pFile, pMsg);
-       _MmsUnregisterEncodeBuffer();
-
-       return ret;
-}
-
-bool _MmsBinaryEncodeContentTypeFieldCode(FILE *pFile, int msgID)
-{
-       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < 2) {
-               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
-                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeMmsVersion: MsgWriteDataFromEncodeBuffer fail \n");
-                       return false;
-               }
-       }
-
-       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_CONTENTTYPE) | 0x80;
-
-       if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos, gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: remained data MsgWriteDataFromEncodeBuffer fail \n");
-               return false;
-       }
-
-       return true;
-}
-
-bool MmsBinaryEncodeSendReqHdrContTypeFildCode(FILE *pFile, int msgID)
-{
-       bool ret = false;
-
-       _MmsRegisterEncodeBuffer(gszMmsEncodeBuf, MSG_MMS_ENCODE_BUFFER_MAX);
-
-       ret = _MmsBinaryEncodeContentTypeFieldCode(pFile, msgID);
-
-       _MmsUnregisterEncodeBuffer();
-
-
-       return ret;
-}
-
-bool _MmsBinaryEncodeReadReport10Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
+static bool __MmsBinaryEncodeReadReport10Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
 {
        int length      = 0;
        char *szTo      = NULL;
@@ -1029,57 +964,57 @@ bool _MmsBinaryEncodeReadReport10Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_
                goto __CATCH;
        }
 
-       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: mmsReadStatus = %d\n", mmsReadStatus);
+       MSG_DEBUG("mmsReadStatus = %d", mmsReadStatus);
 
        __MmsCleanEncodeBuff();
 
        /* msgType */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGTYPE) | 0x80;
-       fieldValue = _MmsGetBinaryValue(MmsCodeMsgType, MMS_MSGTYPE_SEND_REQ) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGTYPE) | 0x80;
+       fieldValue = MmsGetBinaryValue(MmsCodeMsgType, MMS_MSGTYPE_SEND_REQ) | 0x80;
        if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: msgType error\n");
+               MSG_DEBUG("msgType error");
                goto __CATCH;
        }
 
        /* trID (other type of message) */
        if (__MmsBinaryEncodeTrID(pFile, NULL, 0) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: __MmsBinaryEncodeTrID error\n");
+               MSG_DEBUG("__MmsBinaryEncodeTrID error");
                goto __CATCH;
        }
 
        if (__MmsBinaryEncodeMmsVersion(pFile) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: __MmsBinaryEncodeMmsVersion error\n");
+               MSG_DEBUG("__MmsBinaryEncodeMmsVersion error");
                goto __CATCH;
        }
 
        /* Date = Long-integer */
-       if (!__MmsBinaryEncodeDate(pFile)) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: date __MmsBinaryEncodeDate error\n");
+       if (!__MmsBinaryEncodeDate(pFile, 0)) {
+               MSG_DEBUG("date __MmsBinaryEncodeDate error");
                goto __CATCH;
        }
 
        /* From : Insert Token mode */
        if (__MmsBinaryEncodeFrom(pFile) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: __MmsBinaryEncodeFrom fail\n");
+               MSG_DEBUG("__MmsBinaryEncodeFrom fail");
                goto __CATCH;
        }
 
-       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To = %s\n", pMsg->mmsAttrib.szFrom);
+       MSG_DEBUG("To = %s", pMsg->mmsAttrib.szFrom);
 
        /* To = Encoded-string */
        if (pMsg && (strchr(pMsg->mmsAttrib.szFrom, '/') == NULL)) {
                length = strlen(pMsg->mmsAttrib.szFrom);
-               szTo = (char *)malloc(length + 11);
+               szTo = (char *)calloc(1, length + 11);
                if (szTo == NULL) {
-                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: szTo alloc fail\n");
+                       MSG_DEBUG("szTo alloc fail");
                        goto __CATCH;
                }
 
                snprintf(szTo, length + 11, "%s/TYPE=PLMN", pMsg->mmsAttrib.szFrom);
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To = %s\n", szTo);
+               MSG_DEBUG("To = %s", szTo);
 
                if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_TO, szTo) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To __MmsBinaryEncodeAddress fail\n");
+                       MSG_DEBUG("To __MmsBinaryEncodeAddress fail");
                        goto __CATCH;
                }
 
@@ -1089,7 +1024,7 @@ bool _MmsBinaryEncodeReadReport10Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_
                }
        } else {
                if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_TO, pMsg->mmsAttrib.szFrom) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To __MmsBinaryEncodeAddress fail\n");
+                       MSG_DEBUG("To __MmsBinaryEncodeAddress fail");
                        goto __CATCH;
                }
        }
@@ -1110,65 +1045,69 @@ bool _MmsBinaryEncodeReadReport10Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_
                }
        }
 
-       length = MmsBinaryEncodeEncodedStringLen((UINT8*)szSubject);
+       length = __MmsBinaryEncodeEncodedStringLen((UINT8*)szSubject);
        if (length == -1) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: subject MmsBinaryEncodeEncodedStringLen fail \n");
+               MSG_DEBUG("subject MmsBinaryEncodeEncodedStringLen fail");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length + 1) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos, gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: subject MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("subject MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
-       fieldCode = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_SUBJECT) | 0x80;
+       fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_SUBJECT) | 0x80;
        gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = fieldCode;
-       if (MmsBinaryEncodeEncodedString(pFile, (UINT8*)szSubject, length) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: subject MmsBinaryEncodeEncodedString fail \n");
+       if (__MmsBinaryEncodeEncodedString(pFile, (UINT8*)szSubject, length) == false) {
+               MSG_DEBUG("subject MmsBinaryEncodeEncodedString fail");
                goto __CATCH;
        }
 
        /* Msg class */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGCLASS) | 0x80;
-       fieldValue = _MmsGetBinaryValue(MmsCodeMsgClass, MMS_MSGCLASS_AUTO) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGCLASS) | 0x80;
+       fieldValue = MmsGetBinaryValue(MmsCodeMsgClass, MMS_MSGCLASS_AUTO) | 0x80;
        if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: msgClass error\n");
+               MSG_DEBUG("msgClass error");
                goto __CATCH;
        }
 
 
        /* Delivery Report (yes | no) */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_DELIVERYREPORT) | 0x80;
-       fieldValue = _MmsGetBinaryValue(MmsCodeDeliveryReport, MMS_REPORT_NO) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_DELIVERYREPORT) | 0x80;
+       fieldValue = MmsGetBinaryValue(MmsCodeDeliveryReport, MMS_REPORT_NO) | 0x80;
        if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: Delivery Report error\n");
+               MSG_DEBUG("Delivery Report error");
                goto __CATCH;
        }
 
 
        /* Read Reply (Yes | no) */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_READREPLY) | 0x80;
-       fieldValue = _MmsGetBinaryValue(MmsCodeReadReply, MMS_REPORT_NO) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_READREPLY) | 0x80;
+       fieldValue = MmsGetBinaryValue(MmsCodeReadReply, MMS_REPORT_NO) | 0x80;
        if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: Read Reply error\n");
+               MSG_DEBUG("Read Reply error");
                goto __CATCH;
        }
 
 
        /* Sender Visible (hide | show) */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_SENDERVISIBILLITY) | 0x80;
-       fieldValue = _MmsGetBinaryValue(MmsCodeSenderVisibility, MMS_SENDER_SHOW) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_SENDERVISIBILLITY) | 0x80;
+       fieldValue = MmsGetBinaryValue(MmsCodeSenderVisibility, MMS_SENDER_SHOW) | 0x80;
        if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: Sender Visible error\n");
+               MSG_DEBUG("Sender Visible error");
                goto __CATCH;
        }
 
+       /* fixme: MimeType */
+       /* fixme: msgHeader */
+       /* fixme: msgBody */
+
        /* flush remained data on encoding file */
        if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: remained data MsgWriteDataFromEncodeBuffer fail \n");
+               MSG_DEBUG("remained data MsgWriteDataFromEncodeBuffer fail");
                goto __CATCH;
        }
 
@@ -1183,9 +1122,7 @@ __CATCH:
        return false;
 }
 
-
-
-bool _MmsBinaryEncodeReadReport11Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
+static bool __MmsBinaryEncodeReadReport11Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
 {
        UINT8 fieldCode = 0xff;
        UINT8 fieldValue = 0xff;
@@ -1194,16 +1131,16 @@ bool _MmsBinaryEncodeReadReport11Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_
        __MmsCleanEncodeBuff();
 
        /* msgType */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGTYPE) | 0x80;
-       fieldValue = _MmsGetBinaryValue(MmsCodeMsgType, MMS_MSGTYPE_READREC_IND) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGTYPE) | 0x80;
+       fieldValue = MmsGetBinaryValue(MmsCodeMsgType, MMS_MSGTYPE_READREC_IND) | 0x80;
        if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: msgType error\n");
+               MSG_DEBUG("msgType error");
                goto __CATCH;
        }
 
        /* MMS version */
        if (__MmsBinaryEncodeMmsVersion(pFile) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: __MmsBinaryEncodeMmsVersion error\n");
+               MSG_DEBUG("__MmsBinaryEncodeMmsVersion error");
                goto __CATCH;
        }
 
@@ -1214,18 +1151,18 @@ bool _MmsBinaryEncodeReadReport11Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_
        if (strchr(pMsg->mmsAttrib.szFrom, '/') == NULL) {
                int length = 0;
                length = strlen(pMsg->mmsAttrib.szFrom);
-               szTo = (char *)malloc(length + 11);
+               szTo = (char *)calloc(1, length + 11);
 
                if (szTo == NULL) {
-                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: szTo alloc fail\n");
+                       MSG_DEBUG("szTo alloc fail");
                        goto __CATCH;
                }
 
                snprintf(szTo, length + 11,"%s/TYPE=PLMN", pMsg->mmsAttrib.szFrom);
-               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To = %s\n", szTo);
+               MSG_DEBUG("To = %s", szTo);
 
                if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_TO, szTo) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To __MmsBinaryEncodeAddress fail\n");
+                       MSG_DEBUG("To __MmsBinaryEncodeAddress fail");
                        goto __CATCH;
                }
 
@@ -1235,35 +1172,35 @@ bool _MmsBinaryEncodeReadReport11Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_
                }
        } else {
                if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_TO, pMsg->mmsAttrib.szFrom) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: To __MmsBinaryEncodeAddress fail\n");
+                       MSG_DEBUG("To __MmsBinaryEncodeAddress fail");
                        goto __CATCH;
                }
        }
 
        /* From : Insert Token mode */
        if (__MmsBinaryEncodeFrom(pFile) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: __MmsBinaryEncodeFrom fail\n");
+               MSG_DEBUG("__MmsBinaryEncodeFrom fail");
                goto __CATCH;
        }
 
        /* Date = Long-integer */
-       if (!__MmsBinaryEncodeDate(pFile)) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: __MmsBinaryEncodeDate error\n");
+       if (!__MmsBinaryEncodeDate(pFile, 0)) {
+               MSG_DEBUG("__MmsBinaryEncodeDate error");
                goto __CATCH;
        }
 
        /* Read Status (Yes | no) */
-       fieldCode  = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_READSTATUS) | 0x80;
-       fieldValue = _MmsGetBinaryValue(MmsCodeReadStatus, mmsReadStatus) | 0x80;
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_READSTATUS) | 0x80;
+       fieldValue = MmsGetBinaryValue(MmsCodeReadStatus, mmsReadStatus) | 0x80;
 
        if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: Read Status error\n");
+               MSG_DEBUG("Read Status error");
                goto __CATCH;
        };
 
        if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-               MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: remained data MsgWriteDataFromEncodeBuffer fail \n");
+               MSG_DEBUG("remained data MsgWriteDataFromEncodeBuffer fail");
                goto __CATCH;
        }
 
@@ -1278,15 +1215,16 @@ __CATCH:
        return false;
 }
 
-bool MmsBinaryEncodeMsgBody(FILE *pFile, MsgType *pType, MsgBody *pBody, int nPartCount, bool bTemplate)
+static bool __MmsBinaryEncodeMsgBody(FILE *pFile, MsgType *pType, MsgBody *pBody, int nPartCount, bool bTemplate)
 {
        int length = 0;
+       int index = 0;
        MsgMultipart *pMultipart = NULL;
 
-       MSG_DEBUG("MmsBinaryEncodeMsgBody: nPartCount = %d\n", nPartCount);
+       MSG_DEBUG("nPartCount = %d", nPartCount);
 
        if (pFile == NULL || pType == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeMsgBody: invalid file handle\n");
+               MSG_DEBUG("invalid file handle");
                goto __CATCH;
        }
 
@@ -1297,23 +1235,23 @@ bool MmsBinaryEncodeMsgBody(FILE *pFile, MsgType *pType, MsgBody *pBody, int nPa
                 *       Multipart message
                 * ---------------------------*/
 
-               pType->offset = _MmsGetEncodeOffset();
+               pType->offset = __MmsGetEncodeOffset();
 
                /* Content type */
-               length = MmsBinaryEncodeContentTypeLen(pType);
+               length = __MmsBinaryEncodeContentTypeLen(pType);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgBody: MmsBinaryEncodeContentTypeLen fail \n");
+                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen fail");
                        goto __CATCH;
                }
                if (bTemplate == false)
-                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_CONTENTTYPE) | 0x80;
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_CONTENTTYPE) | 0x80;
 
-               if (MmsBinaryEncodeContentType(pFile, pType, length) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgBody: MmsBinaryEncodeContentType fail \n");
+               if (__MmsBinaryEncodeContentType(pFile, pType, length) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeContentType fail");
                        goto __CATCH;
                }
 
-               pBody->offset = _MmsGetEncodeOffset();
+               pBody->offset = __MmsGetEncodeOffset();
 
                /* nEntries */
                if (pBody->pPresentationBody) {
@@ -1323,23 +1261,23 @@ bool MmsBinaryEncodeMsgBody(FILE *pFile, MsgType *pType, MsgBody *pBody, int nPa
                }
 
                if (nEntries >= 0) {
-                       length = MmsBinaryEncodeUintvarLen(nEntries);
+                       length = __MmsBinaryEncodeUintvarLen(nEntries);
                        if (length == -1) {
-                               MSG_DEBUG("MmsBinaryEncodeMsgBody: nEntries MmsBinaryEncodeUintvarLen fail \n");
+                               MSG_DEBUG("nEntries MmsBinaryEncodeUintvarLen fail");
                                goto __CATCH;
                        }
-                       if (MmsBinaryEncodeUintvar(pFile, nEntries, length) == false) {
-                               MSG_DEBUG("MmsBinaryEncodeMsgBody: nEntries MmsBinaryEncodeUintvar fail \n");
+                       if (__MmsBinaryEncodeUintvar(pFile, nEntries, length) == false) {
+                               MSG_DEBUG("nEntries MmsBinaryEncodeUintvar fail");
                                goto __CATCH;
                        }
 
-                       pType->size = _MmsGetEncodeOffset() - pType->offset;
+                       pType->size = __MmsGetEncodeOffset() - pType->offset;
                }
 
                if (nEntries > 0) {
                        if (nEntries && pBody->pPresentationBody) {
-                               if (MmsBinaryEncodeMsgPart(pFile, pType->type, &pBody->presentationType, pBody->pPresentationBody) == false) {
-                                       MSG_DEBUG("MmsBinaryEncodeMsgBody: __MmsBinaryEncodeMsgPart fail \n");
+                               if (__MmsBinaryEncodeMsgPart(pFile, pType->type, &pBody->presentationType, pBody->pPresentationBody) == false) {
+                                       MSG_DEBUG("__MmsBinaryEncodeMsgPart fail");
                                        goto __CATCH;
                                }
 
@@ -1348,64 +1286,68 @@ bool MmsBinaryEncodeMsgBody(FILE *pFile, MsgType *pType, MsgBody *pBody, int nPa
 
                        pMultipart = pBody->body.pMultipart;
                        while (nEntries && pMultipart) {
-                               if (MmsBinaryEncodeMsgPart(pFile, pType->type, &pMultipart->type, pMultipart->pBody) == false) {
-                                       MSG_DEBUG("MmsBinaryEncodeMsgBody: __MmsBinaryEncodeMsgPart fail \n");
+                               if (__MmsBinaryEncodeMsgPart(pFile, pType->type, &pMultipart->type, pMultipart->pBody) == false) {
+                                       MSG_DEBUG("__MmsBinaryEncodeMsgPart fail");
                                        goto __CATCH;
                                }
+
+                               MmsPrintMulitpart(pMultipart, index++);
+
                                pMultipart = pMultipart->pNext;
                                nEntries--;
                        }
                } else {
                        if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                                gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                               MSG_DEBUG("MmsBinaryEncodeMsgBody: Empty message body MsgWriteDataFromEncodeBuffer fail \n");
+                               MSG_DEBUG("Empty message body MsgWriteDataFromEncodeBuffer fail");
                                goto __CATCH;
                        }
                }
 
-               pBody->size = _MmsGetEncodeOffset() - pBody->offset;
+               pBody->size = __MmsGetEncodeOffset() - pBody->offset;
        } else {
                /* ---------------------------
                 *       Singlepart message
                 * ---------------------------*/
-               pType->offset = _MmsGetEncodeOffset();
+               pType->offset = __MmsGetEncodeOffset();
 
-               if (MmsBinaryEncodeContentHeader(pFile, (MimeType)pType->type, pType, false) == false)
+               if (__MmsBinaryEncodeContentHeader(pFile, (MimeType)pType->type, pType, false) == false)
                        goto __CATCH;
 
-               length = MmsBinaryEncodeContentTypeLen(pType);
+               length = __MmsBinaryEncodeContentTypeLen(pType);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgBody: Singlepart MmsBinaryEncodeContentTypeLen fail \n");
+                       MSG_DEBUG("Singlepart MmsBinaryEncodeContentTypeLen fail");
                        goto __CATCH;
                }
 
-               if (MmsBinaryEncodeContentType(pFile, pType, length) == false)
+               if (__MmsBinaryEncodeContentType(pFile, pType, length) == false)
                        goto __CATCH;
 
-               pType->size = _MmsGetEncodeOffset() - pType->offset;
+               pType->size = __MmsGetEncodeOffset() - pType->offset;
 
-               if (MmsBinaryEncodeContentBody(pFile, pBody) == false)
+               if (__MmsBinaryEncodeContentBody(pFile, pBody) == false)
                        goto __CATCH;
        }
 
        return true;
 
 __CATCH:
-       MSG_DEBUG("## MmsBinaryEncodeMsgBody: failed\n");
+       MSG_DEBUG("Failed");
 
        return false;
 }
 
-
-int MmsBinaryEncodeContentTypeLen(MsgType *pType)
+static int __MmsBinaryEncodeContentTypeLen(MsgType *pType)
 {
        int length = 0;
        int     totalLength = 0;
        UINT16 fieldValue = 0xffff;
-       char *szTextType = NULL;
+       const char *szTextType = NULL;
        int     contentType = MIME_UNKNOWN;
 
-       MSG_DEBUG("MSmsBinaryEncodeContentTypeLen:  type\n");
+       bool isAscii = true;
+       unsigned  long tmpLength = 0;
+       unsigned char tmpFileName[MSG_LOCALE_FILENAME_LEN_MAX+1];
 
        /*
         * Content-type-value = Constrained-media | Content-general-form
@@ -1421,14 +1363,14 @@ int MmsBinaryEncodeContentTypeLen(MsgType *pType)
 
        contentType = pType->type;
 
-       fieldValue = _MmsGetBinaryValue(MmsCodeContentType, contentType);
+       fieldValue = MmsGetBinaryValue(MmsCodeContentType, contentType);
        if (fieldValue == UNDEFINED_BINARY || fieldValue == 0x0049)     {
                /* Extension-media type */
-               szTextType = _MmsGetTextValue(MmsCodeContentType, contentType);
+               szTextType = MmsGetTextValue(MmsCodeContentType, contentType);
                if (szTextType != NULL) {
-                       length  = MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
                        if (length == -1) {
-                               MSG_DEBUG("MSmsBinaryEncodeContentTypeLen: szTextType MmsBinaryEncodeTextStringLen fail \n");
+                               MSG_DEBUG("szTextType MmsBinaryEncodeTextStringLen fail");
                                goto __CATCH;
                        }
                        totalLength += length;
@@ -1441,20 +1383,18 @@ int MmsBinaryEncodeContentTypeLen(MsgType *pType)
 
        /* Parameters -------------------------------------------------------------- */
 
-       MSG_DEBUG("MSmsBinaryEncodeContentTypeLen:  parameters    \n\n");
-
        /* Well-known-charset = Any-charset | Integer-value ----------------------- */
 
        if (pType->param.charset != MSG_CHARSET_UNKNOWN) {
-               fieldValue = _MmsGetBinaryValue(MmsCodeCharSet, pType->param.charset);
-               length     = MmsBinaryEncodeIntegerLen(fieldValue);
+               fieldValue = MmsGetBinaryValue(MmsCodeCharSet, pType->param.charset);
+               length     = __MmsBinaryEncodeIntegerLen(fieldValue);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: charSet MmsBinaryEncodeIntegerLen fail \n");
+                       MSG_DEBUG("charSet MmsBinaryEncodeIntegerLen fail");
                        goto __CATCH;
                }
                totalLength += (length + 1);
        } else {
-               if (MmsIsText(contentType)) {   // Any-charset
+               if (MmsIsTextType(contentType)) {       // Any-charset
                        if (!MmsIsVitemContent (contentType, pType->param.szName))
                                totalLength += 2;
                }
@@ -1465,79 +1405,64 @@ int MmsBinaryEncodeContentTypeLen(MsgType *pType)
 
        if (pType->param.szName[0]) {
                char* pszName = NULL;
-
-               if (_MsgIsASCII (pType->param.szName)) {
-                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: szName is consisted of ascii char-set chars. \n");
-
-                       pszName = (char *)malloc(strlen(pType->param.szName) +1);
-                       memset(pszName, 0, (strlen(pType->param.szName)+1));
-                       strcpy(pszName, pType->param.szName);
+               if (MmsIsAsciiString (pType->param.szName)) {
+                       MSG_DEBUG("Name is consisted of ascii char-set chars.");
                } else {
-                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: szName is not consisted of ascii char-set chars. \n");
-                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: pType->param.szName : %s\n", pType->param.szName);
-
-                       /* if msg-server can't support non ascii, then convert non-ascii to '_' by using _MsgReplaceNonAscii*/
-                       int filelen = strlen(pType->param.szName);
-
-                       pszName = (char *)malloc(filelen + 1);
-                       memset(pszName, 0, (filelen + 1));
-                       strncpy(pszName, pType->param.szName, filelen);
-
-                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: pszName : %s\n", pszName);
+                       isAscii = false;
+                       MSG_DEBUG("Name is NOT consisted of ascii char-set chars.");
                }
 
-               //change empty space to '_' in the file name
-               if (_MsgIsSpace(pszName)) {
-                       char *pszTempName = NULL;
-
-                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: szName has space(' '). \n");
+               pszName = g_strdup(pType->param.szName);
 
-                       _MsgReplaceSpecialChar(pszName, &pszTempName, ' ');
+               //change empty space to '_' in the file name
+               MmsReplaceSpaceChar(pszName);
 
-                       if (pszTempName) {
-                               free(pszName);
-                               pszName = pszTempName;
+               if (isAscii == false) {
+                       if (MsgEncode2Base64(pszName, strlen(pszName), &tmpLength, tmpFileName) == true) {
+                               g_free(pszName);
+                               pszName = g_strdup_printf("=?UTF-8?B?%s?=", tmpFileName);
+                               MSG_DEBUG("base64 encode filename=[%s]", pszName);
                        }
-                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: pszName : %s\n", pszName);
                }
 
-               length = MmsBinaryEncodeTextStringLen((UINT8*)pszName);
-               free(pszName);
+               length = __MmsBinaryEncodeTextStringLen((UINT8*)pszName);
 
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: szName MmsBinaryEncodeIntegerLen fail \n");
+                       MSG_DEBUG("szName MmsBinaryEncodeIntegerLen fail");
                        goto __CATCH;
                }
 
+               g_free(pszName);
+
                totalLength += (length + 1);
        }
 
 #ifdef FEATURE_JAVA_MMS
        if (pType->param.szApplicationID) {
-               length = MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szApplicationID);
+               length = __MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szApplicationID);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: szApplicationID MmsBinaryEncodeTextStrinLen fail \n");
+                       MSG_DEBUG("szApplicationID MmsBinaryEncodeTextStrinLen fail");
                        goto __CATCH;
                }
 
                totalLength += (length);
-               if (_MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_APPLICATION_ID) == UNDEFINED_BINARY) {
-                       totalLength += strlen(_MmsGetTextValue(MmsCodeParameterCode, MSG_PARAM_APPLICATION_ID)) + 1; /* NULL */
+               if (MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_APPLICATION_ID) == UNDEFINED_BINARY) {
+                       totalLength += strlen(MmsGetTextValue(MmsCodeParameterCode, MSG_PARAM_APPLICATION_ID)) + 1; /* NULL */
                } else {
                        totalLength++;
                }
        }
 
        if (pType->param.szReplyToApplicationID) {
-               length = MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szReplyToApplicationID);
+               length = __MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szReplyToApplicationID);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: szApplicationID MmsBinaryEncodeTextStrinLen fail \n");
+                       MSG_DEBUG("szApplicationID MmsBinaryEncodeTextStrinLen fail");
                        goto __CATCH;
                }
 
                totalLength += (length);
-               if (_MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_REPLY_TO_APPLICATION_ID) == UNDEFINED_BINARY) {
-                       totalLength += strlen(_MmsGetTextValue(MmsCodeParameterCode, MSG_PARAM_REPLY_TO_APPLICATION_ID)) + 1; /* NULL */
+               if (MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_REPLY_TO_APPLICATION_ID) == UNDEFINED_BINARY) {
+                       totalLength += strlen(MmsGetTextValue(MmsCodeParameterCode, MSG_PARAM_REPLY_TO_APPLICATION_ID)) + 1; /* NULL */
                } else {
                        totalLength++;
                }
@@ -1547,14 +1472,14 @@ int MmsBinaryEncodeContentTypeLen(MsgType *pType)
        /* type, start, & startInfo : multipart/related only parameters -------------- */
        if (contentType == MIME_MULTIPART_RELATED || contentType == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
                /* type ------------------------------------- */
-               fieldValue = _MmsGetBinaryValue(MmsCodeContentType, pType->param.type);
+               fieldValue = MmsGetBinaryValue(MmsCodeContentType, pType->param.type);
                if (fieldValue == UNDEFINED_BINARY || fieldValue == 0x0049) {
                        /* Extension-media type */
-                       szTextType = _MmsGetTextValue(MmsCodeContentType, pType->param.type);
+                       szTextType = MmsGetTextValue(MmsCodeContentType, pType->param.type);
                        if (szTextType != NULL) {
-                               length  = MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
+                               length  = __MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
                                if (length == -1) {
-                                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: type param MmsBinaryEncodeTextStringLen fail \n");
+                                       MSG_DEBUG("type param MmsBinaryEncodeTextStringLen fail");
                                        goto __CATCH;
                                }
                                totalLength += (length + 1);
@@ -1568,9 +1493,9 @@ int MmsBinaryEncodeContentTypeLen(MsgType *pType)
                /* start = Text-string ----------------------- */
                if (pType->param.szStart[0]) {
                        /* start = Text-string */
-                       length  = MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStart);
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStart);
                        if (length == -1) {
-                               MSG_DEBUG("MmsBinaryEncodeContentType: szStart MmsBinaryEncodeTextStringLen fail \n");
+                               MSG_DEBUG("szStart MmsBinaryEncodeTextStringLen fail");
                                goto __CATCH;
                        }
 
@@ -1581,9 +1506,9 @@ int MmsBinaryEncodeContentTypeLen(MsgType *pType)
                /* startInfo = Text-string -------------------- */
                if (pType->param.szStartInfo[0]) {
                        /* StartInfo (with multipart/related) = Text-string */
-                       length  = MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStartInfo);
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStartInfo);
                        if (length == -1) {
-                               MSG_DEBUG("MmsBinaryEncodeContentType: szStartInfo MmsBinaryEncodeTextStringLen fail \n");
+                               MSG_DEBUG("szStartInfo MmsBinaryEncodeTextStringLen fail");
                                goto __CATCH;
                        }
 
@@ -1595,26 +1520,24 @@ int MmsBinaryEncodeContentTypeLen(MsgType *pType)
 
 __CATCH:
 
-       MSG_DEBUG("## MmsBinaryEncodeContentTypeLen: failed");
+       MSG_DEBUG("Failed");
        return -1;
 }
 
-
-
-bool MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
+static bool __MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
 {
        int length = 0;
        UINT16 fieldValue = 0xffff;
-       char *szTextType = NULL;
+       const char *szTextType = NULL;
        int contentType = MIME_UNKNOWN;
 
+       bool isAscii = true;
+       unsigned  long tmpLength = 0;
+       unsigned char tmpFileName[MSG_LOCALE_FILENAME_LEN_MAX+1];
+
 #ifdef FEATURE_JAVA_MMS
-       char *szParameter = NULL;
+       const char *szParameter = NULL;
 #endif
-
-       MSG_DEBUG("************************************************************************************\n");
-       MSG_DEBUG("MmsBinaryEncodeContentType:  C O N T E N T     T Y P E    \n\n");
-
        /*
         * Content-type-value = Constrained-media | Content-general-form
         * Constrained-media  = Constrained-encoding
@@ -1625,30 +1548,32 @@ bool MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
         */
 
        if (pFile == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeContentType: invalid file handle\n");
+               MSG_DEBUG("invalid file handle");
                goto __CATCH;
        }
 
 
        /* Content-Type = Content-general-form ------------------------------- */
 
-       length = MmsBinaryEncodeValueLengthLen(typeLength);
+       length = __MmsBinaryEncodeValueLengthLen(typeLength);
        if (length == -1) {
-               MSG_DEBUG("MSmsBinaryEncodeContentType : MmsBinaryEncodeValueLengthLen fail.\n");
+               MSG_DEBUG("MmsBinaryEncodeValueLengthLen fail.");
                goto __CATCH;
        }
 
-       if (MmsBinaryEncodeValueLength(pFile, typeLength, length) == false) {
-               MSG_DEBUG("MSmsBinaryEncodeContentType : MmsBinaryEncodeValueLength fail.\n");
+       if (__MmsBinaryEncodeValueLength(pFile, typeLength, length) == false) {
+               MSG_DEBUG("MmsBinaryEncodeValueLength fail.");
                goto __CATCH;
        }
 
        contentType = pType->type;
 
-       fieldValue = _MmsGetBinaryValue(MmsCodeContentType, (int)contentType);
+       MSG_SEC_DEBUG("Content Type : %s", MmsGetTextValue(MmsCodeContentType, (int)contentType));
+
+       fieldValue = MmsGetBinaryValue(MmsCodeContentType, (int)contentType);
        if (fieldValue == UNDEFINED_BINARY || fieldValue == 0x0049) {
                /* Extension-media type */
-               szTextType = _MmsGetTextValue(MmsCodeContentType, (int)contentType);
+               szTextType = MmsGetTextValue(MmsCodeContentType, (int)contentType);
                if (szTextType == NULL)
                        fieldValue = 0x00;
        }
@@ -1656,95 +1581,77 @@ bool MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
        if (szTextType == NULL) {
                gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)fieldValue | 0x80;
        } else {
-               length  = MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
+               length  = __MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
                if (length == -1) {
-                       MSG_DEBUG("MSmsBinaryEncodeContentType: szTextType MmsBinaryEncodeTextStringLen fail \n");
+                       MSG_DEBUG("szTextType MmsBinaryEncodeTextStringLen fail");
                        goto __CATCH;
                }
 
-               if (MmsBinaryEncodeTextString(pFile, (UINT8*)szTextType, length) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeContentType: szTextType MmsBinaryEncodeTextString fail \n");
+               if (__MmsBinaryEncodeTextString(pFile, (UINT8*)szTextType, length) == false) {
+                       MSG_DEBUG("szTextType MmsBinaryEncodeTextString fail");
                        goto __CATCH;
                }
        }
 
-       /* Parameters -------------------------------------------------------------- */
-
-       MSG_DEBUG("MmsBinaryEncodeContentType:  P A R M E T E R S    \n\n");
-
        /* Name = Text-string ------------------------------------------------------ */
-
        if (pType->param.szName[0]) {
-               char* pszName = NULL;
-
-               if (_MsgIsASCII (pType->param.szName)) {
-
-                       MSG_DEBUG("MmsBinaryEncodeContentType: szName is consisted of ascii char-set chars. \n");
-
-                       pszName = (char *)malloc(strlen(pType->param.szName) +1);
-                       memset(pszName, 0, (strlen(pType->param.szName)+1));
-                       strcpy(pszName, pType->param.szName);
+               MSG_SEC_DEBUG("Parameter Name : %s", pType->param.szName);
+               char *pszName = NULL;
+               if (MmsIsAsciiString (pType->param.szName)) {
+                       MSG_DEBUG("Name is consisted of ascii char-set chars.");
                } else {
-                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: szName is not consisted of ascii char-set chars. \n");
-
-                       /* if msg-server can't support non ascii, then convert non-ascii to '_' by using _MsgReplaceNonAscii*/
-                       int filelen = strlen(pType->param.szName);
-
-                       pszName = (char *)malloc(filelen + 1);
-                       memset(pszName, 0, (filelen + 1));
-                       strncpy(pszName, pType->param.szName, filelen);
-
-                       MSG_DEBUG("MmsBinaryEncodeContentType: pszName : %s\n", pszName);
+                       isAscii = false;
+                       MSG_DEBUG("Name is NOT consisted of ascii char-set chars.");
                }
 
-               //change empty space to '_' in the file name
-               if (_MsgIsSpace(pszName)) {
-                       char*   pszTempName = NULL;
+               pszName = g_strdup(pType->param.szName);
 
-                       MSG_DEBUG("MmsBinaryEncodeContentType: szName has space(' '). \n");
+               //change empty space to '_' in the file name
+               MmsReplaceSpaceChar(pszName);
 
-                       _MsgReplaceSpecialChar(pszName, &pszTempName, ' ');
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_NAME) | 0x80;
 
-                       if (pszTempName) {
-                               free(pszName);
-                               pszName = pszTempName;
+               if (isAscii == false) {
+                       if (MsgEncode2Base64(pszName, strlen(pszName), &tmpLength, tmpFileName) == true) {
+                               g_free(pszName);
+                               pszName = g_strdup_printf("=?UTF-8?B?%s?=", tmpFileName);
+                               MSG_DEBUG("base64 encode filename=[%s]", pszName);
                        }
-                       MSG_DEBUG("MmsBinaryEncodeContentType: pszName : %s\n", pszName);
                }
 
-               length = MmsBinaryEncodeTextStringLen((UINT8*)pszName);
+               length = __MmsBinaryEncodeTextStringLen((UINT8*)pszName);
+
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentType: szName MmsBinaryEncodeIntegerLen fail \n");
+                       MSG_DEBUG("szName MmsBinaryEncodeIntegerLen fail");
                        free(pszName);
                        goto __CATCH;
                }
-               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_NAME) | 0x80;
 
-               if (MmsBinaryEncodeTextString(pFile, (UINT8*)pszName, length) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeContentType: szName MmsBinaryEncodeTextString fail\n");
+               if (__MmsBinaryEncodeTextString(pFile, (UINT8*)pszName, length) == false) {
+                       MSG_DEBUG("szName MmsBinaryEncodeTextString fail");
                        free(pszName);
                        goto __CATCH;
                }
                free(pszName);
        }
 #ifdef FEATURE_JAVA_MMS
-       MSG_DEBUG(" MmsBinaryEncodeContentType: Application-ID \n");
 
        /* Application-ID: Text-string */
        if (pType->param.szApplicationID) {
-               length = MmsBinaryEncodeTextStringLen((UINT8*) pType->param.szApplicationID);
+               MSG_SEC_DEBUG("Parameter Application ID : %s", pType->param.szApplicationID);
+               length = __MmsBinaryEncodeTextStringLen((UINT8*) pType->param.szApplicationID);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentType: szApplicationID MmsBinaryEncodeIntegerLen Fail \n");
+                       MSG_DEBUG("szApplicationID MmsBinaryEncodeIntegerLen Fail");
                        goto __CATCH;
                }
 
-               fieldValue = _MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_APPLICATION_ID);
+               fieldValue = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_APPLICATION_ID);
 
                if (fieldValue == UNDEFINED_BINARY)
-                       szParameter = _MmsGetTextValue(MmsCodeParameterCode, MSG_PARAM_APPLICATION_ID);
+                       szParameter = MmsGetTextValue(MmsCodeParameterCode, MSG_PARAM_APPLICATION_ID);
 
                if (szParameter == NULL) {
-                       MSG_DEBUG("MmsBinaryEncodeContentType: szParameter is NULL \n");
+                       MSG_DEBUG("szParameter is NULL");
                        goto __CATCH;
                }
 
@@ -1752,8 +1659,8 @@ bool MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
                gCurMmsEncodeBuffPos += strlen(szParameter);
                gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] =(UINT8)NULL;
 
-               if (MmsBinaryEncodeTextString(pFile, (UINT8*) pType->param.szApplicationID, length) == false) {
-                       MSG_DEBUG(" MmsBinaryEncodeContentType: szApplicationID MmsBinaryEncodeTextString fail\n");
+               if (__MmsBinaryEncodeTextString(pFile, (UINT8*) pType->param.szApplicationID, length) == false) {
+                       MSG_DEBUG(" szApplicationID MmsBinaryEncodeTextString fail");
                        goto __CATCH;
                }
 
@@ -1761,19 +1668,20 @@ bool MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
 
        /* ReplyToApplicationID: Text-string */
        if (pType->param.szReplyToApplicationID) {
-               length = MmsBinaryEncodeTextStringLen((UINT8*) pType->param.szReplyToApplicationID);
+               MSG_SEC_DEBUG("Parameter Reply To Application-ID : %s", pType->param.szReplyToApplicationID);
+               length = __MmsBinaryEncodeTextStringLen((UINT8*) pType->param.szReplyToApplicationID);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentType: szReplyToApplicationID MmsBinaryEncodeIntegerLen Fail \n");
+                       MSG_DEBUG("szReplyToApplicationID MmsBinaryEncodeIntegerLen Fail");
                        goto __CATCH;
                }
 
-               fieldValue = _MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_REPLY_TO_APPLICATION_ID);
+               fieldValue = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_REPLY_TO_APPLICATION_ID);
 
                if (fieldValue == UNDEFINED_BINARY)
-                       szParameter = _MmsGetTextValue(MmsCodeParameterCode, MSG_PARAM_REPLY_TO_APPLICATION_ID);
+                       szParameter = MmsGetTextValue(MmsCodeParameterCode, MSG_PARAM_REPLY_TO_APPLICATION_ID);
 
                if (szParameter == NULL) {
-                       MSG_DEBUG("MmsBinaryEncodeContentType: szParameter is NULL \n");
+                       MSG_DEBUG("szParameter is NULL");
                        goto __CATCH;
                }
 
@@ -1781,8 +1689,8 @@ bool MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
                gCurMmsEncodeBuffPos += strlen(szParameter);
                gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] =(UINT8)NULL;
 
-               if (MmsBinaryEncodeTextString(pFile, (UINT8*) pType->param.szReplyToApplicationID, length) == false) {
-                       MSG_DEBUG(" MmsBinaryEncodeContentType: szApplicationID MmsBinaryEncodeTextString fail\n");
+               if (__MmsBinaryEncodeTextString(pFile, (UINT8*) pType->param.szReplyToApplicationID, length) == false) {
+                       MSG_DEBUG("szApplicationID MmsBinaryEncodeTextString fail");
                        goto __CATCH;
                }
        }
@@ -1791,23 +1699,24 @@ bool MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
        /* Well-known-charset = Any-charset | Integer-value ----------------------- */
 
        if (pType->param.charset != MSG_CHARSET_UNKNOWN) {
-               fieldValue = _MmsGetBinaryValue(MmsCodeCharSet, pType->param.charset);
-               length = MmsBinaryEncodeIntegerLen(fieldValue);
+               MSG_DEBUG("Parameter Charset : %d", pType->param.charset);
+               fieldValue = MmsGetBinaryValue(MmsCodeCharSet, pType->param.charset);
+               length = __MmsBinaryEncodeIntegerLen(fieldValue);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentType: charSet MmsBinaryEncodeIntegerLen fail \n");
+                       MSG_DEBUG("charSet MmsBinaryEncodeIntegerLen fail");
                        goto __CATCH;
                }
 
-               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_CHARSET) | 0x80;
-               if (MmsBinaryEncodeInteger(pFile, fieldValue, length) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeContentType: charSet MmsBinaryEncodeInteger fail\n");
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_CHARSET) | 0x80;
+               if (__MmsBinaryEncodeInteger(pFile, fieldValue, length) == false) {
+                       MSG_DEBUG("charSet MmsBinaryEncodeInteger fail");
                        goto __CATCH;
                }
        } else {
                /* Any-charset */
-               if (MmsIsText(contentType)) {
+               if (MmsIsTextType(contentType)) {
                        if (!MmsIsVitemContent (contentType, pType->param.szName)) {
-                               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_CHARSET) | 0x80;
+                               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_CHARSET) | 0x80;
                                fieldValue = 0x0000;    //laconic_warning, just to remove warning message
                                gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)fieldValue | 0x80;
                        }
@@ -1816,45 +1725,47 @@ bool MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
 
        /* type, start, & startInfo : multipart/related only parameters -------------- */
        if (contentType == MIME_MULTIPART_RELATED || contentType == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
+               MSG_SEC_DEBUG("Parameter Content Type : %s", MmsGetTextValue(MmsCodeContentType, pType->param.type));
                /* type ------------------------------------- */
-               fieldValue = _MmsGetBinaryValue(MmsCodeContentType, pType->param.type);
+               fieldValue = MmsGetBinaryValue(MmsCodeContentType, pType->param.type);
                if (fieldValue == UNDEFINED_BINARY || fieldValue == 0x0049) {
                        /* Extension-media type */
-                       szTextType = _MmsGetTextValue(MmsCodeContentType, pType->param.type);
+                       szTextType = MmsGetTextValue(MmsCodeContentType, pType->param.type);
                        if (szTextType == NULL)
                                fieldValue = 0x00;
                }
 
                if (szTextType == NULL) {
                        gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)fieldValue | 0x80;
-                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_TYPE) | 0x80;
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_TYPE) | 0x80;
                } else {
-                       length  = MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
                        if (length == -1) {
-                               MSG_DEBUG("MmsBinaryEncodeContentType: type param MmsBinaryEncodeTextStringLen fail \n");
+                               MSG_DEBUG("type param MmsBinaryEncodeTextStringLen fail");
                                goto __CATCH;
                        }
 
-                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_TYPE) | 0x80;
-                       if (MmsBinaryEncodeTextString(pFile, (UINT8*)szTextType, length) == false) {
-                               MSG_DEBUG("MmsBinaryEncodeContentType: type param MmsBinaryEncodeTextString fail \n");
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_TYPE) | 0x80;
+                       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)szTextType, length) == false) {
+                               MSG_DEBUG("type param MmsBinaryEncodeTextString fail");
                                goto __CATCH;
                        }
                }
 
                /* start = Text-string ----------------------- */
-               if (pType->param.szStart && pType->param.szStart[0]) {
+               if (pType->param.szStart[0]) {
                        /* start = Text-string */
-                       length  = MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStart);
+                       MSG_DEBUG("Parameter Start: %s", pType->param.szStart);
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStart);
                        if (length == -1) {
-                               MSG_DEBUG("MmsBinaryEncodeContentType: szStart MmsBinaryEncodeTextStringLen fail \n");
+                               MSG_DEBUG("szStart MmsBinaryEncodeTextStringLen fail");
                                goto __CATCH;
                        }
 
-                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeParameterCode,
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeParameterCode,
                                                                                                                                                 MSG_PARAM_START) | 0x80;
-                       if (MmsBinaryEncodeTextString(pFile, (UINT8*)pType->param.szStart, length) == false) {
-                               MSG_DEBUG("MmsBinaryEncodeContentType: szStart MmsBinaryEncodeTextString fail \n");
+                       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)pType->param.szStart, length) == false) {
+                               MSG_DEBUG("szStart MmsBinaryEncodeTextString fail");
                                goto __CATCH;
                        }
                }
@@ -1862,15 +1773,16 @@ bool MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
                /* startInfo = Text-string -------------------- */
                if (pType->param.szStartInfo[0]) {
                        /* StartInfo (with multipart/related) = Text-string */
-                       length  = MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStartInfo);
+                       MSG_DEBUG("Parameter StartInfo: %s", pType->param.szStartInfo);
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStartInfo);
                        if (length == -1) {
-                               MSG_DEBUG("MmsBinaryEncodeContentType: szStartInfo MmsBinaryEncodeTextStringLen fail \n");
+                               MSG_DEBUG("szStartInfo MmsBinaryEncodeTextStringLen fail");
                                goto __CATCH;
                        }
 
-                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_START_INFO) | 0x80;
-                       if (MmsBinaryEncodeTextString(pFile, (UINT8*)pType->param.szStartInfo, length) == false) {
-                               MSG_DEBUG("MmsBinaryEncodeContentType: szStartInfo MmsBinaryEncodeTextString fail \n");
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_START_INFO) | 0x80;
+                       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)pType->param.szStartInfo, length) == false) {
+                               MSG_DEBUG("szStartInfo MmsBinaryEncodeTextString fail");
                                goto __CATCH;
                        }
                }
@@ -1879,13 +1791,11 @@ bool MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
        return true;
 
 __CATCH:
-       MSG_DEBUG("## MmsBinaryEncodeContentType: failed");
+       MSG_DEBUG("Failed");
        return false;
 }
 
-
-
-bool MmsBinaryEncodeMsgPart(FILE *pFile, int contentType, MsgType *pType, MsgBody *pBody)
+static bool __MmsBinaryEncodeMsgPart(FILE *pFile, int contentType, MsgType *pType, MsgBody *pBody)
 {
        FILE *pFile2 = NULL;
        char *pData = NULL;
@@ -1895,36 +1805,36 @@ bool MmsBinaryEncodeMsgPart(FILE *pFile, int contentType, MsgType *pType, MsgBod
        if (pType->offset && pType->size) {
                /* header length & body length --------------------------- */
 
-               length = MmsBinaryEncodeUintvarLen(pType->size);
+               length = __MmsBinaryEncodeUintvarLen(pType->size);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: 1. headerLeng MmsBinaryEncodeUintvarLen fail \n");
+                       MSG_DEBUG("1. headerLeng MmsBinaryEncodeUintvarLen fail");
                        goto __CATCH;
                }
 
-               if (MmsBinaryEncodeUintvar(pFile, pType->size, length) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: 1. eaderLeng fail \n");
+               if (__MmsBinaryEncodeUintvar(pFile, pType->size, length) == false) {
+                       MSG_DEBUG("1. eaderLeng fail");
                        goto __CATCH;
                }
 
-               length = MmsBinaryEncodeUintvarLen(pBody->size);
+               length = __MmsBinaryEncodeUintvarLen(pBody->size);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: 1. bodyLeng MmsBinaryEncodeUintvarLen fail \n");
+                       MSG_DEBUG("1. bodyLeng MmsBinaryEncodeUintvarLen fail");
                        goto __CATCH;
                }
 
-               if (MmsBinaryEncodeUintvar(pFile, pBody->size, length) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: 1. bodyLeng fail \n");
+               if (__MmsBinaryEncodeUintvar(pFile, pBody->size, length) == false) {
+                       MSG_DEBUG("1. bodyLeng fail");
                        goto __CATCH;
                }
 
                pFile2 = MsgOpenFile(pType->szOrgFilePath, "rb");
                if (pFile != NULL) {
-                       pData = (char *)malloc(pType->size);
+                       pData = (char *)calloc(1, pType->size);
                        if (pData == NULL)
                                goto __CATCH;
 
                        if (MsgFseek(pFile2, pType->offset, SEEK_SET) < 0) {
-                               MSG_DEBUG("MmsBinaryEncodeMsgPart: MsgFseek fail \n");
+                               MSG_DEBUG("MsgFseek fail");
                                goto __CATCH;
                        }
 
@@ -1933,10 +1843,10 @@ bool MmsBinaryEncodeMsgPart(FILE *pFile, int contentType, MsgType *pType, MsgBod
                        if ((nRead = MsgReadFile(pData, sizeof(char), pType->size, pFile2)) == 0) {
                                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                                       MSG_DEBUG("MmsBinaryEncodeMsgPart: 1. header MsgWriteDataFromEncodeBuffer fail \n");
+                                       MSG_DEBUG("1. header MsgWriteDataFromEncodeBuffer fail");
                                        goto __CATCH;
                                }
-                               pType->offset = _MmsGetEncodeOffset();
+                               pType->offset = __MmsGetEncodeOffset();
                                if(MsgWriteFile(pData, sizeof(char), nRead, pFile) != (size_t)nRead) {
                                        MSG_DEBUG("MsgWriteFile failed");
                                        goto __CATCH;
@@ -1957,68 +1867,68 @@ bool MmsBinaryEncodeMsgPart(FILE *pFile, int contentType, MsgType *pType, MsgBod
                int contentHdrLen  = 0;
 
                /* header length & body length --------------------------- */
-               contentTypeLen = MmsBinaryEncodeContentTypeLen(pType);
-               length = MmsBinaryEncodeValueLengthLen(contentTypeLen);
-               contentHdrLen  = MmsBinaryEncodeContentHeaderLen((MimeType)contentType, pType, true);
+               contentTypeLen = __MmsBinaryEncodeContentTypeLen(pType);
+               length = __MmsBinaryEncodeValueLengthLen(contentTypeLen);
+               contentHdrLen  = __MmsBinaryEncodeContentHeaderLen((MimeType)contentType, pType, true);
 
                if (contentTypeLen == -1 || length == -1 || contentHdrLen == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: headerLeng calculation fail \n");
+                       MSG_DEBUG("headerLeng calculation fail");
                        goto __CATCH;
                }
 
                headerLeng = contentTypeLen + contentHdrLen + length;
-               length = MmsBinaryEncodeUintvarLen(headerLeng);
+               length = __MmsBinaryEncodeUintvarLen(headerLeng);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: headerLeng MmsBinaryEncodeUintvarLen fail \n");
+                       MSG_DEBUG("headerLeng MmsBinaryEncodeUintvarLen fail");
                        goto __CATCH;
                }
 
-               if (MmsBinaryEncodeUintvar(pFile, headerLeng, length) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: headerLeng fail \n");
+               if (__MmsBinaryEncodeUintvar(pFile, headerLeng, length) == false) {
+                       MSG_DEBUG("headerLeng fail");
                        goto __CATCH;
                }
 
-               length = MmsBinaryEncodeUintvarLen(pBody->size);
+               length = __MmsBinaryEncodeUintvarLen(pBody->size);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: bodyLeng MmsBinaryEncodeUintvarLen fail \n");
+                       MSG_DEBUG("bodyLeng MmsBinaryEncodeUintvarLen fail");
                        goto __CATCH;
                }
 
-               if (MmsBinaryEncodeUintvar(pFile, pBody->size, length) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: bodyLeng fail \n");
+               if (__MmsBinaryEncodeUintvar(pFile, pBody->size, length) == false) {
+                       MSG_DEBUG("bodyLeng fail");
                        goto __CATCH;
                }
 
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: 2. header MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("2. header MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
 
                /* content-type & header --------------------------- */
-               pType->offset = _MmsGetEncodeOffset();
+               pType->offset = __MmsGetEncodeOffset();
 
-               if (MmsBinaryEncodeContentType(pFile, pType, contentTypeLen) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: MmsBinaryEncodeContentType fail \n");
+               if (__MmsBinaryEncodeContentType(pFile, pType, contentTypeLen) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeContentType fail");
                        goto __CATCH;
                }
 
-               if (MmsBinaryEncodeContentHeader(pFile, (MsgContentType)contentType, pType, true) == false)     {
-                       MSG_DEBUG("MmsBinaryEncodeMsgPart: MmsBinaryEncodeContentHeader fail \n");
+               if (__MmsBinaryEncodeContentHeader(pFile, (MimeType)contentType, pType, true) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeContentHeader fail");
                        goto __CATCH;
                }
 
-               pType->size = _MmsGetEncodeOffset() - pType->offset;
+               pType->size = __MmsGetEncodeOffset() - pType->offset;
        }
 
        if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos, gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-               MSG_DEBUG("MmsBinaryEncodeMsgPart: contentBody MsgWriteDataFromEncodeBuffer fail \n");
+               MSG_DEBUG("contentBody MsgWriteDataFromEncodeBuffer fail");
                goto __CATCH;
        }
 
        /* content-body --------------------------- */
-       if (MmsBinaryEncodeContentBody(pFile, pBody) == false) {
-               MSG_DEBUG("MmsBinaryEncodeMsgPart: MmsBinaryEncodeContentBody fail \n");
+       if (__MmsBinaryEncodeContentBody(pFile, pBody) == false) {
+               MSG_DEBUG("__MmsBinaryEncodeContentBody fail");
                goto __CATCH;
        }
 
@@ -2036,7 +1946,7 @@ __CATCH:
                pData = NULL;
        }
 
-       MSG_DEBUG("## MmsBinaryEncodeMsgPart: failed\n");
+       MSG_DEBUG("Failed");
        if (pFile2) {
                MsgCloseFile(pFile2);
                pFile2 = NULL;
@@ -2045,15 +1955,11 @@ __CATCH:
        return false;
 }
 
-
-int MmsBinaryEncodeContentHeaderLen(MsgContentType contentType, MsgType *pType, bool bMultipart)
+static int __MmsBinaryEncodeContentHeaderLen(MimeType contentType, MsgType *pType, bool bMultipart)
 {
        int     length = 0;
        int     totalLength = 0;
-       char *szTextValue = NULL;
-
-
-       MSG_DEBUG("MmsBinaryEncodeContentHeaderLen: S T A R T \n\n");
+       const char *szTextValue = NULL;
 
        /* content-id ------------------------------------------------- */
        if (pType->szContentID[0]) {
@@ -2061,18 +1967,18 @@ int MmsBinaryEncodeContentHeaderLen(MsgContentType contentType, MsgType *pType,
                        totalLength++;
                } else {
                        /* content-id = Quoted-string */
-                       length = MmsBinaryEncodeTextStringLen((UINT8*)"Content-ID");
+                       length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-ID");
                        if (length == -1) {
-                               MSG_DEBUG("MmsBinaryEncodeContentHeaderLen: Content-ID MmsBinaryEncodeTextStringLen fail.\n");
+                               MSG_DEBUG("Content-ID MmsBinaryEncodeTextStringLen fail.");
                                goto __CATCH;
                        }
 
                        totalLength += length;
                }
 
-               length = MmsBinaryEncodeQuotedStringLen((UINT8*)pType->szContentID);
+               length = __MmsBinaryEncodeQuotedStringLen((UINT8*)pType->szContentID);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentID MmsBinaryEncodeQuotedStringLen fail.\n");
+                       MSG_DEBUG("pType->szContentID MmsBinaryEncodeQuotedStringLen fail.");
                        goto __CATCH;
                }
                totalLength += length;
@@ -2084,18 +1990,18 @@ int MmsBinaryEncodeContentHeaderLen(MsgContentType contentType, MsgType *pType,
                        totalLength++;
                } else {
                        /* content-location = Quoted-string */
-                       length = MmsBinaryEncodeTextStringLen((UINT8*)"Content-Location");
+                       length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-Location");
                        if (length == -1) {
-                               MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Location MmsBinaryEncodeTextStringLen fail.\n");
+                               MSG_DEBUG("Content-Location MmsBinaryEncodeTextStringLen fail.");
                                goto __CATCH;
                        }
 
                        totalLength += length;
                }
 
-               length = MmsBinaryEncodeTextStringLen((UINT8*)pType->szContentLocation);
+               length = __MmsBinaryEncodeTextStringLen((UINT8*)pType->szContentLocation);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentLocation MmsBinaryEncodeTextStringLen fail.\n");
+                       MSG_DEBUG("pType->szContentLocation MmsBinaryEncodeTextStringLen fail.");
                        goto __CATCH;
                }
 
@@ -2121,20 +2027,20 @@ int MmsBinaryEncodeContentHeaderLen(MsgContentType contentType, MsgType *pType,
                        totalLength += 3;
                } else {
                        /* content-disposition = Quoted-string */
-                       szTextValue = _MmsGetTextValue(MmsCodeMsgDisposition, pType->disposition);
+                       szTextValue = MmsGetTextValue(MmsCodeMsgDisposition, pType->disposition);
 
                        if (szTextValue) {
-                               length = MmsBinaryEncodeTextStringLen((UINT8*)"Content-Disposition");
+                               length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-Disposition");
                                if (length == -1) {
-                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextStringLen fail.\n");
+                                       MSG_DEBUG("Content-Disposition MmsBinaryEncodeTextStringLen fail.");
                                        goto __CATCH;
                                }
 
                                totalLength += length;
 
-                               length = MmsBinaryEncodeTextStringLen((UINT8*)szTextValue);
+                               length = __MmsBinaryEncodeTextStringLen((UINT8*)szTextValue);
                                if (length == -1) {
-                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextStringLen fail.\n");
+                                       MSG_DEBUG("Content-Disposition MmsBinaryEncodeTextStringLen fail.");
                                        goto __CATCH;
                                }
                                totalLength += length;
@@ -2145,85 +2051,87 @@ int MmsBinaryEncodeContentHeaderLen(MsgContentType contentType, MsgType *pType,
        return totalLength;
 
 __CATCH:
-       MSG_DEBUG("## MmsBinaryEncodeContentHeadeLen: failed");
-
+       MSG_DEBUG("Failed");
        return -1;
 }
 
-
-
-bool MmsBinaryEncodeContentHeader(FILE *pFile, MsgContentType contentType, MsgType *pType, bool bMultipart)
+static bool __MmsBinaryEncodeContentHeader(FILE *pFile, MimeType contentType, MsgType *pType, bool bMultipart)
 {
        int     length = 0;
-       char *szTextValue = NULL;
-
-       MSG_DEBUG("MmsBinaryEncodeContentHeader: S T A R T \n\n");
+       const char *szTextValue = NULL;
 
        /* content-id ------------------------------------------------- */
        if (pType->szContentID[0]) {
+
+               MSG_SEC_DEBUG("Content ID : %s", pType->szContentID);
+
                if (bMultipart) { //Binary Encoding
-                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeMsgBodyHeaderCode, MMS_BODYHDR_CONTENTID) | 0x80;
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeMsgBodyHeaderCode, MMS_BODYHDR_CONTENTID) | 0x80;
                } else {
                        /* content-id = Quoted-string */
-                       length = MmsBinaryEncodeTextStringLen((UINT8*)"Content-ID");
+                       length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-ID");
                        if (length == -1) {
-                               MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-ID MmsBinaryEncodeTextStringLen fail.\n");
+                               MSG_DEBUG("Content-ID MmsBinaryEncodeTextStringLen fail.");
                                goto __CATCH;
                        }
 
-                       if (MmsBinaryEncodeTextString(pFile, (UINT8*)"Content-ID", length) == false) {
-                               MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-ID MmsBinaryEncodeTextString fail.\n");
+                       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)"Content-ID", length) == false) {
+                               MSG_DEBUG("Content-ID MmsBinaryEncodeTextString fail.");
                                goto __CATCH;
                        }
                }
 
-               length = MmsBinaryEncodeQuotedStringLen((UINT8*)pType->szContentID);
+               length = __MmsBinaryEncodeQuotedStringLen((UINT8*)pType->szContentID);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentID MmsBinaryEncodeQuotedStringLen fail.\n");
+                       MSG_DEBUG("pType->szContentID MmsBinaryEncodeQuotedStringLen fail.");
                        goto __CATCH;
                }
 
-               if (MmsBinaryEncodeQuotedString(pFile, (UINT8*)pType->szContentID, length) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentID MmsBinaryEncodeQuotedString fail.\n");
+               if (__MmsBinaryEncodeQuotedString(pFile, (UINT8*)pType->szContentID, length) == false) {
+                       MSG_DEBUG("pType->szContentID MmsBinaryEncodeQuotedString fail.");
                        goto __CATCH;
                }
        }
 
        if (pType->szContentLocation[0]) {
+
+               MSG_SEC_DEBUG("Content Location : %s", pType->szContentLocation);
+
                if (bMultipart) { //Binary Encoding
-                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeMsgBodyHeaderCode, MMS_BODYHDR_CONTENTLOCATION) | 0x80;
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeMsgBodyHeaderCode, MMS_BODYHDR_CONTENTLOCATION) | 0x80;
                } else {
                        /* content-location = Quoted-string */
-                       length = MmsBinaryEncodeTextStringLen((UINT8*)"Content-Location");
+                       length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-Location");
                        if (length == -1) {
-                               MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Location MmsBinaryEncodeTextStringLen fail.\n");
+                               MSG_DEBUG("Content-Location MmsBinaryEncodeTextStringLen fail.");
                                goto __CATCH;
                        }
 
-                       if (MmsBinaryEncodeTextString(pFile, (UINT8*)"Content-Location", length) == false) {
-                               MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Location MmsBinaryEncodeTextString fail.\n");
+                       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)"Content-Location", length) == false) {
+                               MSG_DEBUG("Content-Location MmsBinaryEncodeTextString fail.");
                                goto __CATCH;
                        }
                }
 
-               length = MmsBinaryEncodeTextStringLen((UINT8*)pType->szContentLocation);
+               length = __MmsBinaryEncodeTextStringLen((UINT8*)pType->szContentLocation);
                if (length == -1) {
-                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentLocation MmsBinaryEncodeTextStringLen fail.\n");
+                       MSG_DEBUG("pType->szContentLocation MmsBinaryEncodeTextStringLen fail.");
                        goto __CATCH;
                }
 
-               if (MmsBinaryEncodeTextString(pFile, (UINT8*)pType->szContentLocation, length) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentLocation MmsBinaryEncodeTextString fail.\n");
+               if (__MmsBinaryEncodeTextString(pFile, (UINT8*)pType->szContentLocation, length) == false) {
+                       MSG_DEBUG("pType->szContentLocation MmsBinaryEncodeTextString fail.");
                        goto __CATCH;
                }
        }
 
-       /* MIME_APPLICATION_VND_WAP_MULTIPART_RELATEDrequires always "inline" */
+       /* MIME_APPLICATION_VND_WAP_MULTIPART_RELATED requires always "inline" */
 
        if (contentType != MIME_APPLICATION_VND_WAP_MULTIPART_RELATED &&
                contentType != MIME_MULTIPART_RELATED &&
                pType->disposition != INVALID_VALUE) {
 
+               MSG_DEBUG("Content Disposition : %d", pType->disposition);
                /*
                 * Content-disposition-value = Value-length Disposition *(Parameter)
                 * Disposition = Form-data | Attachment | Inline | Token-text
@@ -2235,9 +2143,9 @@ bool MmsBinaryEncodeContentHeader(FILE *pFile, MsgContentType contentType, MsgTy
                if (bMultipart) {//Binary Encoding
 
                        UINT8 fieldValue  = 0xff;
-                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeMsgBodyHeaderCode, MMS_BODYHDR_DISPOSITION) | 0x80;
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeMsgBodyHeaderCode, MMS_BODYHDR_DISPOSITION) | 0x80;
 
-                       fieldValue = _MmsGetBinaryValue(MmsCodeMsgDisposition, pType->disposition) | 0x80;
+                       fieldValue = MmsGetBinaryValue(MmsCodeMsgDisposition, pType->disposition) | 0x80;
 
                        if (fieldValue == 0xff)
                                fieldValue = 0x81;
@@ -2247,28 +2155,28 @@ bool MmsBinaryEncodeContentHeader(FILE *pFile, MsgContentType contentType, MsgTy
                } else {
                        /* content-disposition = Disposition (no support parameter) */
 
-                       szTextValue = _MmsGetTextValue(MmsCodeMsgDisposition, pType->disposition);
+                       szTextValue = MmsGetTextValue(MmsCodeMsgDisposition, pType->disposition);
 
                        if (szTextValue) {
-                               length = MmsBinaryEncodeTextStringLen((UINT8*)"Content-Disposition");
+                               length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-Disposition");
                                if (length == -1) {
-                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextStringLen fail.\n");
+                                       MSG_DEBUG("Content-Disposition MmsBinaryEncodeTextStringLen fail.");
                                        goto __CATCH;
                                }
 
-                               if (MmsBinaryEncodeTextString(pFile, (UINT8*)"Content-Disposition", length) == false) {
-                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextString fail.\n");
+                               if (__MmsBinaryEncodeTextString(pFile, (UINT8*)"Content-Disposition", length) == false) {
+                                       MSG_DEBUG("Content-Disposition MmsBinaryEncodeTextString fail.");
                                        goto __CATCH;
                                }
 
-                               length = MmsBinaryEncodeTextStringLen((UINT8*)szTextValue);
+                               length = __MmsBinaryEncodeTextStringLen((UINT8*)szTextValue);
                                if (length == -1) {
-                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextStringLen fail.\n");
+                                       MSG_DEBUG("Content-Disposition MmsBinaryEncodeTextStringLen fail.");
                                        goto __CATCH;
                                }
 
-                               if (MmsBinaryEncodeTextString(pFile, (UINT8*)szTextValue, length) == false) {
-                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextString fail.\n");
+                               if (__MmsBinaryEncodeTextString(pFile, (UINT8*)szTextValue, length) == false) {
+                                       MSG_DEBUG("Content-Disposition MmsBinaryEncodeTextString fail.");
                                        goto __CATCH;
                                }
                        }
@@ -2278,13 +2186,11 @@ bool MmsBinaryEncodeContentHeader(FILE *pFile, MsgContentType contentType, MsgTy
        return true;
 
 __CATCH:
-       MSG_DEBUG("## MmsBinaryEncodeContentHeader: failed");
+       MSG_DEBUG("Failed");
        return false;
 }
 
-
-
-bool MmsBinaryEncodeContentBody(FILE *pFile, MsgBody *pBody)
+static bool __MmsBinaryEncodeContentBody(FILE *pFile, MsgBody *pBody)
 {
        int nRead = 0;
        char *pData = NULL;
@@ -2301,8 +2207,8 @@ bool MmsBinaryEncodeContentBody(FILE *pFile, MsgBody *pBody)
                if (pData == NULL)
                        goto __CATCH;
 
-               pBody->offset = _MmsGetEncodeOffset();
-               if(MsgWriteFile(pData, sizeof(char), nRead, pFile) != nRead) {
+               pBody->offset = __MmsGetEncodeOffset();
+               if(MsgWriteFile(pData, sizeof(char), nRead, pFile) != (size_t)nRead) {
                        MSG_DEBUG("MsgWriteFile failed");
                        goto __CATCH;
                }
@@ -2318,8 +2224,8 @@ bool MmsBinaryEncodeContentBody(FILE *pFile, MsgBody *pBody)
                        pData = NULL;
                }
        } else if (pBody->body.pText && pBody->size) {
-               pBody->offset = _MmsGetEncodeOffset();
-               if (MsgWriteFile(pBody->body.pText, sizeof(char),pBody->size, pFile) != pBody->size) {
+               pBody->offset = __MmsGetEncodeOffset();
+               if (MsgWriteFile(pBody->body.pText, sizeof(char),(size_t)pBody->size, pFile) != (size_t)pBody->size) {
                        MSG_DEBUG("MsgWriteFile failed");
                        goto __CATCH;
                }
@@ -2334,7 +2240,7 @@ bool MmsBinaryEncodeContentBody(FILE *pFile, MsgBody *pBody)
        return true;
 
 __CATCH:
-       MSG_DEBUG("## MmsBinaryEncodeContentBody: failed\n");
+       MSG_DEBUG("##failed");
        if (pData) {
                free(pData);
                pData = NULL;
@@ -2343,15 +2249,12 @@ __CATCH:
        return false;
 }
 
-
-
 /* =========================================================================
 
    B  I  N  A  R  Y       E  N  C  O  D  I  N  G      U  T  I  L  I  T  Y
 
    =========================================================================*/
-
-static int MmsBinaryEncodeIntegerLen(UINT32 integer)
+static int __MmsBinaryEncodeIntegerLen(UINT32 integer)
 {
        if (integer < 0x80) {
                /* short-integer */
@@ -2381,7 +2284,7 @@ static int MmsBinaryEncodeIntegerLen(UINT32 integer)
  *
  * @param      length [in] gotten from MmsBinaryEncodeIntegerLen()
  */
-static bool MmsBinaryEncodeInteger(FILE *pFile, UINT32 integer, int length)
+static bool __MmsBinaryEncodeInteger(FILE *pFile, UINT32 integer, int length)
 {
        union {
                UINT32 integer;
@@ -2390,14 +2293,14 @@ static bool MmsBinaryEncodeInteger(FILE *pFile, UINT32 integer, int length)
 
 
        if (pFile == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeInteger: source == NULL \n");
+               MSG_DEBUG("source == NULL");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeInteger: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
@@ -2428,8 +2331,7 @@ __CATCH:
        return false;
 }
 
-
-static int MmsBinaryEncodeLongIntegerLen(UINT32 integer)
+static int __MmsBinaryEncodeLongIntegerLen(UINT32 integer)
 {
        int length = 0;
 
@@ -2451,13 +2353,12 @@ static int MmsBinaryEncodeLongIntegerLen(UINT32 integer)
        return length;
 }
 
-
 /*
  * This makes value-length by specified integer value
  *
  * @param      length [in] gotten from MmsBinaryEncodeIntegerLen()
  */
-static bool MmsBinaryEncodeLongInteger(FILE *pFile, UINT32 integer, int length)
+static bool __MmsBinaryEncodeLongInteger(FILE *pFile, UINT32 integer, int length)
 {
        int i  = 0;
        union {
@@ -2472,14 +2373,14 @@ static bool MmsBinaryEncodeLongInteger(FILE *pFile, UINT32 integer, int length)
         */
 
        if (pFile == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeLongInteger: source == NULL \n");
+               MSG_DEBUG("pFile == NULL");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeLongInteger: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
@@ -2500,16 +2401,12 @@ __CATCH:
        return false;
 }
 
-
-
-static int MmsBinaryEncodeTextStringLen(UINT8 *source)
+static int __MmsBinaryEncodeTextStringLen(UINT8 *source)
 {
        int      length = 0;
 
-       MSG_DEBUG("MmsBinaryEncodeTextStringLen: \n");
-
        if (source == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeTextStringLen: source == NULL \n");
+               MSG_DEBUG("source == NULL");
                return -1;
        }
 
@@ -2523,18 +2420,14 @@ static int MmsBinaryEncodeTextStringLen(UINT8 *source)
        return length;
 }
 
-
 /*
  * @param      source [in] originam string
  * @param      length [in] gotten from MmsBinaryEncodeTextStringLen()
  * @param      dest [in] buffer to store quted string
  * @return     changed string length
 */
-static bool MmsBinaryEncodeTextString(FILE *pFile, UINT8 *source, int length)
+static bool __MmsBinaryEncodeTextString(FILE *pFile, UINT8 *source, int length)
 {
-
-       MSG_DEBUG("MmsBinaryEncodeTextString: \n");
-
        /*
         * make text string
         * Text-string = [Quote] *TEXT End-of-string
@@ -2545,14 +2438,14 @@ static bool MmsBinaryEncodeTextString(FILE *pFile, UINT8 *source, int length)
         */
 
        if (pFile == NULL || source == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeTextString: source == NULL \n");
+               MSG_DEBUG("pFile == %p, source = %p", pFile, source);
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeTextString: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
@@ -2572,8 +2465,6 @@ __CATCH:
        return false;
 }
 
-
-
 /*
  * Encode 28bit unsigned integer(Maximum) to uintvar
  *
@@ -2585,7 +2476,7 @@ const UINT32 UINTVAR_LENGTH_2 =  0x00003fff;              //14bit
 const UINT32 UINTVAR_LENGTH_3 =  0x001fffff;           //21bit
 
 
-static int MmsBinaryEncodeUintvarLen(UINT32 integer)
+static int __MmsBinaryEncodeUintvarLen(UINT32 integer)
 {
        UINT32          length  = 0;
 
@@ -2607,8 +2498,7 @@ static int MmsBinaryEncodeUintvarLen(UINT32 integer)
        return length;
 }
 
-
-static bool MmsBinaryEncodeUintvar(FILE *pFile, UINT32 integer, int length)
+static bool __MmsBinaryEncodeUintvar(FILE *pFile, UINT32 integer, int length)
 {
        const char ZERO = 0x00;
        int i = 2;
@@ -2620,14 +2510,14 @@ static bool MmsBinaryEncodeUintvar(FILE *pFile, UINT32 integer, int length)
        } source;
 
        if (pFile == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeUintvar: pFile == INVALID_HBOJ \n");
+               MSG_DEBUG("pFile == INVALID_HBOJ");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeUintvar: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
@@ -2661,29 +2551,26 @@ __CATCH:
        return false;
 }
 
-
-
-static int MmsBinaryEncodeValueLengthLen(UINT32 integer)
+static int __MmsBinaryEncodeValueLengthLen(UINT32 integer)
 {
        int length = 0;
 
        if (integer < 0x1f) {
                length = 1;
        } else {
-               length = MmsBinaryEncodeUintvarLen(integer) + 1;                //LENGTH_QUOTE
+               length = __MmsBinaryEncodeUintvarLen(integer) + 1;              //LENGTH_QUOTE
        }
 
        return length;
 }
 
-
 /*
  * This makes value-length by specified integer value
  *
  * @param      length [in] from MmsBinaryEncodeValueLengthLen()
  * @return     encoded value-length
  */
-static bool MmsBinaryEncodeValueLength(FILE *pFile, UINT32 integer, int length)
+static bool __MmsBinaryEncodeValueLength(FILE *pFile, UINT32 integer, int length)
 {
        /*
         * Value-length = Short-length | (Length-quote Length)
@@ -2694,14 +2581,14 @@ static bool MmsBinaryEncodeValueLength(FILE *pFile, UINT32 integer, int length)
         */
 
        if (pFile == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeValueLength: pFile == INVALID_HBOJ \n");
+               MSG_DEBUG("pFile == INVALID_HBOJ");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeValueLength: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
@@ -2710,8 +2597,8 @@ static bool MmsBinaryEncodeValueLength(FILE *pFile, UINT32 integer, int length)
                gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)integer;
        } else {
                gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)LENGTH_QUOTE;
-               if (MmsBinaryEncodeUintvar(pFile, integer, length - 1) == false) {      // LENGTH_QUOTE
-                       MSG_DEBUG("MmsBinaryEncodeValueLength: MmsBinaryEncodeUintvar fail\n");
+               if (__MmsBinaryEncodeUintvar(pFile, integer, length - 1) == false) {    // LENGTH_QUOTE
+                       MSG_DEBUG("MmsBinaryEncodeUintvar fail");
                        goto __CATCH;
                }
        }
@@ -2722,11 +2609,10 @@ __CATCH:
        return false;
 }
 
-
-static int MmsBinaryEncodeQuotedStringLen(UINT8 *pSrc)
+static int __MmsBinaryEncodeQuotedStringLen(UINT8 *pSrc)
 {
        if (pSrc == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeQuotedStringLen: invalid file\n");
+               MSG_DEBUG("invalid file");
                goto __CATCH;
        }
 
@@ -2736,7 +2622,6 @@ __CATCH:
        return -1;
 }
 
-
 /*
  * make quoted string
  * Quoted-string = <Octet 34> *TEXT End-of-string
@@ -2746,17 +2631,17 @@ __CATCH:
  * @param      dest [out] buffer to store quted string
  * @return     changed string length
 */
-static bool MmsBinaryEncodeQuotedString(FILE *pFile, UINT8 *source, int length)
+static bool __MmsBinaryEncodeQuotedString(FILE *pFile, UINT8 *source, int length)
 {
        if (source == NULL || pFile == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeQuotedString: invalid file\n");
+               MSG_DEBUG("invalid file");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeQuotedString: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
@@ -2772,35 +2657,30 @@ __CATCH:
        return false;
 }
 
-
-
-static int MmsBinaryEncodeEncodedStringLen(UINT8 *source)
+static int __MmsBinaryEncodeEncodedStringLen(UINT8 *source)
 {
        UINT32 charset = 0x6A;          // default = utf-8
        int charLeng            = 0;
        int textLeng            = 0;
        int valueLengthLen      = 0;
 
-
-       MSG_DEBUG("MmsBinaryEncodeEncodedStringLen: \n");
-
        /* value-length charSet text-string */
        /* Estimate charset value length and text string length */
-       charLeng = MmsBinaryEncodeIntegerLen(charset);
+       charLeng = __MmsBinaryEncodeIntegerLen(charset);
        if (charLeng == -1) {
-               MSG_DEBUG("MmsBinaryEncodeEncodedStringLen : charLeng MmsBinaryEncodeTextStringLen fail.\n");
-               goto __CATCH;;
+               MSG_DEBUG(" charLeng MmsBinaryEncodeTextStringLen fail.");
+               goto __CATCH;
        }
 
-       textLeng = MmsBinaryEncodeTextStringLen((UINT8*)source);
+       textLeng = __MmsBinaryEncodeTextStringLen((UINT8*)source);
        if (textLeng == -1)     {
-               MSG_DEBUG("MmsBinaryEncodeEncodedStringLen : textLeng MmsBinaryEncodeTextStringLen fail.\n");
-               goto __CATCH;;
+               MSG_DEBUG(" textLeng MmsBinaryEncodeTextStringLen fail.");
+               goto __CATCH;
        }
 
-       valueLengthLen = MmsBinaryEncodeValueLengthLen(charLeng + textLeng);
+       valueLengthLen = __MmsBinaryEncodeValueLengthLen(charLeng + textLeng);
        if (valueLengthLen == -1) {
-               MSG_DEBUG("MmsBinaryEncodeEncodedStringLen : valLengthLen MmsBinaryEncodeTextStringLen fail.\n");
+               MSG_DEBUG(" valLengthLen MmsBinaryEncodeTextStringLen fail.");
                goto __CATCH;
        }
 
@@ -2810,79 +2690,73 @@ __CATCH:
        return -1;
 }
 
-
 /*
  * This makes value-length by specified integer value
  *
  * @param      length [in] from MmsBinaryEncodeEncodedStringLen()
  * @return     encoded encoded-string
  */
-static bool MmsBinaryEncodeEncodedString(FILE *pFile, UINT8 *source, int length)
+static bool __MmsBinaryEncodeEncodedString(FILE *pFile, UINT8 *source, int length)
 {
        UINT32 charset = 0x6A;          // default = utf-8
        int charLeng = 0;
        int textLeng = 0;
        int valLengthLen = 0;
 
-
-       MSG_DEBUG("MmsBinaryEncodeEncodedString: \n");
-
        /* value-length charSet text-string */
-
        if (pFile == NULL || source == NULL) {
-               MSG_DEBUG("MmsBinaryEncodeEncodedString: invalid input parameter\n");
+               MSG_DEBUG("invalid input parameter");
                goto __CATCH;
        }
 
        /* Estimate charset value length and text string length */
-       charLeng = MmsBinaryEncodeIntegerLen(charset);
+       charLeng = __MmsBinaryEncodeIntegerLen(charset);
        if (charLeng == -1) {
-               MSG_DEBUG("MmsBinaryEncodeEncodedString : charLeng MmsBinaryEncodeTextStringLen fail.\n");
-               goto __CATCH;;
+               MSG_DEBUG("charLeng MmsBinaryEncodeTextStringLen fail.");
+               goto __CATCH;
        }
 
-       textLeng = MmsBinaryEncodeTextStringLen((UINT8*)source);
+       textLeng = __MmsBinaryEncodeTextStringLen((UINT8*)source);
        if (textLeng == -1) {
-               MSG_DEBUG("MmsBinaryEncodeEncodedString : textLeng MmsBinaryEncodeTextStringLen fail.\n");
-               goto __CATCH;;
+               MSG_DEBUG("textLeng MmsBinaryEncodeTextStringLen fail.");
+               goto __CATCH;
        }
 
-       valLengthLen = MmsBinaryEncodeValueLengthLen(charLeng + textLeng);
+       valLengthLen = __MmsBinaryEncodeValueLengthLen(charLeng + textLeng);
        if (valLengthLen == -1) {
-               MSG_DEBUG("MmsBinaryEncodeEncodedString : MmsBinaryEncodeValueLengthLen fail.\n");
+               MSG_DEBUG("MmsBinaryEncodeValueLengthLen fail.");
                goto __CATCH;
        }
 
        if (length != (charLeng + textLeng + valLengthLen))
        {
-               MSG_DEBUG("MmsBinaryEncodeEncodedString: invalid length\n");
+               MSG_DEBUG("invalid length");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("MmsBinaryEncodeEncodedString: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
        /* Value length of charset value and text string */
-       if (MmsBinaryEncodeValueLength(pFile, charLeng + textLeng, valLengthLen) == false) {
-               MSG_DEBUG("MmsBinaryEncodeEncodedString : MmsBinaryEncodeValueLength fail.\n");
+       if (__MmsBinaryEncodeValueLength(pFile, charLeng + textLeng, valLengthLen) == false) {
+               MSG_DEBUG("MmsBinaryEncodeValueLength fail.");
                goto __CATCH;
        }
 
-       /* Write charset on buffer -> integer value not long-integer */
-       if (MmsBinaryEncodeInteger(pFile, charset, charLeng) == false) {
-               MSG_DEBUG("MmsBinaryEncodeEncodedString : MmsBinaryEncodeInteger fail.\n");
+       /* fixme: Write charset on buffer -> integer value not long-integer */
+       if (__MmsBinaryEncodeInteger(pFile, charset, charLeng) == false) {
+               MSG_DEBUG("MmsBinaryEncodeInteger fail.");
                goto __CATCH;
        }
 
-
        /* Write text string on buffer */
-       if (MmsBinaryEncodeTextString(pFile, (UINT8*)source, textLeng) == false) {
-               MSG_DEBUG("MmsBinaryEncodeEncodedString : MmsBinaryEncodeTextString fail.\n");
+       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)source, textLeng) == false) {
+               MSG_DEBUG("MmsBinaryEncodeTextString fail.");
                goto __CATCH;
        }
 
@@ -2892,24 +2766,23 @@ __CATCH:
        return false;
 }
 
-
 static bool __MmsBinaryEncodeFieldCodeAndValue(FILE *pFile, UINT8 fieldCode, UINT8 fieldValue)
 {
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < 2) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeFieldCodeAndValue: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
        if (fieldCode == 0xff) {
-               MSG_DEBUG("__MmsBinaryEncodeFieldCodeAndValue: invalid fieldCode \n");
+               MSG_DEBUG("invalid fieldCode");
                goto __CATCH;
        }
 
        if (fieldValue == 0xff) {
-               MSG_DEBUG("__MmsBinaryEncodeFieldCodeAndValue: invalid fieldValue \n");
+               MSG_DEBUG("invalid fieldValue");
                return true;
        }
 
@@ -2922,49 +2795,50 @@ __CATCH:
        return false;
 }
 
-
-
 static bool __MmsBinaryEncodeTrID(FILE *pFile, char *szTrID, int bufLen)
 {
        int     length    = 0;
        UINT8 fieldCode = 0xff;
        char szBuff[MMS_TR_ID_LEN + 1] = {0, };
-       struct  tm      *dateTime = NULL;
-       time_t  RawTime = 0;
-       time_t  dateSec = 0;
+       struct tm dateTime;
+       time_t RawTime = 0;
+       time_t dateSec = 0;
 
        time(&RawTime);
-       dateTime = localtime(&RawTime);
-       dateSec = mktime(dateTime);
+       localtime_r(&RawTime, &dateTime);
 
+       dateSec = mktime(&dateTime);
 
-       fieldCode = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_TRID) | 0x80;
+       fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_TRID) | 0x80;
        if (fieldCode == 0xff) {
-               MSG_DEBUG("__MmsBinaryEncodeTrID: invalid fieldCode \n");
+               MSG_DEBUG("Invalid fieldCode[0x%02x]", fieldCode & 0x7F);
                goto __CATCH;
        }
 
-       snprintf(szBuff, MMS_TR_ID_LEN + 1, "%lu.%lu", dateSec, (unsigned long)random());
-       MSG_DEBUG("__MmsBinaryEncodeTrID: 2. szBuff = %s\n", szBuff);
+       if (szTrID && strlen(szTrID)) {
+               snprintf(szBuff, MMS_TR_ID_LEN + 1, "%s", szTrID);
+       } else {
+               snprintf(szBuff, MMS_TR_ID_LEN + 1, "%lu.%lu", dateSec, (unsigned long)random());
+               MSG_SEC_DEBUG("Generated Transaction ID = %s", szBuff);
+       }
 
-       length = MmsBinaryEncodeTextStringLen((UINT8*)szBuff);
+       length = __MmsBinaryEncodeTextStringLen((UINT8*)szBuff);
        if (length == -1) {
-               MSG_DEBUG("__MmsBinaryEncodeTrID: MmsBinaryEncodeTextStringLen fail \n");
+               MSG_DEBUG("MmsBinaryEncodeTextStringLen fail");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < (length + 1)) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeTrID: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
-
        gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = fieldCode;
-       if (MmsBinaryEncodeTextString(pFile, (UINT8*)szBuff, length) == false) {
-               MSG_DEBUG("__MmsBinaryEncodeTrID: MmsBinaryEncodeTextString fail\n");
+       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)szBuff, length) == false) {
+               MSG_DEBUG("MmsBinaryEncodeTextString fail");
                goto __CATCH;
        }
 
@@ -2973,6 +2847,7 @@ static bool __MmsBinaryEncodeTrID(FILE *pFile, char *szTrID, int bufLen)
                strncpy(szTrID, szBuff, bufLen - 1);
        }
 
+       MSG_SEC_INFO("X-Mms-Transaction-Id = [%s]", szBuff);
        return true;
 
 __CATCH:
@@ -2985,31 +2860,31 @@ static bool __MmsBinaryEncodeMsgID(FILE *pFile, const char *szMsgID)
        int     length = 0;
        UINT8 fieldCode = 0xff;
 
-       fieldCode = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGID) | 0x80;
+       fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGID) | 0x80;
        if (fieldCode == 0xff) {
-               MSG_DEBUG("__MmsBinaryEncodeTrID: invalid fieldCode \n");
+               MSG_DEBUG("invalid fieldCode");
                goto __CATCH;
        }
 
-       MSG_DEBUG("__MmsBinaryEncodeMsgID: 2. szBuff = %s\n", szMsgID);
+       MSG_DEBUG("2. szBuff = %s", szMsgID);
 
-       length = MmsBinaryEncodeTextStringLen((UINT8*)szMsgID);
+       length = __MmsBinaryEncodeTextStringLen((UINT8*)szMsgID);
        if (length == -1) {
-               MSG_DEBUG("__MmsBinaryEncodeMsgID: MmsBinaryEncodeTextStringLen fail \n");
+               MSG_DEBUG("MmsBinaryEncodeTextStringLen fail");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < (length + 1)) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeTrID: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
        gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = fieldCode;
-       if (MmsBinaryEncodeTextString(pFile, (UINT8*)szMsgID, length) == false) {
-               MSG_DEBUG("__MmsBinaryEncodeTrID: MmsBinaryEncodeTextString fail\n");
+       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)szMsgID, length) == false)       {
+               MSG_DEBUG("MmsBinaryEncodeTextString fail");
                goto __CATCH;
        }
 
@@ -3020,40 +2895,33 @@ __CATCH:
        return false;
 }
 
-
-
 static bool __MmsBinaryEncodeMmsVersion(FILE *pFile)
 {
        UINT8 majorVer = MMS_MAJOR_VERSION;
        UINT8 minorVer = MMS_MINOR_VERSION;
 
-       MSG_DEBUG("__MmsBinaryEncodeMmsVersion: \n");
-
        if (pFile == NULL) {
-               MSG_DEBUG("__MmsBinaryEncodeMmsVersion: invalid input file \n");
-               goto __CATCH;
-       }
-
-       if (majorVer < 1) {
-               MSG_DEBUG("__MmsBinaryEncodeMmsVersion: invalid major version (%d)\n", majorVer);
+               MSG_DEBUG("invalid input file");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < 2) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeMmsVersion: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
-       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_VERSION) | 0x80;
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_VERSION) | 0x80;
 
-       MSG_DEBUG("__MmsBinaryEncodeMmsVersion: major version (%d)\n", majorVer);
-       MSG_DEBUG("__MmsBinaryEncodeMmsVersion: minor version (%d)\n", minorVer);
+       MSG_DEBUG("major version (%d)", majorVer);
+       MSG_DEBUG("minor version (%d)", minorVer);
 
        gpMmsEncodeBuf[gCurMmsEncodeBuffPos] = (majorVer << 4) | (minorVer & 0x0f) | MSB;
 
+       MSG_SEC_INFO("X-Mms-MMS-Version = [0x%02x]", gpMmsEncodeBuf[gCurMmsEncodeBuffPos]);
+
        if (gpMmsEncodeBuf[gCurMmsEncodeBuffPos] < 0x80) {
                gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] |= 0x80;
        } else {
@@ -3066,39 +2934,42 @@ __CATCH:
        return false;
 }
 
-
-
-static bool __MmsBinaryEncodeDate(FILE *pFile)
+static bool __MmsBinaryEncodeDate(FILE *pFile, time_t inpDateSec)
 {
-       struct  tm      *dateTime = NULL;
-       time_t  dateSec = 0;
+       struct tm dateTime;
+       time_t dateSec = 0;
+
+       if (inpDateSec > 0)
+               dateSec = inpDateSec;
+       else
+               dateSec = time(NULL);
 
-       dateSec = time(NULL);
-       dateTime = localtime(&dateSec);
+       localtime_r(&dateSec, &dateTime);
 
-       MSG_DEBUG("%d - %d - %d, %d : %d (SYSTEM)", dateTime->tm_year + 1900, dateTime->tm_mon + 1, dateTime->tm_mday
-               , dateTime->tm_hour, dateTime->tm_min);
+       MSG_SEC_INFO("%d - %d - %d, %d : %d (SYSTEM)", dateTime.tm_year + 1900, dateTime.tm_mon + 1, dateTime.tm_mday
+               , dateTime.tm_hour, dateTime.tm_min);
 
        if (dateSec > 0) {
                int     length  = 0;
-               length = MmsBinaryEncodeLongIntegerLen(dateSec);
+               length = __MmsBinaryEncodeLongIntegerLen(dateSec);
 
                if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < (length + 1)) { // + fieldCode
                        if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                                gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                               MSG_DEBUG("__MmsBinaryEncodeDate: MsgWriteDataFromEncodeBuffer fail \n");
+                               MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                                goto __CATCH;
                        }
                }
 
-               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_DATE) | 0x80;
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_DATE) | 0x80;
 
-               if (MmsBinaryEncodeLongInteger(pFile, dateSec, length) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeDate: date MmsBinaryEncodeLongInteger error\n");
+               if (__MmsBinaryEncodeLongInteger(pFile, dateSec, length) == false) {
+                       MSG_DEBUG("date MmsBinaryEncodeLongInteger error");
                        goto __CATCH;
                }
+
        } else {
-               MSG_DEBUG("__MmsBinaryEncodeDate: date has a negative value (%d) \n", dateSec);
+               MSG_DEBUG("date has a negative value (%d)", dateSec);
                goto __CATCH;
        }
        return true;
@@ -3107,81 +2978,87 @@ __CATCH:
        return false;
 }
 
-
-
 static bool __MmsBinaryEncodeFrom(FILE *pFile)
 {
        if (pFile == NULL) {
-               MSG_DEBUG("__MmsBinaryEncodeFrom: invalid input file \n");
+               MSG_DEBUG("invalid input file");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < 3) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeFrom: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
-       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_FROM) | 0x80;
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_FROM) | 0x80;
        /* length of MMS_INSERT_ADDRESS_TOKEN value */
        gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = 0x01;
-       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeAddressType, MMS_INSERT_ADDRESS_TOKEN) | 0x80;
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeAddressType, MMS_INSERT_ADDRESS_TOKEN) | 0x80;
+
+       MSG_SEC_INFO("From  = [INSERT_ADDRESS_TOKEN]");
        return true;
 
 __CATCH:
        return false;
 }
 
-
 static bool __MmsBinaryEncodeOneAddress(FILE *pFile, MmsFieldCode addrType, char *szAddrStr)
 {
        int length = 0;
 
        if (pFile == NULL) {
-               MSG_DEBUG("__MmsBinaryEncodeOneAddress: invalid input file \n");
+               MSG_DEBUG("invalid input file");
                goto __CATCH;
        }
 
        /* EncodedString */
-       length = MmsBinaryEncodeEncodedStringLen((UINT8*)szAddrStr);
+       length = __MmsBinaryEncodeEncodedStringLen((UINT8*)szAddrStr);
 
        if (length == -1) {
-               MSG_DEBUG("__MmsBinaryEncodeOneAddress: MmsBinaryEncodeEncodedStringLen fail \n");
+               MSG_DEBUG("MmsBinaryEncodeEncodedStringLen fail");
                goto __CATCH;
        }
 
        if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length + 1) {
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeOneAddress: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
-       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeFieldCode, addrType) | 0x80;
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, addrType) | 0x80;
 
 
-       if (MmsBinaryEncodeEncodedString(pFile, (UINT8*)szAddrStr, length) == false) {
-               MSG_DEBUG("__MmsBinaryEncodeOneAddress: MmsBinaryEncodeEncodedString fail \n");
+       if (__MmsBinaryEncodeEncodedString(pFile, (UINT8*)szAddrStr, length) == false) {
+               MSG_DEBUG("MmsBinaryEncodeEncodedString fail");
                goto __CATCH;
        }
 
+       if (addrType == MMS_CODE_TO )
+               MSG_SEC_INFO("To = [%s]", szAddrStr);
+       else if (addrType == MMS_CODE_CC)
+               MSG_SEC_INFO("CC = [%s]", szAddrStr);
+       else if (addrType == MMS_CODE_BCC)
+               MSG_SEC_INFO("Bcc = [%s]", szAddrStr);
+
+
        return true;
 
 __CATCH:
        return false;
 }
 
-
 static bool __MmsBinaryEncodeAddress(FILE *pFile, MmsFieldCode addrType, char *szAddr)
 {
        char *pSingleAddr = NULL;
 
 
        if (pFile == NULL) {
-               MSG_DEBUG("__MmsBinaryEncodeAddress: invalid input file \n");
+               MSG_DEBUG("invalid input file");
                goto __CATCH;
        }
 
@@ -3195,7 +3072,7 @@ static bool __MmsBinaryEncodeAddress(FILE *pFile, MmsFieldCode addrType, char *s
 
                        *pSingleAddr = MSG_CH_NULL;
                        if (__MmsBinaryEncodeOneAddress(pFile, addrType, szAddr) == false) {
-                               MSG_DEBUG("__MmsBinaryEncodeAddress: __MmsBinaryEncodeAddress fail\n");
+                               MSG_DEBUG("__MmsBinaryEncodeAddress fail");
                                goto __CATCH;
                        }
                        *pSingleAddr = MSG_CH_SEMICOLON;
@@ -3204,7 +3081,7 @@ static bool __MmsBinaryEncodeAddress(FILE *pFile, MmsFieldCode addrType, char *s
                        pSingleAddr  = NULL;
                } else {
                        if (__MmsBinaryEncodeOneAddress(pFile, addrType, szAddr) == false) {
-                               MSG_DEBUG("__MmsBinaryEncodeAddress: __MmsBinaryEncodeAddress fail\n");
+                               MSG_DEBUG("__MmsBinaryEncodeAddress fail");
                                goto __CATCH;
                        }
 
@@ -3218,22 +3095,20 @@ __CATCH:
        return false;
 }
 
-
-
 static bool __MmsBinaryEncodeTime(FILE *pFile, MmsFieldCode fieldCode, MmsTimeStruct time)
 {
        int             timeLen  = 0;
        int             length   = 0;
 
        if (pFile == NULL) {
-               MSG_DEBUG("__MmsBinaryEncodeTime: invalid input file \n");
+               MSG_DEBUG("invalid input file");
                goto __CATCH;
        }
 
        if (time.time == 0 ||
                (fieldCode != MMS_CODE_EXPIRYTIME && fieldCode != MMS_CODE_DELIVERYTIME && fieldCode != MMS_CODE_REPLYCHARGINGDEADLINE) ||
                (time.type != MMS_TIMETYPE_ABSOLUTE && time.type != MMS_TIMETYPE_RELATIVE)) {
-               MSG_DEBUG("__MmsBinaryEncodeTime: time.type = %d \n", time.type);
+               MSG_DEBUG("time.type = %d", time.type);
                return true;
        }
 
@@ -3243,19 +3118,19 @@ static bool __MmsBinaryEncodeTime(FILE *pFile, MmsFieldCode fieldCode, MmsTimeSt
         */
 
        if (time.type == MMS_TIMETYPE_RELATIVE) {
-               timeLen = MmsBinaryEncodeIntegerLen(time.time);
+               timeLen = __MmsBinaryEncodeIntegerLen(time.time);
        } else {
-               timeLen = MmsBinaryEncodeLongIntegerLen(time.time);
+               timeLen = __MmsBinaryEncodeLongIntegerLen(time.time);
        }
 
        if (timeLen <= 0) {
-               MSG_DEBUG("__MmsBinaryEncodeTime: MmsBinaryEncodeLongIntegerLen fail \n");
+               MSG_DEBUG("MmsBinaryEncodeLongIntegerLen fail");
                goto __CATCH;
        }
 
-       length = MmsBinaryEncodeValueLengthLen(timeLen + 1);    //time length + time type token
+       length = __MmsBinaryEncodeValueLengthLen(timeLen + 1);  //time length + time type token
        if (length == -1) {
-               MSG_DEBUG("__MmsBinaryEncodeTime: MmsBinaryEncodeValueLengthLen fail \n");
+               MSG_DEBUG("MmsBinaryEncodeValueLengthLen fail");
                goto __CATCH;
        }
 
@@ -3263,31 +3138,31 @@ static bool __MmsBinaryEncodeTime(FILE *pFile, MmsFieldCode fieldCode, MmsTimeSt
 
                if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
                                                                                        gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
-                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: MsgWriteDataFromEncodeBuffer fail \n");
+                       MSG_DEBUG("MsgWriteDataFromEncodeBuffer fail");
                        goto __CATCH;
                }
        }
 
        /* fieldCode */
-       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeFieldCode, fieldCode) | 0x80;
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, fieldCode) | 0x80;
 
        /* value length */
-       if (MmsBinaryEncodeValueLength(pFile, timeLen + 1, length) == false) {
-               MSG_DEBUG("__MmsBinaryEncodeTime: MmsBinaryEncodeValueLength fail \n");
+       if (__MmsBinaryEncodeValueLength(pFile, timeLen + 1, length) == false) {
+               MSG_DEBUG("MmsBinaryEncodeValueLength fail");
                goto __CATCH;
        }
 
        /* time type & value */
        if (time.type == MMS_TIMETYPE_RELATIVE) {
-               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_RELATIVE) | 0x80;
-               if (MmsBinaryEncodeInteger(pFile, time.time, timeLen) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeTime: MmsBinaryEncodeLongInteger fail \n");
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_RELATIVE) | 0x80;
+               if (__MmsBinaryEncodeInteger(pFile, time.time, timeLen) == false)       {
+                       MSG_DEBUG("MmsBinaryEncodeLongInteger fail");
                        goto __CATCH;
                }
        } else {
-               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = _MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_ABSOLUTE) | 0x80;
-               if (MmsBinaryEncodeLongInteger(pFile, time.time, timeLen) == false) {
-                       MSG_DEBUG("__MmsBinaryEncodeTime: MmsBinaryEncodeLongInteger fail \n");
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_ABSOLUTE) | 0x80;
+               if (__MmsBinaryEncodeLongInteger(pFile, time.time, timeLen) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeLongInteger fail");
                        goto __CATCH;
                }
        }
@@ -3298,3 +3173,110 @@ __CATCH:
        return false;
 }
 
+char *_MsgSkipWS3(char *s)
+{
+       while (true) {
+               if ((*s == MSG_CH_CR) ||
+                       (*s == MSG_CH_LF) ||
+                       (*s == MSG_CH_SP) ||
+                       (*s == MSG_CH_TAB))
+                       ++s;
+               else
+                       return s;
+       }
+}
+//////////////////////////////////////////////////////////////////////////////
+static bool __EncodeMmsMessage(MmsMsg *pMmsMsg, const char *raw_filepath)
+{
+       bool encode_ret = false;
+       mode_t file_mode = (S_IRUSR | S_IWUSR);
+
+       if (pMmsMsg == NULL || raw_filepath == NULL) {
+               MSG_DEBUG("Invalid Parameter pMmsMsg = %p , raw_filepath = %p", pMmsMsg, raw_filepath);
+               return false;
+       }
+
+       FILE *pFile = MsgOpenFile(raw_filepath, "wb+");
+
+       if (pFile == NULL) {
+               MSG_FATAL("File Open Error: %s", g_strerror(errno));
+               goto __CATCH;
+       }
+
+       if (MsgFseek(pFile, 0L, SEEK_CUR) < 0) {
+               MSG_DEBUG("File Fseek Error: %s", g_strerror(errno));
+               goto __CATCH;
+       }
+
+       if (fchmod(fileno(pFile), file_mode) < 0) {
+               MSG_DEBUG("File chmod Error: %s", g_strerror(errno));
+               goto __CATCH;
+       }
+
+       switch(pMmsMsg->mmsAttrib.msgType)
+       {
+               case MMS_MSGTYPE_SEND_REQ:
+               case MMS_MSGTYPE_SEND_CONF:
+                       encode_ret = MmsEncodeSendReq(pFile, pMmsMsg);
+                       if (encode_ret == false) {
+                               MSG_DEBUG("Fail to MmsEncodeSendReq");
+                               goto __CATCH;
+                       }
+               break;
+               default:
+                       MSG_DEBUG("Not Support msg type : %d", pMmsMsg->mmsAttrib.msgType);
+                       goto __CATCH;
+               break;
+       }
+
+       MsgFsync(pFile);        //file is written to device immediately, it prevents missing file data from unexpected power off
+       MsgCloseFile(pFile);
+
+       return true;
+
+__CATCH:
+       if (pFile) {
+               MsgCloseFile(pFile);
+       }
+
+       return false;
+}
+
+MmsPluginEncoder *MmsPluginEncoder::pInstance = NULL;
+
+MmsPluginEncoder *MmsPluginEncoder::instance()
+{
+       if (!MmsPluginEncoder::pInstance)
+               MmsPluginEncoder::pInstance = new MmsPluginEncoder();
+
+       return MmsPluginEncoder::pInstance;
+}
+
+MmsPluginEncoder::MmsPluginEncoder(){}
+MmsPluginEncoder::~MmsPluginEncoder(){}
+
+void MmsPluginEncoder::encodeMmsPdu(MMS_DATA_S *pMmsData, msg_message_id_t msgID, const char *pduFilePath)
+{
+       MmsMsg *pMmsMsg = (MmsMsg *)calloc(1, sizeof(MmsMsg));
+
+       if (pMmsMsg) {
+               if (MmsConvertMmsMsg(pMmsMsg, pMmsData) != true) {
+                       MSG_DEBUG("Fail to Compose MMS Message");
+                       goto __CATCH;
+               }
+
+               encodeMmsPdu(pMmsMsg, msgID, pduFilePath);
+       }
+
+__CATCH:
+       MmsReleaseMmsMsg(pMmsMsg);
+       MSG_FREE(pMmsMsg);
+
+}
+
+void MmsPluginEncoder::encodeMmsPdu(MmsMsg *pMmsMsg, msg_message_id_t msgID, const char *pduFilePath)
+{
+       pMmsMsg->msgID = msgID;
+
+       __EncodeMmsMessage(pMmsMsg, pduFilePath);
+}
index 120ae45..15c4490 100755 (executable)
@@ -1,37 +1,29 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#include<stdio.h>
-#include<stdlib.h>
+#include <stdio.h>
+#include <stdlib.h>
 
-#include "MsgDebug.h"
-#include "MsgUtilFile.h"
-#include "MsgMmsTypes.h"
-#include "MsgSoundPlayer.h"
-#include "MsgStorageHandler.h"
-#include "MmsPluginTransport.h"
+#include "MmsPluginTypes.h"
+#include "MmsPluginDebug.h"
 #include "MmsPluginEventHandler.h"
-#include "MmsPluginCodec.h"
 #include "MmsPluginInternal.h"
-#include "MmsPluginSmil.h"
-#include "MsgMmsMessage.h"
-
 
 /*==================================================================================================
-                                     IMPLEMENTATION OF SmsPluginEventHandler - Member Functions
+                                     IMPLEMENTATION OF MmsPluginEventHandler - Member Functions
 ==================================================================================================*/
 MmsPluginEventHandler *MmsPluginEventHandler::pInstance = NULL;
 
@@ -76,12 +68,17 @@ void MmsPluginEventHandler::handleMmsReceivedData(mmsTranQEntity *pRequest, char
                listener.pfMmsConfIncomingCb(&msgInfo, &pRequest->reqID);
 
                //MsgDeleteFile(pRetrievedFilePath + strlen(MSG_DATA_PATH)); // not ipc
-               remove(pRetrievedFilePath); // not ipc
+               if (remove(pRetrievedFilePath) != 0)
+                       MSG_DEBUG("remove fail");
                break;
 
        // received data is retrieve-conf
        case eMMS_RETRIEVE_AUTO_CONF:
        case eMMS_RETRIEVE_MANUAL_CONF:
+               MSG_ADDRESS_INFO_S addrInfo;
+               memset(&addrInfo, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+               msgInfo.addressList = &addrInfo;
+
                MmsPluginInternal::instance()->processRetrieveConf(&msgInfo, pRequest, pRetrievedFilePath);
 
                // callback to MSG FW
@@ -92,6 +89,10 @@ void MmsPluginEventHandler::handleMmsReceivedData(mmsTranQEntity *pRequest, char
                MmsPluginInternal::instance()->processForwardConf(&msgInfo, pRequest);
                break;
 
+       case eMMS_READREPORT_CONF:
+               if (remove(pRetrievedFilePath) != 0)
+                       MSG_DEBUG("remove fail");
+               break;
        default:
                break;
        }
@@ -104,11 +105,16 @@ void MmsPluginEventHandler::handleMmsError(mmsTranQEntity *pRequest)
 
        msg_error_t err = MSG_SUCCESS;
 
-       MSG_MESSAGE_INFO_S msgInfo = {};
-       MMS_RECV_DATA_S recvData = {{0}, };
+       MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
 
        MSG_DEBUG("pRequest->msgId [%d]", pRequest->msgId);
 
+       time_t curTime;
+       curTime = time(NULL);
+
+       msgInfo.displayTime = curTime;
+
        switch (pRequest->eMmsPduType) {
        case eMMS_SEND_REQ:
        case eMMS_SEND_CONF:
@@ -160,6 +166,8 @@ void MmsPluginEventHandler::handleMmsError(mmsTranQEntity *pRequest)
                break;
        }
 
+       MSG_DEBUG("Error value of MsgMmsConfIncomingListner [%d]", err);
+
        MSG_END();
 }
 
index e38f675..3028e1c 100755 (executable)
@@ -1,43 +1,58 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
+#include <stdlib.h>
+#include <time.h>
+#include <curl/curl.h>
+#include "MmsPluginDebug.h"
 #include "MmsPluginHttp.h"
 #include "MmsPluginUserAgent.h"
-#include "stdlib.h"
-#include <time.h>
 #include "MmsPluginConnManWrapper.h"
-#include <curl/curl.h>
-
-static bool __httpGetHeaderField(MMS_HTTP_HEADER_FIELD_T httpHeaderItem, char *szHeaderBuffer);
-static void __httpGetHost(char *szHost, int nBufferLen);
-static void __httpAllocHeaderInfo(curl_slist **responseHeaders, char *szUrl, int ulContentLen);
-
-static MMS_NET_ERROR_T __httpReceiveData(void *ptr, size_t size, size_t nmemb, void *userdata);
-static size_t  __httpGetTransactionCB(void *ptr, size_t size, size_t nmemb, void *userdata);
-static size_t  __httpPostTransactionCB(void *ptr, size_t size, size_t nmemb, void *userdata);
-
-static int __httpCmdInitSession(MMS_PLUGIN_HTTP_DATA_S *httpConfig);
-static int __httpCmdPostTransaction(MMS_PLUGIN_HTTP_DATA_S *httpConfig);
-static int __httpCmdGetTransaction(MMS_PLUGIN_HTTP_DATA_S *httpConfig);
+#include "MsgGconfWrapper.h"
+#include "MmsPluginUtil.h"
 
 static void __http_print_profile(CURL *curl);
+static int __http_debug_cb (CURL *input_curl, curl_infotype input_info_type, char *input_data , size_t input_size, void *input_void);
+
+static void __httpAllocHeaderInfo(curl_slist **responseHeaders, char *szUrl, int ulContentLen);
+static bool __httpGetHeaderField(MMS_HTTP_HEADER_FIELD_T httpHeaderItem, char *szHeaderBuffer);
+static void __httpGetHost(char *szUrl, char *szHost, int nBufferLen);
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
+//static int __http_progress_cb(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
+//{
+//     MSG_INFO("download(%.0f/%.0f) : upload(%.0f/%.0f)", dlnow, dltotal, ulnow, ultotal);
+//     return 0;
+//}
+
+static int __http_debug_cb (CURL *input_curl, curl_infotype input_info_type, char *input_data , size_t input_size, void *input_void)
+{
+       MSG_INFO("curl_infotype [%d] : %s", input_info_type, input_data);
+       return 0;
+}
+
+static size_t __http_write_response_cb(void *ptr, size_t size, size_t nmemb, void *data)
+{
+       MSG_BEGIN();
+       FILE *writehere = (FILE *)data;
+       return fwrite(ptr, size, nmemb, writehere);
+}
+
 static void __http_print_profile(CURL *curl)
 {
        double speed_upload, speed_download, total_time;
@@ -55,54 +70,55 @@ static void __http_print_profile(CURL *curl)
 
        //time
        curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
-       MSG_DEBUG("profile http Time: total %.3f seconds", total_time);
+       MSG_SEC_INFO("profile http Time: total %.3f seconds", total_time);
 
        //url
        curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
-       MSG_DEBUG("profile http Url: %s", url);
+       MSG_SEC_INFO("profile http Url: %s", url);
 
        //size
        curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &size_up);
-       MSG_DEBUG("profile http Size: upload %.3f bytes", size_up);
+       MSG_SEC_INFO("profile http Size: upload %.3f bytes", size_up);
 
        curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &size_down);
-       MSG_DEBUG("profile http Size: download %.3f bytes", size_down);
+       MSG_SEC_INFO("profile http Size: download %.3f bytes", size_down);
 
        curl_easy_getinfo(curl, CURLINFO_HEADER_SIZE, &size);
-       MSG_DEBUG("profile http Size: header %ld bytes", size);
+       MSG_SEC_INFO("profile http Size: header %ld bytes", size);
 
        curl_easy_getinfo(curl, CURLINFO_REQUEST_SIZE, &size);
-       MSG_DEBUG("profile http Size: request %ld bytes", size);
+       MSG_SEC_INFO("profile http Size: request %ld bytes", size);
 
        //speed
        curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD, &speed_upload);
-       MSG_DEBUG("profile http Speed: upload %.3f bytes/sec", speed_upload);
+       MSG_SEC_INFO("profile http Speed: upload %.3f bytes/sec", speed_upload);
 
        curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD, &speed_download);
-       MSG_DEBUG("profile http Speed: download %.3f bytes/sec", speed_download);
+       MSG_SEC_INFO("profile http Speed: download %.3f bytes/sec", speed_download);
 
        //content
        curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &content_type);
-       MSG_DEBUG("profile http Content: type %s", content_type);
+       MSG_SEC_INFO("profile http Content: type %s", content_type);
 
        curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &content_length);
-       MSG_DEBUG("profile http Content: length download %.3f", content_length);
+       MSG_SEC_INFO("profile http Content: length download %.3f", content_length);
 
        curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_UPLOAD, &content_length);
-       MSG_DEBUG("profile http Content: length upload %.3f", content_length);
+       MSG_SEC_INFO("profile http Content: length upload %.3f", content_length);
 
        //ip & port
        curl_easy_getinfo(curl, CURLINFO_PRIMARY_IP, &ip);
-       MSG_DEBUG("profile http primary: ip %s", ip);
+       MSG_SEC_INFO("profile http primary: ip %s", ip);
 
        curl_easy_getinfo(curl, CURLINFO_PRIMARY_PORT, &port);
-       MSG_DEBUG("profile http primary: port %ld", port);
+       MSG_SEC_INFO("profile http primary: port %ld", port);
 
        curl_easy_getinfo(curl, CURLINFO_LOCAL_IP, &ip);
-       MSG_DEBUG("profile http local: ip %s", ip);
+       MSG_SEC_INFO("profile http local: ip %s", ip);
 
        curl_easy_getinfo(curl, CURLINFO_LOCAL_PORT, &port);
-       MSG_DEBUG("profile http local: port %ld", port);
+       MSG_SEC_INFO("profile http local: port %ld", port);
+
        MSG_DEBUG("**************************************************************************************************");
 }
 
@@ -111,32 +127,31 @@ static void __httpAllocHeaderInfo(curl_slist **responseHeaders, char *szUrl, int
        char szBuffer[1025] = {0, };
        char pcheader[HTTP_REQUEST_LEN] = {0, };
 
-
        bool nResult = __httpGetHeaderField(MMS_HH_CONTENT_TYPE, szBuffer);
        if (nResult) {
-               strcat(pcheader,"Content-Type: ");
-               strcat(pcheader, szBuffer);
-               MSG_DEBUG("%s", pcheader);
+               snprintf(pcheader, HTTP_REQUEST_LEN, "Content-Type: %s", szBuffer);
+               MSG_INFO("%s", pcheader);
                *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
        }
 
-       memset(szBuffer, 0, 1025);
-       memset(pcheader, 0, HTTP_REQUEST_LEN);
-       snprintf(szBuffer, 1024, "%d", ulContentLen);
-       if (nResult) {
-               strcat(pcheader, "Content-Length: ");
-               strcat(pcheader, szBuffer);
-               MSG_DEBUG("%s", pcheader);
-               *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
+       if (ulContentLen > 0) {
+               memset(szBuffer, 0, 1025);
+               memset(pcheader, 0, HTTP_REQUEST_LEN);
+               snprintf(szBuffer, 1024, "%d", ulContentLen);
+               if (nResult) {
+                       snprintf(pcheader, HTTP_REQUEST_LEN, "Content-Length: %s", szBuffer);
+                       MSG_INFO("%s", pcheader);
+                       *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
+               }
        }
 
        memset(szBuffer, 0, 1025);
        memset(pcheader, 0, HTTP_REQUEST_LEN);
-       nResult = __httpGetHeaderField(MMS_HH_HOST, szBuffer);
-       if (nResult) {
-               strcat(pcheader, "HOST: ");
-               strcat(pcheader, szBuffer);
-               MSG_DEBUG("%s", pcheader);
+
+       __httpGetHost(szUrl, szBuffer, 1024);
+       if (strlen(szBuffer)){
+               snprintf(pcheader, HTTP_REQUEST_LEN, "Host: %s", szBuffer);
+               MSG_INFO("%s", pcheader);
                *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
        }
 
@@ -144,9 +159,8 @@ static void __httpAllocHeaderInfo(curl_slist **responseHeaders, char *szUrl, int
        memset(pcheader, 0, HTTP_REQUEST_LEN);
        nResult = __httpGetHeaderField(MMS_HH_ACCEPT, szBuffer);
        if (nResult) {
-               strcat(pcheader, "Accept: ");
-               strcat(pcheader, szBuffer);
-               MSG_DEBUG("%s", pcheader);
+               snprintf(pcheader, HTTP_REQUEST_LEN, "Accept: %s", szBuffer);
+               MSG_INFO("%s", pcheader);
                *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
        }
 
@@ -154,9 +168,8 @@ static void __httpAllocHeaderInfo(curl_slist **responseHeaders, char *szUrl, int
        memset(pcheader, 0, HTTP_REQUEST_LEN);
        nResult = __httpGetHeaderField(MMS_HH_ACCEPT_CHARSET, szBuffer);
        if (nResult) {
-               strcat(pcheader, "Accept-Charset: ");
-               strcat(pcheader, szBuffer);
-               MSG_DEBUG("%s", pcheader);
+               snprintf(pcheader, HTTP_REQUEST_LEN, "Accept-Charset: %s", szBuffer);
+               MSG_INFO("%s", pcheader);
                *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
        }
 
@@ -164,41 +177,48 @@ static void __httpAllocHeaderInfo(curl_slist **responseHeaders, char *szUrl, int
        memset(pcheader, 0, HTTP_REQUEST_LEN);
        nResult = __httpGetHeaderField(MMS_HH_ACCEPT_LANGUAGE, szBuffer);
        if (nResult) {
-               strcat(pcheader, "Accept-Language: ");
-               strcat(pcheader, szBuffer);
-               MSG_DEBUG("%s", pcheader);
+               snprintf(pcheader, HTTP_REQUEST_LEN, "Accept-Language: %s", szBuffer);
+               MSG_INFO("%s", pcheader);
                *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
        }
-
+/* NOW not support gzip, deflate encoding in MMS Plugin
        memset(szBuffer, 0, 1025);
        memset(pcheader, 0, HTTP_REQUEST_LEN);
        nResult = __httpGetHeaderField(MMS_HH_ACCEPT_ENCODING, szBuffer);
        if (nResult) {
-               strcat(pcheader, "Accept-Encoding: ");
-               strcat(pcheader, szBuffer);
+               snprintf(pcheader, HTTP_REQUEST_LEN, "Accept-Encoding: %s", szBuffer);
                MSG_DEBUG("%s", pcheader);
                *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
        }
-
+*/
        memset(szBuffer, 0, 1025);
        memset(pcheader, 0, HTTP_REQUEST_LEN);
        nResult = __httpGetHeaderField(MMS_HH_USER_AGENT, szBuffer);
        if (nResult) {
-               strcat(pcheader, "User-Agent: ");
-               strcat(pcheader, szBuffer);
-               MSG_DEBUG("%s", pcheader);
+               snprintf(pcheader, HTTP_REQUEST_LEN, "User-Agent: %s", szBuffer);
+               MSG_INFO("%s", pcheader);
                *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
        }
 
        memset(szBuffer, 0, 1025);
        memset(pcheader, 0, HTTP_REQUEST_LEN);
-       nResult = __httpGetHeaderField(MMS_HH_WAP_PROFILE, szBuffer);
+       nResult = __httpGetHeaderField(MMS_HH_UA_PROFILE, szBuffer);
        if (nResult) {
-               strcat(pcheader, "X-wap-profile: ");
-               strcat(pcheader, szBuffer);
-               MSG_DEBUG("%s", pcheader);
+               snprintf(pcheader, HTTP_REQUEST_LEN, "X-wap-profile: %s", szBuffer);
+               MSG_INFO("%s", pcheader);
                *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
        }
+
+#if defined(FEATURE_SMS_CDMA)
+       memset(szBuffer, 0, 1025);
+       memset(pcheader, 0, HTTP_REQUEST_LEN);
+       nResult = __httpGetHeaderField(MMS_HH_MDN, szBuffer);
+
+       // TODO : if it needs to check http header mdn value, add code to below.
+#endif
+
+       if (ulContentLen > 0)//if post transaction then Disable 'Expect: 100-contine' option
+               *responseHeaders = curl_slist_append(*responseHeaders, "Expect:");
 }
 
 static bool __httpGetHeaderField(MMS_HTTP_HEADER_FIELD_T httpHeaderItem, char *szHeaderBuffer)
@@ -213,14 +233,6 @@ static bool __httpGetHeaderField(MMS_HTTP_HEADER_FIELD_T httpHeaderItem, char *s
                        result = true;
                        break;
 
-               case MMS_HH_HOST:
-                       __httpGetHost(szHeaderBuffer, 1024);
-                       if (strlen(szHeaderBuffer) > 0)
-                               result = true;
-                       else
-                               result = false;
-                       break;
-
                case MMS_HH_ACCEPT:
                        snprintf((char *)szHeaderBuffer, 1024, "%s", MSG_MMS_HH_ACCEPT);
                        result = true;
@@ -243,30 +255,62 @@ static bool __httpGetHeaderField(MMS_HTTP_HEADER_FIELD_T httpHeaderItem, char *s
 
                case MMS_HH_USER_AGENT:
                        {
-                               char szUserAgent[1024 + 1] = {0,};
-
-                               memset(szUserAgent, 0x00, (sizeof(char) * (1024 + 1) ));
-                               snprintf(szUserAgent, 1024, "%s", MSG_MMS_HH_USER_AGENT);
+                               char szUserAgent[1024 + 1];
+                               char *uagent = NULL;
+
+                               uagent = MsgSettingGetString(VCONFKEY_BROWSER_USER_AGENT);
+                               if (uagent && strlen(uagent) > 0) {
+                                       MSG_SEC_INFO("Get UserAgent : %s = %s", VCONFKEY_BROWSER_USER_AGENT, uagent);
+                                       memset(szUserAgent, 0x00, sizeof(szUserAgent));
+                                       MmsRemoveMarkup(uagent, szUserAgent, sizeof(szUserAgent));
+                               } else {
+                                       memset(szUserAgent, 0x00, sizeof(szUserAgent));
+                                       MSG_SEC_INFO("Get Default UserAgent : %s", MSG_MMS_HH_USER_AGENT);
+                                       snprintf(szUserAgent, 1024, "%s", MSG_MMS_HH_USER_AGENT);
+                               }
 
                                snprintf((char *)szHeaderBuffer, 1024, "%s", szUserAgent);
+                               if (uagent) {
+                                       free(uagent);
+                                       uagent = NULL;
+                               }
                                result = true;
                        }
                        break;
 
-               case MMS_HH_WAP_PROFILE:
+               case MMS_HH_UA_PROFILE:
                        {
-                               char szUAProfile[1024 + 1] = {0,};
-
-                               memset(szUAProfile, 0x00, (sizeof(char)*(1024+1) ));
-                               snprintf(szUAProfile, 1024, "%s", MSG_MMS_WAP_PROFILE);
+                               char *szUAProfile = MsgSettingGetString(MSG_MMS_UA_PROFILE);
 
                                snprintf((char *)szHeaderBuffer, 1024, "%s", szUAProfile);
+                               if (szUAProfile) {
+                                       free(szUAProfile);
+                                       szUAProfile = NULL;
+                               }
                                result = true;
                        }
                        break;
 
+#if defined(FEATURE_SMS_CDMA)
+               case MMS_HH_MDN:
+//                     {
+//                             char *mdn = MsgSettingGetString(MSG_SIM_MSISDN);
+//
+//                             if (mdn != NULL && strlen(mdn) > 0) {
+//                                     result = true;
+//                                     snprintf((char *)szHeaderBuffer, 1024, "%s", mdn);
+//                             } else {
+//                                     result = false;
+//                             }
+//                             if (mdn) {
+//                                     free(mdn);
+//                                     mdn = NULL;
+//                             }
+//                     }
+                       break;
+#endif
                default:
-                       MSG_DEBUG("invalid param");
+                       MSG_WARN("invalid param [%d]", httpHeaderItem);
                        break;
                }
        }
@@ -274,17 +318,17 @@ static bool __httpGetHeaderField(MMS_HTTP_HEADER_FIELD_T httpHeaderItem, char *s
        return result;
 }
 
-static void __httpGetHost(char *szHost, int nBufferLen)
+static void __httpGetHost(char *szUrl, char *szHost, int nBufferLen)
 {
-       MmsPluginHttpAgent *pHttpAgent = MmsPluginHttpAgent::instance();
-       MMS_PLUGIN_HTTP_DATA_S *httpConfigData = pHttpAgent->getHttpConfigData();
+       if (szUrl == NULL || szHost == NULL)
+               return;
 
        const char *prefixString = "http://";
-       const char *delim = ":/\\=@";
+       const char *delim = "/\\=@";
 
        int prefixLength = strlen(prefixString);
 
-       char *startPtr = &httpConfigData->mmscConfig.mmscUrl[0];
+       char *startPtr = szUrl;
        char *movePtr = NULL;
 
        MSG_DEBUG("startPtr(%s)", startPtr);
@@ -319,215 +363,123 @@ static void __httpGetHost(char *szHost, int nBufferLen)
        }
 }
 
-
-static MMS_NET_ERROR_T __httpReceiveData(void *ptr, size_t size, size_t nmemb, void *userdata)
+static int __http_multi_perform(void *session)
 {
-       MMS_NET_ERROR_T httpRet = eMMS_UNKNOWN;
-
-       MmsPluginHttpAgent *pHttpAgent = MmsPluginHttpAgent::instance();
-       MMS_PLUGIN_HTTP_CONTEXT_S *pMmsPlgCd = pHttpAgent->getMmsPldCd();
-       long length_received = size * nmemb;
-
-       if (length_received) {
-               //Save the received buffer in a safe place.
-               if (pMmsPlgCd->final_content_buf == NULL) {
-                       MSG_DEBUG("Body Lenghth Read = %d", length_received);
-                       pMmsPlgCd->final_content_buf = (unsigned char *)malloc((length_received + 1) * sizeof(unsigned char));
-                       memset(pMmsPlgCd->final_content_buf,0x0,((length_received + 1) * sizeof(unsigned char)));
-                       MSG_DEBUG(" Global g_final_content_buf=%0x", pMmsPlgCd->final_content_buf);
-               } else {
-                       //realloc pHttpEvent->bodyLen extra and memset
-                       pMmsPlgCd->final_content_buf = (unsigned char *)realloc(pMmsPlgCd->final_content_buf,
-                                       (pMmsPlgCd->bufOffset + length_received + 1) * sizeof(unsigned char));
-                       MSG_DEBUG("Body Lenghth Read = %d Content Length = %d", length_received, pMmsPlgCd->bufOffset);
-                       memset((pMmsPlgCd->final_content_buf +pMmsPlgCd->bufOffset), 0x0,
-                                       ((length_received + 1) * sizeof(unsigned char)));
-                       MSG_DEBUG(" Global g_final_content_buf=%0x", pMmsPlgCd->final_content_buf);
-               }
-
-               //copy body
-               if (pMmsPlgCd->final_content_buf != NULL) {
-                       memcpy( pMmsPlgCd->final_content_buf + pMmsPlgCd->bufOffset, ptr, length_received);
-                       MSG_DEBUG("Current g_bufOffset =%d", pMmsPlgCd->bufOffset);
-                       /*  Content  Received */
-                       MSG_DEBUG("Total Content received PTR =%0X, Content Size =%d", pMmsPlgCd->final_content_buf,
-                                               pMmsPlgCd->bufOffset);
-                       pMmsPlgCd->bufOffset = pMmsPlgCd->bufOffset + length_received;
-                       httpRet = eMMS_UNKNOWN;
-               }
-       } else {
-               MSG_DEBUG("End of Data transfer");
-               MSG_DEBUG("MmsHttpReadData Buffer Size = %d", pMmsPlgCd->bufOffset);
-               MSG_DEBUG("MmsHttpReadData Buffer = %s", pMmsPlgCd->final_content_buf);
-
-               if (pMmsPlgCd->bufOffset == 0) {
-                       /*  This is applicable when - M-ReadRec.inf,M-Ack.ind, M-NotifyResp.ind posted  */
-                       MSG_DEBUG(" Content Size is Zero");
-
-                       if (pMmsPlgCd->final_content_buf != NULL) {
-                               free(pMmsPlgCd->final_content_buf );
-                               pMmsPlgCd->final_content_buf = NULL;
-                       }
-
-                       httpRet = eMMS_HTTP_EVENT_SENT_ACK_COMPLETED;
-               } else if (pMmsPlgCd->final_content_buf != NULL && pMmsPlgCd->bufOffset != 0) {
-                       // Process Http Data
-                       MSG_DEBUG(" Send Received Data to UA");
-                       httpRet = eMMS_HTTP_RECV_DATA; // eMMS_HTTP_RECV_DATA;
-               } else {
-                       httpRet = eMMS_UNKNOWN; // check later
-               }
-
-               return httpRet;
-       }
-
-       return httpRet;
-}
-
-
-static size_t  __httpPostTransactionCB(void *ptr, size_t size, size_t nmemb, void *userdata)
-{
-       MSG_DEBUG(" ======  HTTP_EVENT_SENT ========");
-       long length_received = size * nmemb;
-       __httpReceiveData(ptr, size, nmemb, userdata);
-
-       return length_received;
-}
-
-static size_t  __httpGetTransactionCB(void *ptr, size_t size, size_t nmemb, void *userdata)
-{
-       MSG_DEBUG(" ======  HTTP_EVENT_RECEIVED ========");
-       long length_received = size * nmemb;
-       __httpReceiveData(ptr, size, nmemb, userdata);
-
-       return length_received;
-}
-
-static int __httpCmdInitSession(MMS_PLUGIN_HTTP_DATA_S *httpConfig)
-{
-       MSG_DEBUG("HttpCmd Init Session");
-
-       char proxyAddr[MAX_IPV4_LENGTH + 1] = {0};
-
-       snprintf(proxyAddr, MAX_IPV4_LENGTH + 1, "%s:%d", httpConfig->mmscConfig.httpProxyIpAddr, httpConfig->mmscConfig.proxyPortNo);
-       MSG_DEBUG("profileId [%d], proxyAddr [%s]", httpConfig->currentProfileId, proxyAddr);
-
-       CURL *curl_session = curl_easy_init();
-       if (NULL == curl_session) {
-               MSG_DEBUG("curl_easy_init() failed");
-               return eMMS_HTTP_SESSION_OPEN_FAILED;
-       }
-
-       int curl_status = curl_easy_setopt(curl_session, CURLOPT_PROXY, proxyAddr);
-       if (curl_status != CURLM_OK) {
-               MSG_DEBUG("curl_easy_setopt(): CURLOPT_PROXY failed");
-               curl_easy_cleanup(curl_session);
-               return eMMS_HTTP_SESSION_OPEN_FAILED;
-       }
-
-       httpConfig->session = curl_session;
-
-       return eMMS_HTTP_SESSION_INIT;
-}
-
-
-static int __httpCmdPostTransaction(MMS_PLUGIN_HTTP_DATA_S *httpConfig)
-{
-       int trId;
-
-       MSG_DEBUG("HttpCmd Post Transaction");
-       MSG_DEBUG(" === HTTP Agent Thread : Signal ==> eMMS_HTTP_SIGNAL_POST_TRANSACTION");
+       MSG_BEGIN();
 
-       char deviceName[1024] = {0,};
+       CURLM *multi_handle;
+       CURLMcode rcm;
 
-       MmsPluginCmAgent::instance()->getDeviceName(deviceName);
+       int still_running;
+       int ret = 0;
+       bool connection_open_flag = false;
 
-       MSG_DEBUG("deviceName: [%s]", deviceName);
-       int curl_status = curl_easy_setopt(httpConfig->session, CURLOPT_INTERFACE, deviceName);
+       CURLMsg *msg;
+       int msgs_left;
 
-       if (curl_status != CURLM_OK) {
-               MSG_DEBUG("curl_easy_setopt(): CURLOPT_INTERFACE failed");
+       multi_handle = curl_multi_init();
 
-               return eMMS_EXCEPTIONAL_ERROR;
+       if (curl_multi_add_handle(multi_handle, session) != 0) {
+               MSG_ERR("curl_multi_add_handle is failed");
+               curl_multi_cleanup(multi_handle);
+               return -1;
        }
 
-       CURLcode rc = curl_easy_perform(httpConfig->session);
-
-       __http_print_profile(httpConfig->session);
+       /* we start some action by calling perform right away */
+       rcm = curl_multi_perform(multi_handle, &still_running);
+       MSG_INFO("curl_multi_perform first end : rcm = %d, still_running = %d", rcm, still_running);
 
-       MmsPluginHttpAgent*     httpAgent = MmsPluginHttpAgent::instance();
-       MMS_PLUGIN_HTTP_DATA_S *httpConfigData = httpAgent->getHttpConfigData();
-       if (httpConfigData->sessionHeader) {
-               curl_slist_free_all((curl_slist *)httpConfigData->sessionHeader);
-               httpConfigData->sessionHeader = NULL;
-       }
-
-       if (CURLE_OK != rc) {
-               MSG_DEBUG("curl_easy_perform return error rc[%d]", rc);
+       do {
+               struct timeval timeout;
+               int rc; /* select() return code */
 
-               return eMMS_HTTP_ERROR_NETWORK;
-       }
+               fd_set fdread;
+               fd_set fdwrite;
+               fd_set fdexcep;
+               int maxfd = -1;
 
-       MSG_DEBUG("## End Transaction ##");
-       MSG_DEBUG("############ trID = %d ###########", trId);
+//             long curl_timeo = -1;
 
-       srandom((unsigned int) time(NULL));
-       trId = random() % 1000000000 + 1;
+               FD_ZERO(&fdread);
+               FD_ZERO(&fdwrite);
+               FD_ZERO(&fdexcep);
 
-       httpConfig->transactionId = trId;
+               /* set a suitable timeout to play around with */
+               timeout.tv_sec = 120;
+               timeout.tv_usec = 0;
 
-       return eMMS_HTTP_SENT_SUCCESS;
-}
+//             curl_multi_timeout(multi_handle, &curl_timeo);
+//             if(curl_timeo >= 0) {
+//                     MSG_DEBUG("curl_timeo = %ld", curl_timeo);
+//                     timeout.tv_sec = curl_timeo / 1000;
+//                     if(timeout.tv_sec > 1)
+//                             timeout.tv_sec = 1;
+//                     else
+//                             timeout.tv_usec = (curl_timeo % 1000) * 1000;
+//             }
 
-static int __httpCmdGetTransaction(MMS_PLUGIN_HTTP_DATA_S *httpConfig)
-{
-       int trId;
+               curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
 
-       MSG_DEBUG("HttpCmd Get Transaction");
-       MSG_DEBUG(" === HTTP Agent Thread : Signal ==> eMMS_HTTP_SIGNAL_GET_TRANSACTION");
+               /* In a real-world program you OF COURSE check the return code of the
+               function calls.  On success, the value of maxfd is guaranteed to be
+               greater or equal than -1.  We call select(maxfd + 1, ...), specially in
+               case of (maxfd == -1), we call select(0, ...), which is basically equal
+               to sleep. */
 
-       char deviceName[1024] = {0,};
-       MmsPluginCmAgent::instance()->getDeviceName(deviceName);
-       MSG_DEBUG("deviceName: [%s]", deviceName);
+               rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
 
-       int curl_status = curl_easy_setopt(httpConfig->session, CURLOPT_INTERFACE, deviceName);
-       if (curl_status != CURLM_OK) {
-               MSG_DEBUG("curl_easy_setopt(): CURLOPT_INTERFACE failed");
+               if (rc == -1){/* select error */
+                       MSG_ERR("select error");
+                       ret = -1;
+                       break;
+               } else if (rc == 0){    /* timeout */
+                       MSG_ERR("time out");
+                       ret = -1;
+                       break;
+               } else {/* action */
+                       MSG_DEBUG("rc = %d", rc);
+                       rcm = curl_multi_perform(multi_handle, &still_running);
+               }
 
-               return eMMS_EXCEPTIONAL_ERROR;
-       }
+               connection_open_flag = MmsPluginCmAgent::instance()->getCmStatus();
+               if (connection_open_flag == false) {
+                       MSG_DEBUG("Connection Closed");
+                       ret = -1;
+               }
 
-       CURLcode rc = curl_easy_perform(httpConfig->session);
+               MSG_INFO("curl_multi_perform end : rcm = %d, still_running = %d, cm_open = %d", rcm, still_running, connection_open_flag);
 
-       __http_print_profile(httpConfig->session);
+       } while(still_running && (connection_open_flag == true));
 
-       MmsPluginHttpAgent*     httpAgent = MmsPluginHttpAgent::instance();
-       MMS_PLUGIN_HTTP_DATA_S *httpConfigData = httpAgent->getHttpConfigData();
-       if (httpConfigData->sessionHeader) {
-               curl_slist_free_all((curl_slist *)httpConfigData->sessionHeader);
-               httpConfigData->sessionHeader = NULL;
-       }
+       while ((msg = curl_multi_info_read(multi_handle, &msgs_left))) {
+               if (msg->msg == CURLMSG_DONE) {
 
-       if (CURLE_OK != rc) {
-               MSG_DEBUG("curl_easy_perform return error = %d", rc);
+                       if (msg->easy_handle == session) {
+                               MSG_INFO("HTTP transfer completed with status %d", msg->data.result);
+                               if (msg->data.result != 0) {
+                                       ret = msg->data.result;
+                               }
 
-               return eMMS_HTTP_ERROR_NETWORK;
+                               curl_multi_remove_handle(multi_handle, session);
+                       } else {
+                               MSG_WARN("Unknown handle HTTP transfer completed with status %d", msg->data.result);
+                       }
+               }
        }
 
-       MSG_DEBUG("## End Transaction ##");
-       MSG_DEBUG("############ trID = %d ###########", trId);
-       srandom((unsigned int) time(NULL));
-       trId = random() % 1000000000 + 1;
-       httpConfig->transactionId = trId;
+       curl_multi_cleanup(multi_handle);
 
-       return eMMS_HTTP_SENT_SUCCESS;
+       MSG_END();
+       return ret;
 }
 
 MmsPluginHttpAgent *MmsPluginHttpAgent::pInstance = NULL;
 MmsPluginHttpAgent *MmsPluginHttpAgent::instance()
 {
        if (!pInstance)
+       {
                pInstance = new MmsPluginHttpAgent();
+       }
 
        return pInstance;
 }
@@ -535,139 +487,264 @@ MmsPluginHttpAgent *MmsPluginHttpAgent::instance()
 
 MmsPluginHttpAgent::MmsPluginHttpAgent()
 {
-       MSG_DEBUG("MmsPluginHttpAgent()");
-
-       bzero(&httpConfigData, sizeof(httpConfigData));
-       bzero(&mmsPlgCd, sizeof(mmsPlgCd));
+       MSG_BEGIN();
 
-       httpCmdHandler.clear();
+       abort = false;
+       respfile = NULL;
+       session_header = NULL;
+       session_option = NULL;
 
-       httpCmdHandler[eHTTP_CMD_INIT_SESSION] = &__httpCmdInitSession;
-       httpCmdHandler[eHTTP_CMD_POST_TRANSACTION] = &__httpCmdPostTransaction;
-       httpCmdHandler[eHTTP_CMD_GET_TRANSACTION] = &__httpCmdGetTransaction;
+       transaction_type = MMS_HTTP_TRANSACTION_TYPE_UNKNOWN;
+       MSG_END();
 }
 
 MmsPluginHttpAgent::~MmsPluginHttpAgent()
 {
+       MSG_BEGIN();
 
+       if (session_header) {
+               MSG_DEBUG("session header is exist : free session header");
+               curl_slist_free_all((curl_slist *)session_header);
+               session_header = NULL;
+       }
+
+       if (session_option) {
+               MSG_DEBUG("session is exist : cleanup session");
+               curl_easy_cleanup(session_option);
+               session_option = NULL;
+       }
+
+       MSG_END();
 }
 
-void MmsPluginHttpAgent::SetMMSProfile()
+void MmsPluginHttpAgent::initSession()
 {
        MSG_BEGIN();
 
-       MMSC_CONFIG_DATA_S *mmscConfig = &(httpConfigData.mmscConfig);
+       this->transaction_type = MMS_HTTP_TRANSACTION_TYPE_UNKNOWN;
+
+       if (session_header) {
+               MSG_DEBUG("session header is exist : free session header");
+               curl_slist_free_all((curl_slist *)session_header);
+               session_header = NULL;
+       }
+
+       if (session_option) {
+               MSG_DEBUG("session is exist : cleanup session");
+               curl_easy_cleanup(session_option);
+               session_option = NULL;
+       }
 
-       MmsPluginCmAgent::instance()->getHomeURL(mmscConfig->mmscUrl);
-       if (strlen(mmscConfig->mmscUrl) < 1) {
-               strcpy(mmscConfig->mmscUrl, DEFAULT_MMSC_URL);
+       if (respfile) {
+               fclose(respfile);
+               respfile = NULL;
        }
 
-       MmsPluginCmAgent::instance()->getProxyAddr(mmscConfig->httpProxyIpAddr);
-       mmscConfig->proxyPortNo = MmsPluginCmAgent::instance()->getProxyPort();
+       initAbortFlag();
 
        MSG_END();
 }
 
-int MmsPluginHttpAgent::cmdRequest(MMS_HTTP_CMD_TYPE_T cmdType)
+void MmsPluginHttpAgent::clearSession()
 {
-       MSG_DEBUG("cmdRequest:%x", cmdType);
+       MSG_BEGIN();
 
-       int ret = 0;
+       this->transaction_type = MMS_HTTP_TRANSACTION_TYPE_UNKNOWN;
 
-       ret = httpCmdHandler[cmdType](&httpConfigData);
+       if (session_header) {
+               MSG_DEBUG("session header is exist : free session header");
+               curl_slist_free_all((curl_slist *)session_header);
+               session_header = NULL;
+       }
 
-       return ret;
-}
+       if (session_option) {
+               MSG_DEBUG("session is exist : cleanup session");
+               curl_easy_cleanup(session_option);
+               session_option = NULL;
+       }
 
-MMS_PLUGIN_HTTP_CONTEXT_S* MmsPluginHttpAgent::getMmsPldCd()
-{
-       return &mmsPlgCd;
-}
+       if (respfile) {
+               fclose(respfile);
+               respfile = NULL;
+       }
 
-MMS_PLUGIN_HTTP_DATA_S *MmsPluginHttpAgent::getHttpConfigData()
-{
-       return &httpConfigData;
+       initAbortFlag();
+       MSG_END();
 }
 
-int MmsPluginHttpAgent::setSession(mmsTranQEntity *qEntity)
+MMS_HTTP_ERROR_E MmsPluginHttpAgent::setSession(http_request_info_s &request_info)
 {
-       MSG_DEBUG("%s %d", qEntity->pPostData, qEntity->postDataLen);
+       MSG_BEGIN();
+       MMS_HTTP_ERROR_E http_error = MMS_HTTP_ERROR_NONE;
+       int content_len = 0;
+       char *url = NULL;
 
-       if (qEntity->eHttpCmdType == eHTTP_CMD_POST_TRANSACTION) {
-               MSG_DEBUG("HttpCmd Post Transaction");
-               MSG_DEBUG(" === HTTP Agent Thread : Signal ==> eMMS_HTTP_SIGNAL_POST_TRANSACTION");
+       // Verify request info
+       if (request_info.transaction_type != MMS_HTTP_TRANSACTION_TYPE_GET
+                       && request_info.transaction_type != MMS_HTTP_TRANSACTION_TYPE_POST)
+       {
+               MSG_ERR("transaction_type of request_info is Invaild [%d]", request_info.transaction_type);
+               http_error = MMS_HTTP_ERROR_TRANSACTION_TYPE;
+               goto __CATCH;
+       }
 
-               curl_slist *responseHeaders = NULL;
+       if (request_info.transaction_type == MMS_HTTP_TRANSACTION_TYPE_POST) {
 
-               __httpAllocHeaderInfo(&responseHeaders, NULL, qEntity->postDataLen);
+               if (request_info.post_data == NULL || request_info.post_data_len == 0) {
+                       MSG_ERR("post data info is Invaild");
+                       http_error = MMS_HTTP_ERROR_SESSION;
+                       goto __CATCH;
+               }
+       }
 
-               //Disable 'Expect: 100-contine' option
-               responseHeaders = curl_slist_append(responseHeaders, "Expect:");
+       if (request_info.url == NULL || request_info.proxy == NULL || request_info.interface == NULL) {
+               MSG_ERR("request_info parameter invalid url [%s], proxy [%s] interface [%s]", request_info.url, request_info.proxy, request_info.interface);
+               http_error = MMS_HTTP_ERROR_SESSION;
+               goto __CATCH;
+       }
 
-               MSG_DEBUG(" === MMSCURI = %s === ", httpConfigData.mmscConfig.mmscUrl);
+       //Set type
+       this->transaction_type = request_info.transaction_type;
+       MSG_DEBUG("set transaction type [%d]", this->transaction_type);
 
-               httpConfigData.sessionHeader = (void *)responseHeaders;
+       //Set http Headers
+       if (this->transaction_type == MMS_HTTP_TRANSACTION_TYPE_POST) {
+               content_len = request_info.post_data_len;
+       } else { //MMS_HTTP_TRANSACTION_TYPE_GET
+               content_len = 0;
+       }
 
-               MSG_DEBUG("## Start Transaction : Post ##");
-               curl_easy_setopt(httpConfigData.session, CURLOPT_VERBOSE, true);
-               curl_easy_setopt(httpConfigData.session, CURLOPT_POST, true);
-               curl_easy_setopt(httpConfigData.session, CURLOPT_URL, httpConfigData.mmscConfig.mmscUrl);
-               curl_easy_setopt(httpConfigData.session, CURLOPT_NOPROGRESS, true);
-               curl_easy_setopt(httpConfigData.session, CURLOPT_HTTPHEADER, responseHeaders);
-               curl_easy_setopt(httpConfigData.session, CURLOPT_POSTFIELDS, qEntity->pPostData);
-               curl_easy_setopt(httpConfigData.session, CURLOPT_POSTFIELDSIZE, qEntity->postDataLen);
-               curl_easy_setopt(httpConfigData.session, CURLOPT_WRITEFUNCTION, __httpPostTransactionCB);
+       url = g_strdup(request_info.url);
 
-               curl_easy_setopt(httpConfigData.session, CURLOPT_TCP_NODELAY, 1);
-       } else if (qEntity->eHttpCmdType == eHTTP_CMD_GET_TRANSACTION) {
-               MSG_DEBUG("MmsHttpInitTransactionGet  %d pGetData (%s)", qEntity->getDataLen, qEntity->pGetData);
-               MSG_DEBUG("MmsHttpInitTransactionGet  mmscURL (%s) ", httpConfigData.mmscConfig.mmscUrl);
+       if (url) {
+               __httpAllocHeaderInfo((curl_slist**)&session_header, url, content_len);
+               if (session_header == NULL) {
+                       MSG_ERR("Failed to httpAllocHeaderInfo");
+                       http_error = MMS_HTTP_ERROR_SESSION;
+                       goto __CATCH;
+               }
 
-               char szUrl[MAX_MMSC_URL_LEN] = {0, };
+               free(url);
+               url = NULL;
+       } else {
+               MSG_ERR("Failed to strdup");
+               goto __CATCH;
+       }
 
-               memcpy(szUrl, qEntity->pGetData, qEntity->getDataLen);
 
-               MSG_DEBUG("MmsHttpInitTransactionGet  szURL (%s)", szUrl);
+       //Set curl option
+       session_option = curl_easy_init();
+       if (session_option == NULL) {
+               MSG_ERR("curl_easy_init() failed");
+               http_error = MMS_HTTP_ERROR_SESSION;
+               goto __CATCH;
+       }
 
-               curl_slist *responseHeaders = NULL;
+       curl_easy_setopt(session_option, CURLOPT_PROXY, request_info.proxy);
+       curl_easy_setopt(session_option, CURLOPT_VERBOSE, true);
+       curl_easy_setopt(session_option, CURLOPT_URL, request_info.url);
+       curl_easy_setopt(session_option, CURLOPT_NOPROGRESS, true);
+       curl_easy_setopt(session_option, CURLOPT_HTTPHEADER, session_header);
+       curl_easy_setopt(session_option, CURLOPT_DEBUGFUNCTION , __http_debug_cb);
+       curl_easy_setopt(session_option, CURLOPT_INTERFACE, request_info.interface);
+       //curl_easy_setopt(httpConfigData.session, CURLOPT_PROGRESSFUNCTION, __http_progress_cb); //for debug
+
+       if (respfile) {
+               curl_easy_setopt(session_option, CURLOPT_WRITEFUNCTION, __http_write_response_cb);
+               curl_easy_setopt(session_option, CURLOPT_WRITEDATA, respfile);
+       }
 
-               __httpAllocHeaderInfo(&responseHeaders, NULL, 0);
+       if (transaction_type == MMS_HTTP_TRANSACTION_TYPE_POST) {
+               curl_easy_setopt(session_option, CURLOPT_POST, true);
+               curl_easy_setopt(session_option, CURLOPT_POSTFIELDS, request_info.post_data);
+               curl_easy_setopt(session_option, CURLOPT_POSTFIELDSIZE, request_info.post_data_len);
+       //      curl_easy_setopt(session_option, CURLOPT_TCP_NODELAY, 1);
+       }
 
-               httpConfigData.sessionHeader = (void *)responseHeaders;
+       MSG_END();
+       return http_error;
 
-               MSG_DEBUG("## Start Transaction : Get ##");
-               curl_easy_setopt(httpConfigData.session, CURLOPT_VERBOSE, true);
-               curl_easy_setopt(httpConfigData.session, CURLOPT_URL, szUrl);
-               curl_easy_setopt(httpConfigData.session, CURLOPT_NOPROGRESS, true);
-               curl_easy_setopt(httpConfigData.session, CURLOPT_HTTPHEADER, responseHeaders);
-               curl_easy_setopt(httpConfigData.session, CURLOPT_WRITEFUNCTION, __httpGetTransactionCB);
-       } else {
-               MSG_DEBUG("Unknown eHttpCmdType [%d]", qEntity->eHttpCmdType);
-               return -1;
+__CATCH:
+       //CID 338211: freeing url (with check) in case of error
+       if (url) {
+               free(url);
+               url = NULL;
        }
+       clearSession();
 
-       return 0;
+       MSG_END();
+       return http_error;
 }
 
+MMS_HTTP_ERROR_E MmsPluginHttpAgent::startTransaction()
+{
+       MSG_BEGIN();
+       MMS_HTTP_ERROR_E http_error = MMS_HTTP_ERROR_NONE;
 
-void MmsPluginHttpAgent::clearSession()
+       int rc = __http_multi_perform(session_option);
+
+       __http_print_profile(session_option);
+
+       if (rc != 0) {
+               MSG_ERR("curl_easy_perform return error rc [%d]", rc);
+               http_error = MMS_HTTP_ERROR_TRANSACTION;
+       }
+
+       MSG_END();
+       return http_error;
+}
+
+MMS_HTTP_ERROR_E MmsPluginHttpAgent::httpRequest(http_request_info_s &request_info)
 {
        MSG_BEGIN();
 
-       if (httpConfigData.sessionHeader) {
-               curl_slist_free_all((curl_slist *)httpConfigData.sessionHeader);
-               httpConfigData.sessionHeader = NULL;
+       const char *conf_filename = MSG_DATA_PATH"mms.conf";
+       MMS_HTTP_ERROR_E http_error = MMS_HTTP_ERROR_NONE;
+
+       this->initSession();
+
+       respfile = fopen(conf_filename, "wb");
+
+       //set session
+       http_error = this->setSession(request_info);
+       if (http_error != MMS_HTTP_ERROR_NONE) {
+               MSG_ERR("Fail to setSession");
+               goto __CATCH;
        }
 
-       if (httpConfigData.session == NULL) {
-               MSG_DEBUG("[Error]httpConfigData.session is NULL");
-               return;
+       //transaction
+       http_error = this->startTransaction();
+
+       if (http_error != MMS_HTTP_ERROR_NONE) {
+               MSG_ERR("Fail to startTransaction");
+               goto __CATCH;
+       }
+
+       //close conf file & load response data
+       if (respfile) {
+
+               fclose(respfile);
+               respfile = NULL;
+
+               if (g_file_get_contents(conf_filename, &request_info.response_data, &request_info.response_data_len, NULL) == false) {
+                       MSG_WARN("Fail to g_file_get_contents");
+               }
        }
 
-       curl_easy_cleanup(httpConfigData.session);
+       this->clearSession();
+
+       MSG_END();
+       return http_error;
+
+__CATCH:
+
+       if (respfile) {
+               fclose(respfile);
+               respfile = NULL;
+       }
 
-       httpConfigData.session = NULL;
+       this->clearSession();
 
        MSG_END();
+       return http_error;
 }
index 7e3d831..cc4c0c3 100755 (executable)
@@ -1,43 +1,40 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdlib.h>
 #include <errno.h>
 #include <sys/stat.h>
 
-#include "MsgDebug.h"
+#include "MsgCppTypes.h"
 #include "MsgUtilFile.h"
 #include "MsgException.h"
+#include "MsgSettingTypes.h"
 #include "MsgMmsMessage.h"
-#include "MsgTransportTypes.h"
 #include "MsgGconfWrapper.h"
-#include "MsgSoundPlayer.h"
 #include "MsgStorageHandler.h"
+#include "MsgSerialize.h"
+#include "MsgSpamFilter.h"
+
+#include "MmsPluginDebug.h"
 #include "MmsPluginTypes.h"
 #include "MmsPluginCodec.h"
-#include "MmsPluginSetup.h"
 #include "MmsPluginInternal.h"
 #include "MmsPluginStorage.h"
-#include "MmsPluginHttp.h"
-#include "MmsPluginCodec.h"
-
-#include "MsgNotificationWrapper.h"
-#include "MmsPluginSmil.h"
-
-MmsSetup gMmsSetup;
+#include "MmsPluginAppBase.h"
+#include "MmsPluginMIME.h"
 
 /*==================================================================================================
                                      IMPLEMENTATION OF MmsPluginInternal - Member Functions
@@ -65,7 +62,7 @@ MmsPluginInternal *MmsPluginInternal::instance()
 
 void MmsPluginInternal::processReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST_INFO_S *pRequest, bool *bReject)
 {
-       MSG_DEBUG("processReceivedInd \r\n");
+       MSG_BEGIN();
 
        FILE *pFile = NULL;
        char fileName[MSG_FILENAME_LEN_MAX] = {0,};
@@ -76,22 +73,22 @@ void MmsPluginInternal::processReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQ
                if(MsgCreateFileName(fileName) == false)
                        THROW(MsgException::FILE_ERROR, "MsgCreateFileName error");
 
-               MSG_DEBUG(" File name = %s", fileName);
+               MSG_SEC_DEBUG("File name = %s", fileName);
 
                if(MsgWriteIpcFile(fileName, pMsgInfo->msgText, pMsgInfo->dataSize) == false)
                        THROW(MsgException::FILE_ERROR, "MsgWriteIpcFile error");
 
-               snprintf(fullPath, MAX_FULL_PATH_SIZE+1, MSG_IPC_DATA_PATH"%s", fileName);
+               snprintf(fullPath, MAX_FULL_PATH_SIZE+1, "%s%s", MSG_IPC_DATA_PATH, fileName);
 
                memset(pMsgInfo->msgData, 0x00, sizeof(pMsgInfo->msgData));
                memcpy(pMsgInfo->msgData, fullPath, strlen(fullPath));
                pMsgInfo->bTextSms = false;
        }
 
-       MSG_DEBUG("MMS File Path = %s", pMsgInfo->msgData);
+       MSG_SEC_DEBUG("MMS File Path = %s", pMsgInfo->msgData);
 
-       _MmsInitHeader();
-       _MmsRegisterDecodeBuffer(gszMmsLoadBuf1,  gszMmsLoadBuf2, MSG_MMS_DECODE_BUFFER_MAX);
+       MmsInitHeader();
+       MmsRegisterDecodeBuffer();
 
        if ((pFile = MsgOpenFile(pMsgInfo->msgData, "rb+")) == NULL) {
                MSG_DEBUG("File Open Error: %s", pMsgInfo->msgData);
@@ -100,11 +97,15 @@ void MmsPluginInternal::processReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQ
                if (!MmsBinaryDecodeMsgHeader(pFile, pMsgInfo->dataSize))
                        MSG_DEBUG("Decoding Header Failed \r\n");
 
-               MsgDeleteFile(pMsgInfo->msgData + strlen(MSG_IPC_DATA_PATH));
+               MsgCloseFile(pFile);
+
+               if (remove(pMsgInfo->msgData) != 0)
+                       MSG_DEBUG("Fail remove");
+
 
                switch (mmsHeader.type) {
                case MMS_MSGTYPE_NOTIFICATION_IND:
-                       MSG_DEBUG("MmsProcessNewMsgInd: process noti.ind\n");
+                       MSG_DEBUG("process noti.ind\n");
                        // For Set Value pMsgInfo
                        if (processNotiInd(pMsgInfo, pRequest) == false)
                                *bReject = true;
@@ -113,33 +114,32 @@ void MmsPluginInternal::processReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQ
                        break;
 
                case MMS_MSGTYPE_DELIVERY_IND:
-                       MSG_DEBUG("MmsProcessNewMsgInd: process delivery.ind\n");
+                       MSG_DEBUG("process delivery.ind\n");
                        // For Set Value pMsgInfo
                        processDeliveryInd(pMsgInfo);
                        break;
 
                case MMS_MSGTYPE_READORG_IND:
-                       MSG_DEBUG("MmsProcessNewMsgInd: process readorig.ind\n");
+                       MSG_DEBUG("process readorig.ind\n");
                        processReadOrgInd(pMsgInfo);
                        break;
                default:
                        break;
                }
-
-               MsgCloseFile(pFile);
        }
-       //Check Msg Type & Process(Save ...)
+
+       MSG_END();
 }
 
 bool MmsPluginInternal::processNotiInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST_INFO_S *pRequest)
 {
        MSG_DEBUG("MmsProcessNotiInd");
-       msg_error_t     err = MSG_SUCCESS;
 
        MSG_MMS_HOME_RETRIEVE_TYPE_T retrieveType;
        bool bReportAllowed;
 
        MmsAttrib attrib;
+       MsgDbHandler *dbHandle = getDbHandle();
 
        MmsInitMsgAttrib(&attrib);
 
@@ -155,32 +155,135 @@ bool MmsPluginInternal::processNotiInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST
 
        attrib.expiryTime = mmsHeader.expiryTime;
 
-       MmsPluginStorage *pStorage = MmsPluginStorage::instance();
-       err = pStorage->updateMmsAttrib(pMsgInfo->msgId, &attrib, pMsgInfo->msgType.subType);
-
        if (mmsHeader.pFrom) {
                MmsAddrUtilRemovePlmnString(mmsHeader.pFrom->szAddr);
                // From
                strncpy(pMsgInfo->addressList[0].addressVal, mmsHeader.pFrom->szAddr, MAX_ADDRESS_VAL_LEN);
+               if (MmsAddrUtilCheckEmailAddress(pMsgInfo->addressList[0].addressVal)) {
+                       pMsgInfo->addressList[0].addressType = MSG_ADDRESS_TYPE_EMAIL;
+               }
+       }
+
+       MMS_DATA_S *mms_data = MsgMmsCreate();
+       if (mms_data == NULL) return false;
+       {
+               mms_data->header = MsgMmsCreateHeader();
+
+               if (mms_data->header == NULL) {
+                       MsgMmsRelease(&mms_data);
+                       return false;
+               }
+
+               MMS_HEADER_DATA_S *pHeader = mms_data->header;
+
+               pHeader->messageType = mmsHeader.type;
+
+               snprintf(pHeader->trID, sizeof(pHeader->trID), "%s", mmsHeader.szTrID);
+
+               pHeader->mmsVersion = mmsHeader.version;
+
+               //From
+               if (mmsHeader.pFrom) {
+                       MmsAddrUtilRemovePlmnString(mmsHeader.pFrom->szAddr);
+                       snprintf(pHeader->szFrom, sizeof(pHeader->szFrom), "%s", mmsHeader.pFrom->szAddr);
+               }
+
+               //Subject
+               snprintf(pHeader->szSubject, sizeof(pHeader->szSubject), "%s", mmsHeader.szSubject);
+               //Delivery Report
+               pHeader->bDeliveryReport = (mmsHeader.deliveryReport != MMS_REPORT_YES);
+               //Message Class
+               pHeader->messageClass = mmsHeader.msgClass;
+
+               //Priority
+               pHeader->mmsPriority = mmsHeader.priority;
+
+               //Message Size : pMmsMsg->mmsAttrib.msgSize = mmsHeader.msgSize;
+               //Expiry
+               pHeader->expiry.type = mmsHeader.expiryTime.type;
+               pHeader->expiry.time = mmsHeader.expiryTime.time;
+
+               time_t curTime = time(NULL);
+
+               if (pHeader->expiry.type == MMS_TIMETYPE_RELATIVE) {
+                       pHeader->expiry.type = MMS_TIMETYPE_ABSOLUTE;
+                       pHeader->expiry.time += curTime;
+               }
+
+               //Charge
+               //contentclass
+               //int contentClass;//text | image-basic| image-rich | video-basic | video-rich | megapixel | content-basic | content-rich
+               strncpy(pHeader->contentLocation, mmsHeader.szContentLocation, MMS_LOCATION_LEN);
+
+               pHeader->messageSize = mmsHeader.msgSize;
+
+               MSG_DEBUG("Message size = [%d]", pHeader->messageSize);
+
+               char *pSerializedMms = NULL;
+               int serializeDataSize = 0;
+
+               char pTempFileName[MSG_FILENAME_LEN_MAX+1] = {0};
+               char pTempFilePath[MSG_FILEPATH_LEN_MAX+1] = {0};
+
+               serializeDataSize = MsgSerializeMms(mms_data, &pSerializedMms);
+
+               if (pSerializedMms) {
+                       if (MsgCreateFileName(pTempFileName) == true) {
+                               pMsgInfo->bTextSms = false;
+
+                               snprintf(pTempFilePath, sizeof(pTempFilePath), MSG_IPC_DATA_PATH"%s", pTempFileName);
+
+                               MsgOpenCreateAndOverwriteFile(pTempFilePath, pSerializedMms, serializeDataSize);
+
+                               //set file name
+                               snprintf(pMsgInfo->msgData, sizeof(pMsgInfo->msgData), "%s", pTempFileName);
+                       }
+
+                       free(pSerializedMms);
+               }
+       }
+       MsgMmsRelease(&mms_data);
+
+       // Check contents-location is in noti.ind
+       if (mmsHeader.szContentLocation[0] == '\0') {
+               THROW(MsgException::INCOMING_MSG_ERROR, "######## Contents-location is empty in MMS-Noti-Ind  #######");
+               return false;
        }
 
        int roamState = 0;
+       char pPduFilePath[MAX_FULL_PATH_SIZE] = {0};
 
        roamState = MsgSettingGetInt(VCONFKEY_TELEPHONY_SVC_ROAM);
        MsgSettingGetBool(MMS_SEND_REPORT_ALLOWED, &bReportAllowed);
 
-       if (checkRejectNotiInd(roamState, bReportAllowed, pMsgInfo->msgData)) {
+       if (checkRejectNotiInd(roamState, bReportAllowed, pPduFilePath)) {
                MSG_DEBUG("MMS Message Rejected......");
 
-               pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
-               pMsgInfo->bTextSms = true;
+               pMsgInfo->dataSize = strlen(pPduFilePath);
                memcpy(&pRequest->msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
-
+               snprintf(pRequest->msgInfo.msgData, sizeof(pRequest->msgInfo.msgData), "%s", pPduFilePath);
                pRequest->msgInfo.msgType.subType = MSG_NOTIFYRESPIND_MMS;
 
                return false;
        }
 
+       if (MsgCheckFilter(dbHandle, pMsgInfo)){
+               encodeNotifyRespInd(mmsHeader.szTrID, MSG_DELIVERY_REPORT_DEFERRED, bReportAllowed, pPduFilePath);
+
+               pMsgInfo->dataSize = strlen(pPduFilePath);
+
+               pRequest->msgInfo.bTextSms = false;
+
+               memcpy(&pRequest->msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+
+               snprintf(pRequest->msgInfo.msgData, sizeof(pRequest->msgInfo.msgData), "%s", pPduFilePath);
+               MSG_DEBUG("pRequest->msgInfo.msgData = %s", pRequest->msgInfo.msgData);
+               pRequest->msgInfo.msgType.subType = MSG_NOTIFYRESPIND_MMS;
+               pRequest->msgInfo.folderId = MSG_SPAMBOX_ID;
+
+               return true;
+       }
+
        if (roamState == VCONFKEY_TELEPHONY_SVC_ROAM_OFF) {
                retrieveType = (MSG_MMS_HOME_RETRIEVE_TYPE_T)MsgSettingGetInt(MMS_RECV_HOME_NETWORK);
                MSG_DEBUG("$$$$$$$$$$ MMS_RECV_HOME_NETWORK = %d $$$$$$$$$$$$$", retrieveType);
@@ -191,14 +294,16 @@ bool MmsPluginInternal::processNotiInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST
                if (retrieveType == MSG_ABROAD_RESTRICTED) {
                        MSG_DEBUG("MMS Receiving Setting Restricted was selected.");
                        // m-notify-resp-ind encoding process
-                       memset(pMsgInfo->msgData, 0, MAX_MSG_DATA_LEN + 1);
+                       encodeNotifyRespInd(mmsHeader.szTrID, MSG_DELIVERY_REPORT_DEFERRED, bReportAllowed, pPduFilePath);
+
+                       pMsgInfo->dataSize = strlen(pPduFilePath);
 
-                       encodeNotifyRespInd(mmsHeader.szTrID, MSG_DELIVERY_REPORT_DEFERRED, bReportAllowed, pMsgInfo->msgData);
+                       pRequest->msgInfo.bTextSms = false;
 
-                       pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
-                       pMsgInfo->bTextSms = true;
                        memcpy(&pRequest->msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
 
+                       snprintf(pRequest->msgInfo.msgData, sizeof(pRequest->msgInfo.msgData), "%s", pPduFilePath);
+
                        pRequest->msgInfo.msgType.subType = MSG_NOTIFYRESPIND_MMS;
 
                        return true;
@@ -207,157 +312,103 @@ bool MmsPluginInternal::processNotiInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST
 
        // should send http 'GET'
        if (retrieveType == MSG_HOME_AUTO_DOWNLOAD || retrieveType == MSG_ABROAD_AUTO_DOWNLOAD) {
-               MSG_DEBUG("=========== START AUTO RETRIEVE MODE ============");
-               memset(pMsgInfo->msgData, 0, MAX_MSG_DATA_LEN + 1);
+               //Check if current request sim index is different from default network SIM
+               //Convert auto-retrieve to manual retrieve in case sim indexes are different
+               int default_sim = 0;
+               default_sim = MsgSettingGetInt(MSG_NETWORK_SIM);
 
-               memcpy(pMsgInfo->msgData, mmsHeader.szContentLocation, strlen(mmsHeader.szContentLocation)) ;
+               MSG_DEBUG("default_sim = %d, pMsgInfo->sim_idx = %d", default_sim, pMsgInfo->sim_idx);
 
-               pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
+               if (default_sim == (int)pMsgInfo->sim_idx) {
+                       MSG_DEBUG("=========== START AUTO RETRIEVE MODE ============");
 
-               pMsgInfo->bTextSms = true;
+                       pMsgInfo->dataSize = strlen(mmsHeader.szContentLocation);
 
-               memcpy(&pRequest->msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+                       pRequest->msgInfo.bTextSms = true;
+
+                       memcpy(&pRequest->msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+
+                       snprintf(pRequest->msgInfo.msgData, sizeof(pRequest->msgInfo.msgData), "%s", mmsHeader.szContentLocation);
+
+                       pRequest->msgInfo.msgType.subType = MSG_GET_MMS;
+
+                       MSG_SEC_DEBUG("MSG SUBTYPE = %d msg data %s bTextsms %d", pRequest->msgInfo.msgType.subType, pRequest->msgInfo.msgData, pRequest->msgInfo.bTextSms);
+               } else {
+                       encodeNotifyRespInd(mmsHeader.szTrID, MSG_DELIVERY_REPORT_DEFERRED, bReportAllowed, pPduFilePath);
+
+                       pMsgInfo->dataSize = strlen(pPduFilePath);
 
-               pRequest->msgInfo.msgType.subType = MSG_GET_MMS;
+                       pRequest->msgInfo.bTextSms = false;
 
-               MSG_DEBUG("MSG SUBTYPE = %d msg data %s bTextsms %d", pRequest->msgInfo.msgType.subType, pRequest->msgInfo.msgData, pRequest->msgInfo.bTextSms);
+                       memcpy(&pRequest->msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+
+                       snprintf(pRequest->msgInfo.msgData, sizeof(pRequest->msgInfo.msgData), "%s", pPduFilePath);
+                       MSG_SEC_DEBUG("pRequest->msgInfo.msgData = %s", pRequest->msgInfo.msgData);
+                       pRequest->msgInfo.msgType.subType = MSG_NOTIFYRESPIND_MMS;
+               }
        } else {
-       // should send m-notify-resp-ind
+               // should send m-notify-resp-ind
                MSG_DEBUG("=========== START MANUAL RETRIEVE MODE ===========");
                // m-notify-resp-ind encoding process
-               memset(pMsgInfo->msgData, 0, MAX_MSG_DATA_LEN + 1);
 
                if (retrieveType == MSG_HOME_MANUAL || retrieveType == MSG_ABROAD_MANUAL) {
-                       encodeNotifyRespInd(mmsHeader.szTrID, MSG_DELIVERY_REPORT_DEFERRED, bReportAllowed, pMsgInfo->msgData);
+                       encodeNotifyRespInd(mmsHeader.szTrID, MSG_DELIVERY_REPORT_DEFERRED, bReportAllowed, pPduFilePath);
                }
 
-               pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
-               pMsgInfo->bTextSms = true;
+               pMsgInfo->dataSize = strlen(pPduFilePath);
+
+               pRequest->msgInfo.bTextSms = false;
+
                memcpy(&pRequest->msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
 
+               snprintf(pRequest->msgInfo.msgData, sizeof(pRequest->msgInfo.msgData), "%s", pPduFilePath);
+               MSG_DEBUG("pRequest->msgInfo.msgData = %s", pRequest->msgInfo.msgData);
                pRequest->msgInfo.msgType.subType = MSG_NOTIFYRESPIND_MMS;
        }
 
        return true;
 }
 
-
 void MmsPluginInternal::processDeliveryInd(MSG_MESSAGE_INFO_S *pMsgInfo)
 {
        MSG_BEGIN();
 
-       MmsMsg *pMsg = NULL;
-       bool bFound = false;
-       MmsMsgMultiStatus *pStatus = NULL;
-       MmsMsgMultiStatus *pLastStatus = NULL;
-
-       pMsg = (MmsMsg *)malloc(sizeof(MmsMsg));
+       MmsMsgMultiStatus status;
+       memset(&status, 0x00, sizeof(MmsMsgMultiStatus));
 
-       if (pMsg == NULL) {
-               MSG_DEBUG("fail to allocation memory.");
-               return;
-       }
+       status.msgStatus = mmsHeader.msgStatus;
+       status.handledTime = mmsHeader.date;
+       status.bDeliveryReportIsRead = false;
+       status.bDeliveyrReportIsLast= true;
 
-       MmsInitMsgAttrib(&pMsg->mmsAttrib);
+       MmsAddrUtilRemovePlmnString(mmsHeader.pTo->szAddr);
+       MSG_DEBUG("[INFO] [ADDR: %s, MMSID: %s]",mmsHeader.pTo->szAddr, mmsHeader.szMsgID);
 
-       pMsgInfo->msgType.mainType      = MSG_MMS_TYPE;
-       pMsgInfo->msgType.subType       = MSG_DELIVERYIND_MMS;
+       pMsgInfo->msgType.mainType      = MSG_MMS_TYPE;
+       pMsgInfo->msgType.subType       = MSG_DELIVERYIND_MMS;
        pMsgInfo->bTextSms = true;
+       pMsgInfo->dataSize = 0;
+       memset(pMsgInfo->msgData, 0x00, MAX_MSG_DATA_LEN + 1);
 
-       MSG_DEBUG("#### mmsHeader.szMsgID = %s : when received delivery ind####", mmsHeader.szMsgID);
-
-       int tmpId = (msg_message_id_t)MmsSearchMsgId(mmsHeader.pTo->szAddr, mmsHeader.szMsgID);
-
+       strncpy(pMsgInfo->msgData, getMmsDeliveryStatus(status.msgStatus), MAX_MSG_DATA_LEN);
+       pMsgInfo->dataSize  = strlen(pMsgInfo->msgData);
+       MSG_DEBUG("Delivery Status = %s", pMsgInfo->msgData);
 
-       MSG_DEBUG("tmpId [%d]", tmpId);
-       MSG_DEBUG("mmsHeader.pTo->szAddr [%s]", mmsHeader.pTo->szAddr);
+       strncpy(pMsgInfo->addressList[0].addressVal, mmsHeader.pTo->szAddr, MAX_ADDRESS_VAL_LEN);
 
+       int tmpId = (msg_message_id_t)MmsPluginStorage::instance()->searchMsgId(mmsHeader.pTo->szAddr, mmsHeader.szMsgID);
        if (tmpId > 0) {
-               pMsgInfo->msgId = (msg_message_id_t)tmpId;
-
-               pMsg->mmsAttrib.pMultiStatus = MmsGetMultiStatus(pMsgInfo->msgId);
-
-               pStatus = pMsg->mmsAttrib.pMultiStatus;
-
-               MSG_DEBUG("### pStatus->szTo = %s ###", pStatus->szTo);
-
-               while (pStatus && !bFound) {
-                       MSG_DEBUG("### MmsAddrUtilCompareAddr ###");
-                       MSG_DEBUG("### mmsHeader.pTo->szAddr = %s ###", mmsHeader.pTo->szAddr);
-                       if (MmsAddrUtilCompareAddr( pStatus->szTo, mmsHeader.pTo->szAddr)) {
-                               bFound = true;
-                               break;
-                       }
-
-                       pStatus = pStatus->pNext;
-               }
-
-               if (bFound == false) {
-                       MSG_DEBUG("### bFound == false ###");
-                       /* Queue the delivery report  --------------------------- */
-
-                       pStatus = (MmsMsgMultiStatus *)malloc(sizeof(MmsMsgMultiStatus));
-                       memset(pStatus, 0, sizeof(MmsMsgMultiStatus));
-
-                       pStatus->readStatus = MMS_READSTATUS_NONE;
-                       memset(pStatus->szTo, 0, MSG_ADDR_LEN + 1);
-                       strncpy(pStatus->szTo, mmsHeader.pTo->szAddr, MSG_ADDR_LEN);
-
-                       if (pMsg->mmsAttrib.pMultiStatus == NULL) {
-                               /* first delivery report */
-                               pMsg->mmsAttrib.pMultiStatus = pStatus;
-                       } else {
-                               pLastStatus = pMsg->mmsAttrib.pMultiStatus;
-
-                               while (pLastStatus->pNext) {
-                                       pLastStatus = pLastStatus->pNext;
-                               }
-
-                               pLastStatus->pNext = pStatus;
-                               pLastStatus = pStatus;
-                       }
-               }
-
-               pStatus->handledTime = mmsHeader.date;
-               pStatus->msgStatus = mmsHeader.msgStatus;
-
-               memset(pMsgInfo->msgData, 0x00, MAX_MSG_DATA_LEN + 1);
-               pMsgInfo->dataSize = 0;
-               strncpy(pMsgInfo->msgData, getMmsDeliveryStatus(pStatus->msgStatus), MAX_MSG_DATA_LEN);
-               pMsgInfo->dataSize  = strlen(pMsgInfo->msgData);
-               pMsgInfo->bTextSms = true;
-               MSG_DEBUG("Delivery Status = %s", pMsgInfo->msgData);
-
-               strncpy(pMsgInfo->addressList[0].addressVal, mmsHeader.pTo->szAddr, MAX_ADDRESS_VAL_LEN);
-
-               pStatus->bDeliveryReportIsRead = false;
+               MSG_DEBUG("Found MSG_ID = %d", tmpId);
 
-               _MmsDataUpdateLastStatus(pMsg);
+               //Insert to Delievery DB
+               MmsPluginStorage::instance()->insertDeliveryReport(tmpId, mmsHeader.pTo->szAddr, &status);
 
-               pStatus->bDeliveyrReportIsLast= true;
-
-               MmsUpdateDeliveryReport(pMsgInfo->msgId, pStatus);
+               pMsgInfo->msgId = (msg_message_id_t)tmpId;
 
-               MmsPluginStorage::instance()->addMmsNoti(pMsgInfo);
        } else {
-               MSG_DEBUG("Can't not find Message!");
-               memset(pMsgInfo->msgData, 0x00, MAX_MSG_DATA_LEN + 1);
-               pMsgInfo->dataSize = 0;
-               strncpy(pMsgInfo->msgData, getMmsDeliveryStatus(mmsHeader.msgStatus), MAX_MSG_DATA_LEN);
-
-               MSG_DEBUG("Delivery Status = %s", pMsgInfo->msgData);
-
-               pMsgInfo->dataSize  = strlen(pMsgInfo->msgData);
-
-               MmsAddrUtilRemovePlmnString(mmsHeader.pTo->szAddr);
-
-               strncpy(pMsgInfo->addressList[0].addressVal, mmsHeader.pTo->szAddr, MAX_ADDRESS_VAL_LEN);
+               MSG_DEBUG("Can not find MMS message in DB");
        }
 
-       MsgFreeAttrib(&pMsg->mmsAttrib);
-
-       free(pMsg);
-
        MSG_END();
 }
 
@@ -365,20 +416,11 @@ void MmsPluginInternal::processReadOrgInd(MSG_MESSAGE_INFO_S *pMsgInfo)
 {
        MSG_BEGIN();
 
-       MmsMsg *pMsg = NULL;
-       bool bFound = false;
-       MmsMsgMultiStatus *pStatus = NULL;
-       MmsMsgMultiStatus *pLastStatus = NULL;
-
-       pMsg = (MmsMsg *)malloc(sizeof(MmsMsg));
-
-       if (pMsg == NULL) {
-               MSG_DEBUG("fail to allocation memory.");
+       if (pMsgInfo == NULL) {
+               MSG_DEBUG("parameter err");
                return;
        }
 
-       MmsInitMsgAttrib(&pMsg->mmsAttrib);
-
        pMsgInfo->msgType.mainType = MSG_MMS_TYPE;
        pMsgInfo->msgType.subType = MSG_READORGIND_MMS;
        pMsgInfo->bTextSms = true;
@@ -386,97 +428,30 @@ void MmsPluginInternal::processReadOrgInd(MSG_MESSAGE_INFO_S *pMsgInfo)
        MmsAddrUtilRemovePlmnString(mmsHeader.pFrom->szAddr);
        MmsAddrUtilRemovePlmnString(mmsHeader.pTo->szAddr);
 
-       if (mmsHeader.readStatus != MSG_READ_REPORT_IS_DELETED || (strcmp(mmsHeader.pFrom->szAddr, mmsHeader.pTo->szAddr))) {
-               MSG_DEBUG("#### mmsHeader.szMsgID = %s : when received read orig ind####", mmsHeader.szMsgID);
-
-               int tmpId = MmsSearchMsgId(mmsHeader.pFrom->szAddr, mmsHeader.szMsgID);
-
-               if (tmpId > 0) {
-                       pMsgInfo->msgId = (msg_message_id_t)tmpId;
-
-                       pMsg->mmsAttrib.pMultiStatus = MmsGetMultiStatus(pMsgInfo->msgId);
-
-                       pStatus = pMsg->mmsAttrib.pMultiStatus;
-
-                       MSG_DEBUG("### pStatus->szTo = %s ###", pStatus->szTo);
-
-                       while (pStatus && !bFound) {
-                               MSG_DEBUG("### MmsAddrUtilCompareAddr ###");
-                               MSG_DEBUG("### mmsHeader.pFrom->szAddr = %s ###", mmsHeader.pFrom->szAddr);
-                               if (MmsAddrUtilCompareAddr(pStatus->szTo, mmsHeader.pFrom->szAddr)) {
-                                       bFound = true;
-                                       break;
-                               }
-
-                               pStatus = pStatus->pNext;
-                       }
-
-                       if (bFound == false) {
-                               MSG_DEBUG("### bFound == false ###");
-                               /* Queue the delivery report  --------------------------- */
-
-                               pStatus = (MmsMsgMultiStatus *)malloc(sizeof(MmsMsgMultiStatus));
-                               memset(pStatus, 0, sizeof(MmsMsgMultiStatus));
-
-                               pStatus->msgStatus = MMS_MSGSTATUS_NONE;
-
-                               memset(pStatus->szTo, 0, MSG_ADDR_LEN + 1);
-                               strncpy(pStatus->szTo, mmsHeader.pFrom->szAddr, MSG_ADDR_LEN);
-
-                               if (pMsg->mmsAttrib.pMultiStatus == NULL) {
-                                       /* first readOrg report */
-                                       pMsg->mmsAttrib.pMultiStatus = pStatus;
-                               } else {
-                                       pLastStatus = pMsg->mmsAttrib.pMultiStatus;
-
-                                       while (pLastStatus->pNext) {
-                                               pLastStatus = pLastStatus->pNext;
-                                       }
-
-                                       pLastStatus->pNext = pStatus;
-                                       pLastStatus = pStatus;
-                               }
-                       }
-
-                       pStatus->readTime = mmsHeader.date;
-                       pStatus->readStatus = mmsHeader.readStatus;
-
-                       memset(pMsgInfo->msgData, 0x00, MAX_MSG_DATA_LEN + 1);
-                       pMsgInfo->dataSize = 0;
-                       strncpy(pMsgInfo->msgData, getMmsReadStatus(pStatus->readStatus), MAX_MSG_DATA_LEN);
-                       pMsgInfo->dataSize  = strlen(pMsgInfo->msgData);
-                       pMsgInfo->bTextSms = true;
-                       MSG_DEBUG("read Status = %s", pMsgInfo->msgData);
-
-                       strncpy(pMsgInfo->addressList[0].addressVal, mmsHeader.pTo->szAddr, MAX_ADDRESS_VAL_LEN);
-
-                       pStatus->bReadReplyIsRead = false;
+       memset(pMsgInfo->msgData, 0x00, MAX_MSG_DATA_LEN + 1);
+       pMsgInfo->dataSize = 0;
 
-                       _MmsDataUpdateLastStatus(pMsg);
+       strncpy(pMsgInfo->msgData, getMmsReadStatus(mmsHeader.readStatus), MAX_MSG_DATA_LEN);
+       pMsgInfo->dataSize  = strlen(pMsgInfo->msgData);
 
-                       pStatus->bReadReplyIsLast= true;
+       MSG_DEBUG("read Status = %s", pMsgInfo->msgData);
+       strncpy(pMsgInfo->addressList[0].addressVal, mmsHeader.pFrom->szAddr, MAX_ADDRESS_VAL_LEN);
 
-                       MmsUpdateReadReport(pMsgInfo->msgId, pStatus);
+       int tmpId = MmsPluginStorage::instance()->searchMsgId(mmsHeader.pFrom->szAddr, mmsHeader.szMsgID);
+       if (tmpId > 0) {
+               pMsgInfo->msgId = (msg_message_id_t)tmpId;
 
-                       MmsPluginStorage::instance()->addMmsNoti(pMsgInfo);
-               } else {
-                       MSG_DEBUG("Can't not find Message!");
-                       memset(pMsgInfo->msgData, 0x00, MAX_MSG_DATA_LEN + 1);
-                       pMsgInfo->dataSize = 0;
-                       strncpy(pMsgInfo->msgData, getMmsReadStatus(mmsHeader.readStatus), MAX_MSG_DATA_LEN);
-                       pMsgInfo->dataSize  = strlen(pMsgInfo->msgData);
-                       MSG_DEBUG("read Status = %s", pMsgInfo->msgData);
+               MmsMsgMultiStatus Status;
+               memset(&Status, 0x00, sizeof(MmsMsgMultiStatus));
+               Status.readTime = mmsHeader.date;
+               Status.readStatus = mmsHeader.readStatus;
 
-                       MmsAddrUtilRemovePlmnString(mmsHeader.pTo->szAddr);
+               MmsPluginStorage::instance()->insertReadReport(pMsgInfo->msgId, mmsHeader.pFrom->szAddr, &Status);
 
-                       strncpy(pMsgInfo->addressList[0].addressVal, mmsHeader.pTo->szAddr, MAX_ADDRESS_VAL_LEN);
-               }
+       } else {
+               MSG_DEBUG("Can't not find Message!");
        }
 
-       MsgFreeAttrib(&pMsg->mmsAttrib);
-
-       free(pMsg);
-
        MSG_END();
 }
 
@@ -484,8 +459,6 @@ void MmsPluginInternal::processSendConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTranQEn
 {
        MSG_BEGIN();
 
-       msg_error_t err = MSG_SUCCESS;
-
        MMS_RECV_DATA_S recvData = {{0}, };
 
        pMsgInfo->msgId = pRequest->msgId;
@@ -500,6 +473,7 @@ void MmsPluginInternal::processSendConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTranQEn
 
        if (mmsHeader.responseStatus == MMS_RESPSTATUS_OK) {
                pMsgInfo->networkStatus = MSG_NETWORK_SEND_SUCCESS;
+               pMsgInfo->dataSize = pRequest->postDataLen;
        } else {
                pMsgInfo->networkStatus = MSG_NETWORK_SEND_FAIL;
 
@@ -512,6 +486,22 @@ void MmsPluginInternal::processSendConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTranQEn
                strncpy(pMsgInfo->msgText, responseText, MMS_LOCALE_RESP_TEXT_LEN);
        }
 
+       MSG_ADDRESS_INFO_S addressinfo = {0,};
+       char *msisdn = NULL;
+       msisdn = MsgSettingGetString(MSG_SIM_MSISDN);
+
+       MmsPluginStorage::instance()->getAddressInfo(pMsgInfo->msgId, &addressinfo);
+
+       MSG_MMS_VLD_INFO("%d, MMS Send End %s->%s %s", pMsgInfo->msgId
+                                                                                                       , (msisdn == NULL)?"ME":msisdn
+                                                                                                       , addressinfo.addressVal
+                                                                                                       , (pMsgInfo->networkStatus == MSG_NETWORK_SEND_SUCCESS)?"Success":"Fail");
+
+       if (msisdn) {
+               free(msisdn);
+               msisdn = NULL;
+       }
+
        // set message-id from mmsc
        strncpy(recvData.szMsgID, mmsHeader.szMsgID, MMS_MSG_ID_LEN);
        strncpy(recvData.szTrID, mmsHeader.szTrID, MMS_TR_ID_LEN);
@@ -526,26 +516,18 @@ void MmsPluginInternal::processSendConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTranQEn
 
        MmsMsg *pMsg = NULL;
        MmsPluginStorage::instance()->getMmsMessage(&pMsg);
-       _MmsInitHeader();
-#ifdef __SUPPORT_DRM__
-       _MsgFreeDRMInfo(&pMsg->msgType.drmInfo);
-#endif
-       _MsgFreeBody(&pMsg->msgBody, pMsg->msgType.type);
-
+       MmsInitHeader();
+       MmsReleaseMsgDRMInfo(&pMsg->msgType.drmInfo);
+       MmsReleaseMsgBody(&pMsg->msgBody, pMsg->msgType.type);
 
        MSG_END();
 }
 
-
+#if 1
 void MmsPluginInternal::processRetrieveConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTranQEntity *pRequest, char *pRetrievedFilePath)
 {
        MSG_BEGIN();
 
-       int partCnt = 0;
-       int attachCount = 0;
-       MsgType partHeader;
-       bool bMultipartRelated = false;
-
        msg_error_t err = MSG_SUCCESS;
        MMS_RECV_DATA_S recvData = {{0}, };
 
@@ -583,15 +565,43 @@ void MmsPluginInternal::processRetrieveConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTra
                pMsgInfo->networkStatus = MSG_NETWORK_RETRIEVE_FAIL;
                pMsgInfo->folderId = MSG_INBOX_ID;
                // If failed MMS Retrieve, then saved as MMS Noti Ind Message.
-               pMsgInfo->msgType.subType = MSG_NOTIFICATIONIND_MMS;
+               // It will changed in MsgHandleMmsConfIncomingMsg
+               //pMsgInfo->msgType.subType = MSG_NOTIFICATIONIND_MMS;
+       }
+
+       char *msisdn = NULL;
+       msisdn = MsgSettingGetString(MSG_SIM_MSISDN);
+
+       if (mmsHeader.pFrom)
+               MmsAddrUtilRemovePlmnString(mmsHeader.pFrom->szAddr);
+
+       MSG_MMS_VLD_INFO("%d, MMS Receive %s End %s->%s %s", pMsgInfo->msgId
+                                                                                                               , (pRequest->eMmsPduType == eMMS_RETRIEVE_AUTO_CONF)?"Auto":"Manual"
+                                                                                                               , (mmsHeader.pFrom)?mmsHeader.pFrom->szAddr:"YOU"
+                                                                                                               , (msisdn == NULL)?"ME":msisdn
+                                                                                                               , (pMsgInfo->networkStatus == MSG_NETWORK_RETRIEVE_SUCCESS)?"Success":"Fail");
+
+       /* PLM P141008-05143 :  Notification.Ind address is 1, but MMS retreived Conf address is correct.
+        So adding correct address to addressList buf to compare address in DB while MsgStoUpdateMMSMessage */
+       if (mmsHeader.pFrom) {
+               pMsgInfo->nAddressCnt = 1;
+               strncpy(pMsgInfo->addressList[0].addressVal, mmsHeader.pFrom->szAddr, MAX_ADDRESS_VAL_LEN);
+       }
+
+       if (msisdn) {
+               free(msisdn);
+               msisdn = NULL;
        }
 
        pMsgInfo->dataSize = pRequest->getDataLen;
 
        // set message-id & MMS TPDU file path
-       strcpy(recvData.szMsgID, mmsHeader.szMsgID);
+       snprintf(recvData.szMsgID, sizeof(recvData.szMsgID), "%s", mmsHeader.szMsgID);
+
        if (pRetrievedFilePath)
-               strncpy(recvData.retrievedFilePath, pRetrievedFilePath, sizeof(recvData.retrievedFilePath));
+               strncpy(recvData.retrievedFilePath, pRetrievedFilePath, sizeof(recvData.retrievedFilePath)-1);
+
+       char *filename = NULL;
 
 #ifdef FEATURE_JAVA_MMS
        if (mmsHeader.msgType.param.szApplicationID || mmsHeader.msgType.param.szReplyToApplicationID) {
@@ -603,19 +613,23 @@ void MmsPluginInternal::processRetrieveConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTra
 
                char fullPath[MAX_FULL_PATH_SIZE+1] = {0, };
 
-               char *filename = NULL;
-               filename = strrchr(pRetrievedFilePath, '/');
+               filename = MsgGetFileName(pRetrievedFilePath);
 
-               snprintf(fullPath, MAX_FULL_PATH_SIZE+1, "%s%s", MSG_IPC_DATA_PATH, filename + 1);
+               snprintf(fullPath, MAX_FULL_PATH_SIZE+1, "%s%s", MSG_IPC_DATA_PATH, filename);
 
-               rename(pRetrievedFilePath, fullPath);
+               if (pRetrievedFilePath) {
+                       int ret  = rename(pRetrievedFilePath, fullPath);
+                       if (ret != 0) {
+                               MSG_DEBUG("File rename Error: %s", g_strerror(errno));
+                       }
 
-               if (chmod(fullPath, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) != 0) {
-                       MSG_DEBUG("File Write Error: %s", strerror(errno));
-               }
+                       if (MsgChmod(fullPath, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == false) {
+                               MSG_DEBUG("File Write Error: %s", g_strerror(errno));
+                       }
 
-               if (chown(fullPath, 0, 6502 ) != 0) {
-                       MSG_DEBUG("File Write Error: %s", strerror(errno));
+                       if (MsgChown(fullPath, 0, 6502 ) == false) {
+                               MSG_DEBUG("File Write Error: %s", g_strerror(errno));
+                       }
                }
        }
 #endif
@@ -628,82 +642,177 @@ void MmsPluginInternal::processRetrieveConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTra
 
        MmsPluginStorage *pStorage = MmsPluginStorage::instance();
 
-       MMS_MESSAGE_DATA_S msgData;
-       memset(&msgData, 0, sizeof(MMS_MESSAGE_DATA_S));
+       err = pStorage->updateMmsAttrib(pMsgInfo->msgId, &attrib, pMsgInfo->msgType.subType);
+
+       MSG_DEBUG("Error value of updateMmsAttrib [%d]", err);
 
-       // Conversation is supported only Multipart Related message, Presentation info should be provided
-       if (mmsHeader.msgType.type == MIME_MULTIPART_RELATED || mmsHeader.msgType.type == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
-               char *pSmilDoc = NULL;
+       {//make MmsData & insert multipart
+       MmsMsg *pMmsMsg = NULL;
+       MmsPluginStorage::instance()->getMmsMessage(&pMmsMsg);
+
+       MMS_DATA_S *pMmsData = MsgMmsCreate();
+       if (pMmsData == NULL) {
+               MSG_SEC_DEBUG("Fail to create mms");
+               goto __CATCH;
+       }
+
+       pMmsData->header = MsgMmsCreateHeader();
+
+       MmsConvertMmsData(pMmsMsg, pMmsData);
+       //CID 41996 : MmsConvertMmsData always returns true
+       /*if (MmsConvertMmsData(pMmsMsg, pMmsData) != true) {
+               MSG_DEBUG("Fail to Compose MMS Message");
+               goto __CATCH;
+       }*/
+
+       bool bFiltered = checkFilterMmsBody(pMmsData);
+       if (bFiltered == true) {
+               pMsgInfo->folderId = MSG_SPAMBOX_ID;
+       }
+
+       MMS_MULTIPART_DATA_S *pSmilMultipart = pMmsData->smil;
+       if (pSmilMultipart) {
+               MmsPluginStorage::instance()->insertMultipart(pMsgInfo->msgId, pSmilMultipart);
+       }
+
+       MMSList *multipart_list = pMmsData->multipartlist;
+
+       for (int i = 0; i < (int)g_list_length(multipart_list); i++) {
+               MMS_MULTIPART_DATA_S *pMultipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(multipart_list, i);
+               MmsPluginStorage::instance()->insertMultipart(pMsgInfo->msgId, pMultipart);
+       }
+
+       {//make Preview info for APP
+               MmsPluginAppBase *appBase;
+               appBase = new MmsPluginAppBase(pMmsData);
+               appBase->makePreviewInfo(pMsgInfo->msgId, false, pRetrievedFilePath);
+               appBase->getFirstPageTextFilePath(pMsgInfo->msgText, sizeof(pMsgInfo->msgText));
+               delete appBase;
+       }
+
+       MsgMmsRelease(&pMmsData);
+
+       if (MsgGetFileSize(pRetrievedFilePath, (int *)&pMsgInfo->dataSize) == false) {
+               MSG_SEC_DEBUG("Fail to get mms file size [%s]", pRetrievedFilePath);
+               goto __CATCH;
+       }
+       }//make MmsData & insert multipart
+
+__CATCH:
+       {
                MmsMsg *pMsg = NULL;
-               char szFileName[MSG_FILENAME_LEN_MAX] = {0, };
+               pStorage->getMmsMessage(&pMsg);
+               MmsInitHeader();
+               MmsReleaseMsgDRMInfo(&pMsg->msgType.drmInfo);
+               MmsReleaseMsgBody(&pMsg->msgBody, pMsg->msgType.type);
+               g_free(filename); filename = NULL;
+       }
+       MSG_END();
+}
+#else //NEW process RetrieveConf
+void MmsPluginInternal::processRetrieveConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTranQEntity *pRequest, char *pRetrievedFilePath)
+{
+       MSG_BEGIN();
 
-               msgData.regionCnt = 0;
-               msgData.pageCnt = 0;
-               msgData.attachCnt = 0;
-               msgData.transitionCnt = 0;
-               msgData.metaCnt = 0;
-               memset(msgData.szSmilFilePath, 0, MSG_FILEPATH_LEN_MAX);
+       msg_error_t err = MSG_SUCCESS;
 
-               pSmilDoc = MmsSmilGetPresentationData(pMsgInfo->msgId);
-               MmsSmilParseSmilDoc(&msgData, pSmilDoc);
+       pMsgInfo->msgId = pRequest->msgId;
 
-               MmsPluginStorage::instance()->getMmsMessage(&pMsg);
-               strcpy(szFileName, pMsg->szFileName);
+       pMsgInfo->msgType.mainType = MSG_MMS_TYPE;
+       if (pRequest->eMmsPduType == eMMS_RETRIEVE_AUTO_CONF)
+               pMsgInfo->msgType.subType = MSG_RETRIEVE_AUTOCONF_MMS;
+       else
+               pMsgInfo->msgType.subType = MSG_RETRIEVE_MANUALCONF_MMS;
 
-               err = pStorage->getMsgText(&msgData, pMsgInfo->msgText);
-               err = pStorage->makeThumbnail(&msgData, pMsgInfo->thumbPath, szFileName);
+       strncpy(pMsgInfo->subject, mmsHeader.szSubject, MSG_LOCALE_SUBJ_LEN);
+       strncpy(pRequest->transactionId, mmsHeader.szTrID, MMS_TR_ID_LEN);
+
+       time_t curTime;
+       curTime = time(NULL);
 
-               bMultipartRelated = true;
+       pMsgInfo->displayTime = curTime;
+
+       if (mmsHeader.retrieveStatus == MMS_RETRSTATUS_OK) {
+               pMsgInfo->networkStatus = MSG_NETWORK_RETRIEVE_SUCCESS;
+               pMsgInfo->folderId = MSG_INBOX_ID;
        } else {
-               MSG_DEBUG("Multipart mixed message doesn't support mms conversation");
+               pMsgInfo->networkStatus = MSG_NETWORK_RETRIEVE_FAIL;
+               pMsgInfo->folderId = MSG_INBOX_ID;
+               // If failed MMS Retrieve, then saved as MMS Noti Ind Message.
+               // It will changed in MsgHandleMmsConfIncomingMsg
+               //pMsgInfo->msgType.subType = MSG_NOTIFICATIONIND_MMS;
        }
 
-       err = pStorage->updateMmsAttrib(pMsgInfo->msgId, &attrib, pMsgInfo->msgType.subType);
+       char *msisdn = NULL;
+       msisdn = MsgSettingGetString(MSG_SIM_MSISDN);
 
-       partCnt = MmsGetMediaPartCount(pMsgInfo->msgId);
-       MSG_DEBUG("MmsUiGetMediaAttachInfo: partCnt=%d\n", partCnt );
+       if (mmsHeader.pFrom)
+               MmsAddrUtilRemovePlmnString(mmsHeader.pFrom->szAddr);
 
-       if (partCnt < 0) {
-               MSG_DEBUG("MmsUiGetMediaAttachInfo: partCnt=%d\n", partCnt );
-       } else {
-               for (int i = 0; i < partCnt; ++i) {
-                       if (!MmsGetMediaPartHeader(i, &partHeader)) {
-                               MSG_DEBUG("MmsUiGetMediaAttachInfo: MmsGetMediaPartHeader failed\n" );
-                               break;
-                       }
+       MSG_MMS_VLD_INFO("%d, MMS Receive %s End %s->%s %s", pMsgInfo->msgId
+                                                                                                               , (pRequest->eMmsPduType == eMMS_RETRIEVE_AUTO_CONF)?"Auto":"Manual"
+                                                                                                               , (mmsHeader.pFrom)?mmsHeader.pFrom->szAddr:"YOU"
+                                                                                                               , (msisdn == NULL)?"ME":msisdn
+                                                                                                               , (pMsgInfo->networkStatus == MSG_NETWORK_RETRIEVE_SUCCESS)?"Success":"Fail");
 
-                       if (partHeader.contentSize > 0) {
-                               char szBuf[MSG_FILEPATH_LEN_MAX];
+       if (msisdn) {
+               free(msisdn);
+               msisdn = NULL;
+       }
 
-                               strcpy((char *)szBuf, partHeader.param.szFileName);
-                               sprintf(partHeader.param.szFileName, MSG_DATA_PATH"%s", szBuf);
-                               if (!bMultipartRelated || MmsCheckAdditionalMedia(&msgData, &partHeader))
-                                       attachCount++;
-                       }
+       pMsgInfo->dataSize = pRequest->getDataLen;
+
+
+       {
+               MmsMsg *pMmsMsg = NULL;
+               MmsPluginStorage::instance()->getMmsMessage(&pMmsMsg);
+
+               MMS_DATA_S *pMmsData = MsgMmsCreate();
+               pMmsData->header = MsgMmsCreateHeader();
+
+               if (MmsConvertMmsData(pMmsMsg, pMmsData) != true) {
+                       MSG_DEBUG("Fail to Compose MMS Message");
+                       goto __CATCH;
                }
-       }
-       MSG_DEBUG("attachCount [%d]", attachCount);
-       err = pStorage->updateMmsAttachCount(pMsgInfo->msgId, attachCount);
 
-       if (bMultipartRelated) {
-               _MsgMmsReleasePageList(&msgData);
-               _MsgMmsReleaseRegionList(&msgData);
-               _MsgMmsReleaseAttachList(&msgData);
-               _MsgMmsReleaseTransitionList(&msgData);
-               _MsgMmsReleaseMetaList(&msgData);
-       }
+               char *pSerializedData = NULL;
 
-       MmsMsg *pMsg = NULL;
-       pStorage->getMmsMessage(&pMsg);
-       _MmsInitHeader();
-#ifdef __SUPPORT_DRM__
-       _MsgFreeDRMInfo(&pMsg->msgType.drmInfo);
-#endif
-       _MsgFreeBody(&pMsg->msgBody, pMsg->msgType.type);
+               MsgSerializeMms(pMmsData, &pSerializedData);
+
+               MsgMmsRelease(&pMmsData);
+
+
+               char fileName[MSG_FILENAME_LEN_MAX] = {0};
+               char fileFilePath[MSG_FILEPATH_LEN_MAX] = {0};
+
+               if (MsgCreateFileName(fileName) == false)
+                       goto __CATCH;
 
+               snprintf(fileFilePath, sizeof(fileFilePath), "%s%s", MSG_DATA_PATH, fileName);
+
+               if (!MsgOpenCreateAndOverwriteFile(fileFilePath, (char *)pSerializedData, (int)strlen(pSerializedData))) {
+                       goto __CATCH;
+               }
+
+               snprintf(pMsgInfo->msgData, sizeof(pMsgInfo->msgData), "%s", fileFilePath);
+
+               if (MsgGetFileSize(pRetrievedFilePath, (int *)&pMsgInfo->dataSize) == false) {
+                       MSG_SEC_DEBUG("Fail to get mms file size [%s]", pRetrievedFilePath);
+                       goto __CATCH;
+               }
+       }
+
+__CATCH:
+       {
+               MmsMsg *pMsg = NULL;
+               MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+               MmsInitHeader();
+               MmsReleaseMsgDRMInfo(&pMsg->msgType.drmInfo);
+               MmsReleaseMsgBody(&pMsg->msgBody, pMsg->msgType.type);
+       }
        MSG_END();
 }
-
+#endif
 void MmsPluginInternal::processForwardConf(MSG_MESSAGE_INFO_S *msgInfo, mmsTranQEntity *pRequest)
 {
 
@@ -727,7 +836,7 @@ bool MmsPluginInternal::encodeNotifyRespInd(char *szTrID, msg_delivery_report_st
        if (MsgCreateFileName(pTempFileName) == false)
                return false;
 
-       snprintf(pTempFilePath, MAX_FULL_PATH_SIZE, MSG_DATA_PATH"%s.noti.ind", pTempFileName);
+       snprintf(pTempFilePath, MAX_FULL_PATH_SIZE, "%s%s.noti.ind", MSG_DATA_PATH, pTempFileName);
 
        pFile = MsgOpenMMSFile(pTempFilePath);
 
@@ -736,8 +845,8 @@ bool MmsPluginInternal::encodeNotifyRespInd(char *szTrID, msg_delivery_report_st
                return false;
        }
 
-       if (_MmsEncodeNotiRespInd(pFile, szTrID, iStatus, bReportAllowed) == false) {
-               MSG_DEBUG("MmsEncodeNotifyRespInd: _MmsEncodeNotiRespInd fail");
+       if (MmsEncodeNotiRespInd(pFile, szTrID, iStatus, bReportAllowed) == false) {
+               MSG_DEBUG("MmsEncodeNotifyRespInd: MmsEncodeNotiRespInd fail");
                MsgCloseFile(pFile);
                return false;
        }
@@ -745,7 +854,8 @@ bool MmsPluginInternal::encodeNotifyRespInd(char *szTrID, msg_delivery_report_st
        MsgCloseFile(pFile);
 
        if (pSendFilePath) {
-               snprintf(pSendFilePath, MAX_MSG_DATA_LEN+1, "%s.mms", pTempFilePath);
+               //CID 41993: replaced size 'MAX_MSG_DATA_LEN+1' with MAX_FULL_PATH_SIZE
+               snprintf(pSendFilePath, MAX_FULL_PATH_SIZE, "%s.mms", pTempFilePath);
        } else {
                MSG_DEBUG("[ERROR] pSendFilePath is NULL");
                return false;
@@ -772,7 +882,7 @@ bool MmsPluginInternal::encodeAckInd(char *szTrID, bool bReportAllowed, char *pS
        if (MsgCreateFileName(pTempFileName) == false)
                return false;
 
-       snprintf(pTempFilePath, MAX_FULL_PATH_SIZE, MSG_DATA_PATH"%s.ack.ind", pTempFileName);
+       snprintf(pTempFilePath, MAX_FULL_PATH_SIZE, "%s%s.ack.ind", MSG_DATA_PATH, pTempFileName);
 
        pFile = MsgOpenMMSFile(pTempFilePath);
        if (!pFile) {
@@ -780,8 +890,8 @@ bool MmsPluginInternal::encodeAckInd(char *szTrID, bool bReportAllowed, char *pS
                return false;
        }
 
-       if (_MmsEncodeAckInd(pFile, szTrID, bReportAllowed) == false) {
-               MSG_DEBUG("MmsEncodeAckInd: _MmsEncodeAckInd fail \n" );
+       if (MmsEncodeAckInd(pFile, szTrID, bReportAllowed) == false) {
+               MSG_DEBUG("MmsEncodeAckInd: MmsEncodeAckInd fail \n" );
                MsgCloseFile(pFile);
                return false;
        }
@@ -846,12 +956,87 @@ bool MmsPluginInternal::checkRejectNotiInd(int roamState, bool bReportAllowed, c
                }
        }
 
+       //Duplicate MMS notification
+       int msgId = 0;
+
+       msgId = MmsPluginStorage::instance()->checkDuplicateNotification(mmsHeader.szTrID, mmsHeader.szContentLocation);
+
+       MSG_DEBUG("Msg Id = %d", msgId);
+       if (msgId > 0)
+               return true;
+
        // Not Rejected
        MSG_END();
        return false;
 
 }
 
+
+bool MmsPluginInternal::checkFilterMmsBody(MMS_DATA_S *pMmsData)
+{
+       if (pMmsData == NULL)
+               return false;
+
+       bool bFiltered = false;
+       MMS_PAGE_S *pPage = NULL;
+       MMS_MEDIA_S *pMedia = NULL;
+       char filePath[MSG_FILEPATH_LEN_MAX + 1];
+       gchar *fileContent = NULL;
+       MsgDbHandler *dbHandle = getDbHandle();
+       MimeType mimeType = MIME_UNKNOWN;
+
+       MMS_MESSAGE_DATA_S *mmsMsg = NULL;
+       unique_ptr<MMS_MESSAGE_DATA_S*, void(*)(MMS_MESSAGE_DATA_S**)> buf(&mmsMsg, unique_ptr_deleter);
+       mmsMsg = (MMS_MESSAGE_DATA_S *)new char[sizeof(MMS_MESSAGE_DATA_S)];
+       memset(mmsMsg, 0x00, sizeof(MMS_MESSAGE_DATA_S));
+
+       MsgMmsConvertMmsDataToMmsMessageData(pMmsData, mmsMsg);
+
+       // Get the text data from the 1st slide.
+       if (mmsMsg->pageCnt <= 0) {
+               MSG_WARN("pageCnt : %d", mmsMsg->pageCnt);
+               MsgMmsReleaseMmsLists(mmsMsg);
+               return false;
+       }
+
+       pPage = _MsgMmsGetPage(mmsMsg, 0);
+
+       if (!pPage) {
+               MSG_WARN("page is NULL");
+               MsgMmsReleaseMmsLists(mmsMsg);
+               return false;
+       }
+
+       for (int j = 0; j < pPage->mediaCnt; ++j) {
+               pMedia = _MsgMmsGetMedia(pPage, j);
+
+               if (pMedia && pMedia->mediatype == MMS_SMIL_MEDIA_TEXT) {
+
+                       MmsGetMimeTypeFromFileName(MIME_MAINTYPE_UNKNOWN, pMedia->szFilePath, &mimeType, NULL);
+
+                       if (mimeType == MIME_TEXT_X_VCALENDAR || mimeType == MIME_TEXT_X_VCARD || mimeType == MIME_TEXT_X_VTODO || mimeType == MIME_TEXT_X_VNOTE) {
+                               MSG_DEBUG("Media Type is Text, but Vobject file [%s]", pMedia->szFilePath);
+                       } else {
+                               strncpy(filePath, pMedia->szFilePath, MSG_FILEPATH_LEN_MAX);
+
+                               g_file_get_contents((const gchar *)filePath, &fileContent, NULL, NULL);
+
+                               bFiltered = MsgCheckFilterByWord(dbHandle, (const char *)fileContent);
+
+                               g_free(fileContent);
+                               fileContent = NULL;
+
+                               if (bFiltered == true)
+                                       break;
+                       }
+               }
+       }
+
+       MsgMmsReleaseMmsLists(mmsMsg);
+
+       return bFiltered;
+}
+
 bool MmsPluginInternal::getMmsReport(MmsReport mmsReport)
 {
        bool result = false;
index 02796d2..af59880 100755 (executable)
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <string>
 #include <stdlib.h>
 #include "MmsPluginMIME.h"
-#include "MsgDebug.h"
+#include "MmsPluginDebug.h"
 
-#include "MmsPluginSmil.h"
-#ifndef        NULL
-#define        NULL    0
-#endif
+typedef enum _MimeAppType {
+       MIME_APPLICATION_NONE,
 
+       MIME_APPLICATION_CAMERA,
+       MIME_APPLICATION_VIDEORECORDER,
 
-/* Header field */
-static const char *szMsgField[MSG_FIELD_NUM] =
-{
-       "Return-Path",
-       "Message-ID",
-       "From" ,
-       "To" ,
-       "Cc" ,
-       "Subject",
-       "Date",
-       "Mime-Version",
-       "Content-Type",
-       "Content-Transfer-Encoding",
-       "Content-Disposition", //If start param is given in multipart/related, this field will be ignored
-       "Content-ID", //for start part of multipart/related body
-       "Content-Location",
-       "Content-Name",
-       "Content-Description",
-       "Content-Vendor",
-       "Rights-Issuer",
-       "Return-Receipt-To",                    /* Delivery confirm */
-       "Disposition-Notification-To",  /* Read confirm */
-       "Content-Rep-Pos",
-       "Content-Rep-Size",
-       "Content-Rep-Index"
-};
+       MIME_APPLICATION_IMAGEVIEWER,
+       MIME_APPLICATION_FLASHVIEWER,
+       MIME_APPLICATION_IMAGEEDITOR,
+       MIME_APPLICATION_THEMEVIEWER,
 
-/*  MIME header field parameter */
-static const char *szMsgParam[MSG_PARAM_NUM] =
-{
-       "charset",
-       "name",
-       "filename",
-       "type",         //Only if content-type is multipart/related,
-       "start",        //Only if content-type is multipart/related
-       "start-info",   //Only if content-type is multipart/related
-       "boundary",
-       "report-type", // only used as parameter of Content-Type: multipart/report; report-type=delivery-status;
-#ifdef FEATURE_JAVA_MMS
-       "Application-ID",                               //laconic_javaParamFix
-       "Reply-To-Application-ID",              //laconic_javaParamFix
-#endif
-};
+       MIME_APPLICATION_SOUNDPLAYER,
+       MIME_APPLICATION_MEDIAPLAYER,
+       MIME_APPLICATION_VOICEMEMO,
 
-/* Content-Transfer-Encoding header value */
-static const char *szMsgEncoding[MSG_ENCODING_NUM] =
-{
-       "7bit",
-       "8bit",
-       "binary",
-       "base64",
-       "quoted-printable"
-};
+       MIME_APPLICATION_PICSELVIEWER,
 
-/* Content-Disposition header value */
-static const char *szMsgDisposition[MSG_DISPOSITION_NUM] =
-{
-       "form-data",
-       "attachment",
-       "inline"
-};
+       MIME_APPLICATION_CONTACT,
+       MIME_APPLICATION_ORGANIZER,
 
-static const char *szMsgAddrType[MSG_ADDR_TYPE_NUM] =
-{
-       "/TYPE=PLMN",
-       "",
-       "/TYPE=IPV4",
-       "/TYPE=IPV6",
-       ""
-};
+       MIME_APPLICATION_MAX
+} MimeAppType;
 
-/* character-set value */
-static const char *szMsgCharset [MSG_CHARSET_NUM] =
-{
-       "us-ascii",
-       "utf-16",
-       "usc-2",
-       "utf-8",
-       /* MIME character-set value */
-
-       "iso-2022-kr",
-       "ks_c_5601-1987",
-       "euc_kr",
-       "iso-2022-jp",
-       "iso-2022-jp-2",
-       "iso-8859-1",
-       "iso-8859-2",
-       "iso-8859-3",
-       "iso-8859-4",
-       "iso-8859-5",
-       "iso-8859-6",
-       "iso-8859-6-e",
-       "iso-8859-6-i",
-       "iso-8859-7",
-       "iso-8859-8",
-       "iso-8859-8-i",
-       "iso-8859-9",
-       "iso-8859-10",
-       "iso-8859-15",
-       "Shift_jis",
-       "euc-jp",
-       "gb2312",
-       "big5",
-       "win1251",
-       "window-1251",
-       "windows-1251",
-       "koi8-r",
-       "koi8-u"
-};
 
+typedef struct _MimeTable {
+       const char *szMIME;
+       const char *szExt;
+       bool bDownloadable;
+       MimeType mime;                  /* index of mime type */
+       MimeType contentType;   /* representative mime type */
+       MimeAppType appType;
+       MimeMainType mainType;
+       int binary;
+} MimeTable;
 
 /**************************************************     MIME definition     ***************************************************/
 static const MimeTable mimeTable[] = {
@@ -188,6 +106,7 @@ static const MimeTable mimeTable[] = {
        {"application/vnd.smaf",                                                                "mmf",                          true,           MIME_APPLICATION_VND_SMAF,                                              MIME_APPLICATION_X_SMAF,                                MIME_APPLICATION_SOUNDPLAYER,                   MIME_MAINTYPE_AUDIO,            UNDEFINED_BINARY        },
        {"application/vnd.rn-realmedia",                                                "rm",                           true,           MIME_APPLICATION_VND_RN_REALMEDIA,                              MIME_APPLICATION_VND_RN_REALMEDIA,              MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
        {"application/vnd.sun.j2me.java-archive",                               "jar",                          true,           MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE,             MIME_APPLICATION_JAVA_ARCHIVE,                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_ETC,                      UNDEFINED_BINARY        },
+       {"application/vnd.samsung.theme",                                               "thm",                          true,           MIME_APPLICATION_VND_SAMSUNG_THEME,                             MIME_APPLICATION_VND_SAMSUNG_THEME,             MIME_APPLICATION_THEMEVIEWER,                   MIME_MAINTYPE_THEME,            UNDEFINED_BINARY        },
        {"application/vnd.ms-excel",                                                    "xls",                          true,           MIME_APPLICATION_VND_EXCEL,                                             MIME_APPLICATION_X_EXCEL,                               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      UNDEFINED_BINARY        },
        {"application/vnd.ms-powerpoint",                                               "ppt",                          true,           MIME_APPLICATION_VND_POWERPOINT,                                MIME_APPLICATION_VND_POWERPOINT,                MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      UNDEFINED_BINARY        },
        {"applcation/vnd.ms-word",                                                              "doc",                          true,           MIME_APPLICATION_VND_MSWORD,                                    MIME_APPLICATION_MSWORD,                                MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      UNDEFINED_BINARY        },
@@ -215,8 +134,8 @@ static const MimeTable mimeTable[] = {
        {"audio/amr-wb",                                                                                "amr",                          true,           MIME_AUDIO_AMR_WB,                                                              MIME_AUDIO_AMR_WB,                                              MIME_APPLICATION_VOICEMEMO,                             MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
        {"audio/mmf",                                                                                   "mmf",                          true,           MIME_AUDIO_MMF,                                                                 MIME_AUDIO_MMF,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
        {"audio/smaf",                                                                                  "mmf",                          true,           MIME_AUDIO_SMAF,                                                                MIME_AUDIO_SMAF,                                                MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
-       {"audio/iMelody",                                                                               "imy",                          true,           MIME_AUDIO_IMELODY,                                                             MIME_AUDIO_IMELODY,                                             MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
-       {"audio/imelody",                                                                               "imy",                          true,           MIME_AUDIO_IMELODY2,                                                            MIME_AUDIO_IMELODY,                                             MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/imelody",                                                                               "imy",                          true,           MIME_AUDIO_IMELODY,                                                             MIME_AUDIO_IMELODY,                                             MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/iMelody",                                                                               "imy",                          true,           MIME_AUDIO_IMELODY2,                                                            MIME_AUDIO_IMELODY,                                             MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
        {"audio/melody",                                                                                "imy",                          true,           MIME_AUDIO_MELODY,                                                              MIME_AUDIO_IMELODY,                                             MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
        {"audio/mid",                                                                                   "mid",                          true,           MIME_AUDIO_MID,                                                                 MIME_AUDIO_MID,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
        {"audio/midi",                                                                                  "mid"/*,midi"*/,        true,           MIME_AUDIO_MIDI,                                                                MIME_AUDIO_MID,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
@@ -272,11 +191,16 @@ static const MimeTable mimeTable[] = {
 
        //116
        {"image/vnd.wap.wbmp",                                                                  "wbmp",                         false,          MIME_IMAGE_VND_WAP_WBMP,                                                MIME_IMAGE_WBMP,                                                MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,            0x21    },
+       {"image/vnd.tmo.my5-gif",                                                               "gif",                          false,          MIME_IMAGE_VND_TMO_GIF,                                                 MIME_IMAGE_GIF,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,            UNDEFINED_BINARY        },
+       {"image/vnd.tmo.my5-jpg",                                                               "jpg",                          false,          MIME_IMAGE_VND_TMO_JPG,                                                 MIME_IMAGE_JPG,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,            UNDEFINED_BINARY        },
 
+       // 119
        {"image/x-bmp",                                                                         "bmp",                          false,          MIME_IMAGE_X_BMP,                                                               MIME_IMAGE_BMP,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,            UNDEFINED_BINARY        },
 
+       // 120
        {"message/rfc822",                                                                              "elm",                          false,          MIME_MESSAGE_RFC822,                                                    MIME_MESSAGE_RFC822,                                    MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_MESSAGE,          UNDEFINED_BINARY        },
 
+       //121
        {"multipart/mixed",                                                                     "",                                     false,          MIME_MULTIPART_MIXED,                                                   MIME_MULTIPART_MIXED,                                   MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      0x0c    },
        {"multipart/related",                                                                   "",                                     false,          MIME_MULTIPART_RELATED,                                                 MIME_MULTIPART_RELATED,                                 MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      UNDEFINED_BINARY        },
        {"multipart/alternative",                                                               "",                                     false,          MIME_MULTIPART_ALTERNATIVE,                                             MIME_MULTIPART_ALTERNATIVE,                             MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      0x0f    },
@@ -286,14 +210,15 @@ static const MimeTable mimeTable[] = {
        {"multipart/voice-message",                                                     "",                                     false,          MIME_MULTIPART_VOICE_MESSAGE,                                   MIME_MULTIPART_VOICE_MESSAGE,                   MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      UNDEFINED_BINARY        },
 
        //128
-       {"text/txt",                                                                                    "txt",                          false,          MIME_TEXT_TXT,                                                                  MIME_TEXT_TXT,                                                  MIME_APPLICATION_PICSELVIEWER,                  MIME_MAINTYPE_TEXT,                     UNDEFINED_BINARY        },
+       {"text/txt",                                                                                    "",                             false,          MIME_TEXT_TXT,                                                                  MIME_TEXT_TXT,                                                  MIME_APPLICATION_PICSELVIEWER,                  MIME_MAINTYPE_TEXT,                     UNDEFINED_BINARY        },
        {"text/html",                                                                                   "html"/*,htm"*/,        false,          MIME_TEXT_HTML,                                                                 MIME_TEXT_HTML,                                                 MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x02    },
        {"text/plain",                                                                                  "txt"/*,vbm,url"*/,                             false,          MIME_TEXT_PLAIN,                                                                MIME_TEXT_PLAIN,                                                MIME_APPLICATION_PICSELVIEWER,                  MIME_MAINTYPE_TEXT,                     0x03    },
        {"text/css",                                                                                    "",                                     false,          MIME_TEXT_CSS,                                                                  MIME_TEXT_CSS,                                                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x3d    },
        {"text/xml",                                                                                    "",                                     false,          MIME_TEXT_XML,                                                                  MIME_TEXT_XML,                                                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x28    },
        {"text/iMelody",                                                                                "imy",                          true,           MIME_TEXT_IMELODY,                                                              MIME_TEXT_IMELODY,                                              MIME_APPLICATION_SOUNDPLAYER,                   MIME_MAINTYPE_AUDIO,            UNDEFINED_BINARY        },
+       {"text/calendar",                                                                               "ics",                          true,   MIME_TEXT_CALENDAR,                                                             MIME_TEXT_CALENDAR,                                             MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,             UNDEFINED_BINARY },
 
-       //134
+       //135
        {"text/vnd.wap.wmlscript",                                                              "",                                     false,          MIME_TEXT_VND_WAP_WMLSCRIPT,                                    MIME_TEXT_VND_WAP_WMLSCRIPT,                    MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x09    },
        {"text/vnd.wap.wml",                                                                    "wml",                          false,          MIME_TEXT_VND_WAP_WML,                                                  MIME_TEXT_VND_WAP_WML,                                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x08    },
        {"text/vnd.wap.wta-event",                                                              "",                                     false,          MIME_TEXT_VND_WAP_WTA_EVENT,                                    MIME_TEXT_VND_WAP_WTA_EVENT,                    MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x0a    },
@@ -304,30 +229,32 @@ static const MimeTable mimeTable[] = {
        {"text/vnd.sun.j2me.app-descriptor",                                    "jad",                          true,           MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR,                  MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR,  MIME_APPLICATION_NONE,                                          MIME_MAINTYPE_ETC,                      UNDEFINED_BINARY        },
 
 
-       //142
+       //143
        {"text/x-hdml",                                                                         "",                                     false,          MIME_TEXT_X_HDML,                                                               MIME_TEXT_X_HDML,                                               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x04    },
-       {"text/x-vCalendar",                                                                    "vcs",                          true,           MIME_TEXT_X_VCALENDAR,                                                  MIME_TEXT_X_VCALENDAR,                                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x06    },
-       {"text/x-vCard",                                                                                "vcf",                          true,           MIME_TEXT_X_VCARD,                                                              MIME_TEXT_X_VCARD,                                              MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x07    },
+       {"text/x-vCalendar",                                                                    "vcs",                          true,           MIME_TEXT_X_VCALENDAR,                                                  MIME_TEXT_X_VCALENDAR,                                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_ETC,                      0x06    },
+       {"text/x-vCard",                                                                                "vcf",                          true,           MIME_TEXT_X_VCARD,                                                              MIME_TEXT_X_VCARD,                                              MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_ETC,                      0x07    },
        {"text/x-iMelody",                                                                              "imy",                          true,           MIME_TEXT_X_IMELODY,                                                    MIME_TEXT_X_IMELODY,                                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,            UNDEFINED_BINARY        },
        {"text/x-imelody",                                                                              "imy",                          true,           MIME_TEXT_X_IMELODY2,                                                   MIME_TEXT_X_IMELODY,                                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,            UNDEFINED_BINARY        },
        {"text/x-vnote",                                                                                "vnt",                          true,           MIME_TEXT_X_VNOTE,                                                              MIME_TEXT_X_VNOTE,                                              MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     UNDEFINED_BINARY        },
+       {"text/x-vtodo",                                                                                "vts",                          true,           MIME_TEXT_X_VTODO,                                                              MIME_TEXT_X_VNOTE,                                              MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     UNDEFINED_BINARY        },
 
-       //148
+       //150
        {"video/mpeg4",                                                                         "mp4",                          true,           MIME_VIDEO_MPEG4,                                                               MIME_VIDEO_MP4,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
        {"video/mp4",                                                                                   "mp4",                          true,           MIME_VIDEO_MP4,                                                                 MIME_VIDEO_MP4,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
-       {"video/h263",                                                                                  "3gp"/*,3gpp,mp4"*/,true,               MIME_VIDEO_H263,                                                                MIME_VIDEO_H263,                                                MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
+       {"video/h263",                                                                                  ""/*,3gpp,mp4"*/,true,          MIME_VIDEO_H263,                                                                MIME_VIDEO_H263,                                                MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
        {"video/3gpp",                                                                                  "3gp"/*,3gpp"*/,        true,           MIME_VIDEO_3GPP,                                                                MIME_VIDEO_3GPP,                                                MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
        {"video/3gp",                                                                                   "3gp"/*,3gpp"*/,        true,           MIME_VIDEO_3GP,                                                                 MIME_VIDEO_3GP,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
        {"video/avi",                                                                                   "avi",                          false,          MIME_VIDEO_AVI,                                                                 MIME_VIDEO_AVI,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
        {"video/sdp",                                                                                   "sdp",                          true,           MIME_VIDEO_SDP,                                                                 MIME_APPLICATION_SDP,                                                   MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
        {"video/mp4v-es",                                                                                       "3gp",                          true,           MIME_VIDEO_MP4_ES,                                                                      MIME_VIDEO_3GP,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
        {"video/mpeg",                                                                                  "3gp",                          true,           MIME_VIDEO_MPEG,                                                                        MIME_VIDEO_3GP,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
+       {"video/quicktime",                                                                             "mov",                          true,           MIME_VIDEO_MOV,                                                                 MIME_VIDEO_3GP,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,            UNDEFINED_BINARY        },
 
-       // 157
+       // 160
        {"video/vnd.rn-realvideo",                                                              "rm",                           true,           MIME_VIDEO_VND_RN_REALVIDEO,                                    MIME_VIDEO_VND_RN_REALVIDEO,                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,                    UNDEFINED_BINARY        },
        {"video/vnd.rn-realmedia",                                                              "rm",                           true,           MIME_VIDEO_VND_RN_REALMEDIA,                                    MIME_VIDEO_VND_RN_REALMEDIA,                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,                    UNDEFINED_BINARY        },
 
-       //159
+       //162
        {"video/x-mp4",                                                                         "mp4",                          true,           MIME_VIDEO_X_MP4,                                                               MIME_VIDEO_MP4,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,                    UNDEFINED_BINARY        },
        {"video/x-pv-mp4",                                                                              "mp4",                          true,           MIME_VIDEO_X_PV_MP4,                                                    MIME_VIDEO_MP4,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,                    UNDEFINED_BINARY        },
        {"video/x-pn-realvideo",                                                                "rv",                           true,           MIME_VIDEO_X_PN_REALVIDEO,                                              MIME_VIDEO_VND_RN_REALVIDEO,                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,                    UNDEFINED_BINARY        },
@@ -345,83 +272,10 @@ static const int mimeTableIndex[] = {
        105,            116,            119,
        120,            120,            120,
        121,            121,            121,
-       128,            134,            142,
-       148,            157,            159
+       128,            135,            143,
+       150,            160,            162
 };
 
-
-/*****************             Extension definition      *****************/
-static const ExtTable extTable[] = {
-
-       {"txt",                 MIME_TEXT_PLAIN},
-       {"html",                        MIME_TEXT_HTML},
-       {"htm",                 MIME_TEXT_HTML},
-       {"xhtml",                       MIME_APPLICATION_XHTML_XML},
-       {"wml",                 MIME_TEXT_VND_WAP_WML},
-       {"vcs",                 MIME_TEXT_X_VCALENDAR},
-       {"vcf",                 MIME_TEXT_X_VCARD},
-       {"vnt",                 MIME_TEXT_X_VNOTE},
-       {"smil",                        MIME_APPLICATION_SMIL},
-       {"eml",                 MIME_MESSAGE_RFC822},
-       {"gif",                 MIME_IMAGE_GIF},
-       {"jpeg",                        MIME_IMAGE_JPEG},
-       {"jpg",                 MIME_IMAGE_JPEG},
-       {"jpe",                 MIME_IMAGE_JPEG},
-       {"jpz",                 MIME_IMAGE_JPEG},
-       {"tiff",                        MIME_IMAGE_TIFF},
-       {"tif",                 MIME_IMAGE_TIFF},
-       {"png",                 MIME_IMAGE_PNG},
-       {"pnz",                 MIME_IMAGE_PNG},
-       {"wbmp",                        MIME_IMAGE_VND_WAP_WBMP},
-       {"bmp",                 MIME_IMAGE_BMP},
-       {"au",                          MIME_AUDIO_BASIC},
-       {"snd",                 MIME_AUDIO_BASIC},
-       {"mp3",                 MIME_AUDIO_MP3},
-       {"aac",                 MIME_AUDIO_AAC},
-       {"mp4",                 MIME_AUDIO_MP4},
-       {"m4a",                 MIME_AUDIO_M4A},
-       {"amr",                 MIME_AUDIO_X_AMR},
-       {"mmf",                 MIME_APPLICATION_VND_SMAF},
-       {"imy",                 MIME_AUDIO_X_IMELODY},
-       {"mid",                 MIME_AUDIO_MID},
-       {"midi",                        MIME_AUDIO_MID},
-       {"spm",                 MIME_AUDIO_SP_MIDI},
-       {"wav",                 MIME_AUDIO_WAVE},
-       {"3gp",                 MIME_AUDIO_3GPP},
-       {"3gpp",                        MIME_VIDEO_3GPP},
-       {"rm",                          MIME_VIDEO_VND_RN_REALVIDEO},
-       {"ra",                          MIME_AUDIO_VND_RN_REALAUDIO},
-       {"ram",                 MIME_AUDIO_VND_RN_REALAUDIO},
-       {"wma",                 MIME_AUDIO_X_MS_WMA},
-       {"smp",                 MIME_APPLICATION_STUDIOM},
-       {"avi",                 MIME_VIDEO_AVI},
-       {"sdp",                 MIME_APPLICATION_SDP},
-       {"vbm",                 MIME_TEXT_PLAIN},
-       {"url",                 MIME_TEXT_PLAIN},
-       {"jad",                 MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR},
-       {"jar",                 MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE},
-       {"dd",                          MIME_APPLICATION_VND_OMA_DD_XML},
-       {"dm",                          MIME_APPLICATION_VND_OMA_DRM_MESSAGE},
-       {"dcf",                 MIME_APPLICATION_VND_OMA_DRM_CONTENT},
-       {"rv",                          MIME_VIDEO_X_PN_REALVIDEO},
-       {"ro",                          MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML},
-       {"xls",                 MIME_APPLICATION_X_EXCEL},
-       {"pdf",                 MIME_APPLICATION_PDF},
-       {"ppt",                 MIME_APPLICATION_X_POWERPOINT},
-       {"swf",                 MIME_APPLICATION_X_FLASH},
-       {"svg",                 MIME_IMAGE_SVG},
-       {"doc",                 MIME_APPLICATION_MSWORD},
-       {"wmv",                 MIME_VIDEO_X_MS_WMV},
-       {"asf",                 MIME_VIDEO_X_MS_ASF},
-       {"3ga",                 MIME_AUDIO_M4A},
-       {"xmf",                 MIME_AUDIO_XMF},
-       {"mxmf",                        MIME_AUDIO_MOBILE_XMF},
-       {"pvx",                 MIME_VIDEO_X_PV_PVX},
-       {"oro",                 MIME_APPLICATION_VND_OMA_DRM_RO_XML},
-       {"odf",                 MIME_APPLICATION_VND_OMA_DRM_DCF}
-};
-
-
 static int mimeTableEnum[] =
 {
        MIME_ASTERISK   ,
@@ -472,6 +326,7 @@ static int mimeTableEnum[] =
        MIME_APPLICATION_VND_SMAF       ,
        MIME_APPLICATION_VND_RN_REALMEDIA       ,
        MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE      ,
+       MIME_APPLICATION_VND_SAMSUNG_THEME      ,
        MIME_APPLICATION_VND_EXCEL      ,
        MIME_APPLICATION_VND_POWERPOINT,
        MIME_APPLICATION_VND_MSWORD,
@@ -553,6 +408,8 @@ static int mimeTableEnum[] =
        MIME_IMAGE_SVG  ,
        MIME_IMAGE_SVG1 ,
        MIME_IMAGE_VND_WAP_WBMP ,
+       MIME_IMAGE_VND_TMO_GIF,
+       MIME_IMAGE_VND_TMO_JPG,
        MIME_IMAGE_X_BMP        ,
 
 
@@ -574,6 +431,7 @@ static int mimeTableEnum[] =
        MIME_TEXT_CSS   ,
        MIME_TEXT_XML   ,
        MIME_TEXT_IMELODY       ,
+       MIME_TEXT_CALENDAR,
        MIME_TEXT_VND_WAP_WMLSCRIPT     ,
        MIME_TEXT_VND_WAP_WML   ,
        MIME_TEXT_VND_WAP_WTA_EVENT     ,
@@ -588,7 +446,7 @@ static int mimeTableEnum[] =
        MIME_TEXT_X_IMELODY     ,
        MIME_TEXT_X_IMELODY2 ,
        MIME_TEXT_X_VNOTE ,
-
+       MIME_TEXT_X_VTODO,
 
        MIME_VIDEO_MPEG4        ,
        MIME_VIDEO_MP4  ,
@@ -599,6 +457,7 @@ static int mimeTableEnum[] =
        MIME_VIDEO_SDP  ,
        MIME_VIDEO_MP4_ES,
        MIME_VIDEO_MPEG ,
+       MIME_VIDEO_MOV  ,
        MIME_VIDEO_VND_RN_REALVIDEO     ,
        MIME_VIDEO_VND_RN_REALMEDIA     ,
        MIME_VIDEO_X_MP4        ,
@@ -613,8 +472,8 @@ static int mimeTableEnum[] =
 };
 
 
-#define MIME_MAX_NUM   166
-#define EXT_MAX        67
+#define MIME_MAX_NUM   167
+#define EXT_MAX        68
 #define MIME_SUB_TYPE_VND      1
 #define MIME_SUB_TYPE_X                2
 
@@ -622,41 +481,6 @@ int __MimeGetTableIndexInt(MimeType mime);
 int __MimeGetTableIndexString(const char *szMime);
 MimeMainType __MimeGetMainTypeName(const char *szType);
 
-
-/*
- * This function checks whether a mime is downloadable or not.
- *
- * @param      mime [in] Enumeration number for a MIME type.
- * @return     This function returns true if downloadable, or false.
- */
-bool MimeIsDownloadableInt(MimeType mime)
-{
-       int index;
-
-       index = __MimeGetTableIndexInt(mime);
-       if (index == MIME_UNKNOWN)
-               return false;
-
-       return mimeTable[index].bDownloadable;
-}
-
-/*
- * This function checks whether a mime is downloadable or not.
- *
- * @param      mime [in] MIME string.
- * @return     This function returns true if downloadable, or false.
- */
-bool MimeIsDownloadableString(const char *szMime)
-{
-       int index;
-
-       index = __MimeGetTableIndexString(szMime);
-       if (index == MIME_UNKNOWN)
-               return false;
-
-       return mimeTable[index].bDownloadable;
-}
-
 /*
  * This function checks main type of a MIME.
  *
@@ -674,22 +498,6 @@ MimeMainType MimeGetMainTypeInt(MimeType mime)
        return mimeTable[index].mainType;
 }
 
-/*
- * This function checks main type of a MIME.
- *
- * @param      mime [in] MIME string.
- * @return     This function returns main type of a MIME.
- */
-MimeMainType MimeGetMainTypeString(const char *szMime)
-{
-       int index;
-
-       index = __MimeGetTableIndexString(szMime);
-       if (index == MIME_UNKNOWN)
-               return MIME_MAINTYPE_ETC;
-
-       return mimeTable[index].mainType;
-}
 
 /*
  * This function returns a extension name for a specified MIME.
@@ -709,67 +517,6 @@ char *MimeGetExtFromMimeInt(MimeType mime)
 }
 
 /*
- * This function returns a extension name for a specified MIME.
- *
- * @param      mime [in] MIME string.
- * @return     This function returns Extension string.
- */
-char *MimeGetExtFromMimeString(const char *szMime)
-{
-       int index;
-
-       index = __MimeGetTableIndexString(szMime);
-       if (index == MIME_UNKNOWN)
-               return NULL;
-
-       return (char *)mimeTable[index].szExt;
-}
-
-
-/*
- * This function returns a MIME type for a specified Extension.
- *
- * @param      mime [in] Extension string.
- * @return     This function returns MIME string.
- */
-char *MimeGetMimeFromExtString(const char *szExt)
-{
-       int i;
-
-       for (i = 0; i < EXT_MAX; i++) {
-               if (!strcasecmp( extTable[i].szExt, szExt)) {
-                       int index;
-
-                       index = __MimeGetTableIndexInt(extTable[i].mimeType);
-                       if (index == MIME_UNKNOWN)
-                               return NULL;
-
-                       return (char *)mimeTable[index].szMIME;
-               }
-       }
-
-       return NULL;
-}
-
-/*
- * This function returns a MIME type for a specified Extension.
- *
- * @param      mime [in] Extension string.
- * @return     This function returns MIME string.
- */
-MimeType MimeGetMimeFromExtInt(const char *szExt)
-{
-       int i;
-
-       for (i = 0; i < EXT_MAX; i++) {
-               if (!strcasecmp( extTable[i].szExt, szExt))
-                       return extTable[i].mimeType;
-       }
-
-       return MIME_UNKNOWN;
-}
-
-/*
  * This function returns index number in MIME definition table with MIME enumeration.
  * Internal function.
  */
@@ -797,8 +544,6 @@ int __MimeGetTableIndexInt(MimeType mime)
        return tableIndex;
 }
 
-
-#define MIME_MAX_LEN   43
 /*
  * This function returns index number in MIME definition table with MIME string.
  * Internal function.
@@ -836,7 +581,8 @@ int __MimeGetTableIndexString(const char *szMime)
                free(szMIMEType);
                return 0;
        }
-       strcpy(szMIMEType, szMime);
+
+       strncpy(szMIMEType, szMime, strlen(szMime));
        type = 0;
        subtype = 0;
 
@@ -939,7 +685,7 @@ MimeMainType __MimeGetMainTypeName(const char *szType)
 }
 
 
-
+//For Decode
 // MimeString -> MimeInt
 MimeType MimeGetMimeIntFromMimeString(char *szMimeStr)
 {
@@ -979,22 +725,6 @@ MimeType MimeGetMimeIntFromBi(int binCode)
        return MIME_UNKNOWN;
 }
 
-// BinaryCode -> MimeInt
-char *MimeGetMimeStringFromBi(int binCode)
-{
-       int index;
-
-       if (binCode < 0x00 || binCode > 0x4b)
-               return NULL;
-
-       for (index = 0; index < MIME_MAX_NUM; index++) {
-               if (binCode == mimeTable[index].binary)
-                       return (char *)mimeTable[index].szMIME;
-       }
-
-       return NULL;
-}
-
 // Mimeint -> Binary Value
 int MimeGetBinaryValueFromMimeInt(MimeType mime)
 {
@@ -1007,309 +737,146 @@ int MimeGetBinaryValueFromMimeInt(MimeType mime)
        return mimeTable[index].binary;
 }
 
-// MimeString -> Binary value
-int MimeGetBinaryValueFromMimeString(const char *szMime)
-{
-       int index;
-
-       index = __MimeGetTableIndexString(szMime);
-       if (index == MIME_UNKNOWN)
-               return UNDEFINED_BINARY;
-
-       return mimeTable[index].binary;
-}
+typedef struct {
+       const char *szExt;
+       int mainType;
+       int enumMime;
+       const char *szContentType;
+} ExtTableItem;
+
+#define EXT_TABLE_SIZE (56)
+
+const ExtTableItem extTable[EXT_TABLE_SIZE] = {
+
+       //text
+       {"txt",   MIME_MAINTYPE_TEXT, MIME_TEXT_PLAIN, "text/plain"},
+       {"html",  MIME_MAINTYPE_TEXT, MIME_TEXT_HTML, "text/html"},
+       {"xhtml", MIME_MAINTYPE_TEXT, MIME_APPLICATION_XHTML_XML, "application/xhtml+xml"},
+       {"vcs",   MIME_MAINTYPE_TEXT, MIME_TEXT_X_VCALENDAR, "text/x-vCalendar"},
+       {"vcf",   MIME_MAINTYPE_TEXT, MIME_TEXT_X_VCARD, "text/x-vCard"},
+       {"vnt",   MIME_MAINTYPE_TEXT, MIME_TEXT_X_VNOTE, "text/x-vnote"},
+       {"vts",   MIME_MAINTYPE_TEXT, MIME_TEXT_X_VTODO, "text/x-vtodo"},
+       {"ics",   MIME_MAINTYPE_TEXT, MIME_TEXT_CALENDAR, "text/calendar"},
+
+       //image
+       {"gif",   MIME_MAINTYPE_IMAGE, MIME_IMAGE_GIF, "image/gif"},
+       //{"jpg",   MIME_MAINTYPE_IMAGE, MIME_IMAGE_JPG, "image/jpg"},
+       {"jpg",   MIME_MAINTYPE_IMAGE, MIME_IMAGE_JPEG, "image/jpeg"},
+       {"jpeg",  MIME_MAINTYPE_IMAGE, MIME_IMAGE_JPEG, "image/jpeg"},
+       {"tiff",  MIME_MAINTYPE_IMAGE, MIME_IMAGE_TIFF, "image/tiff"},
+       {"tif",   MIME_MAINTYPE_IMAGE, MIME_IMAGE_TIF, "image/tif"},
+       {"png",   MIME_MAINTYPE_IMAGE, MIME_IMAGE_PNG, "image/png"},
+       {"wbmp",  MIME_MAINTYPE_IMAGE, MIME_IMAGE_VND_WAP_WBMP, "image/vnd.wap.wbmp"},
+       {"bmp",   MIME_MAINTYPE_IMAGE, MIME_IMAGE_BMP, "image/bmp"},
+       {"svg",   MIME_MAINTYPE_IMAGE, MIME_IMAGE_SVG, "image/svg+xml"},
+
+       //audio
+       {"snd",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_BASIC, "audio/basic"},
+       {"amr",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_AMR, "audio/amr"},
+       {"m4a",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_M4A, "audio/m4a"},
+       {"3gp",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_3GPP, "audio/3gpp"},
+       {"3gpp",  MIME_MAINTYPE_AUDIO, MIME_AUDIO_3GPP, "audio/3gpp"},
+       {"mp3",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_MPEG, "audio/mpeg"},
+       {"aac",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_AAC, "audio/aac"},
+       {"imy",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_IMELODY, "audio/imelody"},
+       {"mid",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_MID, "audio/mid"},
+       {"mmf",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_MMF, "audio/mmf"},
+       {"spm",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_SP_MIDI, "audio/sp-midi"},
+       {"wav",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_WAV, "audio/wav"},
+       {"mp4",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_MP4, "audio/mp4"},
+       {"wma",   MIME_MAINTYPE_AUDIO, MIME_AUDIO_X_MS_WMA, "audio/x-ms-wma"},
+       {"rm",    MIME_MAINTYPE_AUDIO, MIME_AUDIO_VND_RN_REALAUDIO, "audio/vnd.rn-realaudio"},
+       {"ra",    MIME_MAINTYPE_AUDIO, MIME_AUDIO_VND_RN_REALAUDIO, "audio/vnd.rn-realaudio"},
+
+       //video
+       {"3gp",   MIME_MAINTYPE_VIDEO, MIME_VIDEO_3GPP, "video/3gpp"},
+       {"3gpp",  MIME_MAINTYPE_VIDEO, MIME_VIDEO_3GPP, "video/3gpp"},
+       {"mp4",   MIME_MAINTYPE_VIDEO, MIME_VIDEO_MP4, "video/mp4"},
+       {"rm",    MIME_MAINTYPE_VIDEO, MIME_VIDEO_VND_RN_REALVIDEO, "video/vnd.rn-realvideo"},
+       {"rv",    MIME_MAINTYPE_VIDEO, MIME_VIDEO_VND_RN_REALVIDEO, "video/vnd.rn-realvideo"},
+       {"avi",   MIME_MAINTYPE_VIDEO, MIME_VIDEO_AVI, "video/avi"},
+       {"asf",   MIME_MAINTYPE_VIDEO, MIME_VIDEO_X_MS_ASF, "video/x-ms-asf"},
+       {"mov", MIME_MAINTYPE_VIDEO, MIME_VIDEO_MOV, "video/quicktime"},
+
+       //application
+       {"smil",  MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_SMIL, "application/smil"},
+       {"rm",    MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_VND_RN_REALMEDIA, "application/vnd.rn-realmedia"},
+       {"ram",   MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_RAM, "application/ram"},
+       {"ppt",   MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_VND_POWERPOINT, "application/vnd.ms-powerpoint"},
+       {"xls",   MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_VND_EXCEL, "application/vnd.ms-excel"},
+       {"doc",   MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_VND_MSWORD, "applcation/vnd.ms-word"},
+       {"pdf",   MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_PDF, "application/pdf"},
+       {"swf",   MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_X_FLASH, "application/x-shockwave-flash"},
+       {"dm",    MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_VND_OMA_DRM_MESSAGE, "application/vnd.oma.drm.message"},
+       {"dcf",   MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_VND_OMA_DRM_CONTENT, "application/vnd.oma.drm.content"},
+       {"dd",    MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_VND_OMA_DD_XML, "application/vnd.oma.dd+xml"},
+       {"ro",    MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML, "application/vnd.oma.drm.rights+xml"},
+       {"ro",    MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML, "application/vnd.oma.drm.rights+wbxml"},
+       {"oro",   MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_VND_OMA_DRM_RO_XML, "application/vnd.oma.drm.ro+xml"},
+       {"odf",   MIME_MAINTYPE_APPLICATION, MIME_APPLICATION_VND_OMA_DRM_DCF, "application/vnd.oma.drm.dcf"},
 
+};
 
-/*
- * This function checks main type of a MIME.
- *
- * @param      mime [in] Enumeration number for a MIME type.
- * @return     This function returns application type of a MIME.
- */
-MimeAppType MimeGetAppTypeFromInt(MimeType mime)
+//GetMimeType from File Extension
+bool MmsGetMimeTypeFromExt(MimeMainType mainType, const char *pExt, MimeType *pMimeType, const char **ppszMimeType)
 {
-       int index;
-
-       index = __MimeGetTableIndexInt(mime);
-       if (index == MIME_UNKNOWN)
-               return MIME_APPLICATION_NONE;
-
-       return mimeTable[index].appType;
-}
+       const ExtTableItem *matchedItem = NULL;
 
-/*
- * This function checks main type of a MIME.
- *
- * @param      mime [in] MIME string.
- * @return     This function returns application type of a MIME.
- */
-MimeAppType MimeGetAppTypeFromString(const char *szMime)
-{
-       int index;
+       if (pExt == NULL)
+               return false;
 
-       index = __MimeGetTableIndexString(szMime);
-       if (index == MIME_UNKNOWN)
-               return MIME_APPLICATION_NONE;
+       if (pMimeType == NULL && ppszMimeType == NULL)
+               return false;
 
-       return mimeTable[index].appType;
-}
+       int extTableMainSize = sizeof(extTable)/sizeof(ExtTableItem);
 
+       for (int i = 0; i < extTableMainSize; i++) {
 
-/*
- * This function returns a application type for a specified Extension.
- *
- * @param      mime [in] Extension string.
- * @return     This function returns application type.
- */
-MimeAppType MimeGetAppTypeFromExtString(const char *szExt)
-{
-       int i;
+               if (strcasecmp(extTable[i].szExt, pExt) == 0) {
 
-       for (i = 0; i < EXT_MAX; i++) {
-               if (!strcasecmp( extTable[i].szExt, szExt)) {
-                       int index;
+                       matchedItem = &extTable[i];
 
-                       index = __MimeGetTableIndexInt(extTable[i].mimeType);
-                       if (index == MIME_UNKNOWN)
-                               return MIME_APPLICATION_NONE;
-                       return mimeTable[index].appType;
+                       if (mainType == extTable[i].mainType) {
+                               break;
+                       }
                }
        }
 
-       return MIME_APPLICATION_NONE;
-}
+       if (matchedItem) {
+               MSG_DEBUG("Found ext = [%s], mainType = [%d], mimeType = [0x%04x], ContentType = [%s]"
+                               , matchedItem->szExt
+                               , matchedItem->mainType
+                               , matchedItem->enumMime
+                               , matchedItem->szContentType);
 
-/*
- * This function gets the representative mime type from MimeType
- *
- * @param      mime [in] Enumeration number for a MIME type.
- * @return     representative mime type Enumeration number
- */
+               if (pMimeType)
+                       *pMimeType = (MimeType)matchedItem->enumMime;
 
-MimeType MimeGetContentTypeFromInt(MimeType mime)
-{
-       int index;
+               if (ppszMimeType)
+                       *ppszMimeType = matchedItem->szContentType;
 
-       for (index = 0; index < MIME_MAX_NUM; index++) {
-               if (mime == mimeTable[index].mime)
-                       return mimeTable[index].contentType;
+               return true;
        }
 
-       return MIME_UNKNOWN;
+       return false;
 }
 
-/*
- * This function gets the representative mime type from mime string
- *
- * @param      szMime - string name of MimeType
- * @return     representative mime type Enumeration number
- */
-
-MimeType MimeGetContentTypeFromString(const char *szMime)
-{
-       int index;
-
-       for (index = 0; index < MIME_MAX_NUM; index++) {
-               if (!strcasecmp(szMime, mimeTable[index].szMIME))
-                       return mimeTable[index].contentType;
-       }
-
-       return MIME_UNKNOWN;
-}
-
-/*
- * This function gets the index from mime string
- *
- * @param      szMime - string name of MimeType
- * @return     Enumeration number for a MIME type.
- */
-
-MimeType MimeGetMimeTypeFromString(const char *szMime)
+bool MmsGetMimeTypeFromFileName(MimeMainType mainType, const char *pFileName, MimeType *pMimeType, const char **ppszMimeType)
 {
-       int index;
-
-       for (index = 0; index < MIME_MAX_NUM; index++) {
-               if (!strcasecmp(szMime, mimeTable[index].szMIME))
-                       return mimeTable[index].mime;
-       }
+       const char *pExt = NULL;
 
-       return MIME_UNKNOWN;
-}
-
-
-int MsgGetCode(MsgHeaderField tableId, char *pStr)
-{
-       int cCode = 0;
-       int nNum = MSG_FIELD_UNKNOWN;
-       char **pTable = NULL;
-
-       switch (tableId) {
-       case MSG_FIELD:
-               nNum = MSG_FIELD_NUM;
-               pTable = (char **)szMsgField;
-               break;
-
-       case MSG_PARAM:
-               nNum = MSG_PARAM_NUM;
-               pTable = (char **)szMsgParam;
-               break;
-
-       case MSG_TYPE:
-               return MimeGetMimeIntFromMimeString(pStr);
-
-       case MSG_CHARSET:
-               nNum = MSG_CHARSET_NUM;
-               pTable = (char **)szMsgCharset;
-               break;
-
-       case MSG_ENCODING:
-               nNum = MSG_ENCODING_NUM;
-               pTable = (char **)szMsgEncoding;
-               break;
-
-       case MSG_DISPOSITION:
-               nNum = MSG_DISPOSITION_NUM;
-               pTable = (char **)szMsgDisposition;
-               break;
-
-       case MSG_ADDR_TYPE:
-               nNum = MSG_ADDR_TYPE_NUM;
-               pTable = (char **)szMsgAddrType;
-               break;
-
-       default:
-               break;
-       }
-
-       for (cCode = 0; cCode < nNum; cCode++) {
-               if (!strcasecmp(pStr, pTable[cCode])) {
-                       return cCode;
-               }
-       }
-
-       return -1;
-}
-
-
-char *MsgGetString(MsgHeaderField tableId, int code)
-{
-       int nNum = MSG_FIELD_UNKNOWN;
-       char **pTable = NULL;
-
-       switch (tableId) {
-       case MSG_FIELD:
-               nNum = MSG_FIELD_NUM;
-               pTable = (char **)szMsgField;
-               break;
-
-       case MSG_PARAM:
-               nNum = MSG_PARAM_NUM;
-               pTable = (char **)szMsgParam;
-               break;
-
-       case MSG_TYPE:
-               if (code != MIME_UNKNOWN && code != -1)
-                       return MimeGetMimeStringFromMimeInt(code);
-               else
-                       return (char *)MSG_UNKNOWN_TYPE_STRING;
-
-       case MSG_CHARSET:
-               nNum = MSG_CHARSET_NUM;
-               pTable = (char **)szMsgCharset;
-               break;
-
-       case MSG_ENCODING:
-               nNum = MSG_ENCODING_NUM;
-               pTable = (char **)szMsgEncoding;
-               break;
-
-       case MSG_DISPOSITION:
-               nNum = MSG_DISPOSITION_NUM;
-               pTable = (char **)szMsgDisposition;
-               break;
-
-       case MSG_ADDR_TYPE:
-               nNum = MSG_ADDR_TYPE_NUM;
-               pTable = (char **)szMsgAddrType;
-               break;
-
-       default:
-               break;
-       }
-
-       if (code < 0 || code >= nNum || !pTable)
-               return (char *)MSG_UNKNOWN_TYPE_STRING;
-
-       return pTable[code];
-}
+       if (pFileName == NULL)
+               return false;
 
-char *_MsgSkipWS3(char *s)
-{
-       while (true) {
-               if ((*s == MSG_CH_CR) ||
-                       (*s == MSG_CH_LF) ||
-                       (*s == MSG_CH_SP) ||
-                       (*s == MSG_CH_TAB))
-                       ++s;
-               else
-                       return s;
-       }
-}
+       if (pMimeType == NULL && ppszMimeType == NULL)
+               return false;
 
+       pExt = strrchr(pFileName, '.');
 
-int _MsgGetCode(MsgHeaderField tableId, char *pStr)
-{
-       int cCode = 0;
-       int nNum = MSG_FIELD_UNKNOWN;
-       char **pTable = NULL;
-
-       switch (tableId) {
-       case MSG_FIELD:
-               nNum = MSG_FIELD_NUM;
-               pTable = (char **)szMsgField;
-               break;
-
-       case MSG_PARAM:
-               nNum = MSG_PARAM_NUM;
-               pTable = (char **)szMsgParam;
-               break;
-
-       case MSG_TYPE:
-               return MimeGetMimeIntFromMimeString(pStr);
-
-       case MSG_CHARSET:
-               nNum = MSG_CHARSET_NUM;
-               pTable = (char **)szMsgCharset;
-               break;
-
-       case MSG_ENCODING:
-               nNum = MSG_ENCODING_NUM;
-               pTable = (char **)szMsgEncoding;
-               break;
-
-       case MSG_DISPOSITION:
-               nNum = MSG_DISPOSITION_NUM;
-               pTable = (char **)szMsgDisposition;
-               break;
-
-       case MSG_ADDR_TYPE:
-               nNum = MSG_ADDR_TYPE_NUM;
-               pTable = (char **)szMsgAddrType;
-               break;
-
-       default:
-               MSG_DEBUG("_MsgGetCode: Invalid tableId [%d] \n", tableId);
-               break;
-       }
+       if (pExt == NULL || *(pExt + 1) == '\0')
+               return false;
 
-       for (cCode = 0; cCode < nNum; cCode++) {
-               if (pTable[cCode] != NULL) {
-                       if (!strcasecmp( pStr, pTable[cCode])) {
-                               return cCode;
-                       }
-               }
-       }
+       pExt = pExt + 1;
 
-       return INVALID_HOBJ;
+       return MmsGetMimeTypeFromExt(mainType, pExt, pMimeType, ppszMimeType);
 }
-
index 6d29df9..f3db2cf 100755 (executable)
@@ -1,40 +1,33 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#include <glib.h>
-#include <pthread.h>
 #include <stdio.h>
-#include <time.h>
-
+#include "MsgException.h"
+#include "MsgGconfWrapper.h"
+#include "MsgUtilFile.h"
+#include "MsgMmsMessage.h"
+#include "MsgSerialize.h"
+#include "MmsPluginDebug.h"
 #include "MmsPluginTypes.h"
 #include "MmsPluginMain.h"
 #include "MmsPluginTransport.h"
-#include "MsgDebug.h"
-#include "MsgException.h"
-
-#include "MmsPluginMain.h"
-#include "MmsPluginMessage.h"
 #include "MmsPluginStorage.h"
 #include "MmsPluginInternal.h"
 #include "MmsPluginEventHandler.h"
-#include "MsgGconfWrapper.h"
 #include "MmsPluginCodec.h"
-#include "MsgUtilFile.h"
-#include "MmsPluginUserAgent.h"
-
 
 /*==================================================================================================
                                                        FUNCTION IMPLEMENTATION
@@ -85,7 +78,7 @@ msg_error_t MmsInitialize()
        MSG_BEGIN();
 
        // remove temp files
-       MsgMmsInitDir();
+       //MsgMmsInitDir();
 
        MSG_END();
 
@@ -123,6 +116,10 @@ msg_error_t MmsSubmitRequest(MSG_REQUEST_INFO_S *pReqInfo)
                MmsPluginTransport::instance()->submitRequest(pReqInfo);
        } catch (MsgException& e) {
                MSG_FATAL("%s", e.what());
+
+               if (e.errorCode() == MsgException::REQ_EXIST_ERROR)
+                       return MSG_SUCCESS;
+
                return MSG_ERR_PLUGIN_TRANSPORT;
        } catch (exception& e) {
                MSG_FATAL("%s", e.what());
@@ -184,14 +181,14 @@ msg_error_t MmsUpdateMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S
        msg_error_t err = MSG_SUCCESS;
 
        try {
-               if (pMsgInfo->networkStatus == MSG_NETWORK_NOT_SEND) {
+               if (pMsgInfo->networkStatus == MSG_NETWORK_NOT_SEND || pMsgInfo->networkStatus == MSG_NETWORK_SENDING) { //draft update
                        err = MmsPluginStorage::instance()->updateMessage(pMsgInfo, pSendOptInfo, pFileData);
                } else {
                        //[Update Message ID & File path only in case of retrieve. Else update Message ID]
-                       if (pMsgInfo->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || pMsgInfo->msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS) {
+                       if (pMsgInfo->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || pMsgInfo->msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS) { //retrieve conf
                                err = MmsPluginStorage::instance()->updateConfMessage(pMsgInfo);
                        } else {
-                               err = MmsPluginStorage::instance()->updateMsgServerID(pMsgInfo, pSendOptInfo);
+                               err = MmsPluginStorage::instance()->updateMsgServerID(pMsgInfo, pSendOptInfo); //update send conf
                        }
                }
        } catch (MsgException& e) {
@@ -208,14 +205,14 @@ msg_error_t MmsUpdateMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S
 }
 
 
-msg_error_t MmsGetMmsMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_MESSAGE_DATA_S *pMmsMsg, char **pDestMsg)
+msg_error_t MmsGetMmsMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char **pDestMsg)
 {
        MSG_BEGIN();
 
        msg_error_t     err = MSG_SUCCESS;
 
        try {
-               err = MmsPluginStorage::instance()->plgGetMmsMessage(pMsg, pSendOptInfo, pMmsMsg, pDestMsg);
+               err = MmsPluginStorage::instance()->getMessage(pMsg, pSendOptInfo, pDestMsg);
        } catch (MsgException& e) {
                MSG_FATAL("%s", e.what());
                return MSG_ERR_PLUGIN_STORAGE;
@@ -288,15 +285,16 @@ msg_error_t MmsComposeReadReport(MSG_MESSAGE_INFO_S *pMsgInfo)
        return MSG_SUCCESS;
 }
 
-
+//FIXME::It used for kies but not now
 msg_error_t MmsRestoreMsg(MSG_MESSAGE_INFO_S *pMsgInfo, char *pRcvBody, int rcvdBodyLen, char *filePath)
 {
        MSG_BEGIN();
 
        if (pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS) {
                FILE *pFile;
-               _MmsInitHeader();
-               _MmsRegisterDecodeBuffer(gszMmsLoadBuf1,  gszMmsLoadBuf2, MSG_MMS_DECODE_BUFFER_MAX);
+
+               MmsInitHeader();
+               MmsRegisterDecodeBuffer();
 
                if ((pFile = MsgOpenFile(pMsgInfo->msgData, "rb+")) == NULL) {
                        MSG_DEBUG("File Open Error: %s", pMsgInfo->msgData);
@@ -311,7 +309,7 @@ msg_error_t MmsRestoreMsg(MSG_MESSAGE_INFO_S *pMsgInfo, char *pRcvBody, int rcvd
                MSG_DEBUG(":::%d :%s ",rcvdBodyLen, pRcvBody);
 
                if (filePath) {
-                       snprintf(filePath, MAX_FULL_PATH_SIZE, MSG_DATA_PATH"BODY_%lu.DATA", random() % 1000000000 + 1);
+                       snprintf(filePath, MAX_FULL_PATH_SIZE, "%sBODY_%lu.DATA", MSG_DATA_PATH, random() % 1000000000 + 1);
                } else {
                        return MSG_ERR_NULL_POINTER;
                }
@@ -326,3 +324,20 @@ msg_error_t MmsRestoreMsg(MSG_MESSAGE_INFO_S *pMsgInfo, char *pRcvBody, int rcvd
        return MSG_SUCCESS;
 }
 
+msg_error_t MmsDeleteMessage(msg_message_id_t msgId)
+{
+       MSG_BEGIN();
+
+       try {
+               MmsPluginStorage::instance()->deleteMmsMessage(msgId);
+       } catch (MsgException& e) {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_STORAGE;
+       } catch (exception& e) {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_STORAGE;
+       }
+
+       MSG_END();
+       return MSG_SUCCESS;
+}
index 46c1c36..a6060c7 100755 (executable)
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
-#include <ctype.h>
+#include <errno.h>
+#include <sys/stat.h>
 
-#include "MsgTypes.h"
 #include "MsgCppTypes.h"
-#include "MsgException.h"
 #include "MsgStorageTypes.h"
 #include "MsgSettingTypes.h"
+#include "MsgUtilFile.h"
+#include "MsgGconfWrapper.h"
+#include "MsgMmsMessage.h"
+#include "MmsPluginTypes.h"
+#include "MmsPluginDebug.h"
 #include "MmsPluginMessage.h"
 #include "MmsPluginMIME.h"
-#include "MmsPluginAvCodec.h"
-#include "MsgUtilFile.h"
-#include "MsgDebug.h"
-#include "MmsPluginCodec.h"
 #include "MmsPluginStorage.h"
-#include "MsgMmsMessage.h"
-#include "MsgGconfWrapper.h"
-
-#include "MmsPluginSMILValidate.h"
-
-
-bool MmsInitMsgAttrib(MmsAttrib *pAttrib)
-{
-       MSG_DEBUG("MmsInitMsgAttrib");
-
-       pAttrib->bAskDeliveryReport = false;
-
-       pAttrib->bAskReadReply = false;
-       pAttrib->bRead = false;
-       pAttrib->bReportAllowed = false;
-       pAttrib->readReportAllowedType = MMS_RECEIVE_READ_REPORT_ALLOWED;
-       pAttrib->readReportSendStatus = MMS_RECEIVE_READ_REPORT_NO_SEND;
-       pAttrib->bReadReportSent = false;
-
-       pAttrib->bHideAddress = false;
-       pAttrib->date = 0;
-       pAttrib->bUseDeliveryCustomTime = false;
-       pAttrib->deliveryTime.type = MMS_TIMETYPE_RELATIVE;
-       pAttrib->deliveryTime.time = 0;
-       pAttrib->bUseExpiryCustomTime = false;
-       pAttrib->expiryTime.type = MMS_TIMETYPE_RELATIVE;
-       pAttrib->expiryTime.time = 0;
-       memset(&pAttrib->expiryTime, 0, sizeof(MmsTimeStruct));
-       pAttrib->msgClass = MMS_MSGCLASS_PERSONAL;
-       pAttrib->msgStatus = MSG_DELIVERY_REPORT_NONE;
-       pAttrib->priority = MMS_PRIORITY_NORMAL;
-       pAttrib->responseStatus = MMS_RESPSTATUS_ERROR;
-       pAttrib->retrieveStatus = MMS_RETRSTATUS_ERROR;
-       pAttrib->contentType = MIME_UNKNOWN;
-       pAttrib->msgSize = 0;
-       pAttrib->bLeaveCopy = true;
-
-       pAttrib->specialMsgType = MMS_SPECIAL_MSG_TYPE_NONE;
-#ifdef __SUPPORT_DRM__
-       pAttrib->drmType = MSG_DRM_TYPE_NONE;
-       pAttrib->roWaitingTimerMax = 0;
-       pAttrib->pszDrmData = NULL;
-#endif
-       pAttrib->version = MMS_VERSION;
-
-       memset(pAttrib->szFrom, 0, MSG_LOCALE_ADDR_LEN + 10);
-       memset(pAttrib->szResponseText, 0, MMS_LOCALE_RESP_TEXT_LEN + 1);
-       memset(pAttrib->szRetrieveText, 0, MMS_LOCALE_RESP_TEXT_LEN + 1);
-       memset(pAttrib->szSubject, 0, MSG_LOCALE_SUBJ_LEN + 1);
-       pAttrib->szTo = NULL;
-       pAttrib->szCc = NULL;
-       pAttrib->szBcc = NULL;
-
-       pAttrib->pMultiStatus = NULL;
-
-       pAttrib->replyCharge.chargeType = MMS_REPLY_NONE;
-       memset(&pAttrib->replyCharge.deadLine , 0, sizeof(MmsTimeStruct));
-       pAttrib->replyCharge.chargeSize = 0;
-       memset(pAttrib->replyCharge.szChargeID, 0, MMS_MSG_ID_LEN);
-
-       return true;
-}
-
-bool MmsInitMsgType(MsgType *pMsgType)
-{
-       MSG_DEBUG("MmsInitMsgType");
-       pMsgType->offset = 0;
-       pMsgType->size = 0;
-       pMsgType->contentSize = 0;
-       pMsgType->disposition = -1;
-       pMsgType->encoding = -1;
-       pMsgType->type = MIME_UNKNOWN;
-       pMsgType->section = -1;
-
-       pMsgType->szOrgFilePath[0] = '\0';
-       pMsgType->szContentID[0] = '\0';
-       pMsgType->szContentLocation[0] = '\0';
-
-       pMsgType->szContentRepPos[0] = '\0';
-       pMsgType->szContentRepSize[0] = '\0';
-       pMsgType->szContentRepIndex[0] = '\0';
-
-       MmsInitMsgContentParam(&pMsgType->param);
-#ifdef __SUPPORT_DRM__
-       __MsgInitMsgDRMInfo(&pMsgType->drmInfo);
-#endif
-
-       return true;
-}
-
-bool MmsInitMsgBody(MsgBody *pMsgBody)
-{
-       MSG_DEBUG("MmsInitMsgBody");
-       pMsgBody->offset = 0;
-       pMsgBody->size = 0;
-       pMsgBody->body.pText = NULL;
-
-       MmsInitMsgType(&pMsgBody->presentationType);
-       pMsgBody->pPresentationBody = NULL;
-
-       memset(pMsgBody->szOrgFilePath, 0, MSG_FILEPATH_LEN_MAX);
-
-       return true;
-}
-
-bool MmsInitMsgContentParam(MsgContentParam *pMsgContentParam)
+#include "MmsPluginUtil.h"
+#include "MmsPluginTcs.h"
+#include "MsgSmil.h"
+#include "MmsPluginAppBase.h"
+
+#define PRINT_KEY_VAL_STR(key, val)\
+if (val) {\
+MSG_DEBUG("%-20s: %s", key, val);\
+}\
+
+#define PRINT_KEY_VAL_INT(key, val)\
+if (val) {\
+MSG_DEBUG("%-20s: %d", key, val);\
+}\
+
+static MsgMultipart *MmsGetNthMultipart(MmsMsg *pMsg, int index);
+static MsgMultipart *MmsMakeMultipart(MimeType mimeType, char *szTitleName, char *szOrgFilePath, char *szContentID, char *szContentLocation);
+static bool MmsSetMsgAddressList(MmsAttrib *pAttrib, const MSG_MESSAGE_INFO_S *pMsgInfo);
+static char *MmsComposeAddress(const MSG_MESSAGE_INFO_S *pMsgInfo, int recipientType);
+static bool MmsInsertPresentation(MmsMsg *pMsg, MimeType mimeType, const char *content_id, char *pData, int size);
+static bool MmsInsertPartFromMultipart(MmsMsg *pMsg, MMS_MULTIPART_DATA_S *pNewMultipart);
+static bool MmsInsertPartToMmsData(MMS_MESSAGE_DATA_S *pMsgData, MMS_MULTIPART_DATA_S *pMultipart);
+static bool MmsInsertMixedPartToMmsData(MMS_MESSAGE_DATA_S *pMsgData, MMS_MULTIPART_DATA_S *pMultipart);
+static void printMmsAttribute(MmsAttrib *pAttrib);
+
+bool convertMediaToMultipart(MMS_MEDIA_S *pSrcMedia, MMS_MULTIPART_DATA_S *pDestMultipart);
+bool convertAttachToMultipart(MMS_ATTACH_S *pSrcMedia, MMS_MULTIPART_DATA_S *pDestMultipart);
+MMSList * MmsConvertAddressToNewStyle(const char *szAddr);
+char *MmsConvertAddressToOldStyle(MMSList *pAddressList);
+
+void printMmsAttribute(MmsAttrib *pAttrib)
 {
-       MSG_DEBUG("MmsInitMsgContentParam");
-       pMsgContentParam->charset = MSG_CHARSET_UNKNOWN;
-       pMsgContentParam->type = MIME_UNKNOWN;
-       pMsgContentParam->szBoundary[0] = '\0';
-       pMsgContentParam->szFileName[0] = '\0';
-       pMsgContentParam->szName[0] = '\0';
-       pMsgContentParam->szStart[0] = '\0';
-       pMsgContentParam->szStartInfo[0] = '\0';
-       pMsgContentParam->pPresentation = NULL;
-       pMsgContentParam->reportType = MSG_PARAM_REPORT_TYPE_UNKNOWN; // only used as parameter of Content-Type: multipart/report; report-type
-#ifdef FEATURE_JAVA_MMS
-       pMsgContentParam->szApplicationID = NULL;
-       pMsgContentParam->szReplyToApplicationID = NULL;
-#endif
-       return true;
+       MSG_ERR_RET_M(pAttrib == NULL, "attribute is NULL");
+
+       MSG_DEBUG("# LeaveCopy [%d]", pAttrib->bLeaveCopy);
+       MSG_DEBUG("# DeliveryTime type [%d], time [%d]", pAttrib->deliveryTime.type, pAttrib->deliveryTime.time);
+       MSG_DEBUG("# ExpiryTime type [%d], time [%d]", pAttrib->expiryTime.type, pAttrib->expiryTime.time);
+       MSG_DEBUG("# Priority [%d]", pAttrib->priority);
+       MSG_DEBUG("# AskDeliveryReport [%d]", pAttrib->bAskDeliveryReport);
+       MSG_DEBUG("# AskReadReply [%d]", pAttrib->bAskReadReply);
 }
 
 bool MmsSetMsgAddressList(MmsAttrib *pAttrib, const MSG_MESSAGE_INFO_S * pMsgInfo)
 {
-       MSG_DEBUG("MmsSetMsgAddressList");
+       MSG_BEGIN();
+
        pAttrib->szTo = MmsComposeAddress(pMsgInfo, MSG_RECIPIENTS_TYPE_TO);
-       MSG_DEBUG("To address: %s", pAttrib->szTo);
+       if (pAttrib->szTo) {
+               MSG_SEC_DEBUG("To address: %s", pAttrib->szTo);
+       }
+
        pAttrib->szCc = MmsComposeAddress(pMsgInfo, MSG_RECIPIENTS_TYPE_CC);
-       MSG_DEBUG("Cc address: %s", pAttrib->szCc);
+       if (pAttrib->szCc) {
+               MSG_SEC_DEBUG("Cc address: %s", pAttrib->szCc);
+       }
+
        pAttrib->szBcc = MmsComposeAddress(pMsgInfo, MSG_RECIPIENTS_TYPE_BCC);
-       MSG_DEBUG("Bcc address: %s", pAttrib->szBcc);
+       if (pAttrib->szBcc) {
+               MSG_SEC_DEBUG("Bcc address: %s", pAttrib->szBcc);
+       }
 
+       MSG_END();
        return true;
 }
 
-void MmsSetMsgMultiStatus(MmsAttrib *pAttrib, const MSG_MESSAGE_INFO_S *pMsgInfo)
-{
-       int     nAddressCnt = 0;
-
-       nAddressCnt = pMsgInfo->nAddressCnt;
-
-       for (int i = 0; i < nAddressCnt; ++i) {
-               pAttrib->pMultiStatus = (MmsMsgMultiStatus *)malloc(sizeof(MmsMsgMultiStatus));
-
-               memset(pAttrib->pMultiStatus->szTo, 0, MAX_ADDRESS_VAL_LEN + 1);
-               strncpy(pAttrib->pMultiStatus->szTo, pMsgInfo->addressList[i].addressVal, MAX_ADDRESS_VAL_LEN);
-
-               MSG_DEBUG("### pMultistatus->szTo = %s ####", pAttrib->pMultiStatus->szTo);
-               pAttrib->pMultiStatus->bDeliveryReportIsRead = false;
-               pAttrib->pMultiStatus->bDeliveyrReportIsLast = false;
-               pAttrib->pMultiStatus->msgStatus = MMS_MSGSTATUS_NONE;
-               pAttrib->pMultiStatus->handledTime = 0;
-               pAttrib->pMultiStatus->bReadReplyIsRead = false;
-               pAttrib->pMultiStatus->bReadReplyIsLast = false;
-               pAttrib->pMultiStatus->readStatus = MMS_READSTATUS_NONE;
-               pAttrib->pMultiStatus->readTime = 0;
-
-               pAttrib->pMultiStatus = pAttrib->pMultiStatus->pNext;
-       }
-}
-
 char *MmsComposeAddress(const MSG_MESSAGE_INFO_S *pMsgInfo, int recipientType)
 {
-       MSG_DEBUG("MmsComposeAddress");
+       MSG_BEGIN();
        int     addrLen = 0;
        int     nAddressCnt = 0;
        int nRecpCnt = 0;
        char pString[MSG_LOCALE_NAME_LEN + MSG_ADDR_LEN + 3] = {0, };
        char *szCompose;
+       const char *typePlmn = "/TYPE=PLMN";
 
        nAddressCnt = pMsgInfo->nAddressCnt;
 
        // Calculate allocated buffer size
        for (int i = 0; i < nAddressCnt; ++i) {
-               MSG_DEBUG("recipientType: %d, address value: %s", pMsgInfo->addressList[i].recipientType, pMsgInfo->addressList[i].addressVal);
+
+               MSG_SEC_DEBUG("recipientType: %d, address value: %s", pMsgInfo->addressList[i].recipientType, pMsgInfo->addressList[i].addressVal);
+
+               if (pMsgInfo->addressList[i].recipientType == MSG_RECIPIENTS_TYPE_UNKNOWN)
+                       pMsgInfo->addressList[i].recipientType = MSG_RECIPIENTS_TYPE_TO;
+
                if (pMsgInfo->addressList[i].recipientType == recipientType) {
                        if (pMsgInfo->addressList[i].addressType == MSG_ADDRESS_TYPE_PLMN) {
-                               addrLen += strlen(MsgGetString(MSG_ADDR_TYPE, MSG_ADDR_TYPE_PHONE));
+                               addrLen += strlen(typePlmn);
                                addrLen += strlen(pMsgInfo->addressList[i].addressVal);
                        } else if (pMsgInfo->addressList[i].addressType == MSG_ADDRESS_TYPE_EMAIL) {
                                addrLen += strlen(pMsgInfo->addressList[i].addressVal);
@@ -229,57 +137,30 @@ char *MmsComposeAddress(const MSG_MESSAGE_INFO_S *pMsgInfo, int recipientType)
        // Address String copy
        for (int i = 0; i < nAddressCnt; ++i) {
                if (pMsgInfo->addressList[i].recipientType == recipientType) {
-                       if (strlen(szCompose) > 0)
-                               strcat(szCompose, MSG_STR_ADDR_DELIMETER);
+                       if (szCompose && strlen(szCompose) > 0)
+                               g_strlcat(szCompose, MSG_STR_ADDR_DELIMETER, addrLen + 1);
 
                        memset(pString, 0x00, (MSG_LOCALE_NAME_LEN + MSG_ADDR_LEN + 3) * sizeof(char));
                        if (pMsgInfo->addressList[i].addressType == MSG_ADDRESS_TYPE_PLMN) {
-                               snprintf(pString, MSG_LOCALE_NAME_LEN + MSG_ADDR_LEN + 3, "%s%s", pMsgInfo->addressList[i].addressVal, MsgGetString(MSG_ADDR_TYPE, MSG_ADDR_TYPE_PHONE));
+                               snprintf(pString, MSG_LOCALE_NAME_LEN + MSG_ADDR_LEN + 3, "%s%s", pMsgInfo->addressList[i].addressVal, typePlmn);
                                MSG_DEBUG("%s", pString);
                        } else if (pMsgInfo->addressList[i].addressType == MSG_ADDRESS_TYPE_EMAIL) {
                                snprintf(pString, MSG_LOCALE_NAME_LEN + MSG_ADDR_LEN + 3, "%s", pMsgInfo->addressList[i].addressVal);
                        } else
                                ; // Need to consider IPV4, IPV6, and Alias formatted address
 
-                       strcat(szCompose, pString);
+                       g_strlcat(szCompose, pString, addrLen + 1);
                }
        }
 
+       MSG_END();
        return szCompose;
 }
 
-
-bool MmsGetMsgBodyfromMsgInfo(const MSG_MESSAGE_INFO_S *pMsgInfo, MMS_MESSAGE_DATA_S *pMsgBody, char *pFileData)
-{
-       MSG_DEBUG("MmsGetMsgBodyfromMsgInfo");
-       memset(pMsgBody, 0, sizeof(MMS_MESSAGE_DATA_S));
-
-       if (pMsgInfo->bTextSms == false) {       //if  the message body was stored in file.
-               _MsgMmsDeserializeMessageData(pMsgBody, pFileData);
-       }
-
-       return true;
-}
-
-int MmsGetSmilRawData(MMS_MESSAGE_DATA_S *pMsgBody, char **pRawdata)
+bool MmsInsertPresentation(MmsMsg *pMsg, MimeType mimeType, const char *content_id, char *pData, int size)
 {
        MSG_BEGIN();
 
-       if (MsgReadSmilFile(pMsgBody->szSmilFilePath, pRawdata) < 0)
-               return false;
-
-       MsgDeleteSmilFile(pMsgBody->szSmilFilePath);
-
-       MSG_END();
-
-       return true;
-}
-
-
-bool MmsInsertPresentation(MmsMsg *pMsg, MsgContentType mimeType, char *pData, int size)
-{
-       MSG_DEBUG("MmsInsertPresentation");
-
        if (pMsg == NULL) {
                MSG_DEBUG("pMsg is NULL");
                return false;
@@ -302,14 +183,21 @@ bool MmsInsertPresentation(MmsMsg *pMsg, MsgContentType mimeType, char *pData, i
        pMsg->msgBody.pPresentationBody->size = size;
        pMsg->msgBody.presentationType.type = mimeType;
        pMsg->msgBody.presentationType.param.charset = MSG_CHARSET_UTF8;
-       snprintf(pMsg->msgBody.presentationType.szContentID, MSG_MSG_ID_LEN + 1, "<_S_>");
 
-       snprintf(pMsg->msgType.param.szStart, MSG_MSG_ID_LEN + 1, pMsg->msgBody.presentationType.szContentID);
+       if (content_id && strlen(content_id) > 0) {
+               snprintf(pMsg->msgBody.presentationType.szContentID, MSG_MSG_ID_LEN + 1, "%s", content_id);
+       } else {
+               snprintf(pMsg->msgBody.presentationType.szContentID, MSG_MSG_ID_LEN + 1, "<_S_>");//default
+       }
+
+       snprintf(pMsg->msgType.param.szStart, MSG_MSG_ID_LEN + 1, "%s", pMsg->msgBody.presentationType.szContentID);
+
        pMsg->msgType.param.type = mimeType;
 
        memset(pMsg->msgBody.pPresentationBody->body.pText, 0, size + 1);
        strncpy(pMsg->msgBody.pPresentationBody->body.pText, pData, size);
 
+       MSG_END();
        return true;
 
 __CATCH:
@@ -327,1139 +215,1262 @@ __CATCH:
        return false;
 }
 
-
-bool MmsInsertPartFromFile(MmsMsg *pMsg, char *szTitleName, char *szOrgFilePath, char *szContentID)
+MsgMultipart *MmsMakeMultipart(MimeType mimeType, char *szTitleName, char *szOrgFilePath, char *szContentID, char *szContentLocation)
 {
-       MSG_DEBUG("MmsInsertPartFromFile");
-
        MsgMultipart *pMultipart = NULL;
-       MsgMultipart *pLastPart = NULL;
-       int nFileSize;
-       MsgContentType mimeType = MIME_UNKNOWN;
-       char *pExt = NULL;
-
-       pExt = strrchr(szOrgFilePath, '.');
-
-       if (pExt == NULL || pExt[0] == '\0' || strrchr(pExt, '/'))
-               mimeType = MIME_UNKNOWN;
-       else {
-               if (strcasecmp(pExt, ".dcf") == 0)
-                       mimeType = MIME_APPLICATION_VND_OMA_DRM_CONTENT;
-               else {
-                       if (MmsGetTypeByFileName((int *)&mimeType, szOrgFilePath) == false)
-                               goto __CATCH;
-               }
-       }
 
-       if (mimeType == MIME_UNKNOWN)
-               mimeType = MIME_APPLICATION_OCTET_STREAM;
+       if ((pMultipart = MmsAllocMultipart()) == NULL)
+               return NULL;
 
-       if (MmsIsMultipart(pMsg->msgType.type) == true) {
-               /* Insert as a multipart */
-               if (MsgGetFileSize(szOrgFilePath, &nFileSize) == false) {
-                       MSG_DEBUG("MsgGetFileSize: failed");
-                       goto __CATCH;
-               }
+       pMultipart->type.type = mimeType;
 
-               pMultipart = MmsMakeMultipart(mimeType, szTitleName, szOrgFilePath, NULL, 0, nFileSize, szContentID);
-               if (pMultipart == NULL)
-                       goto __CATCH;
+       if (szTitleName && szTitleName[0]) {
+               memset(pMultipart->type.param.szName, 0, MSG_LOCALE_FILENAME_LEN_MAX + 1);
+               strncpy(pMultipart->type.param.szName, szTitleName, MSG_LOCALE_FILENAME_LEN_MAX);
+       }
 
-               if (pMsg->mmsAttrib.contentType == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED ||
-                       pMsg->mmsAttrib.contentType == MIME_MULTIPART_MIXED)
-                       pMultipart->type.disposition = MSG_DISPOSITION_ATTACHMENT;
+       if (szContentID && szContentID[0]) {
+               memset(pMultipart->type.szContentID, 0, MSG_MSG_ID_LEN + 1);
+               snprintf(pMultipart->type.szContentID, MSG_MSG_ID_LEN + 1, "<%s>", szContentID);
+       }
 
-               if (pMsg->msgBody.body.pMultipart == NULL) {
-                       pMsg->msgBody.body.pMultipart = pMultipart;
-               } else {
-                       pLastPart = pMsg->msgBody.body.pMultipart;
-                       while (pLastPart->pNext) {
-                               pLastPart = pLastPart->pNext;
-                       }
+       if (szContentLocation && szContentLocation[0]) {
+               memset(pMultipart->type.szContentLocation, 0, MSG_MSG_ID_LEN + 1);
+               snprintf(pMultipart->type.szContentLocation, MSG_MSG_ID_LEN + 1, "%s", szContentLocation);
+       }
 
-                       pLastPart->pNext = pMultipart;
+       if (MmsIsTextType(mimeType) == true) {
+               if (!MmsIsVitemContent (mimeType, pMultipart->type.param.szName)) {
+                       pMultipart->type.param.charset = MSG_CHARSET_UTF8;
                }
-
-               pMsg->msgBody.size += pMultipart->pBody->size;
-               pMsg->msgType.contentSize += pMultipart->pBody->size;
+               pMultipart->type.encoding = MSG_ENCODING_8BIT;
        } else {
-               /* Single part - Insert as a message body */
-               if (pMsg->mmsAttrib.contentType != mimeType || pMsg->msgType.type != mimeType)
-                       goto __CATCH;
+               pMultipart->type.encoding = MSG_ENCODING_BINARY;
+       }
+
+       if (szOrgFilePath) {
+               strncpy(pMultipart->pBody->szOrgFilePath, szOrgFilePath, MSG_FILEPATH_LEN_MAX - 1);
+               strncpy(pMultipart->type.szOrgFilePath, szOrgFilePath, MSG_FILEPATH_LEN_MAX - 1);
+               pMultipart->pBody->offset = 0;
+               pMultipart->pBody->size = MsgGetFileSize(szOrgFilePath);
+       }
+       return pMultipart;
+}
 
-               strncpy(pMsg->msgType.param.szName, szTitleName, MSG_LOCALE_FILENAME_LEN_MAX);
+void MmsComposeNotiMessage(MmsMsg *pMmsMsg, msg_message_id_t msgID)
+{
+       MSG_BEGIN();
 
-               if (MmsIsText(pMsg->msgType.type) == true) {
-                       pMsg->msgType.param.charset = MSG_CHARSET_UTF8;
-                       if (pMultipart)
-                               pMultipart->type.encoding       = MSG_ENCODING_8BIT;
-               } else {
-                       if (pMultipart)
-                               pMultipart->type.encoding       = MSG_ENCODING_BINARY;
-               }
+       struct tm timeInfo;
+       time_t RawTime = 0;
+       time_t nTimeInSecs = 0;
 
-               strncpy(pMsg->msgBody.szOrgFilePath, szOrgFilePath, MSG_FILEPATH_LEN_MAX - 1);
-               if (MsgGetFileSize(szOrgFilePath, &nFileSize) == false) {
-                       MSG_DEBUG("MsgGetFileSize: failed");
-                       goto __CATCH;
-               }
+       MmsInitMsgAttrib(&pMmsMsg->mmsAttrib);
+       MmsInitMsgType(&pMmsMsg->msgType);
+       MmsInitMsgBody(&pMmsMsg->msgBody);
 
-               pMsg->msgBody.offset = 0;
-               pMsg->msgBody.size = nFileSize;
-               pMsg->msgType.contentSize = nFileSize;
-       }
+       pMmsMsg->msgID = msgID;
 
-       pMsg->nPartCount++;
+       pMmsMsg->mmsAttrib.version = mmsHeader.version;
 
-       return true;
+       // setting date
+       time(&RawTime);
+       localtime_r(&RawTime, &timeInfo);
+       nTimeInSecs = mktime(&timeInfo);
 
-__CATCH:
-       return false;
+       pMmsMsg->mmsAttrib.date = nTimeInSecs;
 
-}
+       pMmsMsg->mmsAttrib.bReportAllowed = (mmsHeader.reportAllowed != MMS_REPORTALLOWED_YES);
+       pMmsMsg->mmsAttrib.bAskDeliveryReport = (mmsHeader.deliveryReport != MMS_REPORT_YES);
 
-bool MmsIsMultipart(int type)
-{
-       MSG_DEBUG("MmsIsMultipart");
-       if (type == MIME_MULTIPART_RELATED ||
-               type == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED ||
-               type == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED ||
-               type == MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC ||
-               type == MIME_MULTIPART_MIXED ||
-               type == MIME_MULTIPART_REPORT) {
-               return true;
-       } else {
-               return false;
-       }
-}
+       MSG_DEBUG("######## Version = %d ########", pMmsMsg->mmsAttrib.version);
 
-bool MmsIsText(int type)
-{
-       if (type == MIME_TEXT_PLAIN ||
-               type == MIME_TEXT_HTML ||
-               type == MIME_TEXT_VND_WAP_WML ||
-               type == MIME_TEXT_X_VCARD ||
-               type == MIME_TEXT_X_VCALENDAR ||
-               type == MIME_TEXT_X_VNOTE ||
-               type == MIME_APPLICATION_SMIL ||
-               type == MIME_TEXT_X_IMELODY) {
-               MSG_DEBUG("MmsIsText true.");
-               return true;
-       } else {
-               MSG_DEBUG("MmsIsText false.");
-               return false;
+       strncpy(pMmsMsg->szTrID, mmsHeader.szTrID, MMS_TR_ID_LEN);
+       strncpy(pMmsMsg->szMsgID, mmsHeader.szMsgID, MMS_MSG_ID_LEN);
+       pMmsMsg->szForwardMsgID[0] = '\0';
+
+       if (mmsHeader.pFrom) {
+               MmsAddrUtilRemovePlmnString(mmsHeader.pFrom->szAddr );
+               strncpy(pMmsMsg->mmsAttrib.szFrom, mmsHeader.pFrom->szAddr, MSG_LOCALE_ADDR_LEN + 9);
        }
-}
 
-bool MmsIsVitemContent (int type, char *pszName)
-{
-       switch (type) {
+       strncpy(pMmsMsg->mmsAttrib.szSubject, mmsHeader.szSubject, MSG_LOCALE_SUBJ_LEN);
+       strncpy(pMmsMsg->szContentLocation, mmsHeader.szContentLocation, MMS_LOCATION_LEN);
 
-/*
-*      To make Encoding information right.
-*              case MIME_TEXT_X_VCARD :
-*              case MIME_TEXT_X_VCALENDAR :
-*              case MIME_TEXT_X_VNOTE :        // vnt
-*              {
-*                      MSG_DEBUG("MmsIsVitemContent true.");
-*                      return true;
-*              }
-*
-*/
-       case MIME_TEXT_X_VCARD:
-       case MIME_TEXT_X_VCALENDAR:
-       case MIME_TEXT_X_VNOTE: // vnt
-       case MIME_TEXT_PLAIN:           // vbm - It SHOULD be distinguished from a normal text file.
-               {
-                       char *pszExt = NULL;
-
-                       if (!pszName)
-                               break;
-
-                       // search file extension.
-                       if ((pszExt = strrchr(pszName, '.')) == NULL)
-                               break;
-
-                       if (!strcasecmp(pszExt, ".vbm")) {
-                               MSG_DEBUG("MmsIsVitemContent true.");
-                               return true;
-                       }
-               }
-               break;
+       pMmsMsg->mmsAttrib.msgClass = mmsHeader.msgClass;
+       pMmsMsg->mmsAttrib.msgSize = mmsHeader.msgSize;
+       pMmsMsg->mmsAttrib.expiryTime.type = mmsHeader.expiryTime.type;
+       pMmsMsg->mmsAttrib.expiryTime.time = mmsHeader.expiryTime.time;
+       pMmsMsg->mmsAttrib.dataType = MMS_DATATYPE_NOTIFY;
+       pMmsMsg->mmsAttrib.bRead = false;
+       pMmsMsg->mailbox = MSG_INBOX_ID;
 
-       default:
-               break;
-       }
+       pMmsMsg->mmsAttrib.replyCharge.chargeType = mmsHeader.replyCharge.chargeType;
+       pMmsMsg->mmsAttrib.replyCharge.deadLine.type = mmsHeader.replyCharge.deadLine.type;
+       pMmsMsg->mmsAttrib.replyCharge.deadLine.time = mmsHeader.replyCharge.deadLine.time;
+       pMmsMsg->mmsAttrib.replyCharge.chargeSize = mmsHeader.replyCharge.chargeSize;
 
-       MSG_DEBUG("MmsIsVitemContent false.");
-       return false;
+       strncpy(pMmsMsg->mmsAttrib.replyCharge.szChargeID, mmsHeader.replyCharge.szChargeID, MMS_MSG_ID_LEN);
+
+       MSG_END();
 }
 
-bool _MsgIsASCII(char *pszText)
+void MmsComposeReadReportMessage(MmsMsg *pMmsMsg, const MSG_MESSAGE_INFO_S *pMsgInfo, msg_message_id_t selectedMsgId)
 {
-       int length = strlen(pszText);
-
-       for (int i = 0; i < length; ++i) {
-               if (!isascii(pszText[i])) {
-                       MSG_DEBUG("_MsgIsASCII false.");
-                       return false;
-               }
-       }
+       struct tm timeInfo;
+       time_t RawTime = 0;
+       time_t nTimeInSecs = 0;
 
-       MSG_DEBUG("_MsgIsASCII true.");
-       return true;
-}
+       MmsInitMsgAttrib(&pMmsMsg->mmsAttrib);
+       MmsInitMsgType(&pMmsMsg->msgType);
+       MmsInitMsgBody(&pMmsMsg->msgBody);
 
+       // setting mmsMsg structure
+       pMmsMsg->mailbox = pMsgInfo->folderId;
+       pMmsMsg->msgID = pMsgInfo->msgId;
 
-bool _MsgReplaceNonAscii(char *szInText, char **szOutText, char replaceChar)
-{
-       MSG_DEBUG("_MsgReplaceNonAscii");
-       int nCount = 0;
-       int index = 0;
-       int cLen = 0;
-       char *pNew = NULL;
+       memset(pMmsMsg->szTrID, 0, MMS_TR_ID_LEN + 1);
+       memset(pMmsMsg->szContentLocation, 0, MMS_LOCATION_LEN + 1);
+       memset(pMmsMsg->szForwardMsgID, 0, MMS_MSG_ID_LEN + 1);
 
-       cLen = strlen(szInText);
+       pMmsMsg->mmsAttrib.dataType = MMS_DATATYPE_DRAFT;
 
-       pNew = (char *)malloc(cLen + 1);
+       // setting date
+       time(&RawTime);
+       localtime_r(&RawTime, &timeInfo);
+       nTimeInSecs = mktime(&timeInfo);
+       pMmsMsg->mmsAttrib.date = nTimeInSecs;
 
-       if (pNew == NULL)
-               return false;
+       // setting szMsgId
+       MmsPluginStorage::instance()->getMmsMessageId(selectedMsgId, pMmsMsg);
 
-       memset(pNew, 0, cLen + 1);
+       //setting subject
+       snprintf(pMmsMsg->mmsAttrib.szSubject, sizeof(pMmsMsg->mmsAttrib.szSubject), "%s", pMsgInfo->subject);
 
-       while (*(szInText+nCount) != '\0') {
-               if (0x0001 <= *(szInText+nCount) && *(szInText+nCount) <= 0x007F) {
-                       MSG_DEBUG("_MsgReplaceNonAscii: non ascii characters (1bytes). \n");
-                       pNew[index] = szInText[nCount];
-                       nCount += 1;
-                       index += 1;
-               } else {
-                       MSG_DEBUG("_MsgReplaceNonAscii: UTF-8 characters (2bytes). \n");
-                       pNew[index] = replaceChar;
-                       nCount += 1;
-                       index +=1;
-               }
-       }
+       //setting adddress
+       MmsSetMsgAddressList(&pMmsMsg->mmsAttrib, pMsgInfo);
 
-       *szOutText = pNew;
-       return true;
+       if (pMmsMsg->mmsAttrib.szTo)
+               snprintf(pMmsMsg->mmsAttrib.szFrom, sizeof(pMmsMsg->mmsAttrib.szFrom), "%s", pMmsMsg->mmsAttrib.szTo);
 }
 
-bool _MsgIsSpace(char *pszText)
+msg_error_t MmsMakeMultipartThumbnailInfo(MMS_MULTIPART_DATA_S *pMultipart, char *thumbnail_path)
 {
-       MSG_DEBUG("_MsgIsSpace");
-       if (!pszText) {
-               MSG_DEBUG("_MsgIsSpace: pszText == NULL!\n");
-               return false;
-       }
+       if (pMultipart == NULL || thumbnail_path == NULL)
+               return MSG_ERR_NULL_POINTER;
 
-       if (strchr(pszText, ' ') != NULL)
-               return true;
-       else
-               return false;
-}
+//     if (MimeGetMainTypeString(MimeGetMimeStringFromMimeInt(pMultipart->type)) != MIME_MAINTYPE_VIDEO)
+//             return MSG_ERR_INVALID_PARAMETER;
 
-bool _MsgReplaceSpecialChar(char *szInText, char **szOutText, char specialChar)
-{
-       MSG_DEBUG("_MsgReplaceSpecialChar");
-       char *pszOutText = NULL;
-       char szBuf[10] = {0, };
-       char temp[5] = {0, };
-       int cLen = 0;
-       int i = 0;
-
-       if (!szInText) {
-               MSG_DEBUG("_MsgReplaceSpecialChar: szInText == NULL! \n");
-               return false;
-       }
+       char szFileName[MSG_FILENAME_LEN_MAX+1] = {0, };
+       char szFileNameWoExt[MSG_FILENAME_LEN_MAX+1] = {0, };
+       char thumbPath[MSG_FILEPATH_LEN_MAX+1] = {0, };
+       char *pszExt = NULL;
+       char *pszOrgFileName = NULL;
 
-       if (!szOutText)
-               return false;
+       memset(szFileName, 0x00, MSG_FILENAME_LEN_MAX+1);
+       memset(thumbPath, 0x00, MSG_FILEPATH_LEN_MAX);
 
-       cLen = strlen(szInText);
+       MSG_DEBUG("drm type = %d, %s", pMultipart->drmType, pMultipart->szFilePath);
 
-       if (specialChar == ' ') {
-               if ((pszOutText = (char *)malloc(cLen + 1)) == NULL) {
-                       MSG_DEBUG("_MsgReplaceSpecialChar : %d line. MemAlloc failed.\n", __LINE__);
-                       return false;
+       if (pMultipart->drmType == MSG_DRM_TYPE_NONE) {
+               pszOrgFileName = strrchr(pMultipart->szFilePath, '/');
+               pszExt = strrchr(pMultipart->szFilePath, '.');
+
+               if (NULL == pszOrgFileName || NULL == pszExt) {
+                       MSG_DEBUG("Fail in getting filename without extension string");
+                       return MSG_ERR_PLUGIN_STORAGE;
                }
-               memset(pszOutText, 0, cLen + 1);
 
-               *szOutText = pszOutText;
-       }
+               strncpy(szFileNameWoExt, pszOrgFileName + 1, strlen(pszOrgFileName + 1) - strlen(pszExt));
+               snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "thumb_msg_%s", szFileNameWoExt);
 
-       for (i = 0; i<cLen; i++) {
-               switch (specialChar) {
-               // changed space to '_'
-               case ' ':
-                       pszOutText[i] = (szInText[i] == specialChar) ? '_' : szInText[i];
-                       break;
+               if (!strcasecmp(pszExt, ".png")) {
+                       snprintf(thumbPath, MSG_FILEPATH_LEN_MAX, MSG_THUMBNAIL_PATH"%s.png", szFileName);
+               } else {
+                       snprintf(thumbPath, MSG_FILEPATH_LEN_MAX, MSG_THUMBNAIL_PATH"%s.jpg", szFileName);
+               }
 
-               default:
-                       if (szInText[i] != specialChar) {
-                               temp[0] = szInText[i];
-                               *szOutText = MsgStrAppend(*szOutText, temp);
-                               continue;
-                       } else {
-                               _MsgConvertCharToHex(specialChar, szBuf);
-                               *szOutText = MsgStrAppend(*szOutText, (char *)"%");
-                               *szOutText = MsgStrAppend(*szOutText, szBuf);
-                       }
-                       break;
+               if (MmsMakeImageThumbnail(pMultipart->szFilePath, thumbPath) == true) {
+                       memcpy(thumbnail_path, &thumbPath, strlen(thumbPath));
+                       MSG_DEBUG("Generated thumbnail: %s ", thumbnail_path);
+                       return MSG_SUCCESS;
+               } else {
+                       MSG_DEBUG("Fail of generating thumbnail: %s to %s", pMultipart->szFilePath, thumbPath);
                }
        }
 
-       MSG_DEBUG("_MsgReplaceSpecialChar : output text : [%s]\n", pszOutText);
-
-       return true;
+       return MSG_ERR_PLUGIN_STORAGE;
 }
 
-char *MsgStrAppend(char *szInputStr1, char *szInputStr2)
+void MmsPrintFileInfoForVLD(MMS_MESSAGE_DATA_S *pMmsMsg)
 {
-       MSG_DEBUG("MsgStrAppend");
-       char *szOutputStr = NULL;
+       MMS_PAGE_S *pPage = NULL;
+       MMS_MEDIA_S *pMedia = NULL;
 
-       if (szInputStr1 == NULL) {
-               szOutputStr = MsgStrCopy(szInputStr2);
-       } else {
-               int length1 = 0;
-               int length2 = 0;
-               length1 = MsgStrlen(szInputStr1);
-               length2 = MsgStrlen(szInputStr2);
+       if (pMmsMsg == NULL)
+               return;
 
-               szOutputStr = (char *)malloc(length1 + length2 + 1);
+       if (pMmsMsg->pageCnt > 0) {
+               for (int i = 0; i < pMmsMsg->pageCnt; i++) {
 
-               if (szOutputStr == NULL)
-                       goto __CATCH;
+                       pPage = _MsgMmsGetPage(pMmsMsg, i);
 
-               memset(szOutputStr, 0, length1 + length2 + 1);
+                       if (pPage == NULL)
+                               continue;
 
-               strncpy(szOutputStr, szInputStr1, length1);
+                       for (int j = 0; j < pPage->mediaCnt; j++) {
 
-               if (length2 > 0)
-                       strcat(szOutputStr, szInputStr2);
+                               pMedia = _MsgMmsGetMedia(pPage, j);
+                               if (pMedia == NULL)
+                                       continue;
 
-               free(szInputStr1);
-               szInputStr1 = NULL;
+                               MSG_MMS_VLD_FILE("[%s], %d", pMedia->szFilePath, MsgGetFileSize(pMedia->szFilePath));
+                       }
+               }
        }
 
-       return szOutputStr;
-
-__CATCH:
-       return NULL;
+       int attachCnt = _MsgMmsGetAttachCount(pMmsMsg);
+       if (attachCnt > 0) {
+               for (int i = 0; i < pMmsMsg->attachCnt; i++) {
+               MMS_ATTACH_S *pAttach = _MsgMmsGetAttachment(pMmsMsg, i);
+               MSG_MMS_VLD_FILE("[%s], %d", pAttach->szFilePath, MsgGetFileSize(pAttach->szFilePath));
+               }
+       }
 }
 
-char *MsgStrCopy(const char *string)
+bool IsMatchedMedia(MMS_MEDIA_S *media, MMS_MULTIPART_DATA_S *pMultipart)
 {
-       char *pDst = NULL;
+       if (strlen(pMultipart->szContentID) > 0) {
 
-       if (string) {
-               pDst = (char *)malloc(1 + strlen(string));
-               if (pDst == NULL) {
-                       MSG_DEBUG("MsgStrCopy: pDst MemAlloc Fail \n");
-                       return NULL;
+               char szTempContentID[MSG_MSG_ID_LEN + 1] = {0,};
+               MmsRemoveLessGreaterChar(pMultipart->szContentID, szTempContentID, sizeof(szTempContentID));
+
+               if (strcmp(media->szContentID,  szTempContentID) == 0) {
+                       return true;
                }
 
-               memset(pDst, 0, strlen(string) + 1);
+               if (strcmp(media->szContentLocation,  szTempContentID) == 0) {
+                       return true;
+               }
+       }
 
-               strcpy(pDst,string);
+       if (strlen(pMultipart->szContentLocation) > 0) {
+               if (strcmp(media->szContentID,  pMultipart->szContentLocation) == 0) {
+                       return true;
+               }
 
-               return pDst;
+               if (strcmp(media->szContentLocation,  pMultipart->szContentLocation) == 0) {
+                       return true;
+               }
        }
 
-       return NULL;
+       MSG_DEBUG("There is not matched media cid [%s], cl, [%s], multipart cid [%s], cl, [%s]", media->szContentID, media->szContentLocation, pMultipart->szContentID, pMultipart->szContentLocation);
+       return false;
 }
 
-char *MsgStrNCopy(const char *string, int length)
+MsgMultipart *MmsGetNthMultipart(MmsMsg *pMsg, int index)
 {
-       char *pDst = NULL;
+       MsgMultipart *pPart = NULL;
 
-       if (string) {
-               pDst = (char *)malloc(1 + length);
-               if (pDst == NULL) {
-                       MSG_DEBUG("MsgStrNCopy: pDst MemAlloc Fail \n");
-                       return NULL;
-               }
+       if (MsgIsMultipart(pMsg->msgType.type) == true) {
+
+               pPart = pMsg->msgBody.body.pMultipart;
 
-               memset(pDst, 0, length + 1);
-               strncpy(pDst,string, length);
+               while (pPart && index--) {
+                       pPart = pPart->pNext;
+               }
 
-               return pDst;
+               if (pPart == NULL) {
+                       MSG_DEBUG("There is no such Multipart [index = %d].", index);
+                       return NULL;
+               } else {
+                       return pPart;
+               }
+       } else {
+               MSG_DEBUG("This Msg is not Multipart");
        }
 
        return NULL;
 }
 
-int MsgStrlen(char * pStr)
+bool MmsFindAndInsertPart(MMS_MESSAGE_DATA_S *pMsgData, MMS_MULTIPART_DATA_S *pMultipart)
 {
-       if (pStr == NULL)
-               return 0;
+       bool insert_media = false;
 
-       return strlen(pStr);
-}
+       if (pMsgData->pagelist) {
+               for (int pageIdx = 0; pageIdx < pMsgData->pageCnt; pageIdx++) {
 
-bool _MsgConvertCharToHex(char pSrc, char *pDest)
-{
-       static unsigned char saucHex[] = "0123456789ABCDEF";
+                       MMS_PAGE_S *page = (MMS_PAGE_S *)g_list_nth_data(pMsgData->pagelist, pageIdx);
 
-       pDest[0] = saucHex[pSrc >> 4];
-       pDest[1] = saucHex[pSrc & 0xF];
-       pDest[2] = 0;
+                       if (page && page->medialist) {
 
-       return true;
-}
+                               for (int mediaIdx = 0; mediaIdx < page->mediaCnt; mediaIdx++) {
 
-MsgMultipart *MmsAllocMultipart(void)
-{
-       MsgMultipart *pMultipart = NULL;
+                                       MMS_MEDIA_S *media = (MMS_MEDIA_S *)g_list_nth_data(page->medialist, mediaIdx);
 
-       pMultipart = (MsgMultipart *)malloc(sizeof(MsgMultipart));
+                                       if (media) { // add media
+                                               if (IsMatchedMedia(media, pMultipart) == true) { //matched media
 
-       if (pMultipart == NULL)
-               goto __CATCH;
-
-       pMultipart->pBody = (MsgBody *)malloc(sizeof(MsgBody));
-
-       if (pMultipart == NULL)
-               goto __CATCH;
+//                                                     if (media->mediatype == MMS_SMIL_MEDIA_IMG_OR_VIDEO) { // ref type is not insert part
+//                                                             MSG_DEBUG("## Matched but media type is ref ##");
+//                                                             return false;
+//                                                     }
 
-       MmsInitMsgType(&pMultipart->type);
-       MmsInitMsgBody(pMultipart->pBody);
+                                                       insert_media = true;
+                                                       media->drmType = pMultipart->drmType;
+                                                       snprintf(media->szFilePath, sizeof(media->szFilePath), "%s", pMultipart->szFilePath);
+                                                       snprintf(media->szFileName, sizeof(media->szFileName), "%s", pMultipart->szFileName);
+                                                       snprintf(media->szContentID, sizeof(media->szContentID), "%s", pMultipart->szContentID);
+                                                       snprintf(media->szContentLocation, sizeof(media->szContentLocation), "%s", pMultipart->szContentLocation);
+                                                       snprintf(media->szContentType, sizeof(media->szContentType), "%s", pMultipart->szContentType);
 
-       pMultipart->pNext = NULL;
+                                                       MSG_SEC_DEBUG("InsertPart to pageIndx [%d] mediaIdx[%d] media[%p] : path = [%s], name = [%s], cid = [%s], cl = [%s], ct = [%s]"\
+                                                                       , pageIdx, mediaIdx, media, media->szFilePath, media->szFileName, media->szContentID, media->szContentLocation, media->szContentType);
+                                               }
+                                       }
+                               } //end for media list
+                       }
+               } //end for page list
+       }
 
-       return pMultipart;
+       return insert_media;
+}
 
-__CATCH:
+bool MmsInsertPartToMmsData(MMS_MESSAGE_DATA_S *pMsgData, MMS_MULTIPART_DATA_S *pMultipart)
+{
+       MSG_BEGIN();
 
-       if (pMultipart) {
-               if (pMultipart->pBody) {
-                       free(pMultipart->pBody);
-                       pMultipart->pBody = NULL;
-               }
+       bool isInsert = false;
 
-               free(pMultipart);
-               pMultipart = NULL;
+       if (pMsgData == NULL || pMultipart == NULL) {
+               return false;
        }
 
-       return NULL;
-}
+       isInsert = MmsFindAndInsertPart(pMsgData, pMultipart);
 
+       if (isInsert == false) {
+               MMS_ATTACH_S *attachment = NULL;
+               attachment = (MMS_ATTACH_S *)calloc(sizeof(MMS_ATTACH_S), 1);
+               if (attachment) {
+                       attachment->drmType = pMultipart->drmType;
 
+                       if (strlen(pMultipart->szContentType) > 0) {
+                               snprintf(attachment->szContentType, sizeof(attachment->szContentType), "%s", pMultipart->szContentType);
+                               attachment->mediatype =  pMultipart->type;
+                       }
 
-MsgMultipart *MmsMakeMultipart(MsgContentType mimeType, char *szTitleName, char *szOrgFilePath, void *pData, int offset, int size, char *szContentID)
-{
-       MsgMultipart *pMultipart = NULL;
+                       snprintf(attachment->szFilePath, sizeof(attachment->szFilePath), "%s", pMultipart->szFilePath);
+                       snprintf(attachment->szFileName, sizeof(attachment->szFileName), "%s", pMultipart->szFileName);
+                       attachment->fileSize = MsgGetFileSize(attachment->szFilePath);
 
-       if ((pMultipart = MmsAllocMultipart()) == NULL)
-               goto __CATCH;
-
-       pMultipart->type.type = mimeType;
+                       MSG_SEC_DEBUG("Insert Attach to attachment[%p] : path = [%s], name = [%s], ct = [%s], size = [%d]"\
+                                                       , attachment, attachment->szFilePath, attachment->szFileName, attachment->szContentType, attachment->fileSize);
 
-       if (szTitleName && szTitleName[0]) {
-               memset(pMultipart->type.param.szName, 0, MSG_LOCALE_FILENAME_LEN_MAX + 1);
-               strncpy(pMultipart->type.param.szName, szTitleName, MSG_LOCALE_FILENAME_LEN_MAX);
+                       if (_MsgMmsAddAttachment(pMsgData, attachment) != MSG_SUCCESS) {
+                               g_free(attachment);
+                               return false;
+                       }
+               } else {
+                       return false;
+               }
        }
 
-       if (szContentID && szContentID[0]) {
-               memset(pMultipart->type.szContentID, 0, MSG_MSG_ID_LEN + 1);
-               snprintf(pMultipart->type.szContentID, MSG_MSG_ID_LEN + 1, "<%s>", szContentID);
+       MSG_END();
+       return true;
+}
 
-               memset(pMultipart->type.szContentLocation, 0, MSG_MSG_ID_LEN + 1);
-               snprintf(pMultipart->type.szContentLocation, MSG_MSG_ID_LEN + 1, "%s", szContentID);
-       }
+bool MmsInsertMixedPartToMmsData(MMS_MESSAGE_DATA_S *pMsgData, MMS_MULTIPART_DATA_S *pMultipart)
+{
+       MSG_BEGIN();
 
-       if (MmsIsText(mimeType) == true) {
-               if (!MmsIsVitemContent (mimeType, pMultipart->type.param.szName)) {
-                       pMultipart->type.param.charset = MSG_CHARSET_UTF8;
-               }
-               pMultipart->type.encoding = MSG_ENCODING_8BIT;
-       } else {
-               pMultipart->type.encoding = MSG_ENCODING_BINARY;
+       if (pMsgData == NULL || pMultipart == NULL) {
+               return false;
        }
 
-       if (szOrgFilePath == NULL) {
-               if (pData != NULL) {
-                       if (MmsIsText(mimeType) == true) {
-                               pMultipart->pBody->body.pText = (char *)malloc(size + 1);
-                               if (pMultipart->pBody->body.pText == NULL)
-                                       goto __CATCH;
+       MimeMainType mainType = MimeGetMainTypeInt(pMultipart->type);
+       MmsSmilMediaType mediatype = MMS_SMIL_MEDIA_INVALID;
 
-                               memset(pMultipart->pBody->body.pText, 0, size + 1);
-                       } else {
-                               pMultipart->pBody->body.pBinary = malloc(size);
-                               if (pMultipart->pBody->body.pBinary == NULL)
-                                       goto __CATCH;
+       switch(mainType) {
+       case MIME_MAINTYPE_AUDIO:
+               mediatype = MMS_SMIL_MEDIA_AUDIO;
+               break;
+       case MIME_MAINTYPE_IMAGE:
+               mediatype = MMS_SMIL_MEDIA_IMG;
+               break;
+       case MIME_MAINTYPE_TEXT:
+               mediatype = MMS_SMIL_MEDIA_TEXT;
+               break;
+       case MIME_MAINTYPE_VIDEO:
+               mediatype = MMS_SMIL_MEDIA_VIDEO;
+               break;
+       default :
+               mediatype = MMS_SMIL_MEDIA_INVALID;
+               break;
+       }
 
-                               memset(pMultipart->pBody->body.pBinary, 0, size);
+       if (mediatype != MMS_SMIL_MEDIA_INVALID) {
+               MMS_PAGE_S *pPage = (MMS_PAGE_S *)calloc(1, sizeof(MMS_PAGE_S));
+               MMS_MEDIA_S *media = (MMS_MEDIA_S *)calloc(1, sizeof(MMS_MEDIA_S));
+               if (pPage && media) {
+                       media->mediatype = mediatype;
+                       media->drmType = pMultipart->drmType;
+                       snprintf(media->szFilePath, sizeof(media->szFilePath), "%s", pMultipart->szFilePath);
+                       snprintf(media->szFileName, sizeof(media->szFileName), "%s", pMultipart->szFileName);
+                       snprintf(media->szContentID, sizeof(media->szContentID), "%s", pMultipart->szContentID);
+                       snprintf(media->szContentLocation, sizeof(media->szContentLocation), "%s", pMultipart->szContentLocation);
+                       snprintf(media->szContentType, sizeof(media->szContentType), "%s", pMultipart->szContentType);
+
+                       MSG_SEC_DEBUG("InsertPart to media[%p] type[%d] : path = [%s], name = [%s], cid = [%s], cl = [%s], ct = [%s]"\
+                                       , media, mediatype,  media->szFilePath, media->szFileName, media->szContentID, media->szContentLocation, media->szContentType);
+
+                       if (_MsgMmsAddMedia(pPage, media) != MSG_SUCCESS) {
+                               g_free(pPage);
+                               g_free(media);
+                               return false;
                        }
 
-                       memcpy(pMultipart->pBody->body.pBinary, pData, size);
-                       pMultipart->pBody->size = size;
+                       if (_MsgMmsAddPage(pMsgData, pPage) != MSG_SUCCESS) {
+                               g_free(pPage);
+                               g_free(media);
+                               return false;
+                       }
+               } else {
+                       if (pPage) g_free(pPage);
+                       if (media) g_free(media);
+                       return false;
                }
        } else {
-               if (szOrgFilePath)
-                       strncpy(pMultipart->pBody->szOrgFilePath, szOrgFilePath, MSG_FILEPATH_LEN_MAX - 1);
-
-               pMultipart->pBody->offset = offset;
-               pMultipart->pBody->size = size;
-       }
-
-       return pMultipart;
-
-__CATCH:
-
-       if (pMultipart) {
-               if (pMultipart->pBody) {
-                       if (pMultipart->pBody->body.pText) {
-                               free(pMultipart->pBody->body.pText);
-                               pMultipart->pBody->body.pText = NULL;
+               MMS_ATTACH_S *attachment = NULL;
+               attachment = (MMS_ATTACH_S *)calloc(sizeof(MMS_ATTACH_S), 1);
+               if (attachment) {
+                       attachment->mediatype =  pMultipart->type;
+                       attachment->drmType = pMultipart->drmType;
+                       snprintf(attachment->szContentType, sizeof(attachment->szContentType), "%s", pMultipart->szContentType);
+                       snprintf(attachment->szFilePath, sizeof(attachment->szFilePath), "%s", pMultipart->szFilePath);
+                       snprintf(attachment->szFileName, sizeof(attachment->szFileName), "%s", pMultipart->szFileName);
+                       attachment->fileSize = MsgGetFileSize(attachment->szFilePath);
+                       MSG_SEC_DEBUG("Insert Attach to attachment[%p] : path = [%s], name = [%s], ct = [%s], size = [%d]"\
+                                                       , attachment, attachment->szFilePath, attachment->szFileName, attachment->szContentType, attachment->fileSize);
+
+                       if (_MsgMmsAddAttachment(pMsgData, attachment) != MSG_SUCCESS) {
+                               g_free(attachment);
+                               return false;
                        }
-                       free(pMultipart->pBody);
-                       pMultipart->pBody = NULL;
+               } else {
+                       return false;
                }
-               free(pMultipart);
-               pMultipart = NULL;
        }
 
-       return NULL;
+       MSG_END();
+       return true;
 }
 
-
-bool MmsGetTypeByFileName(int *type, char *szFileName)
+bool MmsInsertPartFromMultipart(MmsMsg *pMsg, MMS_MULTIPART_DATA_S *pNewMultipart)
 {
-       char *pExt   = NULL;
-       AvCodecType AvType = AV_CODEC_NONE;
+       MsgMultipart *pMultipart = NULL;
+       MsgMultipart *pLastPart = NULL;
 
-       /* AVMS unknown or text/image file format identify type from file extention  */
+       if (MmsIsMultipart(pMsg->msgType.type) == true) {
+               /* Insert as a multipart */
+               pMultipart = MmsMakeMultipart(pNewMultipart->type, pNewMultipart->szFileName, pNewMultipart->szFilePath, pNewMultipart->szContentID, pNewMultipart->szContentLocation);
 
-       pExt = strrchr(szFileName, '.');
-       if (pExt == NULL || pExt[0] == '\0')
-               goto __CATCH;
+               if (pMultipart == NULL)
+                       goto __CATCH;
 
-       pExt++;
+               if (pMsg->mmsAttrib.contentType == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED ||
+                       pMsg->mmsAttrib.contentType == MIME_MULTIPART_MIXED)
+                       pMultipart->type.disposition = MSG_DISPOSITION_ATTACHMENT;
 
-       if (strcasecmp(pExt, "mp4") == 0 || strcasecmp(pExt, "mpeg4") == 0 ||
-               strcasecmp(pExt, "3gp") == 0 || strcasecmp(pExt, "3gpp") == 0) {
-               /* Audio / Video format. If file exists already, AvGetFileCodecType() can identify the format  */
-               if (szFileName[0] != '/')
-                       goto __CATCH;
+               if (pMsg->msgBody.body.pMultipart == NULL) {
+                       pMsg->msgBody.body.pMultipart = pMultipart;
+               } else {
+                       pLastPart = pMsg->msgBody.body.pMultipart;
+                       while (pLastPart->pNext) {
+                               pLastPart = pLastPart->pNext;
+                       }
 
-               AvType = AvGetFileCodecType(szFileName);
+                       pLastPart->pNext = pMultipart;
+               }
 
-               switch (AvType) {
-               case AV_DEC_AUDIO_MPEG4:
-                       *type = MIME_AUDIO_MP4;//*type = MIME_AUDIO_3GPP;
-                       break;
+               pMsg->msgBody.size += pMultipart->pBody->size;
+               pMsg->msgType.contentSize += pMultipart->pBody->size;
+       } else {
+               /* Single part - Insert as a message body */
+               if (pMsg->mmsAttrib.contentType != pNewMultipart->type || pMsg->msgType.type != pNewMultipart->type)
+                       goto __CATCH;
 
-               case AV_DEC_VIDEO_MPEG4:
-                       *type = MIME_VIDEO_MP4;
-                       break;
+               strncpy(pMsg->msgType.param.szName, pNewMultipart->szFileName, MSG_LOCALE_FILENAME_LEN_MAX);
 
-               default:
-                       *type = MIME_VIDEO_3GPP;
-                       break;
+               if (MmsIsTextType(pMsg->msgType.type) == true) {
+                       pMsg->msgType.param.charset = MSG_CHARSET_UTF8;
                }
-               return true;
-       }
 
-       if (strcasecmp(pExt, "amr") == 0) {
-               *type = MIME_AUDIO_AMR;
-               return true;
-       } else if ((strcasecmp(pExt, "mid") == 0) || (strcasecmp(pExt, "midi") == 0)) {
-               *type = MIME_AUDIO_MIDI;
-               return true;
-       } else if (strcasecmp(pExt, "imy") == 0) {
-               *type = MIME_TEXT_X_IMELODY;
-               return true;
+               strncpy(pMsg->msgBody.szOrgFilePath, pNewMultipart->szFilePath, MSG_FILEPATH_LEN_MAX - 1);
+               pMsg->msgBody.offset = 0;
+               pMsg->msgBody.size = MsgGetFileSize(pNewMultipart->szFilePath);
+               pMsg->msgType.contentSize = MsgGetFileSize(pNewMultipart->szFilePath);
        }
 
-       *type = MimeGetMimeFromExtInt((const char *)pExt);
+       pMsg->nPartCount++;
 
        return true;
 
 __CATCH:
-
-       *type = MIME_UNKNOWN;
        return false;
 
 }
 
-bool MmsComposeMessage(MmsMsg *pMmsMsg, MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_MESSAGE_DATA_S *pMsgData, char *pFileData)
+bool MmsConvertMsgData(MmsMsg *pMsg, MMS_MESSAGE_DATA_S *pMmsMsg)
 {
        MSG_BEGIN();
 
-       char *pRawData = NULL;
-       AutoPtr<char> buf(&pRawData);
+       //bzero(pMmsMsg, sizeof(MMS_MESSAGE_DATA_S));
+       pMmsMsg->regionCnt = 0;
+       pMmsMsg->pageCnt = 0;
+       pMmsMsg->attachCnt = 0;
+       pMmsMsg->transitionCnt = 0;
+       pMmsMsg->metaCnt = 0;
+       memset(pMmsMsg->szSmilFilePath, 0, MSG_FILEPATH_LEN_MAX);
+
+       if (pMsg->mmsAttrib.contentType == MIME_MULTIPART_RELATED || pMsg->mmsAttrib.contentType == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
+               char *pSmilDoc = NULL;
+               if (pMsg->msgBody.pPresentationBody) {
+                       if (pMsg->msgBody.pPresentationBody->body.pText) {
+                               pSmilDoc = pMsg->msgBody.pPresentationBody->body.pText;
+                               if (pSmilDoc) {
+                                       MsgSmilParseSmilDoc(pMmsMsg, pSmilDoc);
+                               }
 
-       struct tm *timeInfo = NULL;
-       time_t RawTime = 0;
-       time_t nTimeInSecs = 0;
+                               pMmsMsg->smil.type = MIME_APPLICATION_SMIL;
+                               snprintf(pMmsMsg->smil.szContentType, MSG_MSG_ID_LEN, "%s", MimeGetMimeStringFromMimeInt(pMsg->msgBody.presentationType.type));
+                               snprintf(pMmsMsg->smil.szContentID, MSG_MSG_ID_LEN, "%s", pMsg->msgBody.presentationType.szContentID);
+                               snprintf(pMmsMsg->smil.szContentLocation, MSG_MSG_ID_LEN, "%s", pMsg->msgBody.presentationType.szContentLocation);
+                               snprintf(pMmsMsg->smil.szFileName, MSG_FILENAME_LEN_MAX, "%s", pMsg->msgBody.presentationType.param.szName);
+                               snprintf(pMmsMsg->smil.szFilePath, MSG_FILEPATH_LEN_MAX, "%s%s", MSG_DATA_PATH, pMsg->msgBody.presentationType.param.szFileName);
+                       }
+               } else {
+                       MSG_DEBUG("Not Exist pPresentationBody");
+               }
+       }
 
-       msg_error_t     err = MSG_SUCCESS;
+       /*If mms content type is TEXTPLAN add to First Page*/
+       if (pMsg->mmsAttrib.contentType == MIME_TEXT_PLAIN) {
+               MsgType partHeader;
+               int partCnt = pMsg->nPartCount;
 
-       // Initialize mmsMsg structure
-       MmsInitMsgAttrib(&pMmsMsg->mmsAttrib);
-       MmsInitMsgType(&pMmsMsg->msgType);
-       MmsInitMsgBody(&pMmsMsg->msgBody);
+               if (partCnt <= 0) {
+                       MSG_DEBUG("partCnt=%d\n", partCnt );
+               } else {
 
-       // setting mmsMsg structure
-       pMmsMsg->mailbox = pMsgInfo->folderId;
-       pMmsMsg->msgID = pMsgInfo->msgId;
+                       if (MmsGetMediaPartHeader(0, &partHeader) == false) {
+                               MSG_DEBUG("Failed to get MediaPart MmsGetMediaPartHeader" );
+                               goto FREE_CATCH;
+                       }
 
-       memset(pMmsMsg->szTrID, 0, MMS_TR_ID_LEN + 1);
-       memset(pMmsMsg->szContentLocation, 0, MMS_LOCATION_LEN + 1);
-       memset(pMmsMsg->szMsgID, 0, MMS_MSG_ID_LEN + 1);
-       memset(pMmsMsg->szForwardMsgID, 0, MMS_MSG_ID_LEN + 1);
+                       if (partHeader.contentSize > 0) {
+                               char szBuf[MSG_FILEPATH_LEN_MAX + 1] = {0,};
+                               MMS_PAGE_S *page = NULL;
+                               MMS_MEDIA_S *media = NULL;
 
-       pMmsMsg->mmsAttrib.dataType = MMS_DATATYPE_DRAFT;
+                               snprintf(szBuf, sizeof(szBuf), "%s", partHeader.param.szFileName);
+                               snprintf(partHeader.param.szFileName, sizeof(partHeader.param.szFileName), "%s%s", MSG_DATA_PATH, szBuf);
 
-       MSG_DEBUG("## delivery = %d ##", pSendOptInfo->bDeliverReq);
-       MSG_DEBUG("## read = %d ##", pSendOptInfo->option.mmsSendOptInfo.bReadReq);
-       MSG_DEBUG("## priority = %d ##", pSendOptInfo->option.mmsSendOptInfo.priority);
-       MSG_DEBUG("## expiryTime = %d ##", pSendOptInfo->option.mmsSendOptInfo.expiryTime.time);
+                               page =  (MMS_PAGE_S *)calloc(1, sizeof(MMS_PAGE_S));
+                               if (page == NULL) {
+                                       MSG_FATAL("page allocation error");
+                                       goto FREE_CATCH;
+                               }
 
-       if (pSendOptInfo->bSetting == false) {
-               unsigned int expiryTime;
-               MSG_MMS_DELIVERY_TIME_T deliveryTime;
+                               media = (MMS_MEDIA_S *)calloc(1, sizeof(MMS_MEDIA_S));
+                               if (media == NULL) {
+                                       MSG_FATAL("media allocation error");
+                                       free(page);
+                                       goto FREE_CATCH;
+                               }
 
-               pMmsMsg->mmsAttrib.priority = (MmsPriority)MsgSettingGetInt(MMS_SEND_PRIORITY);
+                               media->mediatype = MMS_SMIL_MEDIA_TEXT;
+                               snprintf(media->szFilePath, sizeof(media->szFilePath), "%s", partHeader.param.szFileName);
+                               snprintf(media->szFileName, sizeof(media->szFileName), "%s", partHeader.param.szName);
+                               snprintf(media->szContentID, sizeof(media->szContentID), "%s", partHeader.szContentID);
+                               snprintf(media->szContentLocation, sizeof(media->szContentLocation), "%s", partHeader.szContentLocation);
 
-               MsgSettingGetBool(MMS_SEND_DELIVERY_REPORT, &pMmsMsg->mmsAttrib.bAskDeliveryReport);
-               MsgSettingGetBool(MMS_SEND_READ_REPLY, &pMmsMsg->mmsAttrib.bAskReadReply);
-               MsgSettingGetBool(MSG_KEEP_COPY, &pMmsMsg->mmsAttrib.bLeaveCopy);
+                               _MsgMmsAddMedia(page, media);
 
-               expiryTime = (unsigned int)MsgSettingGetInt(MMS_SEND_EXPIRY_TIME);
+                               _MsgMmsAddPage(pMmsMsg, page);
+                       }
 
-               if (expiryTime == 0)
-                       pMmsMsg->mmsAttrib.expiryTime.type = MMS_TIMETYPE_NONE;
-               else {
-                       pMmsMsg->mmsAttrib.expiryTime.type = MMS_TIMETYPE_RELATIVE;
-                       pMmsMsg->mmsAttrib.expiryTime.time = expiryTime;
                }
+       } else {
 
-               deliveryTime = (MSG_MMS_DELIVERY_TIME_T)MsgSettingGetInt(MMS_SEND_DELIVERY_TIME);
+               int partCnt = pMsg->nPartCount;
 
-               if (deliveryTime == MSG_DELIVERY_TIME_CUSTOM) {
-                       pMmsMsg->mmsAttrib.bUseDeliveryCustomTime = true;
+               for (int i = 0; i < partCnt; ++i) {
 
-                       pMmsMsg->mmsAttrib.deliveryTime.type = MMS_TIMETYPE_RELATIVE;
-                       pMmsMsg->mmsAttrib.deliveryTime.time = (unsigned int)MsgSettingGetInt(MMS_SEND_CUSTOM_DELIVERY);
-               } else {
-                       pMmsMsg->mmsAttrib.bUseDeliveryCustomTime = false;
+                       MsgMultipart *multipart = MmsGetNthMultipart(pMsg, i);
+                       MMS_MULTIPART_DATA_S pMultipart;
+
+                       if (multipart == NULL) {
+                               MSG_DEBUG("multipart is NULL [%d]", i);
+                               goto FREE_CATCH;
+                       }
+
+                       bzero(&pMultipart, sizeof(MMS_MULTIPART_DATA_S));
+
+                       pMultipart.type = (MimeType)multipart->type.type;
+                       MSG_DEBUG("Mime Type : %s :%d", MimeGetMimeStringFromMimeInt(multipart->type.type), multipart->type.type);
+                       snprintf(pMultipart.szContentID, sizeof(pMultipart.szContentID), "%s", multipart->type.szContentID);
+                       snprintf(pMultipart.szContentLocation, sizeof(pMultipart.szContentLocation), "%s", multipart->type.szContentLocation);
+                       snprintf(pMultipart.szFileName, sizeof(pMultipart.szFileName), "%s", multipart->type.param.szName);
+                       snprintf(pMultipart.szFilePath, sizeof(pMultipart.szFilePath), "%s", multipart->pBody->szOrgFilePath);
+                       snprintf(pMultipart.szContentType, sizeof(pMultipart.szContentType), "%s",MimeGetMimeStringFromMimeInt(multipart->type.type));
+
+                       if (multipart->type.drmInfo.drmType != MSG_DRM_TYPE_NONE) {
+                               pMultipart.drmType = multipart->type.drmInfo.drmType;
+                       }
 
-                       pMmsMsg->mmsAttrib.deliveryTime.type = MMS_TIMETYPE_RELATIVE;
-                       pMmsMsg->mmsAttrib.deliveryTime.time = (unsigned int)deliveryTime;
+                       _MsgMmsMultipartPrint(&pMultipart);
+
+                       if (pMsg->mmsAttrib.contentType == MIME_MULTIPART_RELATED || pMsg->mmsAttrib.contentType == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
+                               if (MmsInsertPartToMmsData(pMmsMsg, &pMultipart) == false) {
+                                       MSG_DEBUG("Fail to MmsSetMultipartToMmsData");
+                                       goto FREE_CATCH;
+                               }
+                       } else {
+                               if (MmsInsertMixedPartToMmsData(pMmsMsg, &pMultipart) == false) {
+                                       MSG_DEBUG("Fail to MmsSetMultipartToMmsData");
+                                       goto FREE_CATCH;
+                               }
+                       }
                }
-       } else {
-               pMmsMsg->mmsAttrib.priority = (MmsPriority)pSendOptInfo->option.mmsSendOptInfo.priority;
-               pMmsMsg->mmsAttrib.bAskDeliveryReport = pSendOptInfo->bDeliverReq;
-               pMmsMsg->mmsAttrib.bAskReadReply = pSendOptInfo->option.mmsSendOptInfo.bReadReq;
-               pMmsMsg->mmsAttrib.expiryTime.type = pSendOptInfo->option.mmsSendOptInfo.expiryTime.type;
-               pMmsMsg->mmsAttrib.bLeaveCopy = pSendOptInfo->bKeepCopy;
-
-               if (pMmsMsg->mmsAttrib.expiryTime.type != MMS_TIMETYPE_NONE)
-                       pMmsMsg->mmsAttrib.expiryTime.time = pSendOptInfo->option.mmsSendOptInfo.expiryTime.time;
-
-               pMmsMsg->mmsAttrib.bUseDeliveryCustomTime = pSendOptInfo->option.mmsSendOptInfo.bUseDeliveryCustomTime;
-               pMmsMsg->mmsAttrib.deliveryTime.type = pSendOptInfo->option.mmsSendOptInfo.deliveryTime.type;
-               pMmsMsg->mmsAttrib.deliveryTime.time = pSendOptInfo->option.mmsSendOptInfo.deliveryTime.time;
        }
 
-       MSG_DEBUG("pSendOptInfo->bSetting = %d", pSendOptInfo->bSetting);
-       MSG_DEBUG("pMmsMsg->mmsAttrib.bLeaveCopy = %d", pMmsMsg->mmsAttrib.bLeaveCopy);
-       MSG_DEBUG("pMmsMsg->mmsAttrib.bUseDeliveryCustomTime = %d", pMmsMsg->mmsAttrib.bUseDeliveryCustomTime);
-       MSG_DEBUG("pMmsMsg->mmsAttrib.deliveryTime.type = %d", pMmsMsg->mmsAttrib.deliveryTime.type);
-       MSG_DEBUG("pMmsMsg->mmsAttrib.deliveryTime.time = %d", pMmsMsg->mmsAttrib.deliveryTime.time);
-
-       /* MMS-1.3-con-739 */
-       pMmsMsg->mmsAttrib.msgClass = (MmsMsgClass)MsgSettingGetInt(MMS_SEND_MSG_CLASS);
-       /* MMS-1.3-con-739 */
-#ifdef MMS_13_CON_742_ENABLED
-       /* MMS-1.3-con-742 */
-       pMmsMsg->mmsAttrib.deliveryTime.time = (unsigned int)MsgSettingGetInt(MMS_SEND_DELIVERY_TIME);
-       /* MMS-1.3-con-742 */
-#endif
+       _MsgMmsRemoveEmptyObject(pMmsMsg);
 
-       MSG_DEBUG("@@@ pMmsMsg->mmsAttrib.bAskDeliveryReport = %d @@@", pMmsMsg->mmsAttrib.bAskDeliveryReport);
-       MSG_DEBUG("@@@ pMmsMsg->mmsAttrib.bAskReadReply = %d @@@", pMmsMsg->mmsAttrib.bAskReadReply);
-       MSG_DEBUG("@@@ pMmsMsg->mmsAttrib.priority = %d @@@", pMmsMsg->mmsAttrib.priority);
+       MSG_END();
+       return true;
+FREE_CATCH:
+       return false;
+}
 
-       // setting date
-       time(&RawTime);
-       timeInfo = localtime(&RawTime);
-       nTimeInSecs = mktime(timeInfo);
-       pMmsMsg->mmsAttrib.date = nTimeInSecs;
+void MmsPrintMmsMsg(const MmsMsg *pMmsMsg)
+{
+       MmsMsgType msgType = pMmsMsg->mmsAttrib.msgType;
+       if (msgType == MMS_MSGTYPE_SEND_REQ) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_SEND_REQ");
+       } else if (msgType == MMS_MSGTYPE_SEND_CONF) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_SEND_CONF");
+       } else if (msgType == MMS_MSGTYPE_NOTIFICATION_IND) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_NOTIFICATION_IND");
+       } else if (msgType == MMS_MSGTYPE_NOTIFYRESP_IND) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_NOTIFYRESP_IND");
+       } else if (msgType == MMS_MSGTYPE_RETRIEVE_CONF) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_RETRIEVE_CONF");
+       } else if (msgType == MMS_MSGTYPE_ACKNOWLEDGE_IND) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_ACKNOWLEDGE_IND");
+       } else if (msgType == MMS_MSGTYPE_DELIVERY_IND) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_DELIVERY_IND");
+       } else if (msgType == MMS_MSGTYPE_READREC_IND) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_READREC_IND");
+       } else if (msgType == MMS_MSGTYPE_READORG_IND) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_READORG_IND");
+       } else if (msgType == MMS_MSGTYPE_FORWARD_REQ) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_FORWARD_REQ");
+       } else if (msgType == MMS_MSGTYPE_FORWARD_CONF) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_FORWARD_CONF");
+       } else if (msgType == MMS_MSGTYPE_READ_REPLY) {
+               PRINT_KEY_VAL_STR("mms type", "MMS_MSGTYPE_READ_REPLY");
+       } else {
+               PRINT_KEY_VAL_STR("mms type", "Unknown");
+       }
 
-       //setting subject
-       strcpy(pMmsMsg->mmsAttrib.szSubject, pMsgInfo->subject);
+       PRINT_KEY_VAL_STR("mms ver", pMmsMsg->mmsAttrib.version);
 
-       //setting adddress
-       MmsSetMsgAddressList(&pMmsMsg->mmsAttrib, pMsgInfo);
-       MmsGetMsgBodyfromMsgInfo(pMsgInfo, pMsgData, pFileData);
+}
 
-       int pageCnt = _MsgMmsGetPageCount(pMsgData);
+int MmsUpdateMultipartList(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+       MMSList *multipart_list = NULL;
 
-       if (pageCnt == 0) {     // Multipart mixed
-               pMmsMsg->mmsAttrib.contentType = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED;
-               pMmsMsg->msgType.type = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED;
-       } else {        // Multipart related
+       if (MmsPluginStorage::instance()->getMultipartList(pMsgInfo->msgId, &multipart_list) != MSG_SUCCESS)
+               return -1;
 
-               int RawDataSize = 0;
+       for (int i = 0; i < (int)g_list_length(multipart_list); i++) {
+               MMS_MULTIPART_DATA_S *pMultipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(multipart_list, i);
+               MmsPluginStorage::instance()->updateMultipart(pMsgInfo->msgId, true, pMultipart);
+       }
 
-               time_t RawTime = 0;
-               time(&RawTime);
-               snprintf(pMsgData->szSmilFilePath, MSG_FILEPATH_LEN_MAX, "%lu", RawTime);
+       MSG_END();
+       return 0;
+}
 
-               MsgMMSCreateSMIL(pMsgData);
+int MmsUpdatePreviewData(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
 
-               RawDataSize = MmsGetSmilRawData(pMsgData, &pRawData);
-               if (RawDataSize < 0) {
-                       MSG_DEBUG("Smil file size is less than 0");
-                       return false;
-               }
-               MSG_DEBUG("%s", pRawData);
-               if (pRawData)
-                       MmsInsertPresentation(pMmsMsg, MIME_APPLICATION_SMIL, pRawData, strlen(pRawData));
-
-               pMmsMsg->mmsAttrib.contentType = MIME_APPLICATION_VND_WAP_MULTIPART_RELATED;
-               pMmsMsg->msgType.type = MIME_APPLICATION_VND_WAP_MULTIPART_RELATED;
-
-               for (int i = 0; i < pageCnt; ++i) {
-                       MMS_PAGE_S *pPage = _MsgMmsGetPage(pMsgData, i);
-                       int mediaCnt = pPage->mediaCnt;
-                       MSG_DEBUG("PAGE %d's media Cnt: %d", i+1, mediaCnt);
-
-                       for (int j = 0; j < mediaCnt; ++j) {
-                               MMS_MEDIA_S *pMedia = _MsgMmsGetMedia(pPage, j);
-
-                               switch (pMedia->mediatype) {
-                               case MMS_SMIL_MEDIA_IMG:
-                               case MMS_SMIL_MEDIA_VIDEO:
-                               case MMS_SMIL_MEDIA_AUDIO:
-                               case MMS_SMIL_MEDIA_TEXT:
-                                       if (pMedia->szFilePath[0] != 0) {
-                                               if (!MmsInsertPartFromFile(pMmsMsg, pMedia->szFileName, pMedia->szFilePath, pMedia->szContentID))
-                                                       return false;
-                                       }
-                                       break;
+       char szFullPath[MSG_FILEPATH_LEN_MAX] = {0, };
 
-                               default:
-                                       break;
-                               }
-                       }
-               }
+       MmsMsg *mmsMsg = NULL;
+       unique_ptr<MmsMsg*, void(*)(MmsMsg**)> buf(&mmsMsg, unique_ptr_deleter);
+       mmsMsg = (MmsMsg *)new char[sizeof(MmsMsg)];
+       memset(mmsMsg, 0x00, sizeof(MmsMsg));
 
-               char szFileName[MSG_FILENAME_LEN_MAX+1] = {0, };;
-               snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%d.mms", pMsgInfo->msgId);
+       MmsPluginStorage::instance()->getMmsRawFilePath(pMsgInfo->msgId, szFullPath, sizeof(szFullPath));
+       MmsPluginDecoder::instance()->decodeMmsPdu(mmsMsg, pMsgInfo->msgId, szFullPath);
 
-               MmsPluginStorage *pStorage = MmsPluginStorage::instance();
-               err = pStorage->getMsgText(pMsgData, pMsgInfo->msgText);
-               err = pStorage->makeThumbnail(pMsgData, pMsgInfo->thumbPath, szFileName);
+       {//make Preview info for APP
+               MmsPluginAppBase appBase(mmsMsg);
+               appBase.makePreviewInfo(pMsgInfo->msgId, true, szFullPath);
+               appBase.getFirstPageTextFilePath(pMsgInfo->msgText, sizeof(pMsgInfo->msgText));
        }
+       MmsReleaseMmsMsg(mmsMsg);
+       MSG_END();
+       return 0;
+}
 
-#ifdef FEATURE_JAVA_MMS
-       MSG_DEBUG("msgAppId: valid:%d appId:%s replyToAppId:%s", pMsgData->msgAppId.valid, pMsgData->msgAppId.appId, pMsgData->msgAppId.replyToAppId);
-       if (pMsgData->msgAppId.valid) { // check if msgAppId.valid is true, both appId and replytoappId must have a meaning data
-               if (pMsgData->msgAppId.appId[0] != 0) {
-                       pMmsMsg->msgType.param.szApplicationID = (char *)malloc(strlen(pMsgData->msgAppId.appId) + 1);
-                       if (pMmsMsg->msgType.param.szApplicationID == NULL) {
-                               MSG_DEBUG("Error: out of Memory");
-                               return false;
-                       }
-                       memset(pMmsMsg->msgType.param.szApplicationID, 0, strlen(pMsgData->msgAppId.appId) + 1);
+//MmsMsg -> MMS_DATA_S
+bool MmsConvertMmsData(MmsMsg *pMmsMsg, MMS_DATA_S *pMmsData)
+{
+       MSG_BEGIN();
 
-                       strcpy(pMmsMsg->msgType.param.szApplicationID, pMsgData->msgAppId.appId);
-               }
+       MMS_HEADER_DATA_S *pHeaderData = pMmsData->header;
+       if (pHeaderData) {
 
-               if (pMsgData->msgAppId.replyToAppId[0] != 0) {
-                       pMmsMsg->msgType.param.szReplyToApplicationID = (char *)malloc(strlen(pMsgData->msgAppId.replyToAppId) + 1);
-                       if (pMmsMsg->msgType.param.szReplyToApplicationID == NULL) {
-                               MSG_DEBUG("Error: out of Memory");
-                               return false;
-                       }
-                       memset(pMmsMsg->msgType.param.szReplyToApplicationID, 0, strlen(pMsgData->msgAppId.replyToAppId) + 1);
+               snprintf(pHeaderData->messageID,  sizeof(pHeaderData->messageID), "%s", pMmsMsg->szMsgID);
+               snprintf(pHeaderData->trID,  sizeof(pHeaderData->trID), "%s", pMmsMsg->szTrID);
+               snprintf(pHeaderData->contentLocation,  sizeof(pHeaderData->contentLocation), "%s", pMmsMsg->szContentLocation);
+               snprintf(pHeaderData->szContentType,  sizeof(pHeaderData->szContentType), "%s", MimeGetMimeStringFromMimeInt(pMmsMsg->mmsAttrib.contentType));
+
+               pHeaderData->messageType = pMmsMsg->mmsAttrib.msgType;
+               pHeaderData->mmsVersion = pMmsMsg->mmsAttrib.version;
+               pHeaderData->messageClass = pMmsMsg->mmsAttrib.msgClass;
+               pHeaderData->contentClass = 0;
+               pHeaderData->mmsPriority = pMmsMsg->mmsAttrib.priority;
+               pHeaderData->expiry.type = pMmsMsg->mmsAttrib.expiryTime.type;
+               pHeaderData->expiry.time = pMmsMsg->mmsAttrib.expiryTime.time;
+
+               pHeaderData->bDeliveryReport = pMmsMsg->mmsAttrib.bAskDeliveryReport;
+               pHeaderData->date = pMmsMsg->mmsAttrib.date;
+               pHeaderData->mmsVersion = pMmsMsg->mmsAttrib.version;
 
-                       strcpy(pMmsMsg->msgType.param.szReplyToApplicationID, pMsgData->msgAppId.replyToAppId);
+               pHeaderData->bReadReport = pMmsMsg->mmsAttrib.bAskReadReply;
+               pHeaderData->bHideAddress = pMmsMsg->mmsAttrib.bHideAddress;
+
+               snprintf(pHeaderData->szSubject, sizeof(pHeaderData->szSubject), "%s", pMmsMsg->mmsAttrib.szSubject);
+
+               pHeaderData->to = MmsConvertAddressToNewStyle(pMmsMsg->mmsAttrib.szTo);
+               pHeaderData->cc = MmsConvertAddressToNewStyle(pMmsMsg->mmsAttrib.szCc);
+               pHeaderData->bcc = MmsConvertAddressToNewStyle(pMmsMsg->mmsAttrib.szBcc);
+
+               snprintf(pHeaderData->szFrom, sizeof(pHeaderData->szFrom), "%s", pMmsMsg->mmsAttrib.szFrom);
+       }
+
+       if (pMmsMsg->mmsAttrib.contentType == MIME_MULTIPART_RELATED || pMmsMsg->mmsAttrib.contentType == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
+
+               MMS_MULTIPART_DATA_S *pMultipart = MsgMmsCreateMultipart();
+               if (pMultipart) {
+                       pMultipart->type = MIME_APPLICATION_SMIL;
+                       snprintf(pMultipart->szContentType, sizeof(pMultipart->szContentType), "%s", "application/smil");
+                       snprintf(pMultipart->szContentID, sizeof(pMultipart->szContentID), "%s", pMmsMsg->msgBody.presentationType.szContentID);
+                       snprintf(pMultipart->szContentLocation, sizeof(pMultipart->szContentLocation), "%s", pMmsMsg->msgBody.presentationType.szContentLocation);
+                       snprintf(pMultipart->szFileName, sizeof(pMultipart->szFileName), "%s", pMmsMsg->msgBody.presentationType.param.szName);
+                       snprintf(pMultipart->szFilePath, sizeof(pMultipart->szFilePath), MSG_DATA_PATH"%s", pMmsMsg->msgBody.presentationType.param.szFileName);
+
+                       pMmsData->smil = pMultipart;
                }
        }
-#endif
 
-       //Processing Attachment List
-       for (int i = 0; i < _MsgMmsGetAttachCount(pMsgData); ++i) {
-               MMS_ATTACH_S *pMedia = _MsgMmsGetAttachment(pMsgData, i);
-               if (pMedia->szFilePath[0] != 0) {
-                       if (!MmsInsertPartFromFile(pMmsMsg, pMedia->szFileName, pMedia->szFilePath, NULL))
-                               return false;
+       int partCnt = pMmsMsg->nPartCount;
+
+       for (int i = 0; i < partCnt; ++i) {
+
+               MsgMultipart *multipart = MmsGetNthMultipart(pMmsMsg, i);
+
+               if (multipart) {
+
+                       MMS_MULTIPART_DATA_S *pMultipart = MsgMmsCreateMultipart();
+
+                       if (pMultipart) {
+                               pMultipart->type = (MimeType)multipart->type.type;
+
+                               snprintf(pMultipart->szContentType, sizeof(pMultipart->szContentType), "%s",MimeGetMimeStringFromMimeInt(multipart->type.type));
+                               snprintf(pMultipart->szContentID, sizeof(pMultipart->szContentID), "%s", multipart->type.szContentID);
+                               snprintf(pMultipart->szContentLocation, sizeof(pMultipart->szContentLocation), "%s", multipart->type.szContentLocation);
+                               snprintf(pMultipart->szFileName, sizeof(pMultipart->szFileName), "%s", multipart->type.param.szName);
+                               snprintf(pMultipart->szFilePath, sizeof(pMultipart->szFilePath), "%s", multipart->pBody->szOrgFilePath);
+
+#ifdef __SUPPORT_DRM__
+                               if (multipart->type.drmInfo.drmType != MSG_DRM_TYPE_NONE) {
+                                       pMultipart->drmType = multipart->type.drmInfo.drmType;
+                               }
+#endif
+                               pMmsData->multipartlist = g_list_append(pMmsData->multipartlist, pMultipart);
+                       }
                }
        }
 
+       MSG_END();
        return true;
 }
 
-void MmsComposeNotiMessage(MmsMsg *pMmsMsg, msg_message_id_t msgID)
+//For Encode raw file
+bool MmsConvertMmsMsg(MmsMsg *pMmsMsg, MMS_DATA_S *pMmsData)
 {
        MSG_BEGIN();
 
-       struct tm *timeInfo = NULL;
-       time_t RawTime = 0;
-       time_t nTimeInSecs = 0;
-
+       // Initialize mmsMsg structure
        MmsInitMsgAttrib(&pMmsMsg->mmsAttrib);
        MmsInitMsgType(&pMmsMsg->msgType);
        MmsInitMsgBody(&pMmsMsg->msgBody);
 
-       pMmsMsg->msgID = msgID;
+       pMmsMsg->mmsAttrib.dataType = MMS_DATATYPE_DRAFT;
 
-       pMmsMsg->mmsAttrib.version = mmsHeader.version;
+       MMS_HEADER_DATA_S *pHeaderData = pMmsData->header;
 
-       // setting date
-       time(&RawTime);
-       timeInfo = localtime(&RawTime);
-       nTimeInSecs = mktime(timeInfo);
-       pMmsMsg->mmsAttrib.date = nTimeInSecs;
+       if (pHeaderData) {
 
-       pMmsMsg->mmsAttrib.bReportAllowed = mmsHeader.reportAllowed;
-       pMmsMsg->mmsAttrib.bAskDeliveryReport = mmsHeader.deliveryReport;
+               if (strlen(pHeaderData->contentLocation) > 0) {
+                       snprintf(pMmsMsg->szContentLocation, sizeof(pMmsMsg->szContentLocation), "%s", pHeaderData->contentLocation);
+               }
 
-       MSG_DEBUG("######## Version = %d ########", pMmsMsg->mmsAttrib.version);
+               pMmsMsg->mmsAttrib.contentType = (MimeType)pHeaderData->contentType;
+               pMmsMsg->msgType.type = pHeaderData->contentType;
+               pMmsMsg->mmsAttrib.date = pHeaderData->date;
+               pMmsMsg->mmsAttrib.bAskDeliveryReport = pHeaderData->bDeliveryReport;
+               pMmsMsg->mmsAttrib.deliveryTime.type = pHeaderData->delivery.type;
+               pMmsMsg->mmsAttrib.deliveryTime.time = pHeaderData->delivery.time;
+               pMmsMsg->mmsAttrib.expiryTime.type = pHeaderData->expiry.type;
+               pMmsMsg->mmsAttrib.expiryTime.time = pHeaderData->expiry.time;
+               pMmsMsg->mmsAttrib.msgClass = (MmsMsgClass)pHeaderData->messageClass;
+
+               if (strlen(pHeaderData->messageID) > 0) {
+                       snprintf(pMmsMsg->szMsgID, sizeof(pMmsMsg->szMsgID), "%s", pHeaderData->messageID);
+               }
 
-       strncpy(pMmsMsg->szTrID, mmsHeader.szTrID, MMS_TR_ID_LEN);
-       strncpy(pMmsMsg->szMsgID, mmsHeader.szMsgID, MMS_MSG_ID_LEN);
-       pMmsMsg->szForwardMsgID[0] = '\0';
+               pMmsMsg->mmsAttrib.msgType = (MmsMsgType)pHeaderData->messageType;
+               pMmsMsg->mmsAttrib.version  = pHeaderData->mmsVersion;
+               pMmsMsg->mmsAttrib.priority = (MmsPriority)pHeaderData->mmsPriority;
+               pMmsMsg->mmsAttrib.bAskReadReply = pHeaderData->bReadReport;
+               pMmsMsg->mmsAttrib.bHideAddress = pHeaderData->bHideAddress;
 
-       if (mmsHeader.pFrom) {
-               MmsAddrUtilRemovePlmnString(mmsHeader.pFrom->szAddr );
-               strncpy(pMmsMsg->mmsAttrib.szFrom, mmsHeader.pFrom->szAddr, MSG_LOCALE_ADDR_LEN + 9);
-       }
+               if (strlen(pHeaderData->trID) > 0) {
+                       snprintf(pMmsMsg->szTrID, sizeof(pMmsMsg->szTrID), "%s", pHeaderData->trID);
+               }
 
-       strncpy(pMmsMsg->mmsAttrib.szSubject, mmsHeader.szSubject, MSG_LOCALE_SUBJ_LEN);
-       strncpy(pMmsMsg->szContentLocation, mmsHeader.szContentLocation, MMS_LOCATION_LEN);
 
-       pMmsMsg->mmsAttrib.msgClass = mmsHeader.msgClass;
-       pMmsMsg->mmsAttrib.msgSize = mmsHeader.msgSize;
-       pMmsMsg->mmsAttrib.expiryTime.type = mmsHeader.expiryTime.type;
-       pMmsMsg->mmsAttrib.expiryTime.time = mmsHeader.expiryTime.time;
-       pMmsMsg->mmsAttrib.dataType = MMS_DATATYPE_NOTIFY;
-       pMmsMsg->mmsAttrib.bRead = false;
-       pMmsMsg->mailbox = MSG_INBOX_ID;
+               snprintf(pMmsMsg->mmsAttrib.szSubject, sizeof(pMmsMsg->mmsAttrib.szSubject), "%s", pHeaderData->szSubject);
 
-       pMmsMsg->mmsAttrib.replyCharge.chargeType = mmsHeader.replyCharge.chargeType;
-       pMmsMsg->mmsAttrib.replyCharge.deadLine.type = mmsHeader.replyCharge.deadLine.type;
-       pMmsMsg->mmsAttrib.replyCharge.deadLine.time = mmsHeader.replyCharge.deadLine.time;
-       pMmsMsg->mmsAttrib.replyCharge.chargeSize = mmsHeader.replyCharge.chargeSize;
+               pMmsMsg->mmsAttrib.szTo = MmsConvertAddressToOldStyle(pHeaderData->to);
+               pMmsMsg->mmsAttrib.szCc = MmsConvertAddressToOldStyle(pHeaderData->cc);
+               pMmsMsg->mmsAttrib.szBcc = MmsConvertAddressToOldStyle(pHeaderData->bcc);
 
-       strncpy(pMmsMsg->mmsAttrib.replyCharge.szChargeID, mmsHeader.replyCharge.szChargeID, MMS_MSG_ID_LEN);
+               snprintf(pMmsMsg->mmsAttrib.szFrom, sizeof(pMmsMsg->mmsAttrib.szFrom), "%s", pHeaderData->szFrom);
+       } //CID 41988: Moving all de-referencing of pHeaderData inside null-check block
 
-       MSG_END();
-}
+       printMmsAttribute(&pMmsMsg->mmsAttrib);
 
-bool MmsGetMmsMessageBody(MmsMsg *pMmsMsg, char *retrievedFilePath)
-{
-       FILE *pFile     = NULL;
-       MsgMultipart *pMultipart = NULL;
-       int attachmax = MSG_ATTACH_MAX;
-       int nSize = 0;
+       if (pMmsData->multipartlist) {
 
-       /*      read from MMS raw file  */
-       if (retrievedFilePath)
-               strncpy(pMmsMsg->szFileName, retrievedFilePath + strlen(MSG_DATA_PATH), strlen(retrievedFilePath + strlen(MSG_DATA_PATH)));
-       else
-               goto __CATCH;
+               if (pMmsData->smil) {
 
-       pFile = MsgOpenFile(retrievedFilePath, "rb");
+                       MMS_MULTIPART_DATA_S *smil_multipart = pMmsData->smil;
 
-       if (pFile == NULL) {
-               MSG_DEBUG( "_MmsReadMsgBody: invalid mailbox\n");
-               goto __CATCH;
-       }
+                       if (smil_multipart) {
 
-       if (MsgGetFileSize(retrievedFilePath, &nSize) == false) {
-               MSG_DEBUG("MsgGetFileSize: failed");
-               goto __CATCH;
-       }
+                               pMmsMsg->mmsAttrib.contentType = MIME_APPLICATION_VND_WAP_MULTIPART_RELATED;
+                               pMmsMsg->msgType.type = MIME_APPLICATION_VND_WAP_MULTIPART_RELATED;
 
-       _MmsRegisterDecodeBuffer(gszMmsLoadBuf1,
-                                                         gszMmsLoadBuf2,
-                                                         MSG_MMS_DECODE_BUFFER_MAX);
+                               gchar *contents = NULL;
+                               gsize length = 0;
 
-       if (MmsBinaryDecodeMsgHeader(pFile, nSize) == false) {
-               MSG_DEBUG( "_MmsReadMsgBody: MmsBinaryDecodeMsgHeader fail...\n");
-               goto __CATCH;
-       }
+                               if (MsgAccessFile(smil_multipart->szFilePath, F_OK)) {
+                                       g_file_get_contents(smil_multipart->szFilePath, &contents, &length, NULL);
 
-       if (MmsBinaryDecodeMsgBody(pFile, retrievedFilePath, nSize) == false) {
-               MSG_DEBUG( "_MmsReadMsgBody: MmsBinaryDecodeMsgBody fail\n");
-               goto __CATCH;
-       }
+                                       MmsInsertPresentation(pMmsMsg, MIME_APPLICATION_SMIL, NULL, contents, length);
 
-       /* Set mmsHeader.msgType & msgBody to pMsg ----------- */
+                                       g_free(contents);
 
-       pMmsMsg->mmsAttrib.contentType = (MsgContentType)mmsHeader.msgType.type;
+                               } else {
+                                       contents = smil_multipart->pMultipartData;
+                                       length = smil_multipart->nMultipartDataLen;
 
-       memcpy(&(pMmsMsg->msgType), &(mmsHeader.msgType), sizeof(MsgType));
-       memcpy(&(pMmsMsg->msgBody), &(mmsHeader.msgBody), sizeof(MsgBody));
+                                       MmsInsertPresentation(pMmsMsg, MIME_APPLICATION_SMIL, NULL, contents, length);
+                               }
+                       }
+               } else {
+                       pMmsMsg->mmsAttrib.contentType = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED;
+                       pMmsMsg->msgType.type = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED;
+               }
 
-       MSG_DEBUG("#############################");
-       MSG_DEBUG("## pMmsMsg->msgType.type = %d ##", pMmsMsg->msgType.type);
-       MSG_DEBUG("## pMmsMsg->msgType.szContentID = %s ##", pMmsMsg->msgType.szContentID);
-       MSG_DEBUG("## pMmsMsg->msgType.szContentLocation = %s ##", pMmsMsg->msgType.szContentLocation);
-       MSG_DEBUG("#############################");
+               int len = g_list_length(pMmsData->multipartlist);
 
-       if (pMmsMsg->msgBody.pPresentationBody) {
-               if(MsgFseek(pFile, pMmsMsg->msgBody.pPresentationBody->offset, SEEK_SET) < 0)
-                       goto __CATCH;
+               for (int i = 0; i < len; i++) {
 
-               pMmsMsg->msgBody.pPresentationBody->body.pText = (char *)malloc(pMmsMsg->msgBody.pPresentationBody->size + 1);
-               if (pMmsMsg->msgBody.pPresentationBody->body.pText == NULL)
-                       goto __CATCH;
+                       MMS_MULTIPART_DATA_S *multipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(pMmsData->multipartlist, i);
 
-               memset(pMmsMsg->msgBody.pPresentationBody->body.pText, 0, pMmsMsg->msgBody.pPresentationBody->size + 1);
-               ULONG nRead = 0;
-               nRead = MsgReadFile(pMmsMsg->msgBody.pPresentationBody->body.pText, sizeof(char), pMmsMsg->msgBody.pPresentationBody->size, pFile);
+                       if (multipart) {
+                               if (multipart->type == MIME_UNKNOWN)
+                                       multipart->type = MimeGetMimeIntFromMimeString(multipart->szContentType);
 
-               if (nRead == 0)
-                       goto __CATCH;
+                               if (MmsInsertPartFromMultipart(pMmsMsg, multipart) == false) {
+                                       return false;
+                               }
+                       }
+               } //end for
        }
 
-       MsgCloseFile(pFile);
-       pFile = NULL;
+       MSG_END();
+       return true;
+}
 
-       /* nPartCount */
-       pMmsMsg->nPartCount = 0;
+char *MmsConvertAddressToOldStyle(MMSList *pAddressList)
+{
+       MSG_BEGIN();
+       int addrLen = 0;
+       int nAddressCnt = 0;
+       char pString[MSG_LOCALE_NAME_LEN + MSG_ADDR_LEN + 3] = {0, };
+       char *szCompose = NULL;
 
-       if (MsgIsMultipart(mmsHeader.msgType.type) == true) {
-               pMultipart = pMmsMsg->msgBody.body.pMultipart;
-               while (pMultipart) {
-                       pMmsMsg->nPartCount++;
+       nAddressCnt = g_list_length(pAddressList);
 
-                       if (pMultipart->type.type == MIME_TEXT_PLAIN)
-                               attachmax++;
+       // Calculate allocated buffer size
+       for (int i = 0; i < nAddressCnt; ++i) {
 
-                       if ((mmsHeader.msgType.type == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED) ||
-                               (mmsHeader.msgType.type == MIME_MULTIPART_MIXED)) {
-                               if ((pMmsMsg->nPartCount >= attachmax ) && (pMultipart->pNext != NULL)) {
-                                       _MsgFreeBody(pMultipart->pNext->pBody, pMultipart->pNext->type.type);
+               MMS_ADDRESS_DATA_S * pAddressData = (MMS_ADDRESS_DATA_S *)g_list_nth_data(pAddressList, i);
+               if (pAddressData) {
+                       MSG_SEC_DEBUG("address type : %d, address value: %s", pAddressData->address_type, pAddressData->address_val);
+                       if (pAddressData->address_type == MSG_ADDRESS_TYPE_PLMN) {
+                               addrLen += strlen("/TYPE=PLMN");
+                               addrLen += strlen(pAddressData->address_val);
+                       } else {
+                               addrLen += strlen(pAddressData->address_val);
+                       }
+               }
+       }
 
-                                       free(pMultipart->pNext->pBody);
-                                       pMultipart->pNext->pBody = NULL;
+       if (nAddressCnt > 1)
+               addrLen = addrLen + nAddressCnt - 1;
 
-                                       free(pMultipart->pNext);
+       szCompose = (char *)calloc(addrLen + 1, 1);
 
-                                       pMultipart->pNext = NULL;
-                                       break;
+       if (szCompose) {
+               // Address String copy
+               for (int i = 0; i < nAddressCnt; ++i) {
+                       MMS_ADDRESS_DATA_S * pAddressData = (MMS_ADDRESS_DATA_S *)g_list_nth_data(pAddressList, i);
+
+                       if (pAddressData) {
+                               if (strlen(szCompose) > 0)
+                                       g_strlcat(szCompose, MSG_STR_ADDR_DELIMETER, addrLen + 1 - strlen(szCompose));
+
+                               memset(pString, 0x00, (MSG_LOCALE_NAME_LEN + MSG_ADDR_LEN + 3) * sizeof(char));
+                               if (pAddressData->address_type == MSG_ADDRESS_TYPE_PLMN) {
+                                       snprintf(pString, MSG_LOCALE_NAME_LEN + MSG_ADDR_LEN + 3, "%s%s", pAddressData->address_val, "/TYPE=PLMN");
+                                       MSG_DEBUG("%s", pString);
+                               } else {
+                                       snprintf(pString, MSG_LOCALE_NAME_LEN + MSG_ADDR_LEN + 3, "%s", pAddressData->address_val);
                                }
+
+                               g_strlcat(szCompose, pString, addrLen + 1 - strlen(szCompose));
                        }
-                       pMultipart = pMultipart->pNext;
                }
-       } else {
-               if (pMmsMsg->msgBody.size > 0)
-                       pMmsMsg->nPartCount++;
        }
 
-       //call before processing urgent event.
-       _MmsInitHeader();
-       _MmsUnregisterDecodeBuffer();
+       MSG_END();
+       return szCompose;
 
-       return true;
+}
 
-__CATCH:
+MMSList * MmsConvertAddressToNewStyle(const char *szAddr)
+{
+       MMSList *pAddressList = NULL;
+       MMS_ADDRESS_DATA_S *pAddressData = NULL;
 
-       _MmsInitHeader();
-       _MmsUnregisterDecodeBuffer();
+       char *pTempChar = NULL;
+       char *pStartPtr= NULL;
+       char *pEndPtr= NULL;
 
-       if (pFile != NULL) {
-               MsgCloseFile(pFile);
-               pFile = NULL;
-       }
+       if (szAddr == NULL)
+               return NULL;
 
-       _MsgFreeBody(&pMmsMsg->msgBody, pMmsMsg->msgType.type);
-       MSG_DEBUG("_MmsReadMsgBody:    E  N  D    ( fail )    ******************** \n");
+       pTempChar = strdup(szAddr);
 
-       return false;
-}
+       pStartPtr = pTempChar;
 
-#ifdef MMS_DELIEVERY_IND_ENABLED
-MmsMsgMultiStatus *MmsComposeDeliveryIndMessage(MmsMsg *pMmsMsg, msg_message_id_t msgId)
-{
-       MmsMsgMultiStatus *pStatus = NULL;
-       MmsMsgMultiStatus *pLastStatus = NULL;
-       bool bFound = false;
+       while (pStartPtr && pStartPtr[0]) {
 
-       MmsInitMsgAttrib(&pMmsMsg->mmsAttrib);
-       MmsInitMsgType(&pMmsMsg->msgType);
-       MmsInitMsgBody(&pMmsMsg->msgBody);
+               int addLen = 0;
+               char tempAddress[512] = {0,};
+               char tempAddress2[512] = {0,};
 
-       pMmsMsg->mmsAttrib.version = mmsHeader.version;
+               pEndPtr = strchr(pStartPtr, MSG_CH_SEMICOLON);
 
-       pMmsMsg->mmsAttrib.pMultiStatus = MmsGetMultiStatus(msgId);
+               if (pEndPtr) {
+                       addLen = pEndPtr - pStartPtr;
+               } else {
+                       addLen = strlen(pStartPtr);
+               }
 
-       pStatus = pMmsMsg->mmsAttrib.pMultiStatus;
+               if (addLen) {
+                       strncpy(tempAddress, pStartPtr, addLen);
+                       int addr_type;
+                       int addLen2;
+                       char *pSlash = strchr(tempAddress, '/');
 
-       MSG_DEBUG("### pStatus->szTo = %s ###", pStatus->szTo);
+                       if (pSlash) {
+                               addLen2 = pSlash - tempAddress;
+                               addr_type = MSG_ADDRESS_TYPE_PLMN;
+                       } else {
+                               addLen2 = strlen(tempAddress);
+                               addr_type = MSG_ADDRESS_TYPE_EMAIL;
+                       }
 
-       while (pStatus && !bFound) {
-               MSG_DEBUG("### MmsAddrUtilCompareAddr ###");
-               MSG_DEBUG("### mmsHeader.pTo->szAddr = %s ###", mmsHeader.pTo->szAddr);
-               if (MmsAddrUtilCompareAddr(pStatus->szTo, mmsHeader.pTo->szAddr)) {
-                       bFound = true;
+                       if (addLen2) {
+                               strncpy(tempAddress2, tempAddress, addLen2);
+                               pAddressData = MsgMmsCreateAddress(addr_type, tempAddress2);
+                       }
+
+                       if (pAddressData)
+                               pAddressList = g_list_append(pAddressList, pAddressData);
+
+                       pStartPtr = pStartPtr + addLen + 1;
+               } else {
                        break;
                }
-
-               pStatus = pStatus->pNext;
        }
 
-       if (bFound == false) {
-               MSG_DEBUG("### bFound == false ###");
-               /* Queue the delivery report  --------------------------- */
+       if (pTempChar)
+               free(pTempChar);
+
+       MSG_END();
+       return pAddressList;
+}
+
+bool convertMediaToMultipart(MMS_MEDIA_S *pSrcMedia, MMS_MULTIPART_DATA_S *pDestMultipart)
+{
+       bzero(pDestMultipart, sizeof(MMS_MULTIPART_DATA_S));
 
-               pStatus = (MmsMsgMultiStatus *)malloc(sizeof(MmsMsgMultiStatus));
-               memset(pStatus, 0, sizeof(MmsMsgMultiStatus));
+       snprintf(pDestMultipart->szContentID, sizeof(pDestMultipart->szContentID), "%s", pSrcMedia->szContentID);
+       snprintf(pDestMultipart->szContentLocation, sizeof(pDestMultipart->szContentLocation), "%s", pSrcMedia->szContentLocation);
+       snprintf(pDestMultipart->szFileName, sizeof(pDestMultipart->szFileName), "%s", pSrcMedia->szFileName);
+       snprintf(pDestMultipart->szFilePath, sizeof(pDestMultipart->szFilePath), "%s", pSrcMedia->szFilePath);
 
-               pStatus->readStatus = MMS_READSTATUS_NONE;
 
-               memset(pStatus->szTo, 0, MSG_ADDR_LEN + 1);
-               strncpy(pStatus->szTo, mmsHeader.pTo->szAddr, MSG_ADDR_LEN);
+       if (strlen(pSrcMedia->szContentType) > 0) {
+               snprintf(pDestMultipart->szContentType, sizeof(pDestMultipart->szContentType), "%s", pSrcMedia->szContentType);
+               pDestMultipart->type = MimeGetMimeIntFromMimeString(pSrcMedia->szContentType);
 
-               if (pMmsMsg->mmsAttrib.pMultiStatus == NULL) {
-                       /* first delivery report */
-                       pMmsMsg->mmsAttrib.pMultiStatus = pStatus;
+       } else {
+               MimeMainType mainType = MIME_MAINTYPE_UNKNOWN;
+               MimeType pMimeType = MIME_UNKNOWN;
+               const char *pszMimeType = NULL;
+
+               if (pSrcMedia->mediatype == MMS_SMIL_MEDIA_IMG)
+                       mainType = MIME_MAINTYPE_IMAGE;
+               else if (pSrcMedia->mediatype == MMS_SMIL_MEDIA_AUDIO)
+                       mainType = MIME_MAINTYPE_AUDIO;
+               else if (pSrcMedia->mediatype ==  MMS_SMIL_MEDIA_VIDEO)
+                       mainType = MIME_MAINTYPE_VIDEO;
+               else if (pSrcMedia->mediatype == MMS_SMIL_MEDIA_TEXT)
+                       mainType = MIME_MAINTYPE_TEXT;
+
+               MmsGetMimeTypeFromFileName(mainType, pSrcMedia->szFilePath, &pMimeType, &pszMimeType);
+
+               if (pszMimeType) {
+                       snprintf(pDestMultipart->szContentType, sizeof(pDestMultipart->szContentType), "%s", pszMimeType);
+                       pDestMultipart->type = pMimeType;
                } else {
-                       pLastStatus = pMmsMsg->mmsAttrib.pMultiStatus;
-                       while (pLastStatus->pNext) {
-                               pLastStatus = pLastStatus->pNext;
-                       }
+                       snprintf(pDestMultipart->szContentType, sizeof(pDestMultipart->szContentType), "%s", "application/octet-stream");
+                       pDestMultipart->type = MIME_APPLICATION_OCTET_STREAM;
+               }
+       }
+
+       return true;
+}
+
+bool convertAttachToMultipart(MMS_ATTACH_S *pSrcMedia, MMS_MULTIPART_DATA_S *pDestMultipart)
+{
+       bzero(pDestMultipart, sizeof(MMS_MULTIPART_DATA_S));
 
-                       pLastStatus->pNext = pStatus;
-                       pLastStatus = pStatus;
+       snprintf(pDestMultipart->szFileName, sizeof(pDestMultipart->szFileName), "%s", pSrcMedia->szFileName);
+       snprintf(pDestMultipart->szFilePath, sizeof(pDestMultipart->szFilePath), "%s", pSrcMedia->szFilePath);
+
+       if (strlen(pSrcMedia->szContentType) > 0) {
+               snprintf(pDestMultipart->szContentType, sizeof(pDestMultipart->szContentType), "%s", pSrcMedia->szContentType);
+               pDestMultipart->type = MimeGetMimeIntFromMimeString(pSrcMedia->szContentType);
+       } else {
+
+               MimeMainType mainType = MIME_MAINTYPE_UNKNOWN;
+               MimeType pMimeType = MIME_UNKNOWN;
+               const char *pszMimeType = NULL;
+
+               MmsGetMimeTypeFromFileName(mainType, pSrcMedia->szFilePath, &pMimeType, &pszMimeType);
+
+               if (pszMimeType) {
+                       snprintf(pDestMultipart->szContentType, sizeof(pDestMultipart->szContentType), "%s", pszMimeType);
+                       pDestMultipart->type = pMimeType;
+               } else {
+                       snprintf(pDestMultipart->szContentType, sizeof(pDestMultipart->szContentType), "%s", "application/octet-stream");
+                       pDestMultipart->type = MIME_APPLICATION_OCTET_STREAM;
                }
        }
 
-       pStatus->handledTime = mmsHeader.date;
-       pStatus->msgStatus = mmsHeader.msgStatus;
-       pStatus->bDeliveryReportIsRead = false;
+       return true;
+}
+
+bool convertMsgMultipartToMultipart(MsgMultipart *pSrcMultipart, MMS_MULTIPART_DATA_S *pDestMultipart)
+{
+       pDestMultipart->type = (MimeType)pSrcMultipart->type.type;
 
-       _MmsDataUpdateLastStatus(pMmsMsg);
+       MSG_DEBUG("Mime Type : %s :%d", MimeGetMimeStringFromMimeInt(pSrcMultipart->type.type), pSrcMultipart->type.type);
+       snprintf(pDestMultipart->szContentID, sizeof(pDestMultipart->szContentID), "%s", pSrcMultipart->type.szContentID);
+       snprintf(pDestMultipart->szContentLocation, sizeof(pDestMultipart->szContentLocation), "%s", pSrcMultipart->type.szContentLocation);
+       snprintf(pDestMultipart->szFileName, sizeof(pDestMultipart->szFileName), "%s", pSrcMultipart->type.param.szName);
+       snprintf(pDestMultipart->szFilePath, sizeof(pDestMultipart->szFilePath), "%s", pSrcMultipart->pBody->szOrgFilePath);
 
-       pStatus->bDeliveyrReportIsLast = true;
+       snprintf(pDestMultipart->szContentType, sizeof(pDestMultipart->szContentType), "%s", MimeGetMimeStringFromMimeInt(pSrcMultipart->type.type));
 
-       return pStatus;
+       if (pSrcMultipart->type.drmInfo.drmType != MSG_DRM_TYPE_NONE) {
+               pDestMultipart->drmType = pSrcMultipart->type.drmInfo.drmType;
+       }
+
+       return true;
 }
-#endif
 
-void MmsComposeReadReportMessage(MmsMsg *pMmsMsg, const MSG_MESSAGE_INFO_S *pMsgInfo, msg_message_id_t selectedMsgId)
+gint __compare_str(gconstpointer a, gconstpointer b)
 {
-       struct tm *timeInfo = NULL;
-       time_t RawTime = 0;
-       time_t nTimeInSecs = 0;
+       return g_strcmp0((char *)a, (char *)b);
+}
 
-       MmsInitMsgAttrib(&pMmsMsg->mmsAttrib);
-       MmsInitMsgType(&pMmsMsg->msgType);
-       MmsInitMsgBody(&pMmsMsg->msgBody);
+// change file name to Ascii & space -> '_'
+// If replaced filename is duplicated, then it append number
+bool MmsChangeFileNameToAscii(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       int pageCnt;
+       int mediaCnt;
+       int attachCnt;
 
-       // setting mmsMsg structure
-       pMmsMsg->mailbox = pMsgInfo->folderId;
-       pMmsMsg->msgID = pMsgInfo->msgId;
+       GList *r_list = NULL;//renamed file list
 
-       memset(pMmsMsg->szTrID, 0, MMS_TR_ID_LEN + 1);
-       memset(pMmsMsg->szContentLocation, 0, MMS_LOCATION_LEN + 1);
-       memset(pMmsMsg->szForwardMsgID, 0, MMS_MSG_ID_LEN + 1);
+       pageCnt = g_list_length(pMsgData->pagelist);
 
-       pMmsMsg->mmsAttrib.dataType = MMS_DATATYPE_DRAFT;
+       for (int i = 0; i < pageCnt; i++) {
+               MMS_PAGE_S *pPage = NULL;
+               pPage = (MMS_PAGE_S *)g_list_nth_data(pMsgData->pagelist, i);
+               if (pPage == NULL) {
+                       //CID 355351: Freeing r_list in case of error too to prevent memory leak
+                       if (r_list != NULL)
+                               g_list_free(r_list);
+                       return false;
+               }
 
-       // setting date
-       time(&RawTime);
-       timeInfo = localtime(&RawTime);
-       nTimeInSecs = mktime(timeInfo);
-       pMmsMsg->mmsAttrib.date = nTimeInSecs;
+               mediaCnt = g_list_length(pPage->medialist);
+               for (int j = 0; j < mediaCnt; j++) {
+                       MMS_MEDIA_S *pMedia = NULL;
+                       pMedia = (MMS_MEDIA_S *)g_list_nth_data(pPage->medialist, j);
+                       if (pMedia == NULL) {
+                               //CID 355351: Freeing r_list in case of error too to prevent memory leak
+                               if (r_list != NULL)
+                                       g_list_free(r_list);
+                               return false;
+                       }
 
-       // setting szMsgId
-       MmsPluginStorage::instance()->getMmsMessageId(selectedMsgId, pMmsMsg);
+                       if (strlen(pMedia->szFileName) > 0) {
+                               char *str = NULL;
 
-       //setting subject
-       strcpy(pMmsMsg->mmsAttrib.szSubject, pMsgInfo->subject);
+                               MmsReplaceSpaceChar(pMedia->szFileName);
 
-       //setting adddress
-       MmsSetMsgAddressList(&pMmsMsg->mmsAttrib, pMsgInfo);
+                               str = MmsReplaceNonAsciiUtf8(pMedia->szFileName, '_');
 
-       if (pMmsMsg->mmsAttrib.szTo)
-               strncpy(pMmsMsg->mmsAttrib.szFrom, pMmsMsg->mmsAttrib.szTo, strlen(pMmsMsg->mmsAttrib.szTo));
-}
+                               if (str) {
+                                       int count = 1;
+                                       char *str2 = g_strdup(str);
+                                       char *ext = strrchr(str, '.');
 
-int MmsSearchMsgId(char *toNumber, char *szMsgID)
-{
-       MSG_BEGIN();
+                                       if (ext == NULL || *(ext + 1) == '\0') {
+                                               ext = NULL;
+                                       } else {
+                                               *ext = '\0';
+                                               ext = ext + 1;
+                                       }
 
-       int msgId;
+                                       while (g_list_find_custom(r_list, str2, __compare_str) != NULL) {
 
-       msgId = MmsPluginStorage::instance()->searchMsgId(toNumber, szMsgID);
+                                               g_free(str2);
 
-       if (msgId < 0)
-               return 0;
+                                               if (ext)
+                                                       str2 = g_strdup_printf("%s_%d.%s", str, count++, ext);
+                                               else
+                                                       str2 = g_strdup_printf("%s_%d", str, count++);
+                                       }
 
-       MSG_END();
+                                       g_free(str);
 
-       return msgId;
-}
+                                       snprintf(pMedia->szFileName, sizeof(pMedia->szFileName), "%s", str2);
 
-void MmsUpdateDeliveryReport(msg_message_id_t msgId, MmsMsgMultiStatus *pStatus)
-{
-       MSG_BEGIN();
+                                       MSG_DEBUG("replace filename [%s]", pMedia->szFileName);
 
-       MmsPluginStorage::instance()->updateDeliveryReport(msgId, pStatus);
+                                       r_list = g_list_append(r_list, pMedia->szFileName);
 
-       MSG_END();
-}
+                                       g_free(str2);
+                               }
+                       }
+               }//end for media
+       }//end for page
+
+       attachCnt = g_list_length(pMsgData->attachlist);
+       for (int i = 0; i < attachCnt; i++) {
+               MMS_ATTACH_S *pAttach = NULL;
+               pAttach = (MMS_ATTACH_S *)g_list_nth_data(pMsgData->attachlist, i);
+               if (pAttach == NULL) {
+                       //CID 355351: Freeing r_list in case of error too to prevent memory leak
+                       if(r_list != NULL)
+                               g_list_free(r_list);
+                       return false;
+               }
 
-void MmsUpdateReadReport(msg_message_id_t msgId, MmsMsgMultiStatus *pStatus)
-{
-       MSG_BEGIN();
+               if (strlen(pAttach->szFileName) > 0) {
+                       char *str = NULL;
 
-       MmsPluginStorage::instance()->updateReadReport(msgId, pStatus);
+                       MmsReplaceSpaceChar(pAttach->szFileName);
 
-       MSG_END();
-}
+                       str = MmsReplaceNonAsciiUtf8(pAttach->szFileName, '_');
+                       if (str) {
+                               int count = 1;
+                               char *str2 = g_strdup(str);
+                               char *ext = strrchr(str, '.');
 
-MmsMsgMultiStatus *MmsGetMultiStatus(msg_message_id_t msgId)
-{
-       MmsMsgMultiStatus *pMultiStatus;
+                               if (ext == NULL || *(ext + 1) == '\0') {
+                                       ext = NULL;
+                               } else {
+                                       *ext = '\0';
+                                       ext = ext + 1;
+                               }
 
-       pMultiStatus = MmsPluginStorage::instance()->getMultiStatus(msgId);
+                               while (g_list_find_custom(r_list, str2, __compare_str) != NULL) {
 
-       MSG_DEBUG("### szTo = %s ###", pMultiStatus->szTo);
+                                       g_free(str2);
 
-       MSG_END();
+                                       if (ext)
+                                               str2 = g_strdup_printf("%s_%d.%s", str, count++, ext);
+                                       else
+                                               str2 = g_strdup_printf("%s_%d", str, count++);
+                               }
 
-       return pMultiStatus;
-}
+                               g_free(str);
 
-bool MmsCheckAdditionalMedia(MMS_MESSAGE_DATA_S *pMsgData, MsgType *partHeader)
-{
-       if (_MsgMmsFindMatchedMedia(pMsgData, partHeader->param.szFileName))
-               return false;
-       else
-               return true;
-}
+                               snprintf(pAttach->szFileName, sizeof(pAttach->szFileName), "%s", str2);
 
-#ifdef __SUPPORT_DRM__
-bool __MsgInitMsgDRMInfo(MsgDRMInfo *pMsgDrmInfo)
-{
-       pMsgDrmInfo->contentType = MIME_UNKNOWN;
-       pMsgDrmInfo->drmType = MSG_DRM_TYPE_NONE;
-
-       pMsgDrmInfo->szContentName = NULL;
-       pMsgDrmInfo->szContentURI = NULL;
-       pMsgDrmInfo->szContentDescription = NULL;
-       pMsgDrmInfo->szContentVendor = NULL;
-       pMsgDrmInfo->szRightIssuer = NULL;
-       pMsgDrmInfo->szDrm2FullPath = NULL;
-       pMsgDrmInfo->roWaitingTimerMax = 0;
-       pMsgDrmInfo->bFwdLock = false;
-       pMsgDrmInfo->bNoScreen = false;
-       pMsgDrmInfo->bNoRingTone = false;
-       pMsgDrmInfo->pszContentType = NULL;
+                               MSG_DEBUG("replace filename [%s]", pAttach->szFileName);
+
+                               g_free(str2);
+                       }
+               }
+
+       }//end for attach
+
+       g_list_free(r_list);
 
        return true;
 }
-#endif
+
index 38df2aa..3c5ab54 100755 (executable)
@@ -1,28 +1,28 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
+#include "MsgMmsMessage.h"
+#include "MmsPluginDebug.h"
 #include "MmsPluginSMILValidate.h"
-#include "MsgDebug.h"
-#include "MsgUtilFile.h"
 #include "MmsPluginSmil.h"
-#include "MsgMmsMessage.h"
+
 
 #define MSG_RETURN_VAL_IF_FAIL(Expr, Val)                                      \
                if (!(Expr)) {                                                                          \
-                       MSG_DEBUG("%s:[%s] Failed - %d\n", __FUNCTION__, __LINE__, Val); \
+                       MSG_DEBUG("%s:[%d] Failed - %d\n", __FUNCTION__, __LINE__, Val); \
                        return Val;                                                                             \
                };
 
@@ -103,7 +103,7 @@ MSG_SMIL_ERR_E _MsgMMSAddDefaultSMILRootLayout(MMS_MESSAGE_DATA_S *pMsgData)
        pMsgData->rootlayout.height.value = MSG_SMIL_ROOT_LAYOUT_HEIGHT;
        pMsgData->rootlayout.height.bUnitPercent = MSG_SMIL_ROOT_LAYOUT_IN_PERCENT;
 
-       pMsgData->rootlayout.bgColor = MmsSmilAtoIHexa((char *)&pContent[1]);
+       pMsgData->rootlayout.bgColor = MsgSmilAtoIHexa((char *)&pContent[1]);
 
        MSG_END();
        return MSG_SMIL_SUCCESS;
@@ -235,7 +235,7 @@ MSG_SMIL_ERR_E _MsgMMSAddDefaultFirstSMILRegion(MMS_MESSAGE_DATA_S *pMsgData, bo
                pRegion->fit = MMSUI_IMAGE_REGION_FIT_MEET;
        else
                pRegion->fit = MMSUI_IMAGE_REGION_FIT_HIDDEN;
-       pRegion->bgColor = MmsSmilAtoIHexa((char *)&pContent[1]);
+       pRegion->bgColor = MsgSmilAtoIHexa((char *)&pContent[1]);
 
        pRegion->nLeft.value = MSG_SMIL_FIRST_REG_LEFT;
        pRegion->nLeft.bUnitPercent = true;
@@ -285,7 +285,7 @@ MSG_SMIL_ERR_E _MsgMMSAddDefaultSecondSMILRegion(MMS_MESSAGE_DATA_S *pMsgData, b
                pRegion->fit = MMSUI_IMAGE_REGION_FIT_MEET;
        else
                pRegion->fit = MMSUI_IMAGE_REGION_FIT_HIDDEN;
-       pRegion->bgColor = MmsSmilAtoIHexa((char *)&pContent[1]);
+       pRegion->bgColor = MsgSmilAtoIHexa((char *)&pContent[1]);
 
        pRegion->nLeft.value = MSG_SMIL_SECOND_REG_LEFT;
        pRegion->nLeft.bUnitPercent = true;
@@ -335,7 +335,7 @@ MSG_SMIL_ERR_E _MsgMMSAddDefaultFullSMILRegion(MMS_MESSAGE_DATA_S *pMsgData)
                pRegion->fit = MMSUI_IMAGE_REGION_FIT_MEET;
        else
                pRegion->fit = MMSUI_IMAGE_REGION_FIT_HIDDEN;
-       pRegion->bgColor = MmsSmilAtoIHexa((char *)&pContent[1]);
+       pRegion->bgColor = MsgSmilAtoIHexa((char *)&pContent[1]);
 
        pRegion->nLeft.value = MSG_SMIL_FULL_REG_LEFT;
        pRegion->nLeft.bUnitPercent = true;
diff --git a/plugin/mms_plugin/MmsPluginSmil.cpp b/plugin/mms_plugin/MmsPluginSmil.cpp
deleted file mode 100755 (executable)
index 5ef0bbc..0000000
+++ /dev/null
@@ -1,2101 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include<stdio.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <ctype.h>
-#include "MmsPluginSmil.h"
-#include "MmsPluginMessage.h"
-#include "MmsPluginStorage.h"
-#include "MsgDebug.h"
-#include "MmsPluginCodec.h"
-#include "MsgMmsMessage.h"
-
-#include "MsgTypes.h"
-#include "MmsPluginSetup.h"
-#include "MsgUtilFile.h"
-
-/* static variables */
-static char gszEmptyRawDoc[] = "<smil><head><layout></layout></head><body></body></smil>";
-static MmsSmilDoc *__gpaMmsSmilDoc[MMS_SMIL_MAX_DOC]={NULL, };
-static char gszColor[MMS_SMIL_COLOR_SIZE] = {0, };
-
-
-char *MmsSmilGetPresentationData(msg_message_id_t msgId)
-{
-       MmsMsg *pMsg;
-
-       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
-
-       if (pMsg == NULL) {
-               MSG_DEBUG("pMsg is NULL");
-               goto _LCATCH;
-       }
-
-       if (msgId != pMsg->msgID) {
-               MSG_DEBUG("Invalid Message Id");
-               return NULL;
-       }
-
-       if (!pMsg->msgBody.pPresentationBody)
-               goto _LCATCH;
-
-       if (!pMsg->msgBody.pPresentationBody->body.pText)
-               goto _LCATCH;
-       else
-               return pMsg->msgBody.pPresentationBody->body.pText;
-
-_LCATCH:
-       return NULL;
-}
-
-bool MmsSmilParseSmilDoc(MMS_MESSAGE_DATA_S *pMmsMsg, char *pSmilDoc)
-{
-       xmlDocPtr doc;
-       xmlNodePtr cur;
-       MSG_DEBUG("%s", pSmilDoc);
-       doc = xmlParseMemory(pSmilDoc, strlen(pSmilDoc));
-
-       if (doc == NULL) {
-               MSG_DEBUG("Document not parsed successfully. \n");
-               return false;
-       }
-
-       cur = xmlDocGetRootElement(doc);
-
-       if (cur == NULL) {
-               MSG_DEBUG("empty document\n");
-               xmlFreeDoc(doc);
-               return false;
-       }
-
-       if (xmlStrcmp(cur->name, (const xmlChar *) "smil")) {
-               MSG_DEBUG("document of the wrong type, root node != smil");
-               xmlFreeDoc(doc);
-               return false;
-       }
-
-       MmsSmilGetElement(pMmsMsg, cur);
-
-       xmlFreeDoc(doc);
-
-       return true;
-}
-
-void MmsSmilGetElement(MMS_MESSAGE_DATA_S *pMmsMsg, xmlNode *a_node)
-{
-       MSG_BEGIN();
-
-       int elementType;
-       int attrType;
-       MMS_SMIL_ROOTLAYOUT rootlayout = {};
-       static bool cmd[ELEMENT_MAX] = {false, };
-       static MMS_SMIL_REGION *pRegion;
-       static MMS_PAGE_S *pPage;
-       static MMS_MEDIA_S *pMedia;
-       static MMS_SMIL_TRANSITION *pTransition;
-       static MMS_SMIL_META *pMeta;
-
-       xmlNode *cur_node = NULL;
-
-       for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
-               MSG_DEBUG("******* node, name: %s ***\n", cur_node->name);
-
-               if (cur_node->type == XML_ELEMENT_NODE) {
-                       // Get Smil Element =====================================================
-                       MSG_DEBUG("*** node type: Element, name: %s ***\n", cur_node->name);
-
-                       switch (elementType = MmsSmilGetElementID((char *)cur_node->name)) {
-                       case ELEMENT_ROOTLAYOUT:
-                               memset(cmd, 0, ELEMENT_MAX);
-                               cmd[ELEMENT_ROOTLAYOUT] = true;
-                               break;
-
-                       case ELEMENT_REGION:
-                               pRegion = (MMS_SMIL_REGION *)calloc(sizeof(MMS_SMIL_REGION), 1);
-                               memset(cmd, 0, ELEMENT_MAX);
-                               cmd[ELEMENT_REGION] = true;
-                               break;
-
-                       case ELEMENT_TRANSITION:
-                               pTransition = (MMS_SMIL_TRANSITION *)calloc(sizeof(MMS_SMIL_TRANSITION), 1);
-                               memset(cmd, 0, ELEMENT_MAX);
-                               cmd[ELEMENT_TRANSITION] = true;
-                               break;
-
-                       case ELEMENT_META:
-                               pMeta = (MMS_SMIL_META *)calloc(sizeof(MMS_SMIL_META), 1);
-                               memset(cmd, 0, ELEMENT_MAX);
-                               cmd[ELEMENT_META] = true;
-                               break;
-
-                       case ELEMENT_PAR:
-                               pPage = (MMS_PAGE_S *)calloc(sizeof(MMS_PAGE_S), 1);
-                               memset(cmd, 0, ELEMENT_MAX);
-                               cmd[ELEMENT_PAR] = true;
-                               break;
-
-                       case ELEMENT_PARAM: // Need to check the original element type
-                               break;
-
-                       case ELEMENT_TEXT:
-                               pMedia = (MMS_MEDIA_S *)calloc(sizeof(MMS_MEDIA_S), 1);
-                               pMedia->mediatype = MMS_SMIL_MEDIA_TEXT;
-                               memset(cmd, 0, ELEMENT_MAX);
-                               cmd[ELEMENT_TEXT] = true;
-                               break;
-
-                       case ELEMENT_IMG:
-                               pMedia = (MMS_MEDIA_S *)calloc(sizeof(MMS_MEDIA_S), 1);
-                               pMedia->mediatype = MMS_SMIL_MEDIA_IMG;
-                               memset(cmd, 0, ELEMENT_MAX);
-                               cmd[ELEMENT_IMG] = true;
-                               break;
-
-                       case ELEMENT_AUDIO:
-                               pMedia = (MMS_MEDIA_S *)calloc(sizeof(MMS_MEDIA_S), 1);
-                               pMedia->mediatype = MMS_SMIL_MEDIA_AUDIO;
-                               memset(cmd, 0, ELEMENT_MAX);
-                               cmd[ELEMENT_AUDIO] = true;
-                               break;
-
-                       case ELEMENT_VIDEO:
-                               pMedia = (MMS_MEDIA_S *)calloc(sizeof(MMS_MEDIA_S), 1);
-                               pMedia->mediatype = MMS_SMIL_MEDIA_VIDEO;
-                               memset(cmd, 0, ELEMENT_MAX);
-                               cmd[ELEMENT_VIDEO] = true;
-                               break;
-
-                       case ELEMENT_REF:
-                               pMedia = (MMS_MEDIA_S *)calloc(sizeof(MMS_MEDIA_S), 1);
-                               pMedia->mediatype = MMS_SMIL_MEDIA_IMG_OR_VIDEO;
-                               memset(cmd, 0, ELEMENT_MAX);
-                               cmd[ELEMENT_REF] = true;
-                               break;
-
-                       case ELEMENT_ANIMATE:
-                               pMedia = (MMS_MEDIA_S *)calloc(sizeof(MMS_MEDIA_S), 1);
-                               pMedia->mediatype = MMS_SMIL_MEDIA_ANIMATE;
-                               memset(cmd, 0, ELEMENT_MAX);
-                               cmd[ELEMENT_ANIMATE] = true;
-                               break;
-
-                       default:
-                               memset(cmd, 0, ELEMENT_MAX);
-                               break;
-                       }
-
-                       //Get Smil Attribute =====================================================
-                       xmlAttr *pAttr = cur_node->properties;
-                       SMIL_ATTRIBUTE_T paramType = ATTRIBUTE_UNKNOWN;
-
-                       for ( ; pAttr; pAttr = pAttr->next) {
-                               MSG_DEBUG("AttributeType: (%s, %s) ", pAttr->name, pAttr->children->content);
-                               switch (attrType = MmsSmilGetAttrID((char *)pAttr->name)) {
-                               case ATTRIBUTE_ID:
-                                       {
-                                               if (cmd[ELEMENT_REGION]) {
-                                                       strncpy(pRegion->szID, (char *)pAttr->children->content, MAX_SMIL_REGION_ID - 1);
-                                               } else if (cmd[ELEMENT_TRANSITION]) {
-                                                       strncpy(pTransition->szID, (char *)pAttr->children->content, MAX_SMIL_TRANSITION_ID - 1);
-                                               } else if (cmd[ELEMENT_META]) {
-                                                       strncpy(pMeta->szID, (char *)pAttr->children->content, MAX_SMIL_META_ID - 1);
-                                               }
-                                       }
-                                       break;
-
-                               case ATTRIBUTE_TOP:
-                                       {
-                                               int bUnitPercent;
-                                               int value;
-
-                                               if (strchr((char *)pAttr->children->content, '%'))
-                                                       bUnitPercent = true;
-                                               else
-                                                       bUnitPercent = false;
-
-                                               value = atoi((char *)pAttr->children->content);
-
-                                               if (cmd[ELEMENT_REGION]) {
-                                                       pRegion->nTop.bUnitPercent = bUnitPercent;
-                                                       pRegion->nTop.value = value;
-                                               }
-                                       }
-                                       break;
-
-                               case ATTRIBUTE_LEFT:
-                                       {
-                                               int bUnitPercent;
-                                               int value;
-
-                                               if (strchr((char *)pAttr->children->content, '%'))
-                                                       bUnitPercent = true;
-                                               else
-                                                       bUnitPercent = false;
-
-                                               value = atoi((char *)pAttr->children->content);
-
-                                               if (cmd[ELEMENT_REGION]) {
-                                                       pRegion->nLeft.bUnitPercent = bUnitPercent;
-                                                       pRegion->nLeft.value = value;
-                                               }
-                                       }
-                                       break;
-
-
-                               case ATTRIBUTE_WIDTH:
-                                       {
-                                               int bUnitPercent;
-                                               int value;
-
-                                               if (strchr((char *)pAttr->children->content, '%'))
-                                                       bUnitPercent = true;
-                                               else
-                                                       bUnitPercent = false;
-
-                                               value = atoi((char *)pAttr->children->content);
-
-                                               if (cmd[ELEMENT_ROOTLAYOUT]) {
-                                                       rootlayout.width.bUnitPercent = bUnitPercent;
-                                                       rootlayout.width.value = value;
-                                               } else if (cmd[ELEMENT_REGION]) {
-                                                       pRegion->width.bUnitPercent = bUnitPercent;
-                                                       pRegion->width.value = value;
-                                               }
-                                       }
-                                       break;
-
-                               case ATTRIBUTE_HEIGHT:
-                                       {
-                                               int bUnitPercent;
-                                               int value;
-
-                                               if (strchr((char *)pAttr->children->content, '%'))
-                                                       bUnitPercent = true;
-                                               else
-                                                       bUnitPercent = false;
-
-                                               value = atoi((char *)pAttr->children->content);
-
-                                               if (cmd[ELEMENT_ROOTLAYOUT]) {
-                                                       rootlayout.height.bUnitPercent = bUnitPercent;
-                                                       rootlayout.height.value = value;
-                                               } else if (cmd[ELEMENT_REGION]) {
-                                                       pRegion->height.bUnitPercent = bUnitPercent;
-                                                       pRegion->height.value = value;
-                                               }
-                                       }
-                                       break;
-
-                               case ATTRIBUTE_FIT:
-                                       if (cmd[ELEMENT_REGION]) {
-                                               if (!strcmp((char *)pAttr->children->content, "meet")) {
-                                                       pRegion->fit = MMSUI_IMAGE_REGION_FIT_MEET;
-                                               } else {
-                                                       pRegion->fit = MMSUI_IMAGE_REGION_FIT_HIDDEN;
-                                               }
-                                       }
-                                       break;
-
-                               case ATTRIBUTE_BGCOLOR:
-                                       if (cmd[ELEMENT_ROOTLAYOUT])
-                                               rootlayout.bgColor = MmsSmilGetColorValue(pAttr->children->content);
-                                       else if (cmd[ELEMENT_REGION])
-                                               pRegion->bgColor = MmsSmilGetColorValue(pAttr->children->content);
-                                       else if (cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.nBgColor = MmsSmilGetColorValue(pAttr->children->content);
-                                       else
-                                               pMedia->sMedia.sAVI.nBgColor = MmsSmilGetColorValue(pAttr->children->content);
-
-                                       break;
-
-                               case ATTRIBUTE_DUR:
-                                       if (cmd[ELEMENT_PAR])
-                                               pPage->nDur =  MmsSmilGetTime((char *)pAttr->children->content);
-                                       else if (cmd[ELEMENT_TRANSITION])
-                                               pTransition->nDur =  MmsSmilGetTime((char *)pAttr->children->content);
-                                       else if (cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.nDurTime =  MmsSmilGetTime((char *)pAttr->children->content);
-                                       else
-                                               pMedia->sMedia.sAVI.nDurTime =  MmsSmilGetTime((char *)pAttr->children->content);
-
-                                       break;
-
-                               case ATTRIBUTE_SRC:
-                                       {
-                                               char *szSrc;
-                                               char szTmpSrc[MSG_FILEPATH_LEN_MAX] = {0,};
-                                               char szOutBuf[MSG_FILEPATH_LEN_MAX] = {0, };
-                                               int cLen;
-                                               MsgMultipart *pPart = NULL;
-                                               MmsMsg *pMsg;
-
-                                               szSrc = MsgChangeHexString((char *)pAttr->children->content);
-
-                                               memcpy(pMedia->szSrc, szSrc, strlen(szSrc) + 1);
-                                               free(szSrc);
-
-                                               cLen = strlen(pMedia->szSrc);
-                                               if (!strncasecmp(pMedia->szSrc, "cid:", 4)) {
-                                                       strncpy(szTmpSrc, pMedia->szSrc + 4, cLen - 4);
-                                                       szTmpSrc[cLen - 4] = '\0';
-                                               } else {
-                                                       strncpy(szTmpSrc, pMedia->szSrc, cLen);
-                                                       szTmpSrc[cLen] = '\0';
-                                               }
-
-                                               MmsPluginStorage::instance()->getMmsMessage(&pMsg);
-                                               pPart = pMsg->msgBody.body.pMultipart;
-#ifndef __SUPPORT_DRM__
-                                               MmsSmilGetMediaSrcForNormalMsg(szOutBuf, szTmpSrc, pPart);
-#else
-                                               MmsSmilGetMediaSrcForNormalMsg(szOutBuf, szTmpSrc, pPart, pMedia);
-#endif
-
-                                               strcpy(pMedia->szSrc, szOutBuf);
-                                               MmsSmilGetMediaFilePath(pMedia, szTmpSrc, pMsg->msgID);
-                                       }
-                                       break;
-
-                               case ATTRIBUTE_COLOR:
-                                       if (cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.nColor = MmsSmilGetColorValue(pAttr->children->content);
-                                       break;
-
-                               case ATTRIBUTE_SIZE:
-                                       if (cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.nSize = atoi((char *)pAttr->children->content);
-                                       break;
-
-                               case ATTRIBUTE_BOLD:
-                                       if (cmd[ELEMENT_TEXT]) {
-                                               pMedia->sMedia.sText.bBold = MmsSmilGetFontAttrib((char *)pAttr->children->content);
-                                       }
-                                       break;
-
-                               case ATTRIBUTE_UNDERLINE:
-                                       if (cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.bUnderLine = MmsSmilGetFontAttrib((char *)pAttr->children->content);
-                                       break;
-
-                               case ATTRIBUTE_ITALIC:
-                                       if (cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.bItalic = MmsSmilGetFontAttrib((char *)pAttr->children->content);
-                                       break;
-
-                               case ATTRIBUTE_REVERSE:
-                                       if (cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.bReverse = MmsSmilGetFontAttrib((char *)pAttr->children->content);
-                                       break;
-
-                               case ATTRIBUTE_DIRECTION:
-                                       if (cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.nDirection = MmsSmilGetFontDirection((char *)pAttr->children->content);
-                                       break;
-                               case ATTRIBUTE_REGION:
-                                       strncpy(pMedia->regionId, (char *)pAttr->children->content, MAX_SMIL_REGION_ID - 1);
-                                       break;
-
-                               case ATTRIBUTE_TRANSIN:
-                                       if (cmd[ELEMENT_TEXT])
-                                               strncpy(pMedia->sMedia.sText.szTransInId, (char *)pAttr->children->content, MAX_SMIL_TRANSIN_ID - 1);
-                                       else
-                                               strncpy(pMedia->sMedia.sAVI.szTransInId, (char *)pAttr->children->content, MAX_SMIL_TRANSIN_ID - 1);
-                                       break;
-
-                               case ATTRIBUTE_TRANSOUT:
-                                       if (cmd[ELEMENT_TEXT])
-                                               strncpy(pMedia->sMedia.sText.szTransOutId, (char *)pAttr->children->content, MAX_SMIL_TRANSOUT_ID - 1);
-                                       else
-                                               strncpy(pMedia->sMedia.sAVI.szTransOutId, (char *)pAttr->children->content, MAX_SMIL_TRANSOUT_ID - 1);
-                                       break;
-
-                               case ATTRIBUTE_BEGIN:
-                                       if (cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.nBegin = MmsSmilGetTime((char *)pAttr->children->content);
-                                       else
-                                               pMedia->sMedia.sAVI.nBegin = MmsSmilGetTime((char *)pAttr->children->content);
-                                       break;
-
-                               case ATTRIBUTE_END:
-                                       if (cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.nEnd = MmsSmilGetTime((char *)pAttr->children->content);
-                                       else
-                                               pMedia->sMedia.sAVI.nEnd = MmsSmilGetTime((char *)pAttr->children->content);
-                                       break;
-
-                               case ATTRIBUTE_REPEAT_COUNT:
-                                       if (cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.nRepeat = atoi((char *)pAttr->children->content);
-                                       else
-                                               pMedia->sMedia.sAVI.nRepeat = atoi((char *)pAttr->children->content);
-                                       break;
-
-                               case ATTRIBUTE_NAME:
-                                       if (!strcmp((char *)pAttr->children->content, "foreground-color") || !strcmp((char *)pAttr->children->content, "foregroundcolor"))
-                                               paramType = ATTRIBUTE_FGCOLOR;
-                                       else if (!strcmp((char *)pAttr->children->content, "background-color") || !strcmp((char *)pAttr->children->content, "backgroundcolor"))
-                                               paramType = ATTRIBUTE_BGCOLOR;
-                                       else if (!strcmp((char *)pAttr->children->content, "textsize"))
-                                               paramType = ATTRIBUTE_SIZE;
-                                       else if (!strcmp((char *)pAttr->children->content, "textattribute"))
-                                               paramType = ATTRIBUTE_TEXTFORMAT;
-
-                                       if (cmd[ELEMENT_META])
-                                               strncpy(pMeta->szName, (char *)pAttr->children->content, MAX_SMIL_META_NAME - 1);
-                                       break;
-
-                               case ATTRIBUTE_VALUE:
-                                       if (paramType == ATTRIBUTE_SIZE && cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.nSize = MmsSmilGetFontSizeValue((char *)pAttr->children->content);
-                                       else if (paramType == ATTRIBUTE_FGCOLOR && cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.nColor =  MmsSmilGetColorValue(pAttr->children->content);
-                                       else if (paramType == ATTRIBUTE_BGCOLOR && cmd[ELEMENT_TEXT])
-                                               pMedia->sMedia.sText.nBgColor =  MmsSmilGetColorValue(pAttr->children->content);
-                                       else if (paramType == ATTRIBUTE_TEXTFORMAT && cmd[ELEMENT_TEXT]) {
-                                               MmsSmilFontType fontType;
-
-                                               fontType = MmsSmilGetFontTypeValue((char *)pAttr->children->content);
-
-                                               if (fontType == MMS_SMIL_FONT_TYPE_BOLD)
-                                                       pMedia->sMedia.sText.bBold = true;
-                                               else
-                                                       pMedia->sMedia.sText.bBold = false;
-
-                                               if (fontType == MMS_SMIL_FONT_TYPE_ITALIC)
-                                                       pMedia->sMedia.sText.bItalic = true;
-                                               else
-                                                       pMedia->sMedia.sText.bItalic = false;
-
-                                               if (fontType == MMS_SMIL_FONT_TYPE_UNDERLINE)
-                                                       pMedia->sMedia.sText.bUnderLine = true;
-                                               else
-                                                       pMedia->sMedia.sText.bUnderLine = false;
-                                       }
-                                       break;
-
-                               case ATTRIBUTE_ALT:
-                                       strncpy(pMedia->szAlt, (char *)pAttr->children->content, MAX_SMIL_ALT_LEN - 1);
-                                       break;
-
-                               case ATTRIBUTE_TYPE:
-                                       pTransition->nType = (MmsSmilTransType)atoi((char *)pAttr->children->content);
-
-                                       switch (pTransition->nType) {
-                                       case MMS_SMIL_TRANS_SLIDEWIPE:
-                                               pTransition->nSubType = MMS_SMIL_TRANS_SUB_FROM_LEFT;
-                                               break;
-                                       case MMS_SMIL_TRANS_BARWIPE:
-                                               pTransition->nSubType = MMS_SMIL_TRANS_SUB_TOP_TO_BOTTOM;
-                                               break;
-                                       case MMS_SMIL_TRANS_BARNDOORWIPE:
-                                               pTransition->nSubType = MMS_SMIL_TRANS_SUB_HORIZONTAL;
-                                               break;
-                                       default:
-                                               pTransition->nSubType = MMS_SMIL_TRANS_SUB_NONE;
-                                               break;
-                                       }
-
-                                       break;
-
-                               case ATTRIBUTE_SUBTYPE:
-                                       pTransition->nSubType = (MmsSmilTransSubType)atoi((char *)pAttr->children->content);
-                                       break;
-
-                               case ATTRIBUTE_CONTENT:
-                                       strncpy(pMeta->szContent, (char *)pAttr->children->content, MAX_SMIL_META_CONTENT - 1);
-                                       break;
-                               default:
-                                       MSG_DEBUG("Undefined Attribute was found!!!!!");
-                               }
-                       }
-
-                       if (paramType == ATTRIBUTE_UNKNOWN && cmd[ELEMENT_REGION]) {
-                               // Insert a region to region list
-                               _MsgMmsAddRegion(pMmsMsg, pRegion);
-                       } else if (paramType == ATTRIBUTE_UNKNOWN && cmd[ELEMENT_PAR]) {
-                               //Insert a page to page list
-                               _MsgMmsAddPage(pMmsMsg, pPage);
-                       } else if (paramType == ATTRIBUTE_UNKNOWN && (cmd[ELEMENT_TEXT] ||cmd[ELEMENT_IMG] ||cmd[ELEMENT_AUDIO] ||cmd[ELEMENT_VIDEO] ||cmd[ELEMENT_ANIMATE])) {
-                               //Insert a media to media list
-                               _MsgMmsAddMedia(pPage, pMedia);
-                       } else if (paramType == ATTRIBUTE_UNKNOWN && cmd[ELEMENT_ROOTLAYOUT]) {
-                               _MsgMmsSetRootLayout(pMmsMsg, &rootlayout);
-                       } else if (paramType == ATTRIBUTE_UNKNOWN && cmd[ELEMENT_TRANSITION]) {
-                               //Insert a transition to transition list
-                               _MsgMmsAddTransition(pMmsMsg, pTransition);
-                       } else if (paramType == ATTRIBUTE_UNKNOWN && cmd[ELEMENT_META]) {
-                               //Insert a meta to meta list
-                               _MsgMmsAddMeta(pMmsMsg, pMeta);
-                       }
-
-                       paramType = ATTRIBUTE_UNKNOWN;
-               }
-
-               MmsSmilGetElement(pMmsMsg, cur_node->children);
-       }
-
-       MSG_END();
-}
-
-
-int MmsSmilGetColorValue(xmlChar *content)
-{
-       int color;
-
-       if (content[0] == '#')  // RGB value
-               color = MmsSmilAtoIHexa((char *)&content[1]);
-       else if (content[0] == '0' && (content[1] == 'x' || content[1] == 'X'))
-               color = MmsSmilAtoIHexa((char *)&content[2]);
-       else {
-               MSG_DEBUG("Invalid Color Value");
-               color = -1;
-       }
-
-       return color;
-}
-
-int MmsSmilAtoIHexa(char *pInput)
-{
-       int res = 0;
-       int len = 0;
-       int temp = 1;
-       int i  = 0;
-       int j = 0;
-       char *pOutput = NULL;
-
-       MSG_DEBUG("__MmsSmilAtoIHexa() enter..\n");
-
-       len = strlen(pInput);
-       pOutput = (char *)malloc(len + 1);
-
-       if (pOutput == NULL) {
-               MSG_DEBUG("__MmsSmilAtoIHexa: Memory full \n");
-               goto __CATCH;
-       }
-
-       memset(pOutput, 0, len + 1);
-
-       for (i = len - 1; i >= 0; i--) {
-               for (j = 0; j < (len - 1 - i); j++) {
-                       temp *= 16;
-               }
-
-               switch (pInput[i]) {
-               case '0':
-                       pOutput[i] = 0;
-                       break;
-
-               case '1':
-                       pOutput[i] = 1;
-                       break;
-
-               case '2':
-                       pOutput[i] = 2;
-                       break;
-
-               case '3':
-                       pOutput[i] = 3;
-                       break;
-
-               case '4':
-                       pOutput[i] = 4;
-                       break;
-
-               case '5':
-                       pOutput[i] = 5;
-                       break;
-
-               case '6':
-                       pOutput[i] = 6;
-                       break;
-
-               case '7':
-                       pOutput[i] = 7;
-                       break;
-
-               case '8':
-                       pOutput[i] = 8;
-                       break;
-
-               case '9':
-                       pOutput[i] = 9;
-                       break;
-
-               case 'a':
-               case 'A':
-                       pOutput[i] = 10;
-                       break;
-
-               case 'b':
-               case 'B':
-                       pOutput[i] = 11;
-                       break;
-
-               case 'c':
-               case 'C':
-                       pOutput[i] = 12;
-                       break;
-
-               case 'd':
-               case 'D':
-                       pOutput[i] = 13;
-                       break;
-
-               case 'e':
-               case 'E':
-                       pOutput[i] = 14;
-                       break;
-
-               case 'f':
-               case 'F':
-                       pOutput[i] = 15;
-                       break;
-               }
-
-               res += (pOutput[i] * temp);
-               temp = 1;
-       }
-
-__CATCH:
-
-       if (pOutput) {
-               free(pOutput);
-               pOutput = NULL;
-       }
-
-       return res;
-}
-
-int MmsSmilGetTime(char *pValue)
-{
-       char *pTemp = NULL;
-       bool bMSec = false;
-       int retVal = 0;
-       int i = 0;
-       int len = 0;
-
-       if (pValue == NULL || pValue[0] == '\0')
-               return 0;
-
-       len = strlen(pValue);
-
-       /* Default time unit -> millisecond */
-       if (strstr(pValue, "msec"))
-               bMSec = true;
-
-       if (strstr(pValue, "ms"))
-               bMSec = true;
-
-       pTemp = (char *)malloc(strlen(pValue) + 1);
-
-       if (NULL == pTemp) {
-               MSG_DEBUG("__MmsSmilGetTime : malloc for <time> attribute is failed \n");
-               return 0;
-       }
-
-       while (isdigit(pValue[i])) {
-               pTemp[i] = pValue[i];
-               i++;
-       }
-       pTemp[i] = '\0';
-
-       /* Detect 's' and 'ms' here */
-       retVal = atoi(pTemp);
-
-       if (bMSec == false)
-               retVal *= 1000;
-
-       if (pTemp) {
-               free(pTemp);
-               pTemp = NULL;
-       }
-
-       return retVal;
-}
-#ifndef __SUPPORT_DRM__
-int MmsSmilGetMediaSrcForNormalMsg(char *szOutbuf, char *szInBuf, MsgMultipart *pPart)
-#else
-int MmsSmilGetMediaSrcForNormalMsg(char *szOutbuf, char *szInBuf, MsgMultipart *pPart, MMS_MEDIA_S *pMedia)
-#endif
-{
-       char szContentID[MSG_MSG_ID_LEN + 1] = {0, };
-       char szContentLI[MSG_MSG_ID_LEN + 1] = {0, };
-       int cLen  = 0;
-       int nPart = 0;
-
-       MSG_DEBUG("szInBuf: %s", szInBuf);
-       while (pPart && pPart->pBody) {
-               if (pPart->type.szContentID[0]) {
-                       cLen = strlen(pPart->type.szContentID);
-
-                       if (pPart->type.szContentID[0] == '<' && pPart->type.szContentID[cLen - 1] == '>') {
-                               strncpy(szContentID, &pPart->type.szContentID[1], cLen - 2);
-                               szContentID[cLen - 2] = '\0';
-                       } else if (pPart->type.szContentID[0] == MSG_CH_QUOT && pPart->type.szContentID[cLen-1] == MSG_CH_QUOT) {
-                               strncpy(szContentID, &pPart->type.szContentID[1], cLen - 2);
-                               szContentID[cLen - 2] = '\0';
-                       } else {
-                               strncpy(szContentID, pPart->type.szContentID, cLen);
-                               szContentID[cLen] = '\0';
-                       }
-               } else {
-                       szContentID[0] = '\0';
-               }
-
-               MSG_DEBUG("szContentID: %s", szContentID);
-
-               if (pPart->type.szContentLocation[0]) {
-                       cLen = strlen(pPart->type.szContentLocation);
-
-                       if (pPart->type.szContentLocation[0] == MSG_CH_QUOT &&
-                               pPart->type.szContentLocation[cLen-1] == MSG_CH_QUOT) {
-                               strncpy(szContentLI, &pPart->type.szContentLocation[1], cLen-2);
-                               szContentLI[cLen-2] = '\0';
-                       } else {
-                               strncpy(szContentLI, pPart->type.szContentLocation, cLen);
-                               szContentLI[cLen] = '\0';
-                       }
-               } else {
-                       szContentLI[0] = '\0';
-               }
-
-               MSG_DEBUG("szContentLocation: %s", szContentLI);
-
-               if (strcasecmp(szContentID, szInBuf) == 0) {
-                       strcpy(szOutbuf, pPart->type.param.szFileName);
-                       MSG_DEBUG("match with szContentID.");
-                       goto RETURN;
-               } else {
-                       char *szInFileName = strrchr(szInBuf, '/');
-
-                       if (szInFileName == NULL) {
-                               szInFileName = szInBuf;
-                       } else
-                               szInFileName++;
-
-                       if (strcasecmp(szContentLI, szInFileName) == 0) {
-                               strcpy(szOutbuf, pPart->type.param.szFileName);
-                               MSG_DEBUG("match with szContentLI.");
-                               goto RETURN;
-                       } else if (strcasecmp(pPart->type.param.szName, szInBuf) == 0) {
-                               strcpy(szOutbuf, pPart->type.param.szFileName);
-                               MSG_DEBUG("match with pPart->type.param.szName.");
-                               goto RETURN;
-                       } else if (strlen(szContentID) > 4) {
-                               if (strcasecmp(strtok(szContentID, "."), strtok(szInBuf, ".")) == 0) {
-                                       strcpy(szOutbuf, pPart->type.param.szFileName);
-                                       MSG_DEBUG("only name is match with szContentID.");
-                                       goto RETURN;
-                               }
-                       } else if (strlen(szContentLI) > 4) {
-                               if (strcasecmp(strtok(szContentLI, "."), strtok(szInBuf, ".")) == 0) {
-                                       strcpy(szOutbuf, pPart->type.param.szFileName);
-                                       MSG_DEBUG("only name is match with szContentLI.");
-                                       goto RETURN;
-                               }
-                       }
-               }
-
-               nPart++;
-               pPart = pPart->pNext;
-       }
-
-       return -1;
-
-RETURN:
-#ifdef __SUPPORT_DRM__
-       pMedia->drmType = pPart->type.drmInfo.drmType;
-
-       if (pPart->type.drmInfo.szDrm2FullPath != NULL) {
-               MSG_DEBUG("szDrm2FullPath: %s", pPart->type.drmInfo.szDrm2FullPath);
-               strncpy(pMedia->szDrm2FullPath, pPart->type.drmInfo.szDrm2FullPath, MSG_FILEPATH_LEN_MAX - 1);
-       }
-#endif
-       return nPart;
-
-}
-
-int    MmsSmilGetElementID(char *pString)
-{
-       if (!strcmp(pString, "smil"))
-               return ELEMENT_SMIL;
-       else if (!strcmp(pString, "head"))
-               return ELEMENT_HEAD;
-       else if (!strcmp(pString, "layout"))
-               return ELEMENT_LAYOUT;
-       else if (!strcmp(pString, "root-layout"))
-               return ELEMENT_ROOTLAYOUT;
-       else if (!strcmp(pString, "region"))
-               return ELEMENT_REGION;
-       else if (!strcmp(pString, "body"))
-               return ELEMENT_BODY;
-       else if (!strcmp(pString, "par"))
-               return ELEMENT_PAR;
-       else if (!strcmp(pString, "param"))
-               return ELEMENT_PARAM;
-       else if (!strcmp(pString, "text"))
-               return ELEMENT_TEXT;
-       else if (!strcmp(pString, "img"))
-               return ELEMENT_IMG;
-       else if (!strcmp(pString, "audio"))
-               return ELEMENT_AUDIO;
-       else if (!strcmp(pString, "video"))
-               return ELEMENT_VIDEO;
-       else if (!strcmp(pString, "ref"))
-               return ELEMENT_REF;
-       else if (!strcmp(pString, "animate"))
-               return ELEMENT_ANIMATE;
-       else if (!strcmp(pString, "root-layout"))
-               return ELEMENT_HEAD;
-       else if (!strcmp(pString, "transition"))
-               return ELEMENT_TRANSITION;
-       else if (!strcmp(pString, "meta"))
-               return ELEMENT_META;
-       else
-               return -1;
-}
-
-int    MmsSmilGetAttrID(char *pString)
-{
-       if (!strcmp(pString, "id"))
-               return ATTRIBUTE_ID;
-       else if (!strcmp(pString, "top"))
-               return ATTRIBUTE_TOP;
-       else if (!strcmp(pString, "left"))
-               return ATTRIBUTE_LEFT;
-       else if (!strcmp(pString, "width"))
-               return ATTRIBUTE_WIDTH;
-       else if (!strcmp(pString, "height"))
-               return ATTRIBUTE_HEIGHT;
-       else if (!strcmp(pString, "fit"))
-               return ATTRIBUTE_FIT;
-       else if (!strcmp(pString, "backgroundColor"))
-               return ATTRIBUTE_BGCOLOR;
-       else if (!strcmp(pString, "dur"))
-               return ATTRIBUTE_DUR;
-       else if (!strcmp(pString, "src"))
-               return ATTRIBUTE_SRC;
-       else if (!strcmp(pString, "color"))
-               return ATTRIBUTE_COLOR;
-       else if (!strcmp(pString, "bold"))
-               return ATTRIBUTE_BOLD;
-       else if (!strcmp(pString, "underline"))
-               return ATTRIBUTE_UNDERLINE;
-       else if (!strcmp(pString, "italic"))
-               return ATTRIBUTE_ITALIC;
-       else if (!strcmp(pString, "reverse"))
-               return ATTRIBUTE_REVERSE;
-       else if (!strcmp(pString, "direction"))
-               return ATTRIBUTE_DIRECTION;
-       else if (!strcmp(pString, "size"))
-               return ATTRIBUTE_SIZE;
-       else if (!strcmp(pString, "font"))
-               return ATTRIBUTE_FONT;
-       else if (!strcmp(pString, "region"))
-               return ATTRIBUTE_REGION;
-       else if (!strcmp(pString, "name"))
-               return ATTRIBUTE_NAME;
-       else if (!strcmp(pString, "value"))
-               return ATTRIBUTE_VALUE;
-       else if (!strcmp(pString, "alt"))
-               return ATTRIBUTE_ALT;
-       else if (!strcmp(pString, "type"))
-               return ATTRIBUTE_TYPE;
-       else if (!strcmp(pString, "subtype"))
-               return ATTRIBUTE_SUBTYPE;
-       else if (!strcmp(pString, "content"))
-               return ATTRIBUTE_CONTENT;
-       else if (!strcmp(pString, "transIn"))
-               return ATTRIBUTE_TRANSIN;
-       else if (!strcmp(pString, "transOut"))
-               return ATTRIBUTE_TRANSOUT;
-       else if (!strcmp(pString, "begin"))
-               return ATTRIBUTE_BEGIN;
-       else if (!strcmp(pString, "end"))
-               return ATTRIBUTE_END;
-       else if (!strcmp(pString, "repeatCount"))
-               return ATTRIBUTE_REPEAT_COUNT;
-       else
-               return -1;
-}
-
-bool MmsSmilGetFontAttrib(char *pString)
-{
-       if (!strcmp(pString, "true"))
-               return true;
-       else
-               return false;
-}
-
-MmsTextDirection MmsSmilGetFontDirection(char *pString)
-{
-       MmsTextDirection direction = MMS_TEXT_DIRECTION_INVALID;
-
-       if (!strcmp(pString, "right"))
-               direction = MMS_TEXT_DIRECTION_RIGHT;
-       else if (!strcmp(pString, "down"))
-               direction = MMS_TEXT_DIRECTION_DOWN;
-
-       return direction;
-}
-
-int MmsSmilGetFontSizeValue(char *pString)
-{
-       MSG_DEBUG(" #### content = %s #### ", pString);
-       if (!strcmp(pString, "small"))
-               return MMS_SMIL_FONT_SIZE_SMALL;
-       else if (!strcmp(pString, "normal"))
-               return MMS_SMIL_FONT_SIZE_NORMAL;
-       else if (!strcmp(pString, "large"))
-               return MMS_SMIL_FONT_SIZE_LARGE;
-       else
-               return atoi(pString);
-}
-
-MmsSmilFontType MmsSmilGetFontTypeValue(char *pString)
-{
-       MSG_DEBUG(" #### content = %s #### ", pString);
-
-       if (!strcmp(pString, "normal"))
-               return MMS_SMIL_FONT_TYPE_NORMAL;
-       else if (!strcmp(pString, "italic"))
-               return MMS_SMIL_FONT_TYPE_ITALIC;
-       else if (!strcmp(pString, "bold"))
-               return MMS_SMIL_FONT_TYPE_BOLD;
-       else if (!strcmp(pString, "underline"))
-               return MMS_SMIL_FONT_TYPE_UNDERLINE;
-       else
-               return MMS_SMIL_FONT_TYPE_NORMAL;
-}
-
-bool MmsSmilGetMediaFilePath(MMS_MEDIA_S *pMedia, char *pszTemp, int msgID)
-{
-       if (!pMedia) {
-               MSG_DEBUG("pMedia is NULL");
-               return false;
-       }
-
-       snprintf(pMedia->szFilePath, MSG_FILEPATH_LEN_MAX, "%s%s", MSG_DATA_PATH, pMedia->szSrc);
-       MSG_DEBUG("pMedia's filePath: %s", pMedia->szFilePath);
-
-       __MmsGetRealFileName(pMedia->mediatype, pMedia->szSrc, pMedia->szFileName, msgID);
-       MSG_DEBUG("pMedia's fileName: %s", pMedia->szFileName);
-
-       snprintf(pMedia->szContentID, MSG_MSG_ID_LEN+1, "%s", pszTemp);
-       MSG_DEBUG("pMedia's ContentID: %s", pMedia->szContentID);
-
-       return true;
-}
-
-
-/**    @fn             bool MMSGenerateSmilBuffer(MMS_MESSAGE_DATA_S *pstMsgBody)
- *     @brief  Forms Smil Buffer using pstMsgBody. \n
- *     @param[in/out]  pstMsgBody is Message handle. \n
- *     @retval TRUE                            In case of Success. \n
- *     @retval FALSE                           In case of failure. \n
- */
-bool MMSGenerateSmilBuffer(MMS_MESSAGE_DATA_S *pstMsgBody)
-{
-       HMmsSmil hSmilDoc = INVALID_HOBJ;
-       int nIndex;
-       int nMediaIndex;
-       int nTotalPageNum;
-       int nTotalMediaNum;
-       int nRegionCount;
-       MMS_PAGE_S *pstPage;
-       MMS_MEDIA_S *pstMedia;
-       MMS_SMIL_REGION *pstRegion;
-       char *pszRawData;
-
-       MSG_BEGIN();
-
-       hSmilDoc = MmsSmilCreateEmptySmilDoc();
-       MSG_DEBUG("Smil Doc =%d",hSmilDoc);
-       if (INVALID_HOBJ == hSmilDoc) {
-               MSG_DEBUG("Invalid SmilDoc[%d]",hSmilDoc);
-               return false;
-       }
-       // Add Root Layout to Smil Document
-       if (false == MmsSmilAddRootLayout(hSmilDoc, &(pstMsgBody->rootlayout))) {
-               MSG_DEBUG("MmsSmilAddRootLayout Failed");
-               MmsSmilDestroyDoc(hSmilDoc);
-       }
-       //Add Region list to Smil Document
-       nRegionCount = pstMsgBody->regionCnt;
-       MSG_DEBUG(" Region Count =%d",nRegionCount);
-       for (nIndex = 0; nIndex < nRegionCount; nIndex++) {
-               MSG_DEBUG("Calling _MsgMmsGetSmilRegion");
-               pstRegion = _MsgMmsGetSmilRegion(pstMsgBody, nIndex);
-               if (NULL == pstRegion) {
-                       MSG_DEBUG("pstRegion is NULL");
-                       MmsSmilDestroyDoc(hSmilDoc);
-                       return false;
-               }
-               MSG_DEBUG("Calling MmsSmilAddRegion");
-               if (false == MmsSmilAddRegion(hSmilDoc, pstRegion)) {
-                       MSG_DEBUG("Adding Region to smil doc failed");
-                       MmsSmilDestroyDoc(hSmilDoc);
-                       return false;
-               }
-       }
-       // Add page list to Smil Document
-        nTotalPageNum = pstMsgBody->pageCnt ;
-       MSG_DEBUG(" Page Count =%d",nTotalPageNum);
-       for (nIndex = 0; nIndex < nTotalPageNum; nIndex++) {
-               MSG_DEBUG("Calling _MsgMmsGetPage");
-               pstPage = _MsgMmsGetPage(pstMsgBody, nIndex);
-               if (NULL == pstPage) {
-                       MSG_DEBUG("pstPage is NULL");
-                       MmsSmilDestroyDoc(hSmilDoc);
-                       return false;
-               }
-               // Add page to smil doc
-               MSG_DEBUG("Calling MmsSmilAddPage");
-               if (false == MmsSmilAddPage(hSmilDoc, pstPage)) {
-                       MSG_DEBUG("Adding page to smil doc failed");
-                       MmsSmilDestroyDoc(hSmilDoc);
-                       return false;
-               }
-               nTotalMediaNum = pstPage->mediaCnt;
-               MSG_DEBUG(" Media Count =%d",nTotalMediaNum);
-               for (nMediaIndex = 0; nMediaIndex < nTotalMediaNum; nMediaIndex++) {
-                       MSG_DEBUG("Calling _MsgMmsGetMedia");
-                       pstMedia = _MsgMmsGetMedia(pstPage, nMediaIndex);
-                       if (NULL == pstMedia) {
-                               MSG_DEBUG("pMedia is NULL");
-                               MmsSmilDestroyDoc(hSmilDoc);
-                               return false;
-                       }
-                       MSG_DEBUG("Calling MmsSmilAddMedia");
-                       if (false == MmsSmilAddMedia(hSmilDoc, nIndex, nMediaIndex, pstMedia, pstMedia->szContentID)) {
-                               MSG_DEBUG("MmsSmilAddMedia failed");
-                               MmsSmilDestroyDoc(hSmilDoc);
-                               return false;
-                       }
-               }
-       }
-       MSG_DEBUG("MMSGenerateSmilBuffer: Start update template");
-       pszRawData = MmsSmilGetRawData(hSmilDoc);
-       if (NULL == pszRawData) {
-               MSG_DEBUG("MMSGenerateSmilBuffer: MmsSmilGetRawData failed");
-               MmsSmilDestroyDoc(hSmilDoc);
-               return false;
-       }
-
-       char fullpath[MSG_FILEPATH_LEN_MAX] = {0,};
-       snprintf(fullpath, MSG_FILEPATH_LEN_MAX, MSG_SMIL_FILE_PATH"%s", pstMsgBody->szSmilFilePath);
-
-       if (MsgWriteSmilFile(fullpath, pszRawData, strlen(pszRawData) + 1) == false) {
-               MSG_DEBUG("MMSGenerateSmilBuffer: MsgWriteSmilFile failed");
-               xmlFree((xmlChar*)pszRawData);
-               MmsSmilDestroyDoc(hSmilDoc);
-               return false;
-       }
-
-       MSG_DEBUG("MMSGenerateSmilBuffer: complete update template\n");
-       xmlFree((xmlChar*)pszRawData);
-       MmsSmilDestroyDoc(hSmilDoc);
-       MSG_END();
-       return true;
-}
-
-/**    @fn             static HMmsSmil MmsSmilCreateEmptySmilDoc(void)
- *     @brief  Creates default Smil Doc based on input gszEmptyRawDoc. \n
- *     @retval Returns Smil Document number. \n
- */
-HMmsSmil MmsSmilCreateEmptySmilDoc(void)
-{
-       HMmsSmil hMmsSmil;
-
-       MSG_BEGIN();
-
-       hMmsSmil = MmsSmilCreateSmilDoc(gszEmptyRawDoc);
-
-       MSG_DEBUG("Create an empty smilDoc.(Handle = %d)", hMmsSmil);
-
-       MSG_END();
-
-       return hMmsSmil;
-}
-
-/**    @fn                     static HMmsSmil MmsSmilCreateSmilDoc(char *pszRawData)
- *     @brief          Creates Smil Doc based on input pszRawData. \n
- *     @param[in]      pszRawData is smil buffer. \n
- *     @retval         Returns Smil Document number. \n
- */
-HMmsSmil MmsSmilCreateSmilDoc(char *pszRawData)
-{
-       int nSmilDocNo = 0;
-       xmlNodePtr stRootNode;
-
-       MSG_BEGIN();
-
-       // Destroy smil doc if present
-       if (NULL != __gpaMmsSmilDoc[nSmilDocNo]) {
-               MSG_DEBUG("Calling MmsSmilDestroyDoc");
-               if (false == MmsSmilDestroyDoc(nSmilDocNo)) {
-                       MSG_DEBUG("MmsSmilDestroyDoc: Failed!");
-               }
-       }
-
-       for (nSmilDocNo = 0; nSmilDocNo < MMS_SMIL_MAX_DOC; nSmilDocNo++) {
-               if (NULL == __gpaMmsSmilDoc[nSmilDocNo])
-                       break;
-       }
-
-       if (MMS_SMIL_MAX_DOC == nSmilDocNo) {
-               MSG_DEBUG("SmilDoc table is full. Can't create.");
-               return INVALID_HOBJ;
-       }
-       __gpaMmsSmilDoc[nSmilDocNo] = (MmsSmilDoc*)malloc(sizeof(MmsSmilDoc));
-       if (NULL ==  __gpaMmsSmilDoc[nSmilDocNo]) {
-               MSG_DEBUG("Memory Allocation Failed.");
-               return INVALID_HOBJ;
-       }
-       memset(__gpaMmsSmilDoc[nSmilDocNo], 0, sizeof(MmsSmilDoc));
-
-       __gpaMmsSmilDoc[nSmilDocNo]->pSmilDoc = xmlParseMemory(pszRawData, strlen(pszRawData));
-       if (NULL == __gpaMmsSmilDoc[nSmilDocNo]->pSmilDoc) {
-               MSG_DEBUG("Document not parsed successfully.");
-               if (false == MmsSmilDestroyDoc(nSmilDocNo)) {
-                       MSG_DEBUG("MmsSmilDestroyDoc: Failed!");
-               }
-               return INVALID_HOBJ;
-       }
-       stRootNode = xmlDocGetRootElement(__gpaMmsSmilDoc[nSmilDocNo]->pSmilDoc);
-       if (NULL == stRootNode) {
-               MSG_DEBUG("Empty document\n");
-               if (false == MmsSmilDestroyDoc(nSmilDocNo)) {
-                       MSG_DEBUG("MmsSmilDestroyDoc: Failed!");
-               }
-               return INVALID_HOBJ;
-       }
-       if (xmlStrcmp(stRootNode->name, (const xmlChar *) "smil")) {
-               MSG_DEBUG("Document of the wrong type, root node != smil");
-               if (false == MmsSmilDestroyDoc(nSmilDocNo)) {
-                       MSG_DEBUG("MmsSmilDestroyDoc: Failed!");
-               }
-               return INVALID_HOBJ;
-       }
-
-       __gpaMmsSmilDoc[nSmilDocNo]->pstRootNode = stRootNode;
-
-       MSG_END();
-       return ((HMmsSmil)nSmilDocNo);
-}
-
-/**    @fn                     static bool MmsSmilDestroyDoc(HMmsSmil hSmilDoc)
- *     @brief          Destroys Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @retval TRUE                            In case of Success. \n
- *     @retval FALSE                           In case of failure. \n
- */
-bool MmsSmilDestroyDoc(HMmsSmil hSmilDoc)
-{
-       int nSmilDocNo = (int)hSmilDoc;
-       bool bFlag = true;
-       MSG_BEGIN();
-
-       if (0 <= nSmilDocNo &&
-               nSmilDocNo < MMS_SMIL_MAX_DOC &&
-               __gpaMmsSmilDoc[nSmilDocNo]) {
-               if (__gpaMmsSmilDoc[nSmilDocNo]->pSmilDoc) {
-                       xmlFreeDoc(__gpaMmsSmilDoc[nSmilDocNo]->pSmilDoc);
-               }
-
-               if (__gpaMmsSmilDoc[nSmilDocNo]->pstRootNode) {
-                       //Need to Check
-               }
-               free(__gpaMmsSmilDoc[nSmilDocNo]);
-               __gpaMmsSmilDoc[nSmilDocNo] = NULL;
-       } else {
-               MSG_DEBUG("Invalid SmilDoc(hSmilDoc:%d)", nSmilDocNo);
-               bFlag =  false;
-       }
-
-       MSG_END();
-       return bFlag;
-}
-
-/**    @fn                     static bool IsValidSmilDocNo(int nSmilDocNo)
- *     @brief          Form Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @retval         Returns Smil Buffer     In case of success. \n
- *     @retval         Returns NULL                    In case of failure. \n
- */
-bool IsValidSmilDocNo(int nSmilDocNo)
-{
-       bool bIsValidSmil = false;
-
-       MSG_BEGIN();
-
-       if (0 <= nSmilDocNo &&
-               nSmilDocNo < MMS_SMIL_MAX_DOC &&
-               __gpaMmsSmilDoc[nSmilDocNo] &&
-               __gpaMmsSmilDoc[nSmilDocNo]->pSmilDoc) {
-               bIsValidSmil = true;
-       }
-
-       MSG_END();
-       return bIsValidSmil;
-}
-
-/**    @fn                     static char  MmsSmilGetRawData(HMmsSmil hSmilDoc)
- *     @brief          Form Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @retval         Returns Smil Buffer     In case of success. \n
- *     @retval         Returns NULL                    In case of failure. \n
- */
-char *MmsSmilGetRawData(HMmsSmil hSmilDoc)
-{
-       int nSmilDocNo = (int)hSmilDoc;
-       char *pszRawData = NULL;
-
-       MSG_BEGIN();
-
-       if (IsValidSmilDocNo(nSmilDocNo)) {
-               xmlSaveFormatFileEnc("-", __gpaMmsSmilDoc[nSmilDocNo]->pSmilDoc, "UTF-8", 1);
-               xmlDocDumpMemory(__gpaMmsSmilDoc[nSmilDocNo]->pSmilDoc, (xmlChar **)(&pszRawData) , NULL);
-               if (NULL == pszRawData) {
-                       MSG_DEBUG("Invalid pSmilDoc (now wellformed document)");
-               }
-               MSG_END();
-       } else {
-               MSG_DEBUG("Invalid SmilDoc(hSmilDoc:%d)", nSmilDocNo);
-       }
-       return pszRawData;
-}
-
-/**    @fn                     static bool MmsSmilAddPage(HMmsSmil hSmilDoc, MMS_PAGE_S *pstSmilPage)
- *     @brief          Add Page to Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @param[in]      pstSmilPage specifies page information. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool MmsSmilAddPage(HMmsSmil hSmilDoc, MMS_PAGE_S *pstSmilPage)
-{
-       int nSmilDocNo = hSmilDoc;
-
-       MSG_BEGIN();
-
-       bool ret = true;
-
-       if (IsValidSmilDocNo(nSmilDocNo)) {
-               xmlNodePtr pstParElement;
-               xmlNodePtr pstBodyElement;
-               xmlNodePtr pstParList;
-               char szBuf[MSG_STDSTR_SHORT] = {0, };
-
-               pstBodyElement = UtilxmlStringGetNodeList(__gpaMmsSmilDoc[nSmilDocNo]->pstRootNode, (char *)"body");
-
-               if (NULL == pstBodyElement) {
-                       MSG_DEBUG("There is no <body> node. Can't create <par> node.");
-                       return false;
-               }
-               MSG_DEBUG("Body Element Name = %s", (char *)pstBodyElement->name);
-               /* Create "par"  node and insert it */
-               pstParElement = xmlNewNode(NULL, (xmlChar *)"par");
-
-               if (NULL == pstParElement) {
-                       MSG_DEBUG("Can't create <par> node. (from XmlParser) \n");
-                       return false;
-               }
-               MSG_DEBUG("Par Element Name = %s", (char *)pstParElement->name);
-
-               /* Add attributes to "par" */
-               if (pstSmilPage->nDur > 0) {
-                       snprintf(szBuf, MSG_STDSTR_SHORT, "%dms", pstSmilPage->nDur);
-                       xmlSetProp(pstParElement, (const xmlChar *)"dur", (const xmlChar *)szBuf);
-               }
-               /* Find the insertion point : right sibling of the last <par> node or first child of <body> */
-
-               pstParList = xmlGetLastChild(pstBodyElement);
-
-               if (pstParList) {
-                       ret = __MmsSmilInsertNode(pstBodyElement, pstParList, pstParElement);
-               } else {
-                       ret = __MmsInsertFirstChild(pstBodyElement, pstParElement);
-               }
-       } else {
-               MSG_DEBUG("Invalid SmilDoc(hSmilDoc:%d)", nSmilDocNo);
-               return false;
-       }
-
-       return ret;
-}
-
-/**    @fn                     static bool MmsSmilAddRootLayout(HMmsSmil hSmilDoc, MMS_SMIL_ROOTLAYOUT *pstSmilRootLayout)
- *     @brief          Add Rootlayout to Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @param[in]      pstSmilRootLayout specifies RootLayout information. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool MmsSmilAddRootLayout(HMmsSmil hSmilDoc, MMS_SMIL_ROOTLAYOUT *pstSmilRootLayout)
-{
-       int nSmilDocNo = hSmilDoc;
-       xmlNodePtr pstRootLayout = NULL;
-       xmlNodePtr pstLayoutList = NULL;
-       xmlNodePtr pstRootLayoutList = NULL;
-       char szBuf[MSG_STDSTR_SHORT] = {0, };
-
-       MSG_BEGIN();
-
-       if (IsValidSmilDocNo(nSmilDocNo)) {
-               pstLayoutList = UtilxmlStringGetNodeList(__gpaMmsSmilDoc[nSmilDocNo]->pstRootNode, (char *)"layout");
-
-               if (NULL == pstLayoutList) {
-                       MSG_DEBUG("There is no <layout> node. Can't create <root-layout> node.");
-                       return false;
-               }
-               MSG_DEBUG("Layout Element Name = %s ", (char *)pstLayoutList->name);
-
-               pstRootLayoutList = UtilxmlStringGetNodeList(__gpaMmsSmilDoc[nSmilDocNo]->pstRootNode, (char *)"root-layout");
-
-               if (NULL != pstRootLayoutList) {
-                       MSG_DEBUG("MmsSmilAddRootLayout: There is <root-layout> node already");
-                       MSG_DEBUG("Root Layout Element Name = %s  type=%d\n", (char *)pstRootLayoutList->name);
-                       return false;
-               }
-               /* Create "root-layout" node and insert it */
-               pstRootLayout = xmlNewNode(NULL, (xmlChar *)"root-layout");
-               if (NULL == pstRootLayout) {
-                       MSG_DEBUG("Can't create <root-layout> node. (from XmlParser)");
-                       return false;
-               }
-               MSG_DEBUG("Root Layout Element Name = %s", (char *)pstRootLayout->name);
-
-               if (pstSmilRootLayout->bgColor != SP_NO_COLOR_SET) {    // Replace value later
-                       xmlSetProp(pstRootLayout, (const xmlChar *)"backgroundColor", (const xmlChar *)__MmsSmilFindColorValue(pstSmilRootLayout->bgColor));
-               }
-               MSG_DEBUG(" Set Width");
-               if (true == pstSmilRootLayout->width.bUnitPercent) {
-                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRootLayout->width.value);
-                       xmlSetProp(pstRootLayout, (const xmlChar *)"width", (const xmlChar *)szBuf);
-               } else {
-                       if (pstSmilRootLayout->width.value > 0) {
-                               snprintf(szBuf, MSG_STDSTR_SHORT, "%d", pstSmilRootLayout->width.value);
-                               xmlSetProp(pstRootLayout, (const xmlChar *)"width", (const xmlChar *)szBuf);
-                       } else {
-                               xmlSetProp(pstRootLayout, (const xmlChar *)"width", (const xmlChar *)"100%");
-                       }
-               }
-               MSG_DEBUG(" Set Height");
-               if (true == pstSmilRootLayout->height.bUnitPercent) {
-                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRootLayout->height.value);
-                       xmlSetProp(pstRootLayout, (const xmlChar *)"height", (const xmlChar *)szBuf);
-               } else {
-                       if (pstSmilRootLayout->height.value > 0) {
-                               snprintf(szBuf, MSG_STDSTR_SHORT, "%d", pstSmilRootLayout->height.value);
-                               xmlSetProp(pstRootLayout, (const xmlChar *)"height", (const xmlChar *)szBuf);
-                       } else {
-                               xmlSetProp(pstRootLayout, (const xmlChar *)"height", (const xmlChar *)"100%");
-                       }
-               }
-               __MmsInsertFirstChild(pstLayoutList, pstRootLayout);
-
-               return true;
-       } else {
-               MSG_DEBUG("Invalid SmilDoc(hSmilDoc:%d)", nSmilDocNo);
-               return false;
-       }
-
-}
-
-
-/**    @fn                     static bool MmsSmilAddRegion(HMmsSmil hSmilDoc, MMS_SMIL_REGION *pstSmilRegion)
- *     @brief          Add Region to Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @param[in]      pstSmilRegion specifies Region information. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool MmsSmilAddRegion(HMmsSmil hSmilDoc, MMS_SMIL_REGION *pstSmilRegion)
-{
-       int nSmilDocNo = hSmilDoc;
-
-       MSG_BEGIN();
-
-       if (IsValidSmilDocNo(nSmilDocNo)) {
-               int nRootWidth = 0;
-               int nRootHeight = 0;
-               xmlNodePtr pstRegion;
-               xmlNodePtr pstLayoutList;
-               xmlNodePtr pstRootLayoutList;
-               xmlAttrPtr pAttribute;
-               char szBuf[MSG_STDSTR_SHORT] = {0, };
-
-               pstLayoutList = UtilxmlStringGetNodeList(__gpaMmsSmilDoc[nSmilDocNo]->pstRootNode, (char *)"layout");
-               if (NULL == pstLayoutList) {
-                       MSG_DEBUG(" There is no <layout> node. Can't create <region> node");
-                       return false;
-               }
-               MSG_DEBUG("Layout Element Name = %s ", (char *)pstLayoutList->name);
-
-               /* Find the insertion point : right sibling of the last root-layout node or first child of pLayout */
-               pstRootLayoutList = UtilxmlStringGetNodeList(__gpaMmsSmilDoc[nSmilDocNo]->pstRootNode, (char *)"root-layout");
-
-               if (NULL == pstRootLayoutList) {
-                       MSG_DEBUG("There is no <root-layout> node. Can't create <root-layout> node.");
-                       return false;
-               } else {
-                       MSG_DEBUG("Root Layout Element Name = %s ", (char *)pstRootLayoutList->name);
-                       pAttribute =  pstRootLayoutList->properties;
-               }
-
-               if (NULL == pAttribute) {
-                       MSG_DEBUG("There is no Attribute in <root-layout> node.");
-                       return false;
-               }
-
-               xmlAttrPtr pstAttr = pAttribute;
-               for ( ; pstAttr; pstAttr = pstAttr->next) {
-                       int     attrType;
-                       MSG_DEBUG("AttributeType: (%s, %s) ", pstAttr->name, pstAttr->children->content);
-                       switch (attrType = MmsSmilGetAttrID((char *)pstAttr->name)) {
-                       case ATTRIBUTE_WIDTH:
-                               {
-                                       int bUnitPercent;
-
-                                       if (strchr((char *)pstAttr->children->content, '%'))
-                                               bUnitPercent = true;
-                                       else
-                                               bUnitPercent = false;
-
-                                       nRootWidth = atoi((char *)pstAttr->children->content);
-                               }
-                               break;
-
-                       case ATTRIBUTE_HEIGHT:
-                               {
-                                       int bUnitPercent;
-
-                                       if (strchr((char *)pstAttr->children->content, '%'))
-                                               bUnitPercent = true;
-                                       else
-                                               bUnitPercent = false;
-
-                                       nRootHeight = atoi((char *)pstAttr->children->content);
-                               }
-                               break;
-                       }
-               }
-
-               /* Create "region" node and insert it */
-               MSG_DEBUG("Create Region Node");
-               pstRegion = xmlNewNode(NULL, (xmlChar *)"region");
-               if (NULL == pstRegion) {
-                       MSG_DEBUG("Can't create <region> node. (from XmlParser)");
-                       return false;
-               }
-               /* Add attributes */
-               if (pstSmilRegion) {
-                       MSG_DEBUG(" [Set Attribute] : Region Id");
-                       if (strlen(pstSmilRegion->szID) > 0) {
-                               xmlSetProp(pstRegion, (const xmlChar *)"id", (const xmlChar *)pstSmilRegion->szID);
-                       }
-                       MSG_DEBUG(" [Set Attribute] : BkGrd Color");
-                       // Default Color WHITE, always send
-                       if (pstSmilRegion->bgColor != SP_NO_COLOR_SET) {
-                               xmlSetProp(pstRegion, (const xmlChar *)"backgroundColor", (const xmlChar *)__MmsSmilFindColorValue(pstSmilRegion->bgColor));
-                       }
-                       MSG_DEBUG(" [Set Attribute] : Width");
-
-                       if (true == pstSmilRegion->width.bUnitPercent) {
-                               if (pstSmilRegion->width.value > 0) {
-                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRegion->width.value);
-                                       xmlSetProp(pstRegion, (const xmlChar *)"width", (const xmlChar *)szBuf);
-                                       MSG_DEBUG("MmsSmilAddRegion: pstSmilRegion->width = %d   \n", pstSmilRegion->width.value);
-                               }
-                       } else {
-                               // Note: nRootWidth should be in terms of value(pixel) not unitpercent(%)
-                               // Validation should be done before this.
-                               if (pstSmilRegion->width.value >= 0 &&
-                                       pstSmilRegion->width.value <= nRootWidth) {
-                                       int iWidth = (pstSmilRegion->width.value * 100) / nRootWidth;
-
-                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", iWidth);
-                                       xmlSetProp(pstRegion, (const xmlChar *)"width", (const xmlChar *)szBuf);
-                                       MSG_DEBUG("MmsSmilAddRegion: pstSmilRegion->width= %d  iWidth = %d \n", pstSmilRegion->width.value, iWidth);
-                               }
-                       }
-                       MSG_DEBUG(" [Set Attribute] : Height");
-                       if (true == pstSmilRegion->height.bUnitPercent) {
-                               if (pstSmilRegion->height.value > 0) {
-                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRegion->height.value);
-                                       xmlSetProp(pstRegion, (const xmlChar *)"height", (const xmlChar *)szBuf);
-                                       MSG_DEBUG("MmsSmilAddRegion: pstSmilRegion->height = %d   \n", pstSmilRegion->height.value);
-                               }
-                       } else {
-                               // Note: nRootHeight should be in terms of value(pixel) not unitpercent(%)
-                               // Validation should be done before this.
-                               if (pstSmilRegion->height.value >= 0 &&
-                                       pstSmilRegion->height.value <= nRootHeight) {
-                                       int iHeight = (pstSmilRegion->height.value * 100) / nRootHeight;
-
-                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", iHeight);
-                                       xmlSetProp(pstRegion, (const xmlChar *)"height", (const xmlChar *)szBuf);
-                                       MSG_DEBUG("MmsSmilAddRegion: pstSmilRegion->height = %d  iHeight = %d \n", pstSmilRegion->height.value, iHeight);
-                               }
-                       }
-                       MSG_DEBUG(" [Set Attribute] : Left");
-                       if (true == pstSmilRegion->nLeft.bUnitPercent) {
-                               if (pstSmilRegion->nLeft.value > 0) {
-                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRegion->nLeft.value);
-                                       xmlSetProp(pstRegion, (const xmlChar *)"left", (const xmlChar *)szBuf);
-                                       MSG_DEBUG("MmsSmilAddRegion: pstSmilRegion->left = %d   \n", pstSmilRegion->nLeft.value);
-                               }
-                       } else {
-                               // Note: nRootWidth should be in terms of value(pixel) not unitpercent(%)
-                               // Validation should be done before this.
-                               if (pstSmilRegion->nLeft.value >= 0) {
-                                       int iLeft = (pstSmilRegion->nLeft.value * 100) / nRootWidth;
-
-                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", iLeft);
-                                       xmlSetProp(pstRegion, (const xmlChar *)"left", (const xmlChar *)szBuf);
-                                       MSG_DEBUG("MmsSmilAddRegion: SmilRegion->iLeft = %d       iLeft = %d \n", pstSmilRegion->nLeft.value, iLeft);
-                               }
-                       }
-                       MSG_DEBUG(" [Set Attribute] : Top");
-                       if (true == pstSmilRegion->nTop.bUnitPercent) {
-                               if (pstSmilRegion->nTop.value > 0) {
-                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRegion->nTop.value);
-                                       xmlSetProp(pstRegion, (const xmlChar *)"top", (const xmlChar *)szBuf);
-                                       MSG_DEBUG("MmsSmilAddRegion: pstSmilRegion->nTop= %d   \n", pstSmilRegion->nTop.value);
-                               }
-                       } else {
-                               // Note: nRootHeight should be in terms of value(pixel) not unitpercent(%)
-                               // Validation should be done before this.
-                               if (pstSmilRegion->nTop.value >= 0) {
-                                       int iTop = (pstSmilRegion->nTop.value * 100) / nRootHeight;
-
-                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", iTop);
-                                       xmlSetProp(pstRegion, (const xmlChar *)"top", (const xmlChar *)szBuf);
-                                       MSG_DEBUG("MmsSmilAddRegion: pstSmilRegion->nTop= %d  iTop = %d \n", pstSmilRegion->nTop.value, iTop);
-                               }
-                       }
-                       MSG_DEBUG(" [Set Attribute] : Fit");
-                       //Fit Attribute
-                       if (MMSUI_IMAGE_REGION_FIT_MEET == pstSmilRegion->fit) {
-                               xmlSetProp(pstRegion, (const xmlChar *)"fit", (const xmlChar *)"meet");
-                       } else if (MMSUI_IMAGE_REGION_FIT_HIDDEN == pstSmilRegion->fit) {
-                               xmlSetProp(pstRegion, (const xmlChar *)"fit", (const xmlChar *)"hidden");
-                       }
-               } else
-                       MSG_DEBUG("There is no attribute in <region> node\n");
-
-               MSG_END();
-               return true;
-       } else {
-               MSG_DEBUG("Invalid SmilDoc(hSmilDoc:%d)\n", nSmilDocNo);
-               return false;
-       }
-}
-
-/**    @fn                     static bool MmsSmilAddMedia( HMmsSmil hSmilDoc, int nPageNo, MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
- *     @brief          Add Media to Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @param[in]      nPageNo specifies page number to which media belongs. \n
- *     @param[in]      pstSmilMedia specifies Media information. \n
- *     @param[in]      pszContentID specifies Content ID of media. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool MmsSmilAddMedia( HMmsSmil hSmilDoc, int nPageNo, int nMediaIdx, MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
-{
-       int nSmilDocNo = hSmilDoc;
-
-       MSG_BEGIN();
-
-       if (NULL == pszContentID) {
-               MSG_DEBUG(" Content Id is NULL");
-               return false;
-       }
-       memset(pszContentID, 0, MMS_CONTENT_ID_LEN + 1);
-       if (IsValidSmilDocNo(nSmilDocNo)) {
-               int nIndex = 0;
-               xmlNode *pstMedia;
-               xmlNode *pstLastChild;
-               xmlNodePtr pstParList;
-               char *pszExt ;
-
-               pstParList = UtilxmlStringGetNodeList(__gpaMmsSmilDoc[nSmilDocNo]->pstRootNode, (char *)"par");
-               if (NULL == pstParList) {
-                       MSG_DEBUG("There is no <par> node. Can't create <media> node.");
-                       return false;
-               }
-               MSG_DEBUG("Par Element Name = %s ", (char *)pstParList->name);
-               for (nIndex = 0; (pstParList &&  nIndex < nPageNo); nIndex++) {
-                       pstParList = pstParList->next;
-               }
-               if (NULL == pstParList) {
-                       MSG_DEBUG("There is no such page node. Can't insert <media> node.");
-                       return false;
-               }
-               MSG_DEBUG("Par Element Name = %s ", (char *)pstParList->name);
-               /* Find insertion point and make a contentID */
-
-               pstLastChild = xmlGetLastChild(pstParList);
-
-               pszExt = strrchr(pstSmilMedia->szFileName, '.');
-               if (pszExt && !strrchr(pszExt, '/'))
-                       snprintf(pszContentID, MSG_MSG_ID_LEN+1, "%lu_%lu%s", (ULONG)nPageNo, (ULONG)nMediaIdx, pszExt);
-               else
-                       snprintf(pszContentID, MSG_MSG_ID_LEN+1, "%lu_%lu", (ULONG)nPageNo, (ULONG)nMediaIdx);
-
-               /* Create <media> node and insert set attribute */
-               MSG_DEBUG(" Create Media Node");
-               switch (pstSmilMedia->mediatype) {
-               case MMS_SMIL_MEDIA_TEXT:
-                       pstMedia = __MmsCreateTextNode(pstSmilMedia, pszContentID);
-                       break;
-               case MMS_SMIL_MEDIA_AUDIO:
-               case MMS_SMIL_MEDIA_VIDEO:
-               case MMS_SMIL_MEDIA_IMG:
-                       pstMedia = __MmsCreateMMNode(pstSmilMedia, pszContentID);
-                       break;
-               default:
-                       MSG_DEBUG("Invalid media type. Can't insert such-<media> node.");
-                       return false;
-               }
-
-               if (NULL == pstMedia) {
-                       MSG_DEBUG("Can't create <media> node. (from XmlParser) (media-type:%d)", pstSmilMedia->mediatype);
-                       return false;
-               }
-
-               /* Find the insertion point : the last child of <par> node */
-               if (pstLastChild)
-                       __MmsSmilInsertNode(pstParList, pstLastChild, pstMedia);
-               else
-                       __MmsInsertFirstChild(pstParList, pstMedia);
-
-               MSG_END();
-               return true;
-       } else {
-               MSG_DEBUG("MmsSmilAddMedia: Invalid SmilDoc(hSmilDoc:%d)\n", nSmilDocNo);
-               return false;
-       }
-}
-
-/**    @fn                     static xmlNode *__MmsCreateTextNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
- *     @brief          Create Text Element. \n
- *     @param[in]      pstSmilMedia specifies Media information. \n
- *     @param[in]      pszContentID specifies Content ID of media. \n
- *     @retval         Text Element node               In case of Success. \n
- *     @retval         NULL                            In case of failure. \n
- */
-xmlNode *__MmsCreateTextNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
-{
-       xmlNode *pstMedia = NULL;
-       xmlNode *pstParam = NULL;
-       char szBuf[MSG_STDSTR_SHORT] = {0, };
-       char szSizeBuf[MSG_STDSTR_SHORT] = {0, };
-
-       MSG_BEGIN();
-
-       pstMedia = xmlNewNode(NULL, (xmlChar *)"text");
-       if (NULL == pstMedia) {
-               MSG_DEBUG("Can't create <Text> node.");
-               return NULL;
-       }
-       MSG_DEBUG("Text Element Name = %s ", (char *)pstMedia->name);
-
-       /* Add attributes */
-       if (pstSmilMedia) {
-               MSG_DEBUG("[Set Attribute] Region Id ");
-               if (strlen(pstSmilMedia->regionId) > 0) {
-                       xmlSetProp(pstMedia, (const xmlChar *)"region", (const xmlChar *)pstSmilMedia->regionId);
-               }
-               MSG_DEBUG("[Set Attribute] Begin ");
-               if (pstSmilMedia->sMedia.sText.nBegin > 0) {
-                       snprintf (szBuf, sizeof(szBuf), "%dms", pstSmilMedia->sMedia.sText.nBegin);
-                       xmlSetProp(pstMedia, (const xmlChar *)"begin", (const xmlChar *) szBuf);
-               }
-               MSG_DEBUG("[Set Attribute] Duration");
-               if (pstSmilMedia->sMedia.sText.nDurTime > 0) {
-                       snprintf (szBuf, sizeof(szBuf), "%dms", pstSmilMedia->sMedia.sText.nDurTime);
-                       xmlSetProp(pstMedia, (const xmlChar *)"dur", (const xmlChar *)szBuf);
-               }
-               MSG_DEBUG("[Set Attribute] Alternate");
-               if (strlen(pstSmilMedia->szAlt) > 0) {
-                       snprintf (szBuf, sizeof(szBuf), "%s", pstSmilMedia->szAlt);
-                       xmlSetProp(pstMedia, (const xmlChar *)"alt", (const xmlChar *)szBuf);
-               }
-               MSG_DEBUG("[Set Attribute] Src");
-
-               char szFilePathWithCid[MMS_CONTENT_ID_LEN + 5]; // for "cid:"
-
-               snprintf (szFilePathWithCid, sizeof(szFilePathWithCid), "cid:%s", pszContentID);
-               _MmsSmilSetAttribute(pstMedia, (char *)"src", szFilePathWithCid);
-
-               MSG_DEBUG("[Set Attribute] Font Foreground Color");
-
-               if (pstSmilMedia->sMedia.sText.nColor!= SP_BLACK) {     // Chnage after getting exact values
-                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
-
-                       if (NULL == pstParam) {
-                               MSG_DEBUG("Cannot create <param> node");
-                               return false;
-                       }
-                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"foreground-color");
-                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)__MmsSmilFindColorValue(pstSmilMedia->sMedia.sText.nColor));
-                       __MmsInsertFirstChild(pstMedia, pstParam);
-               }
-
-               MSG_DEBUG("[Set Attribute] Font Background Color");
-
-               if (pstSmilMedia->sMedia.sText.nBgColor != SP_BLACK) {  // Chnage after getting exact values
-                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
-
-                       if (NULL == pstParam) {
-                               MSG_DEBUG("Cannot create <param> node");
-                               return false;
-                       }
-                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"background-color");
-                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)__MmsSmilFindColorValue(pstSmilMedia->sMedia.sText.nBgColor));
-                       __MmsInsertFirstChild(pstMedia, pstParam);
-               }
-
-               MSG_DEBUG("[Set Attribute] Size");
-               if (pstSmilMedia->sMedia.sText.nSize > 0) {
-                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
-                       if (NULL == pstParam) {
-                               MSG_DEBUG(" __MmsCreateTextNode: cannot create <param> node \n");
-                               return false;
-                       }
-
-                       if (pstSmilMedia->sMedia.sText.nSize  <= MMS_SMIL_FONT_SIZE_SMALL)
-                               strcpy(szSizeBuf, "small");
-                       else if ((pstSmilMedia->sMedia.sText.nSize  > MMS_SMIL_FONT_SIZE_SMALL) && (pstSmilMedia->sMedia.sText.nSize  < MMS_SMIL_FONT_SIZE_LARGE))
-                               strcpy(szSizeBuf, "normal");
-                       else
-                               strcpy(szSizeBuf, "large");
-
-                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"textsize");
-                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)szSizeBuf);
-                       __MmsInsertFirstChild(pstMedia, pstParam);
-               }
-
-               if (pstSmilMedia->sMedia.sText.bBold == true) {
-                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
-                       if (NULL == pstParam) {
-                               MSG_DEBUG(" __MmsCreateTextNode: cannot create <param> node \n");
-                               return false;
-                       }
-
-                       strcpy(szSizeBuf, "bold");
-
-                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"textattribute");
-                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)szSizeBuf);
-                       __MmsInsertFirstChild(pstMedia, pstParam);
-               }
-
-               if (pstSmilMedia->sMedia.sText.bItalic == true) {
-                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
-                       if (NULL == pstParam) {
-                               MSG_DEBUG(" __MmsCreateTextNode: cannot create <param> node \n");
-                               return false;
-                       }
-
-                       strcpy(szSizeBuf, "italic");
-
-                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"textattribute");
-                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)szSizeBuf);
-                       __MmsInsertFirstChild(pstMedia, pstParam);
-               }
-
-               if (pstSmilMedia->sMedia.sText.bUnderLine == true) {
-                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
-                       if (NULL == pstParam) {
-                               MSG_DEBUG(" __MmsCreateTextNode: cannot create <param> node \n");
-                               return false;
-                       }
-
-                       strcpy(szSizeBuf, "underline");
-
-                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"textattribute");
-                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)szSizeBuf);
-                       __MmsInsertFirstChild(pstMedia, pstParam);
-               }
-       }
-
-       MSG_END();
-       return pstMedia;
-}
-
-/**    @fn                     static xmlNode *__MmsCreateMMNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
- *     @brief          Create Image/Audio/Video Element. \n
- *     @param[in]      pstSmilMedia specifies Media information. \n
- *     @param[in]      pszContentID specifies Content ID of media. \n
- *     @retval         Image/Audio/Video Element node  In case of Success. \n
- *     @retval         NULL                                                    In case of failure. \n
- */
-xmlNode *__MmsCreateMMNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
-{
-       xmlNode *pstMedia = NULL;
-       char szBuf[MSG_STDSTR_SHORT] = {0, };
-
-       MSG_BEGIN();
-
-       if (!pstSmilMedia)
-               return NULL;
-
-       switch (pstSmilMedia->mediatype) {
-       case MMS_SMIL_MEDIA_AUDIO:
-               pstMedia = xmlNewNode(NULL, (xmlChar *)"audio");
-               break;
-
-       case MMS_SMIL_MEDIA_VIDEO:
-               pstMedia = xmlNewNode(NULL, (xmlChar *)"video");
-               break;
-
-       case MMS_SMIL_MEDIA_IMG:
-               pstMedia = xmlNewNode(NULL, (xmlChar *)"img");
-               break;
-       default:
-               MSG_DEBUG("Invalid media type. Can't insert such-<media> node.");
-               return NULL;
-       }
-
-       if (pstSmilMedia) {
-               char szFilePathWithCid[MMS_CONTENT_ID_LEN + 5];         // for "cid:"
-
-               MSG_DEBUG("[Set Attribute] Region Id ");
-               if (strlen(pstSmilMedia->regionId) > 0) {
-                       xmlSetProp(pstMedia, (const xmlChar *)"region", (const xmlChar *)pstSmilMedia->regionId);
-               }
-               MSG_DEBUG("[Set Attribute] Src ");
-               snprintf (szFilePathWithCid, sizeof(szFilePathWithCid), "cid:%s", pszContentID);
-               _MmsSmilSetAttribute(pstMedia, (char *)"src", szFilePathWithCid);
-
-               MSG_DEBUG("[Set Attribute] Begin ");
-               if (pstSmilMedia->sMedia.sAVI.nBegin > 0) {
-                       snprintf (szBuf, sizeof(szBuf), "%dms", pstSmilMedia->sMedia.sAVI.nBegin);
-                       xmlSetProp(pstMedia, (const xmlChar *)"begin", (const xmlChar *)szBuf);
-               }
-               MSG_DEBUG("[Set Attribute] Duration ");
-               if (pstSmilMedia->sMedia.sAVI.nDurTime > 0) {
-                       snprintf (szBuf, sizeof(szBuf), "%dms", pstSmilMedia->sMedia.sAVI.nDurTime);
-                       xmlSetProp(pstMedia, (const xmlChar *)"dur", (const xmlChar *)szBuf);
-               }
-               MSG_DEBUG("[Set Attribute] Alt ");
-               if (strlen(pstSmilMedia->szAlt) > 0) {
-                       snprintf (szBuf, sizeof(szBuf), "%s", pstSmilMedia->szAlt);
-                       xmlSetProp(pstMedia, (const xmlChar *)"alt", (const xmlChar *)szBuf);
-               }
-       } else {
-               MSG_DEBUG("There is no attribute in such-<media> node");
-       }
-
-       MSG_END();
-       return pstMedia;
-}
-
-/**    @fn                     static bool __MmsInsertFirstChild(xmlNode *pstParent, xmlNode *pstCurr)
- *     @brief          Inserts first child to parent node. \n
- *     @param[in]      pstParent specifies Parent node. \n
- *     @param[in]      pstCurr specifies Child node. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool __MmsInsertFirstChild(xmlNode *pstParent, xmlNode *pstCurr)
-{
-       bool bFlag = true;
-
-       MSG_BEGIN();
-
-        if (NULL == xmlAddChild(pstParent, pstCurr)) {
-               MSG_DEBUG("%s Node not added", pstCurr->name);
-               bFlag = false;
-        }
-
-        MSG_END();
-        return bFlag;
-}
-
-
-/**    @fn                     static bool __MmsSmilInsertNode(xmlNode *pstParent, xmlNode *pstLeftSibling, xmlNode *pstCurr)
- *     @brief          Inserts node. \n
- *     @param[in]      pstParent specifies Parent node. \n
- *     @param[in]      pstLeftSibling specifies Left Sibling node. \n
- *     @param[in]      pstCurr specifies Child node. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool __MmsSmilInsertNode(xmlNode *pstParent, xmlNode *pstLeftSibling, xmlNode *pstCurr)
-{
-       MSG_BEGIN();
-       bool bFlag = true;
-
-       if (pstLeftSibling) {
-               /* Parent Node is Unused */
-
-               while (pstLeftSibling->next !=NULL)
-                       pstLeftSibling = pstLeftSibling->next;
-
-                if (NULL == xmlAddNextSibling(pstLeftSibling, pstCurr)) {
-                       MSG_DEBUG("%s Node not added", pstCurr->name);
-                       bFlag = false;
-                }
-       } else {
-                if (NULL == xmlAddChild(pstParent, pstCurr)) {
-                        MSG_DEBUG("%s Node not added", pstCurr->name);
-                       bFlag = false;
-                }
-       }
-       MSG_END();
-       return bFlag;
-}
-
-
-bool __MmsGetRealFileName(MmsSmilMediaType mediaType, char *pszSrc, char *pszName, int msgID)
-{
-       MsgType partHeader;
-       int partCnt;
-       int i;
-
-       MSG_DEBUG("__MmsUiGetRealFileName: mediaType[%d]", mediaType);
-       MSG_DEBUG("__MmsUiGetRealFileName: pszSrc[%s]\n", pszSrc);
-
-       if (!pszName) {
-               MSG_DEBUG("__MmsUiGetRealFileName: pszName is null\n");
-               return false;
-       }
-
-       if (mediaType == MMS_SMIL_MEDIA_TEXT || mediaType == MMS_SMIL_MEDIA_INVALID) {
-               MSG_DEBUG("__MmsUiGetRealFileName: invalid mediaType(=%d)\n", mediaType);
-               return false;
-       }
-
-       partCnt = MmsGetMediaPartCount(msgID);
-
-       if (partCnt < 0) {
-               MSG_DEBUG("__MmsUiGetRealFileName: partCnt < 0, (=%d)\n", partCnt);
-               return false;
-       }
-
-       for (i = 0; i < partCnt; i++) {
-               MmsGetMediaPartHeader(i, &partHeader);
-
-               if (mediaType == MMS_SMIL_MEDIA_AUDIO ||
-                       mediaType == MMS_SMIL_MEDIA_VIDEO ||
-                       mediaType == MMS_SMIL_MEDIA_IMG) {
-                       if (!strcmp(partHeader.param.szFileName , pszSrc)) {
-                               // Found
-                               MSG_DEBUG("__MmsUiGetRealFileName: pszSrc[%s]\n", pszSrc);
-                               break;
-                       }
-               }
-       }
-
-       if (i == partCnt)
-               return false;
-
-       if (partHeader.param.szName[0] != '\0') {
-               int nameLen = strlen(partHeader.param.szName);
-
-               if (nameLen > MSG_FILENAME_LEN_MAX - 1) {
-                       ;//Need to check
-               } else {
-                       strcpy(pszName, partHeader.param.szName);
-               }
-
-               return true;
-       }
-       return false;
-}
-
-/**    @fn                     static void _MmsSmilSetAttribute(xmlNode *pNode, char *szField, char *szValue)
- *     @brief          Sets Attribute. \n
- *     @param[in]      pNode specifies node. \n
- *     @param[in]      szField specifies attribute field. \n
- *     @param[in]      szValue specifies value of field \n
- */
-void _MmsSmilSetAttribute(xmlNode *pNode, char *szField, char *szValue)
-{
-       MSG_BEGIN();
-
-       if (pNode && szField && strlen(szField)) {
-               if (szValue && strlen(szValue)) {
-                       xmlSetProp(pNode, (const xmlChar *)szField, (const xmlChar *)szValue);
-               } else {
-                       xmlSetProp(pNode, (const xmlChar *)szField, (const xmlChar *)"");
-               }
-       }
-
-       MSG_END();
-}
-
-/**    @fn                     static char *__MmsSmilFindColorValue(int nValue)
- *     @brief          Converts color to RGB. \n
- *     @param[in]      nValue specifies color value. \n
- *     @retval         RGB value. \n
- */
-char *__MmsSmilFindColorValue(int nValue)
-{
-       unsigned char red = (nValue & 0xFF0000) >> 16;
-       unsigned char green = (nValue & 0x00FF00) >> 8;
-       unsigned char blue = nValue & 0x0000FF;
-
-       MSG_BEGIN();
-
-       snprintf(gszColor,MMS_SMIL_COLOR_SIZE, "#%02x%02x%02x", red, green, blue);
-       MSG_DEBUG("__MmsSmilFindColorValue: gszColor %s \n", gszColor);
-
-       MSG_END();
-       return gszColor;
-}
-
-/**    @fn                     static xmlNodePtr UtilxmlStringGetNodeList(xmlNodePtr pstNode, char *pszValue)
- *     @brief          Get node based on pszValue. \n
- *     @param[in]      pNode specifies node. \n
- *     @param[in]      pszName specifies name field. \n
- *     @retval         RGB value. \n
- */
-xmlNodePtr UtilxmlStringGetNodeList(xmlNodePtr pstNode, char *pszName)
-{
-       MSG_BEGIN();
-
-       if ((NULL != pstNode) && (NULL != pszName)) {
-               xmlNodePtr pstTempNode;
-               xmlNodePtr pstReturnNode;
-
-               pstTempNode = pstNode;
-
-               for ( ; pstTempNode; pstTempNode = pstTempNode->next) {
-                       MSG_DEBUG("\n Node Name = %s[%p] children =%p \n", (char *)pstTempNode->name, pstTempNode, pstTempNode->children);
-                       MSG_DEBUG("\n Compare Parent Node = %s[%p] \n", (char *)pstTempNode->name, pstTempNode);
-                       if (0 == strcasecmp((char *)pstTempNode->name, pszName)) {
-                               return pstTempNode;
-                       }
-
-                       if (pstTempNode->children) {
-                               MSG_DEBUG("\n Enter Inside\n");
-                               pstReturnNode = UtilxmlStringGetNodeList(pstTempNode->children, pszName);
-                               if (NULL != pstReturnNode) {
-                                       return pstReturnNode;
-                               }
-                       }
-
-               }
-       }
-       return NULL;
-}
-
index bebed16..13df9db 100755 (executable)
@@ -1,56 +1,40 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdlib.h>
 #include <sys/stat.h>
 #include <errno.h>
 
-#include <mm_file.h>
-#include <mm_util_jpeg.h>
-
-#include "MsgDebug.h"
+#include "MsgCppTypes.h"
 #include "MsgException.h"
 #include "MsgUtilFile.h"
 #include "MsgMmsMessage.h"
-#include "MsgNotificationWrapper.h"
-#include "MsgUtilStorage.h"
-
+#include "MsgStorageTypes.h"
+#include "MsgSmil.h"
+#include "MsgSerialize.h"
+#include "MmsPluginDebug.h"
 #include "MmsPluginStorage.h"
-#include "MmsPluginSetup.h"
-#include "MmsPluginStorage.h"
-#include "MmsPluginCodec.h"
-#include "MmsPluginSmil.h"
+#include "MmsPluginMessage.h"
 #include "MmsPluginDrm.h"
-#include <media-thumbnail.h>
-#include <mm_util_imgp.h>
-#include <mm_util_jpeg.h>
-#include "MsgHelper.h"
-
-static void __MmsReleaseMmsLists(MMS_MESSAGE_DATA_S *mms_data)
-{
-       _MsgMmsReleasePageList(mms_data);
-       _MsgMmsReleaseRegionList(mms_data);
-       _MsgMmsReleaseAttachList(mms_data);
-       _MsgMmsReleaseTransitionList(mms_data);
-       _MsgMmsReleaseMetaList(mms_data);
-}
+#include "MmsPluginMIME.h"
+#include "MmsPluginTcs.h"
+#include "MmsPluginUtil.h"
+#include "MmsPluginComposer.h"
+#include "MmsPluginAppBase.h"
 
-/*==================================================================================================
-                                     IMPLEMENTATION OF SmsPluginStorage - Member Functions
-==================================================================================================*/
 MmsPluginStorage *MmsPluginStorage::pInstance = NULL;
 
 
@@ -62,9 +46,7 @@ MmsPluginStorage::MmsPluginStorage()
 
 MmsPluginStorage::~MmsPluginStorage()
 {
-       if (dbHandle.disconnect() != MSG_SUCCESS) {
-               MSG_DEBUG("DB Disconnect Fail");
-       }
+
 }
 
 
@@ -82,366 +64,292 @@ void MmsPluginStorage::getMmsMessage(MmsMsg **pMmsMsg)
        *pMmsMsg = &mmsMsg;
 }
 
-
-void MmsPluginStorage::addMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData)
+void MmsPluginStorage::composeReadReport(MSG_MESSAGE_INFO_S *pMsgInfo)
 {
-       MSG_BEGIN();
+       FILE *pFile = NULL;
 
-       msg_error_t     err;
+       msg_read_report_status_t readStatus;
+       int     version;
 
-       MmsMsg mmsMsg;
+       memcpy(&readStatus, pMsgInfo->msgData, sizeof(msg_read_report_status_t));
 
-       bzero(&mmsMsg, sizeof(mmsMsg));
+       MSG_DEBUG("pMsgInfo->msgId = %d", pMsgInfo->msgId);
 
-       mode_t file_mode = (S_IRUSR | S_IWUSR);
+       version = MmsPluginStorage::instance()->getMmsVersion(pMsgInfo->msgId);
 
-       if (pMsgInfo->msgType.subType == MSG_SENDREQ_MMS) {
+       snprintf((char *)pMsgInfo->msgData, MAX_MSG_DATA_LEN+1, "%s%d-Read-Rec.ind", MSG_DATA_PATH, pMsgInfo->msgId);
 
-               char szTemp[MAX_MSG_DATA_LEN + 1];
+       if (version == 0x90)
+               pMsgInfo->msgType.subType = MSG_READREPLY_MMS;
+       else
+               pMsgInfo->msgType.subType = MSG_READRECIND_MMS;
 
-               MMS_MESSAGE_DATA_S mmsMsgData;
-               bzero(&mmsMsgData,sizeof(MMS_MESSAGE_DATA_S));
-               if (MmsComposeMessage(&mmsMsg, pMsgInfo, pSendOptInfo, &mmsMsgData, pFileData) != true) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+       MmsComposeReadReportMessage(&mmsMsg, pMsgInfo, pMsgInfo->msgId);
 
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       __MmsReleaseMmsLists(&mmsMsgData);
+       pFile = MsgOpenFile(pMsgInfo->msgData, "wb+");
+       if (!pFile)
+               THROW(MsgException::MMS_PLG_ERROR, "MsgOpenMMSFile Error");
 
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS Message Compose Error");
+       if (version == 0x90) {
+               MSG_DEBUG("### version 1.0 ###");
+               if (MmsEncodeReadReport10(pFile, &mmsMsg, readStatus) != true) {
+                       MsgCloseFile(pFile);
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS Encode Read Report 1.0 Error");
                }
-
-               char fileName[MSG_FILENAME_LEN_MAX+1] = {0,};
-
-               FILE *pFile = NULL;
-
-               strcpy(szTemp,pMsgInfo->msgData);
-
-               snprintf((char *)pMsgInfo->msgData, MAX_MSG_DATA_LEN+1, MSG_DATA_PATH"%d.mms", pMsgInfo->msgId);
-
-               if (addMmsMsgToDB(&mmsMsg, pMsgInfo, _MsgMmsGetAttachCount(&mmsMsgData)) != MSG_SUCCESS) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       __MmsReleaseMmsLists(&mmsMsgData);
-
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS Stroage Error");
+       } else {
+               MSG_DEBUG("### version 1.1 ###");
+               if (MmsEncodeReadReport11(pFile, &mmsMsg, readStatus) != true) {
+                       MsgCloseFile(pFile);
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS Encode Read Report 1.1 Error");
                }
+       }
 
-               strcpy((char *)pMsgInfo->msgData,szTemp);
+       MsgCloseFile(pFile);
+}
 
-               snprintf(fileName, MSG_FILENAME_LEN_MAX+1, MSG_DATA_PATH"%d", mmsMsg.msgID);
+msg_error_t MmsPluginStorage::addMmsMsgToDB(MmsMsg *pMmsMsg, const char *raw_filepath)
+{
+       MSG_BEGIN();
 
-               pFile = MsgOpenMMSFile(fileName);
-               if (!pFile) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       __MmsReleaseMmsLists(&mmsMsgData);
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS File open Error");
-               }
+       MsgDbHandler *dbHandle = getDbHandle();
 
-               if (fchmod(fileno(pFile), file_mode) < 0) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       __MmsReleaseMmsLists(&mmsMsgData);
-                       MsgCloseFile(pFile);
+       char sqlQuery[MAX_QUERY_LEN + 1];
 
-                       THROW(MsgException::MMS_PLG_ERROR, "chmod() error: %s", strerror(errno));
-               }
+       // Add Message
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, '%s', '%s', '%s', '%s', '%s', %d, %d, %ld, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d);",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, pMmsMsg->msgID, pMmsMsg->szTrID, pMmsMsg->szMsgID, pMmsMsg->szForwardMsgID, pMmsMsg->szContentLocation,
+                       raw_filepath, pMmsMsg->mmsAttrib.version, pMmsMsg->mmsAttrib.dataType, pMmsMsg->mmsAttrib.date, pMmsMsg->mmsAttrib.bHideAddress,
+                       pMmsMsg->mmsAttrib.bAskDeliveryReport, pMmsMsg->mmsAttrib.bReportAllowed, pMmsMsg->mmsAttrib.readReportAllowedType,
+                       pMmsMsg->mmsAttrib.bAskReadReply, pMmsMsg->mmsAttrib.bRead, pMmsMsg->mmsAttrib.readReportSendStatus, pMmsMsg->mmsAttrib.bReadReportSent,
+                       pMmsMsg->mmsAttrib.priority, pMmsMsg->mmsAttrib.bLeaveCopy, pMmsMsg->mmsAttrib.msgSize, pMmsMsg->mmsAttrib.msgClass,
+                       pMmsMsg->mmsAttrib.expiryTime.time,     0/*pMmsMsg->mmsAttrib.bUseDeliveryCustomTime*/, pMmsMsg->mmsAttrib.deliveryTime.time, pMmsMsg->mmsAttrib.msgStatus);
 
-               if (_MmsEncodeSendReq(pFile, &mmsMsg) != true) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       __MmsReleaseMmsLists(&mmsMsgData);
-                       MsgCloseFile(pFile);
+       MSG_DEBUG("\n!!!!!!!!! QUERY : %s\n", sqlQuery);
 
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS Message Encode Send Req Error");
-               }
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
 
-               MsgFsync(pFile);        //file is written to device immediately, it prevents missing file data from unexpected power off
-               MsgCloseFile(pFile);
+       MSG_END();
 
-               _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-               MsgFreeAttrib(&mmsMsg.mmsAttrib);
-               __MmsReleaseMmsLists(&mmsMsgData);
+       return MSG_SUCCESS;
+}
 
-       } else if (pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS) {
-               MSG_DEBUG("######## MmsPlgAddMessage -> MSG_NOTIFICATIONIND_MMS ###########");
+#if 1 //old
+msg_error_t MmsPluginStorage::updateConfMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
 
-               MmsComposeNotiMessage(&mmsMsg, pMsgInfo->msgId);
+       MsgDbHandler *dbHandle = getDbHandle();
 
-               //Need to store mms specific data (contents location, TrID, ExpiryTime, Delivery Report, message ID)
-               if (addMmsMsgToDB(&mmsMsg, pMsgInfo) != MSG_SUCCESS) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS Stroage Error");
-               }
-       } else if (pMsgInfo->msgType.subType == MSG_SENDCONF_MMS || pMsgInfo->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS) {
-               MmsMsg *pMsg = NULL;
-               char szTemp[MAX_MSG_DATA_LEN + 1]= {0, };
+       char sqlQuery[MAX_QUERY_LEN + 1];
 
-               if (!_MmsReadMsgBody(pMsgInfo->msgId, true, true, pFileData))
-                       THROW(MsgException::MMS_PLG_ERROR, "_MmsReadMsgBody Error");
+       MMS_RECV_DATA_S *pMmsRecvData = (MMS_RECV_DATA_S *)pMsgInfo->msgData;
 
-               MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+       MSG_DEBUG("###### pMsgInfo->msgData = %s #######", pMmsRecvData->retrievedFilePath);
 
-               if (pMsgInfo->msgType.subType == MSG_SENDCONF_MMS)
-                       pMsgInfo->networkStatus = MSG_NETWORK_SEND_SUCCESS;
-               else
-                       pMsgInfo->networkStatus = MSG_NETWORK_RETRIEVE_SUCCESS;
-               strcpy(szTemp,pMsgInfo->msgData);
-               memset(pMsgInfo->msgData, 0, MAX_MSG_DATA_LEN + 1);
-               strncpy(pMsgInfo->msgData, pFileData, MAX_MSG_DATA_LEN);
-
-               MmsPluginStorage *pStorage = MmsPluginStorage::instance();
-
-               MMS_MESSAGE_DATA_S mmsMsgData;
-               bzero(&mmsMsgData,sizeof(MMS_MESSAGE_DATA_S));
-               if (mmsHeader.msgType.type == MIME_MULTIPART_RELATED || mmsHeader.msgType.type == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
-                       char *pSmilDoc;
-                       MmsMsg *pMsg = NULL;
-                       char szFileName[MSG_FILENAME_LEN_MAX] = {0, };
-
-                       mmsMsgData.regionCnt = 0;
-                       mmsMsgData.pageCnt = 0;
-                       mmsMsgData.attachCnt = 0;
-                       mmsMsgData.transitionCnt = 0;
-                       mmsMsgData.metaCnt = 0;
-                       memset(mmsMsgData.szSmilFilePath, 0, MSG_FILEPATH_LEN_MAX);
-
-                       pSmilDoc = MmsSmilGetPresentationData(pMsgInfo->msgId);
-                       MmsSmilParseSmilDoc(&mmsMsgData, pSmilDoc);
-                       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
-                       strcpy(szFileName, pMsg->szFileName);
-
-                       err = pStorage->getMsgText(&mmsMsgData, pMsgInfo->msgText);
-                       err = pStorage->makeThumbnail(&mmsMsgData, pMsgInfo->thumbPath, szFileName);
-
-                       __MmsReleaseMmsLists(&mmsMsgData);
-               }
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MESSAGE_ID = '%s', FILE_PATH = '%s' WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, pMmsRecvData->szMsgID, pMmsRecvData->retrievedFilePath, pMsgInfo->msgId);
 
-               if (addMmsMsgToDB(pMsg, pMsgInfo) != MSG_SUCCESS) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+       MSG_DEBUG("SQLQuery = %s", sqlQuery);
 
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS Stroage Error");
-               }
-               memset(pMsgInfo->msgData, 0, MAX_MSG_DATA_LEN + 1);
-               strcpy((char *)pMsgInfo->msgData,szTemp);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
 
-               _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+       MSG_END();
 
-       } else if (pMsgInfo->msgType.subType == MSG_READREPLY_MMS || pMsgInfo->msgType.subType == MSG_READRECIND_MMS) {
-               MSG_DEBUG("######## MmsPlgAddMessage -> MSG_READREPLY_MMS || MSG_READRECIND_MMS ###########");
+       return MSG_SUCCESS;
+}
 
-               char filePath[MAX_FULL_PATH_SIZE+1] = {0, };
-               FILE *pFile = NULL;
+#else //new
 
-               msg_read_report_status_t readStatus;
-               msg_message_id_t selectedMsgId;
-               int     version;
+msg_error_t MmsPluginStorage::updateRetriveConf(msg_message_id_t msgId, MMS_DATA_S *pMmsData)
+{
+       MSG_BEGIN();
 
-               memcpy(&readStatus, pMsgInfo->msgData, sizeof(msg_read_report_status_t));
-               memcpy(&selectedMsgId, pMsgInfo->msgData + sizeof(msg_read_report_status_t), sizeof(msg_message_id_t));
+       MsgDbHandler *dbHandle = getDbHandle();
 
-               version = MmsPluginStorage::instance()->getMmsVersion(selectedMsgId);
+       char sqlQuery[MAX_QUERY_LEN + 1];
 
-               snprintf((char *)pMsgInfo->msgData, MAX_MSG_DATA_LEN+1, MSG_DATA_PATH"%d.mms", pMsgInfo->msgId);
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-               MmsComposeReadReportMessage(&mmsMsg, pMsgInfo, selectedMsgId);
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "UPDATE %s "
+                       "SET ASK_DELIVERY_REPORT = %d, ASK_READ_REPLY = %d, PRIORITY = %d, VERSION = %d, MESSAGE_ID = '%s' "
+                       "WHERE MSG_ID = %d;"
+                       , MMS_PLUGIN_MESSAGE_TABLE_NAME
+                       , pMmsData->header->bDeliveryReport
+                       , pMmsData->header->bReadReport
+                       , pMmsData->header->mmsPriority
+                       , pMmsData->header->mmsVersion
+                       , pMmsData->header->messageID
+                       , msgId);
 
-               if (addMmsMsgToDB(&mmsMsg, pMsgInfo) != MSG_SUCCESS) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
+       MSG_DEBUG("QUERY : [%s]", sqlQuery);
 
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS Stroage Error");
-               }
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
 
-               snprintf(filePath, MAX_FULL_PATH_SIZE+1, MSG_DATA_PATH"%d", mmsMsg.msgID);
-               pFile = MsgOpenMMSFile(filePath);
-               if (!pFile) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       MsgCloseFile(pFile);
-                       pFile = NULL;
+       MSG_END();
 
-                       THROW(MsgException::MMS_PLG_ERROR, "MsgOpenMMSFile error");
-               }
+       return MSG_SUCCESS;
+}
 
-               if (fchmod(fileno(pFile), file_mode) < 0) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       MsgCloseFile(pFile);
-                       pFile = NULL;
+msg_error_t MmsPluginStorage::updateConfMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+       int err;
 
-                       THROW(MsgException::MMS_PLG_ERROR, "chmod() error: %s", strerror(errno));
-               }
+       char *pSerializedMms = NULL;
+       gsize pSerializedMmsSize = 0;
 
-               if (version == 0x90) {
-                       MSG_DEBUG("### version 1.0 ###");
-                       if (_MmsEncodeReadReport10(pFile, &mmsMsg, readStatus) != true) {
-                               MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                               MsgCloseFile(pFile);
-                               pFile = NULL;
+       char working_dir[MSG_FILENAME_LEN_MAX+1] = {0,};
+       MMS_DATA_S *pMmsData = NULL;
 
-                               THROW(MsgException::MMS_PLG_ERROR, "MMS Encode Read Report 1.0 Error");
-                       }
-               } else {
-                       MSG_DEBUG("### version 1.1 ###");
-                       if (_MmsEncodeReadReport11(pFile, &mmsMsg, readStatus) != true) {
-                               MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                               MsgCloseFile(pFile);
-                               pFile = NULL;
+       //pMsgInfo->msgData is Filepath of json
+       g_file_get_contents(pMsgInfo->msgData, &pSerializedMms, &pSerializedMmsSize, NULL);
 
-                               THROW(MsgException::MMS_PLG_ERROR, "MMS Encode Read Report 1.1 Error");
-                       }
-               }
+       if (MsgDeserializeMmsData(pSerializedMms, strlen(pSerializedMms), &pMmsData) != 0) {
+               MSG_DEBUG("Fail to Deserialize Message Data");
+               return MSG_ERR_NULL_MSGHANDLE;
+       }
 
-               MsgFsync(pFile);
-               MsgCloseFile(pFile);
-               pFile = NULL;
+       updateRetriveConf(pMsgInfo->msgId, pMmsData);
 
-               _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+       snprintf(working_dir, sizeof(working_dir), MSG_DATA_PATH"%d.mms.dir", pMsgInfo->msgId);
 
-               MsgFreeAttrib(&mmsMsg.mmsAttrib);
+       MsgMmsSetMultipartListData(pMmsData);//app file -> data
 
-       } else if (pMsgInfo->msgType.subType == MSG_FORWARD_MMS) {
-               MSG_DEBUG("######## MmsPlgAddMessage -> MSG_FORWARD_MMS ###########");
+       MsgMmsSetMultipartListFilePath(working_dir, pMmsData);//data -> svc file
 
-               char filePath[MAX_FULL_PATH_SIZE + 1] = {0, };
-               char szTemp[MAX_MSG_DATA_LEN + 1] = {0, };
-               FILE *pFile = NULL;
-               MMS_MESSAGE_DATA_S mmsMsgData;
+       MMS_MULTIPART_DATA_S *pSmilMultipart = pMmsData->smil;
+       if (pSmilMultipart) {
+               MmsPluginStorage::instance()->insertMultipart(pMsgInfo->msgId, pSmilMultipart);
+       }
 
-               if (MmsComposeMessage(&mmsMsg, pMsgInfo, pSendOptInfo, &mmsMsgData, pFileData) != true) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       __MmsReleaseMmsLists(&mmsMsgData);
+       MMSList *multipart_list = pMmsData->multipartlist;
+       for (int i = 0; i < (int)g_list_length(multipart_list); i++) {
+               MMS_MULTIPART_DATA_S *pMultipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(multipart_list, i);
 
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS Message Compose Error");
-               }
+               MmsPluginStorage::instance()->insertMultipart(pMsgInfo->msgId, pMultipart);
+       }
 
-               strcpy(szTemp,pMsgInfo->msgData);
+       {//make Preview info for APP
+               MmsPluginAppBase appBase(pMmsData);
+               appBase.makePreviewInfo(pMsgInfo->msgId, true, NULL);
+               appBase.getFirstPageTextFilePath(pMsgInfo->msgText, sizeof(pMsgInfo->msgText));
+       }
 
-               snprintf((char *)pMsgInfo->msgData, MAX_MSG_DATA_LEN + 1, MSG_DATA_PATH"%d.mms", pMsgInfo->msgId);
+       MsgMmsRelease(&pMmsData);
+       MSG_END();
 
-               if (addMmsMsgToDB(&mmsMsg, pMsgInfo, _MsgMmsGetAttachCount(&mmsMsgData)) != MSG_SUCCESS) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       __MmsReleaseMmsLists(&mmsMsgData);
+       return MSG_SUCCESS;
+}
+#endif
 
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS Stroage Error");
-               }
+msg_error_t MmsPluginStorage::updateMsgServerID(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo)
+{
+       MSG_BEGIN();
 
-               strcpy((char *)pMsgInfo->msgData,szTemp);
+       MsgDbHandler *dbHandle = getDbHandle();
 
-               snprintf(filePath, MAX_FULL_PATH_SIZE + 1 , MSG_DATA_PATH"%d", mmsMsg.msgID);
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-               pFile = MsgOpenMMSFile(filePath);
-               if (!pFile) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       __MmsReleaseMmsLists(&mmsMsgData);
-                       MsgCloseFile(pFile);
-                       pFile = NULL;
+       MMS_RECV_DATA_S *pMmsRecvData = (MMS_RECV_DATA_S *)pMsgInfo->msgData;
 
-                       THROW(MsgException::MMS_PLG_ERROR, "MsgOpenMMSFile error");
-               }
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MESSAGE_ID = '%s' WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, pMmsRecvData->szMsgID, pMsgInfo->msgId);
 
-               if (fchmod(fileno(pFile), file_mode) < 0) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       __MmsReleaseMmsLists(&mmsMsgData);
-                       MsgCloseFile(pFile);
-                       pFile = NULL;
+       MSG_DEBUG("SQLQuery = %s", sqlQuery);
 
-                       THROW(MsgException::MMS_PLG_ERROR, "chmod() error: %s", strerror(errno));
-               }
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
 
-               if (_MmsEncodeSendReq(pFile, &mmsMsg) != true) {
-                       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-                       MsgFreeAttrib(&mmsMsg.mmsAttrib);
-                       __MmsReleaseMmsLists(&mmsMsgData);
-                       MsgCloseFile(pFile);
-                       pFile = NULL;
+       if (pSendOptInfo != NULL) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET ASK_DELIVERY_REPORT = %d, ASK_READ_REPLY = %d, PRIORITY = %d, EXPIRY_TIME = %d \
+                               WHERE MSG_ID = %d;", MMS_PLUGIN_MESSAGE_TABLE_NAME, pSendOptInfo->bDeliverReq, pSendOptInfo->option.mmsSendOptInfo.bReadReq,
+                               pSendOptInfo->option.mmsSendOptInfo.priority, pSendOptInfo->option.mmsSendOptInfo.expiryTime.time, pMsgInfo->msgId);
 
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS Message Encode Send Req Error");
-               }
-               MsgFsync(pFile);
-               MsgCloseFile(pFile);
-               pFile = NULL;
+               MSG_DEBUG("SQLQuery = %s", sqlQuery);
 
-               _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-               MsgFreeAttrib(&mmsMsg.mmsAttrib);
-               __MmsReleaseMmsLists(&mmsMsgData);
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       return MSG_ERR_DB_EXEC;
+               }
        }
 
+       //dbHandle->finalizeQuery();
+
        MSG_END();
-}
 
+       return MSG_SUCCESS;
+}
 
-void MmsPluginStorage::composeReadReport(MSG_MESSAGE_INFO_S *pMsgInfo)
+msg_error_t MmsPluginStorage::insertDeliveryReport(msg_message_id_t msgId, char *address, MmsMsgMultiStatus *pStatus)
 {
-       FILE *pFile = NULL;
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       msg_read_report_status_t readStatus;
-       int     version;
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       memcpy(&readStatus, pMsgInfo->msgData, sizeof(msg_read_report_status_t));
+       //( MSG_ID INTEGER , ADDRESS_VAL TEXT , STATUS_TYPE INTEGER , STATUS INTEGER DEFAULT 0 , TIME DATETIME);
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s "
+                       "(MSG_ID, ADDRESS_VAL, STATUS_TYPE, STATUS, TIME) "
+                       "VALUES (%d, '%s', %d, %d, %d);",
+                       MSGFW_REPORT_TABLE_NAME, msgId, address, MSG_REPORT_TYPE_DELIVERY, pStatus->msgStatus, (int)pStatus->handledTime);
 
-       MSG_DEBUG("pMsgInfo->msgId = %d", pMsgInfo->msgId);
+       MSG_DEBUG("QUERY : [%s]", sqlQuery);
 
-       version = MmsPluginStorage::instance()->getMmsVersion(pMsgInfo->msgId);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
 
-       snprintf((char *)pMsgInfo->msgData, MAX_MSG_DATA_LEN+1, MSG_DATA_PATH"%d-Read-Rec.ind", pMsgInfo->msgId);
+       return MSG_SUCCESS;
+}
 
-       if (version == 0x90)
-               pMsgInfo->msgType.subType = MSG_READREPLY_MMS;
-       else
-               pMsgInfo->msgType.subType = MSG_READRECIND_MMS;
+msg_error_t MmsPluginStorage::insertReadReport(msg_message_id_t msgId, char *address, MmsMsgMultiStatus *pStatus)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       MmsComposeReadReportMessage(&mmsMsg, pMsgInfo, pMsgInfo->msgId);
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       pFile = MsgOpenFile(pMsgInfo->msgData, "wb+");
-       if (!pFile)
-               THROW(MsgException::MMS_PLG_ERROR, "MsgOpenMMSFile Error");
+       //( MSG_ID INTEGER , ADDRESS_VAL TEXT , STATUS_TYPE INTEGER , STATUS INTEGER DEFAULT 0 , TIME DATETIME);
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s "
+                       "(MSG_ID, ADDRESS_VAL, STATUS_TYPE, STATUS, TIME) "
+                       "VALUES (%d, '%s', %d, %d, %d);",
+                       MSGFW_REPORT_TABLE_NAME, msgId, address, MSG_REPORT_TYPE_READ, pStatus->readStatus, (int)pStatus->readTime);
 
-       if (version == 0x90) {
-               MSG_DEBUG("### version 1.0 ###");
-               if (_MmsEncodeReadReport10(pFile, &mmsMsg, readStatus) != true) {
-                       MsgCloseFile(pFile);
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS Encode Read Report 1.0 Error");
-               }
-       } else {
-               MSG_DEBUG("### version 1.1 ###");
-               if (_MmsEncodeReadReport11(pFile, &mmsMsg, readStatus) != true) {
-                       MsgCloseFile(pFile);
-                       THROW(MsgException::MMS_PLG_ERROR, "MMS Encode Read Report 1.1 Error");
-               }
-       }
+       MSG_DEBUG("QUERY : [%s]", sqlQuery);
 
-       MsgCloseFile(pFile);
-}
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
 
+       return MSG_SUCCESS;
+}
 
-msg_error_t MmsPluginStorage::addMmsMsgToDB(MmsMsg *pMmsMsg, const MSG_MESSAGE_INFO_S *pMsgInfo, int attachCnt)
+msg_error_t MmsPluginStorage::updateMmsAttrib(msg_message_id_t msgId, MmsAttrib *attrib, MSG_SUB_TYPE_T msgSubType)
 {
        MSG_BEGIN();
 
+       MsgDbHandler *dbHandle = getDbHandle();
+
        char sqlQuery[MAX_QUERY_LEN + 1];
 
-       // Add Message
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, '%s', '%s', '%s', '%s', '%s', %d, %d, %ld, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d);",
-                       MMS_PLUGIN_MESSAGE_TABLE_NAME, pMmsMsg->msgID, pMmsMsg->szTrID, pMmsMsg->szMsgID, pMmsMsg->szForwardMsgID, pMmsMsg->szContentLocation,
-                       pMsgInfo->msgData, pMmsMsg->mmsAttrib.version, pMmsMsg->mmsAttrib.dataType, pMmsMsg->mmsAttrib.date, pMmsMsg->mmsAttrib.bHideAddress,
-                       pMmsMsg->mmsAttrib.bAskDeliveryReport, pMmsMsg->mmsAttrib.bReportAllowed, pMmsMsg->mmsAttrib.readReportAllowedType,
-                       pMmsMsg->mmsAttrib.bAskReadReply, pMmsMsg->mmsAttrib.bRead, pMmsMsg->mmsAttrib.readReportSendStatus, pMmsMsg->mmsAttrib.bReadReportSent,
-                       pMmsMsg->mmsAttrib.priority, pMmsMsg->mmsAttrib.bLeaveCopy, pMmsMsg->mmsAttrib.msgSize, pMmsMsg->mmsAttrib.msgClass,
-                       pMmsMsg->mmsAttrib.expiryTime.time,     pMmsMsg->mmsAttrib.bUseDeliveryCustomTime, pMmsMsg->mmsAttrib.deliveryTime.time, pMmsMsg->mmsAttrib.msgStatus);
 
-       MSG_DEBUG("\n!!!!!!!!! QUERY : %s\n", sqlQuery);
+       if (msgSubType == MSG_NOTIFICATIONIND_MMS) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET EXPIRY_TIME = %d WHERE MSG_ID = %d;",
+                               MMS_PLUGIN_MESSAGE_TABLE_NAME, attrib->expiryTime.time, msgId);
+       } else if (msgSubType == MSG_RETRIEVE_AUTOCONF_MMS || msgSubType == MSG_RETRIEVE_MANUALCONF_MMS) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET ASK_DELIVERY_REPORT = %d, ASK_READ_REPLY = %d, PRIORITY = %d, VERSION = %d WHERE MSG_ID = %d;",
+                               MMS_PLUGIN_MESSAGE_TABLE_NAME, attrib->bAskDeliveryReport, attrib->bAskReadReply, attrib->priority, attrib->version, msgId);
+       }
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_EXEC;
+       MSG_DEBUG("QUERY : [%s]", sqlQuery);
 
-       if (updateMmsAttachCount(pMmsMsg->msgID, attachCnt) != MSG_SUCCESS)
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_EXEC;
 
        MSG_END();
@@ -450,1113 +358,1252 @@ msg_error_t MmsPluginStorage::addMmsMsgToDB(MmsMsg *pMmsMsg, const MSG_MESSAGE_I
 }
 
 
-msg_error_t    MmsPluginStorage::plgGetMmsMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_MESSAGE_DATA_S *pMmsMsg, char **pDestMsg)
+msg_error_t MmsPluginStorage::updateMmsAttachCount(msg_message_id_t msgId, int count)
 {
        MSG_BEGIN();
 
-       msg_error_t     err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       int partCnt = 0;
-       unsigned int nSize = 0;
+       char sqlQuery[MAX_QUERY_LEN + 1];
 
-       MsgType partHeader;
-       MmsAttrib pMmsAttrib;
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET ATTACHMENT_COUNT = %d WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, count, msgId);
 
-       char szBuf[MSG_FILEPATH_LEN_MAX] = {0, };
-       bool bMultipartRelated = false;
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to execute query [%s]", sqlQuery);
+               return MSG_ERR_DB_EXEC;
+       }
 
-       if (pSendOptInfo != NULL) {
-               char sqlQuery[MAX_QUERY_LEN + 1];
+       MSG_END();
 
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT ASK_DELIVERY_REPORT, KEEP_COPY, ASK_READ_REPLY, PRIORITY, EXPIRY_TIME, CUSTOM_DELIVERY_TIME, DELIVERY_TIME \
-                               FROM %s WHERE MSG_ID = %d;", MMS_PLUGIN_MESSAGE_TABLE_NAME, pMsg->msgId);
+       return MSG_SUCCESS;
+}
 
-               MSG_DEBUG("### SQLQuery = %s ###", sqlQuery);
+void MmsPluginStorage::getMmsFromDB(msg_message_id_t msgId, MmsMsg *pMmsMsg)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
 
-               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
-                       MSG_DEBUG("MSG_ERR_DB_PREPARE");
+       char sqlQuery[MAX_QUERY_LEN + 1];
 
-               if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-                       pSendOptInfo->bDeliverReq = dbHandle.columnInt(0);
-                       MSG_DEBUG("## delivery = %d ##", pSendOptInfo->bDeliverReq);
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-                       pSendOptInfo->bKeepCopy = dbHandle.columnInt(1);
-                       MSG_DEBUG("## bKeepCopy = %d ##", pSendOptInfo->bKeepCopy);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT VERSION, DATA_TYPE,  DATE, HIDE_ADDRESS, ASK_DELIVERY_REPORT, REPORT_ALLOWED, \
+                       READ_REPORT_ALLOWED_TYPE, ASK_READ_REPLY, READ, READ_REPORT_SEND_STATUS, READ_REPORT_SENT, PRIORITY, \
+                       MSG_SIZE, MSG_CLASS, EXPIRY_TIME, CUSTOM_DELIVERY_TIME, DELIVERY_TIME, MSG_STATUS, \
+                       MESSAGE_ID, TRANSACTION_ID, CONTENTS_LOCATION, FILE_PATH \
+                       FROM %s WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, msgId);
 
-                       pSendOptInfo->option.mmsSendOptInfo.bReadReq = dbHandle.columnInt(2);
-                       MSG_DEBUG("## bReadReq = %d ##", pSendOptInfo->option.mmsSendOptInfo.bReadReq);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               MSG_DEBUG("MSG_ERR_DB_PREPARE");
 
-                       pSendOptInfo->option.mmsSendOptInfo.priority = dbHandle.columnInt(3);
-                       MSG_DEBUG("## priority = %d ##", pSendOptInfo->option.mmsSendOptInfo.priority);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               int i = 0;
+               pMmsMsg->mmsAttrib.version = dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.dataType = (MmsDataType)dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.date = dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.bHideAddress = dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.bAskDeliveryReport = dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.bReportAllowed = dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.readReportAllowedType = (MmsRecvReadReportType)dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.bAskReadReply = dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.bRead = dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.readReportSendStatus = (MmsRecvReadReportSendStatus)dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.bReadReportSent = dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.priority = (MmsPriority)dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.msgSize = dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.msgClass = (MmsMsgClass)dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.expiryTime.time = dbHandle->columnInt(i++);
+               i++;//CUSTOM_DELIVERY_TIME
+               pMmsMsg->mmsAttrib.deliveryTime.time = dbHandle->columnInt(i++);
+               pMmsMsg->mmsAttrib.msgStatus = (msg_delivery_report_status_t)dbHandle->columnInt(i++);
+               snprintf(pMmsMsg->szMsgID, sizeof(pMmsMsg->szMsgID), "%s", dbHandle->columnText(i++));
+               snprintf(pMmsMsg->szTrID, sizeof(pMmsMsg->szTrID), "%s", dbHandle->columnText(i++));
+               snprintf(pMmsMsg->szContentLocation, sizeof(pMmsMsg->szContentLocation), "%s", dbHandle->columnText(i++));
+               snprintf(pMmsMsg->szFileName, sizeof(pMmsMsg->szFileName), "%s", dbHandle->columnText(i++));
+       }
 
-                       pSendOptInfo->option.mmsSendOptInfo.expiryTime.time = (unsigned int)dbHandle.columnInt(4);
-                       MSG_DEBUG("## expiryTime = %d ##", pSendOptInfo->option.mmsSendOptInfo.expiryTime.time);
 
-                       pSendOptInfo->option.mmsSendOptInfo.bUseDeliveryCustomTime = (unsigned int)dbHandle.columnInt(5);
-                       MSG_DEBUG("## bUseDeliveryCustomTime = %d ##", pSendOptInfo->option.mmsSendOptInfo.bUseDeliveryCustomTime);
+       dbHandle->finalizeQuery();
+}
 
-                       pSendOptInfo->option.mmsSendOptInfo.deliveryTime.time = (unsigned int)dbHandle.columnInt(6);
-                       MSG_DEBUG("## deliveryTime = %d ##", pSendOptInfo->option.mmsSendOptInfo.deliveryTime.time);
-               } else {
-                       dbHandle.finalizeQuery();
-                       return MSG_ERR_DB_STEP;
-               }
+msg_error_t MmsPluginStorage::getMmsMessageId(msg_message_id_t selectedMsgId, MmsMsg *pMmsMsg)
+{
+       msg_error_t err = MSG_SUCCESS;
 
-               dbHandle.finalizeQuery();
-       }
+       int rowCnt = 0;
 
-       if (_MmsReadMsgBody(pMsg->msgId, true, false, NULL) == false) {
-               MSG_DEBUG("The MMS Message might include drm contents!!!");
+       MsgDbHandler *dbHandle = getDbHandle();
 
-#ifdef __SUPPORT_DRM__
-               if (MmsDrm2GetConvertState() == MMS_DRM2_CONVERT_REQUIRED) {
-                       bool bRetToConvert = true;
+       char sqlQuery[MAX_QUERY_LEN + 1];
 
-                       bRetToConvert = MmsDrm2ConvertMsgBody(mmsHeader.msgType.szOrgFilePath);
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-                       MmsDrm2SetConvertState(MMS_DRM2_CONVERT_FINISH);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MESSAGE_ID FROM %s WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, selectedMsgId);
 
-                       if (bRetToConvert) {
-                               remove(mmsHeader.msgType.szOrgFilePath);
-                               rename(MMS_DECODE_DRM_CONVERTED_TEMP_FILE, mmsHeader.msgType.szOrgFilePath);
+       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
-                               if (MmsDrm2ReadMsgConvertedBody(pMsg, true, false, NULL) == false) {
-                                       MSG_DEBUG("MmsLoadMsg:MmsDrm2ReadMsgConvertedBody() returns false\n");
-                                       goto L_CATCH;
-                               }
-                       } else {
-                               goto L_CATCH;
-                       }
-               }
-#endif
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               dbHandle->freeTable();
+               MSG_DEBUG("[Error]Failed to Get Table");
+               return MSG_ERR_DB_NORECORD;
        }
 
-       MmsGetMsgAttrib(pMsg->msgId, &pMmsAttrib);
+       if (rowCnt != 1) {
+               dbHandle->freeTable();
+               MSG_DEBUG("[Error] MSG_ERR_DB_NORECORD");
+               return MSG_ERR_DB_NORECORD;
+       }
 
-       pMmsMsg->regionCnt = 0;
-       pMmsMsg->pageCnt = 0;
-       pMmsMsg->attachCnt = 0;
-       pMmsMsg->transitionCnt = 0;
-       pMmsMsg->metaCnt = 0;
-       memset(pMmsMsg->szSmilFilePath, 0, MSG_FILEPATH_LEN_MAX);
+       dbHandle->getColumnToString(1, MMS_MSG_ID_LEN + 1, pMmsMsg->szMsgID);
 
-       if (pMmsAttrib.contentType == MIME_MULTIPART_RELATED || pMmsAttrib.contentType == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
-               char *pSmilDoc = NULL;
+       dbHandle->freeTable();
 
-               pSmilDoc = MmsSmilGetPresentationData(pMsg->msgId);
-               if (!pSmilDoc) {
-                       goto L_CATCH;
-               }
+       return MSG_SUCCESS;
+}
 
-               MmsSmilParseSmilDoc(pMmsMsg, pSmilDoc);
-               bMultipartRelated = true;
-       }
 
-       partCnt = MmsGetMediaPartCount(pMsg->msgId);
-       MSG_DEBUG("MmsUiGetMediaAttachInfo: partCnt=%d\n", partCnt);
+int MmsPluginStorage::getMmsVersion(msg_message_id_t selectedMsgId)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int rowCnt = 0;
+       int version = 0;
+
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       char sqlQuery[MAX_QUERY_LEN + 1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       if (partCnt < 0) {
-               MSG_DEBUG("MmsUiGetMediaAttachInfo: partCnt=%d\n", partCnt);
-               goto FREE_CATCH;
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT VERSION FROM %s WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, selectedMsgId);
+
+       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               dbHandle->freeTable();
+               MSG_DEBUG("[Error]Failed to Get Table");
+               return version;
        }
 
-       for (int i = 0; i < partCnt; ++i) {
-               if (!MmsGetMediaPartHeader(i, &partHeader)) {
-                       MSG_DEBUG("MmsUiGetMediaAttachInfo: MmsGetMediaPartHeader failed\n");
-                       goto FREE_CATCH;
-               }
+       if (rowCnt != 1) {
+               dbHandle->freeTable();
+               MSG_DEBUG("[Error]MSG_ERR_DB_NORECORD");
+               return version;
+       }
 
-               if (partHeader.contentSize > 0) {
-                       if (!strcasecmp(partHeader.param.szFileName, "cid:")) {
-                               strncpy((char *)szBuf, &partHeader.param.szFileName[4], MSG_FILEPATH_LEN_MAX - 1);
-                       } else {
-                               strcpy((char *)szBuf, partHeader.param.szFileName);
-                       }
-                       sprintf(partHeader.param.szFileName, MSG_DATA_PATH"%s", szBuf);
+       version = dbHandle->getColumnToInt(1);
 
-                       if (!bMultipartRelated || MmsCheckAdditionalMedia(pMmsMsg, &partHeader)) {
+       dbHandle->freeTable();
 
-                               MMS_ATTACH_S *attachment = NULL;
-                               int tempType;
+       return version;
+}
 
-                               attachment = (MMS_ATTACH_S *)calloc(sizeof(MMS_ATTACH_S), 1);
+/* reject_msg_support */
+msg_error_t MmsPluginStorage::getTrID(MSG_MESSAGE_INFO_S *pMsgInfo,char *pszTrID,int nBufferLen)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
 
-                               MsgGetTypeByFileName(&tempType, partHeader.param.szFileName);
-                               attachment->mediatype = (MimeType)tempType;
+       char sqlQuery[MAX_QUERY_LEN + 1];
 
-                               strcpy(attachment->szFilePath, partHeader.param.szFileName);
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-                               strncpy(attachment->szFileName, partHeader.param.szName, MSG_FILENAME_LEN_MAX -1);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT TRANSACTION_ID FROM %s WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, pMsgInfo->msgId);
 
-                               attachment->fileSize = partHeader.contentSize;
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
 
-                               _MsgMmsAddAttachment(pMmsMsg, attachment);
-                       }
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               if (dbHandle->columnText(0) != NULL) {
+                       strncpy(pszTrID, (char *)dbHandle->columnText(0), nBufferLen - 1);
+                       pszTrID[nBufferLen-1] = '\0';
                }
-       }
+       } else {
+               dbHandle->finalizeQuery();
 
-       *pDestMsg = _MsgMmsSerializeMessageData(pMmsMsg, &nSize);
+               return MSG_ERR_DB_STEP;
+       }
 
-       __MmsReleaseMmsLists(pMmsMsg);
+       dbHandle->finalizeQuery();
 
+       return MSG_SUCCESS;
+}
+/* reject_msg_support */
 
-       MmsMsg *pStoMmsMsg;
-       MmsPluginStorage::instance()->getMmsMessage(&pStoMmsMsg);
-       _MmsInitHeader();
-       _MmsUnregisterDecodeBuffer();
-#ifdef __SUPPORT_DRM__
-       _MsgFreeDRMInfo(&pStoMmsMsg->msgType.drmInfo);
-#endif
-       _MsgFreeBody(&pStoMmsMsg->msgBody, pStoMmsMsg->msgType.type);
+msg_error_t MmsPluginStorage::getAddressInfo(msg_message_id_t msgId, MSG_ADDRESS_INFO_S *pAddrInfo)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       pMsg->dataSize = nSize;
+       char sqlQuery[MAX_QUERY_LEN+1];
 
-       if (err != MSG_SUCCESS)
-               MSG_DEBUG("MmsPlgUpdateMessage : Update MMS Message Failed");
+       // Add Address
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       MSG_END();
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                       "A.ADDRESS_TYPE, "
+                       "A.RECIPIENT_TYPE, "
+                       "A.CONTACT_ID, "
+                       "A.ADDRESS_VAL "
+                       "FROM %s A, %s B "
+                       "WHERE A.CONV_ID = B.CONV_ID "
+                       "AND B.MSG_ID = %d;",
+                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                       msgId);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
 
-       return err;
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               pAddrInfo->addressType = dbHandle->columnInt(0);
+               pAddrInfo->recipientType = dbHandle->columnInt(1);
+               pAddrInfo->contactId = dbHandle->columnInt(2);
 
-FREE_CATCH:
-       if (bMultipartRelated) {
-               __MmsReleaseMmsLists(pMmsMsg);
+               strncpy(pAddrInfo->addressVal, (char*)dbHandle->columnText(3), MAX_ADDRESS_VAL_LEN);
+       } else {
+               dbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
        }
 
-L_CATCH:
-       {
-               MmsMsg *pMsg;
-               MmsPluginStorage::instance()->getMmsMessage(&pMsg);
-               _MmsInitHeader();
+       dbHandle->finalizeQuery();
 
-               _MmsUnregisterDecodeBuffer();
-#ifdef __SUPPORT_DRM__
-               _MsgFreeDRMInfo(&pMsg->msgType.drmInfo);
-#endif
-               _MsgFreeBody(&pMsg->msgBody, pMsg->msgType.type);
-
-               return MSG_ERR_STORAGE_ERROR;
-       }
-       MSG_END();
+       return MSG_SUCCESS;
 }
 
 
-msg_error_t MmsPluginStorage::updateMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData)
+msg_error_t MmsPluginStorage::getMmsRawFilePath(msg_message_id_t msgId, char *pFilepath, size_t filePathLen)
 {
-       MSG_BEGIN();
-
-       msg_error_t     err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       MmsMsg mmsMsg;
-       bzero(&mmsMsg, sizeof(mmsMsg));
-
-       char filePath[MAX_FULL_PATH_SIZE+1] = {0, };
        char sqlQuery[MAX_QUERY_LEN + 1];
 
-       unsigned int addrId = 0;
-       FILE *pFile = NULL;
-
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET ASK_DELIVERY_REPORT = %d, KEEP_COPY = %d, ASK_READ_REPLY = %d, EXPIRY_TIME = %d, CUSTOM_DELIVERY_TIME = %d, DELIVERY_TIME= %d, PRIORITY = %d \
-                       WHERE MSG_ID = %d;", MMS_PLUGIN_MESSAGE_TABLE_NAME, pSendOptInfo->bDeliverReq, pSendOptInfo->bKeepCopy, pSendOptInfo->option.mmsSendOptInfo.bReadReq,
-                       pSendOptInfo->option.mmsSendOptInfo.expiryTime.time, pSendOptInfo->option.mmsSendOptInfo.bUseDeliveryCustomTime, pSendOptInfo->option.mmsSendOptInfo.deliveryTime.time,
-                       pSendOptInfo->option.mmsSendOptInfo.priority, pMsgInfo->msgId);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_EXEC;
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILE_PATH FROM %s WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, msgId);
 
-       MMS_MESSAGE_DATA_S mmsMsgData;
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
 
-       if (MmsComposeMessage(&mmsMsg, pMsgInfo, pSendOptInfo, &mmsMsgData, pFileData) != true) {
-               _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-               MsgFreeAttrib(&mmsMsg.mmsAttrib);
-               __MmsReleaseMmsLists(&mmsMsgData);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               if (dbHandle->columnText(0) != NULL) {
+                       snprintf(pFilepath, filePathLen, "%s", (char *)dbHandle->columnText(0));
+               }
+       } else {
+               dbHandle->finalizeQuery();
 
-               THROW(MsgException::MMS_PLG_ERROR, "MMS Message Compose Error");
+               return MSG_ERR_DB_STEP;
        }
 
-       snprintf(filePath, MAX_FULL_PATH_SIZE+1, MSG_DATA_PATH"%d", mmsMsg.msgID);
+       dbHandle->finalizeQuery();
 
-       pFile = MsgOpenMMSFile(filePath);
+       return MSG_SUCCESS;
+}
 
-       if (_MmsEncodeSendReq(pFile, &mmsMsg) != true) {
-               _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-               MsgFreeAttrib(&mmsMsg.mmsAttrib);
-               __MmsReleaseMmsLists(&mmsMsgData);
-               MsgCloseFile(pFile);
 
-               THROW(MsgException::MMS_PLG_ERROR, "MMS Message Encode Send Req Error");
-       }
+int MmsPluginStorage::searchMsgId(char *toNumber, char *szMsgID)
+{
+       int msgId = -1;
 
-       MsgCloseFile(pFile);
+       msg_folder_id_t folderId = MSG_SENTBOX_ID;
 
-       _MsgFreeBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
-       MsgFreeAttrib(&mmsMsg.mmsAttrib);
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       __MmsReleaseMmsLists(&mmsMsgData);
+       char sqlQuery[MAX_QUERY_LEN + 1];
 
-       MSG_END();
+       MmsAddrUtilRemovePlmnString(toNumber);
 
-       return err;
-}
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.MSG_ID FROM %s A, %s B \
+                       WHERE A.MSG_ID = B.MSG_ID AND A.FOLDER_ID = %d AND B.MESSAGE_ID LIKE '%%%s%%'",
+                       MSGFW_MESSAGE_TABLE_NAME, MMS_PLUGIN_MESSAGE_TABLE_NAME, folderId, szMsgID);
 
-msg_error_t MmsPluginStorage::updateConfMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
+       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               msgId = dbHandle->columnInt(0);
+       }
+
+       dbHandle->finalizeQuery();
+
+       return msgId;
+}
+
+msg_error_t MmsPluginStorage::getMsgText(MMS_MESSAGE_DATA_S *pMmsMsg, char *pMsgText)
 {
-       MSG_BEGIN();
+       MMS_PAGE_S *pPage = NULL;
+       MMS_MEDIA_S *pMedia = NULL;
 
-       char sqlQuery[MAX_QUERY_LEN + 1];
+       if (pMmsMsg == NULL)
+               return MSG_ERR_NULL_POINTER;
 
-       MMS_RECV_DATA_S *pMmsRecvData = (MMS_RECV_DATA_S *)pMsgInfo->msgData;
+       // Get the text data from the 1st slide.
+       if (pMmsMsg->pageCnt > 0) {
+               pPage = _MsgMmsGetPage(pMmsMsg, 0);
 
-       MSG_DEBUG("###### pMsgInfo->msgData = %s #######", pMmsRecvData->retrievedFilePath);
+               if (pPage) {
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MESSAGE_ID = '%s', FILE_PATH = '%s' WHERE MSG_ID = %d;",
-                       MMS_PLUGIN_MESSAGE_TABLE_NAME, pMmsRecvData->szMsgID, pMmsRecvData->retrievedFilePath, pMsgInfo->msgId);
+                       for (int j = 0; j < pPage->mediaCnt; ++j) {
 
-       MSG_DEBUG("SQLQuery = %s", sqlQuery);
+                               pMedia = _MsgMmsGetMedia(pPage, j);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_EXEC;
+                               if (pMedia && pMedia->mediatype == MMS_SMIL_MEDIA_TEXT) {
 
-       MSG_END();
+                                       MimeType mimeType = MIME_UNKNOWN;
+                                       MmsGetMimeTypeFromFileName(MIME_MAINTYPE_UNKNOWN, pMedia->szFilePath, &mimeType, NULL);
+
+                                       if (mimeType == MIME_TEXT_X_VCALENDAR || mimeType == MIME_TEXT_X_VCARD || mimeType == MIME_TEXT_X_VTODO || mimeType == MIME_TEXT_X_VNOTE) {
+                                               MSG_DEBUG("Media Type is Text, but Vobject file [%s]", pMedia->szFilePath);
+                                       } else {
+                                               strncpy(pMsgText, pMedia->szFilePath, MAX_MSG_TEXT_LEN);
+                                       }
+                                       break;
+                               }
+                       }
+               }
+       }
 
        return MSG_SUCCESS;
 }
 
-
-msg_error_t MmsPluginStorage::updateMsgServerID(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo)
+msg_error_t MmsPluginStorage::insertPreviewInfo(int msgId, int type, const char *value, int count)
 {
-       MSG_BEGIN();
+       MsgDbHandler *dbHandle = getDbHandle();
 
        char sqlQuery[MAX_QUERY_LEN + 1];
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       MMS_RECV_DATA_S *pMmsRecvData = (MMS_RECV_DATA_S *)pMsgInfo->msgData;
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MESSAGE_ID = '%s' WHERE MSG_ID = %d;",
-                       MMS_PLUGIN_MESSAGE_TABLE_NAME, pMmsRecvData->szMsgID, pMsgInfo->msgId);
+       //(MSG_ID INTEGER, TYPE INTEGER, INFO TEXT)
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "INSERT INTO %s "
+                       "(MSG_ID, TYPE, VALUE, COUNT)"
+                       "VALUES (%d, %d, \"%s\", %d);",
+                       MSGFW_MMS_PREVIEW_TABLE_NAME, msgId, type, value, count);
 
-       MSG_DEBUG("SQLQuery = %s", sqlQuery);
+       MSG_DEBUG("QUERY : [%s]", sqlQuery);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_EXEC;
 
-       if (pSendOptInfo != NULL) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET ASK_DELIVERY_REPORT = %d, ASK_READ_REPLY = %d, PRIORITY = %d, EXPIRY_TIME = %d \
-                               WHERE MSG_ID = %d;", MMS_PLUGIN_MESSAGE_TABLE_NAME, pSendOptInfo->bDeliverReq, pSendOptInfo->option.mmsSendOptInfo.bReadReq,
-                               pSendOptInfo->option.mmsSendOptInfo.priority, pSendOptInfo->option.mmsSendOptInfo.expiryTime.time, pMsgInfo->msgId);
+       return MSG_SUCCESS;
+}
 
-               MSG_DEBUG("SQLQuery = %s", sqlQuery);
+msg_error_t MmsPluginStorage::removePreviewInfo(int msgId)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
 
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                       return MSG_ERR_DB_EXEC;
-               }
-       }
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       char filePath[MSG_FILEPATH_LEN_MAX + 1] = {0,};
 
-       dbHandle.finalizeQuery();
+       // remove thumbnail file
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "SELECT VALUE FROM %s "
+                       "WHERE MSG_ID = %d AND (TYPE=%d OR TYPE=%d);",
+                       MSGFW_MMS_PREVIEW_TABLE_NAME, msgId, MSG_MMS_ITEM_TYPE_IMG, MSG_MMS_ITEM_TYPE_VIDEO);
 
-       MSG_END();
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               return MSG_ERR_DB_PREPARE;
+       }
 
-       return MSG_SUCCESS;
-}
+       while (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
 
+               memset(filePath, 0x00, sizeof(filePath));
+               strncpy(filePath, (char *)dbHandle->columnText(0), MSG_FILEPATH_LEN_MAX);
+               if (remove(filePath) == -1)
+                       MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+               else
+                       MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
+       }
 
-msg_error_t MmsPluginStorage::updateNetStatus(msg_message_id_t msgId, msg_network_status_t netStatus)
-{
-       char sqlQuery[MAX_QUERY_LEN + 1];
+       dbHandle->finalizeQuery();
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       //(MSG_ID INTEGER, TYPE INTEGER, INFO TEXT)
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "DELETE FROM %s WHERE MSG_ID= %d;",
+                       MSGFW_MMS_PREVIEW_TABLE_NAME, msgId);
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET NETWORK_STATUS = %d WHERE MSG_ID = %d;",
-                       MSGFW_MESSAGE_TABLE_NAME, netStatus, msgId);
+       MSG_DEBUG("QUERY : [%s]", sqlQuery);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_EXEC;
 
        return MSG_SUCCESS;
 }
 
-
-msg_error_t MmsPluginStorage::updateDeliveryReport(msg_message_id_t msgId, MmsMsgMultiStatus *pStatus)
+msg_error_t MmsPluginStorage::deleteMmsMessage(int msgId)
 {
+       MsgDbHandler *dbHandle = getDbHandle();
+
        char sqlQuery[MAX_QUERY_LEN + 1];
+       char filePath[MSG_FILEPATH_LEN_MAX + 1] = {0,};
+       char dirPath[MSG_FILEPATH_LEN_MAX + 1]= {0,};
+
+       //remove DB Preview
+       removePreviewInfo(msgId);
+
+       deleteMultipartList(msgId);
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILE_PATH FROM %s WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, msgId);
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET DELIVERY_REPORT_STATUS = %d, DELIVERY_REPORT_TIME = %ld WHERE MSG_ID = %d;",
-                       MSGFW_MESSAGE_TABLE_NAME, pStatus->msgStatus, pStatus->handledTime, msgId);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               return MSG_ERR_DB_PREPARE;
+       }
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_EXEC;
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               strncpy(filePath, (char *)dbHandle->columnText(0), MSG_FILEPATH_LEN_MAX);
 
-       return MSG_SUCCESS;
-}
+               snprintf(dirPath, MSG_FILEPATH_LEN_MAX, "%s.dir", filePath);
 
+               //delete pdu file
+               if (remove(filePath) == -1)
+                       MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+               else
+                       MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
+
+               //delete multipart files
+               MsgRmRf(dirPath);
+
+               //delete multipart dir
+               rmdir(dirPath);
+
+       } else {
+               MSG_DEBUG("MsgStepQuery() Error [%s]", sqlQuery);
+               dbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle->finalizeQuery();
 
-msg_error_t MmsPluginStorage::updateReadReport(msg_message_id_t msgId, MmsMsgMultiStatus *pStatus)
-{
-       char sqlQuery[MAX_QUERY_LEN + 1];
 
+       // Delete Data from MMS table
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, msgId);
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET READ_REPORT_STATUS = %d, READ_REPORT_TIME = %lu WHERE MSG_ID = %d;",
-                       MSGFW_MESSAGE_TABLE_NAME, pStatus->readStatus, pStatus->readTime, msgId);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               return MSG_ERR_DB_EXEC;
+       }
 
+       // Delete Data from MMS STATUS table
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;",
+                       MSGFW_REPORT_TABLE_NAME, msgId);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
                return MSG_ERR_DB_EXEC;
+       }
 
        return MSG_SUCCESS;
 }
 
-
-msg_error_t MmsPluginStorage::updateMmsAttrib(msg_message_id_t msgId, MmsAttrib *attrib, MSG_SUB_TYPE_T msgSubType)
+msg_error_t MmsPluginStorage::insertMultipart(msg_message_id_t msgId, MMS_MULTIPART_DATA_S *pMultipart)
 {
        MSG_BEGIN();
 
-       char sqlQuery[MAX_QUERY_LEN + 1];
+       MsgDbHandler *dbHandle = getDbHandle();
 
+       char sqlQuery[MAX_QUERY_LEN + 1];
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       if (msgSubType == MSG_NOTIFICATIONIND_MMS) {
-               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET EXPIRY_TIME = %d WHERE MSG_ID = %d;",
-                               MMS_PLUGIN_MESSAGE_TABLE_NAME, attrib->expiryTime.time, msgId);
-       } else if (msgSubType == MSG_RETRIEVE_AUTOCONF_MMS || msgSubType == MSG_RETRIEVE_MANUALCONF_MMS) {
-               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET ASK_DELIVERY_REPORT = %d, ASK_READ_REPLY = %d, PRIORITY = %d WHERE MSG_ID = %d;",
-                               MMS_PLUGIN_MESSAGE_TABLE_NAME, attrib->bAskDeliveryReport, attrib->bAskReadReply, attrib->priority, msgId);
+       if (pMultipart == NULL) {
+               MSG_ERR("NULL parameter");
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
-       MSG_DEBUG("QUERY : [%s]", sqlQuery);
+#if 0
+       //( MSG_ID INTEGER NOT NULL , SEQ INTEGER DEFAULT 0, CONTENT_TYPE TEXT,         NAME TEXT, CHARSET INTEGER,     CONTENT_ID TEXT, CONTENT_LOCATION TEXT, FILE_PATH TEXT, TEXT TEXT,);
+       if (pMultipart->type == MIME_APPLICATION_SMIL) {//Smil
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s "
+                               "(MSG_ID, SEQ, CONTENT_TYPE, NAME, CONTENT_ID, CONTENT_LOCATION, TEXT) "
+                               "VALUES (%d, -1, '%s', '%s', '%s', '%s' , '%s');",
+                               MSGFW_MMS_MULTIPART_TABLE_NAME, msgId, pMultipart->szContentType, pMultipart->szFileName, pMultipart->szContentID, pMultipart->szContentLocation, (char *)pMultipart->data);
+
+       } else if (MmsIsText(pMultipart->type)) {//Text
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s "
+                               "(MSG_ID, CONTENT_TYPE, NAME, CHARSET, CONTENT_ID, CONTENT_LOCATION, TEXT) "
+                               "VALUES (%d, '%s', '%s', %d, '%s', '%s' ,'%s');",
+                               MSGFW_MMS_MULTIPART_TABLE_NAME, msgId, pMultipart->szContentType, pMultipart->szFileName, pMultipart->char_set, pMultipart->szContentID, pMultipart->szContentLocation, (char *)pMultipart->data);
+       } else {
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s "
+                               "(MSG_ID, CONTENT_TYPE, NAME, CONTENT_ID, CONTENT_LOCATION, FILE_PATH) "
+                               "VALUES (%d, '%s', '%s', '%s', '%s' ,'%s');",
+                               MSGFW_MMS_MULTIPART_TABLE_NAME, msgId, pMultipart->szContentType, pMultipart->szFileName, pMultipart->szContentID, pMultipart->szContentLocation, (char *)pMultipart->szFilePath);
+       }
+#else
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_EXEC;
+       if (pMultipart->type == MIME_APPLICATION_SMIL) {//Smil
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s "
+                                               "(MSG_ID, SEQ, CONTENT_TYPE, NAME, CONTENT_ID, CONTENT_LOCATION, FILE_PATH) "
+                                               "VALUES (%d, -1, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\");",
+                                               MSGFW_MMS_MULTIPART_TABLE_NAME, msgId, pMultipart->szContentType, pMultipart->szFileName, pMultipart->szContentID, pMultipart->szContentLocation, (char *)pMultipart->szFilePath);
 
-       MSG_END();
+       } else {
+               const char *pszMimeType = NULL;
 
-       return MSG_SUCCESS;
-}
+               if (strlen(pMultipart->szContentType) == 0) {
+                       MmsGetMimeTypeFromFileName(MIME_MAINTYPE_UNKNOWN, pMultipart->szFilePath, &pMultipart->type, &pszMimeType);
+                       snprintf(pMultipart->szContentType, sizeof(pMultipart->szContentType), "%s", pszMimeType);
+                       MSG_DEBUG("pMultipart->szContentType = %s", pMultipart->szContentType);
+               }
 
+               /* make tcs_bc_level & malware_allow value */
+               pMultipart->tcs_bc_level = -1;
+               //CID 41991: pMultipart->szFilePath is an array, hence checking for null is not required
+               if (strlen(pMultipart->szFilePath) > 0 && MsgAccessFile(pMultipart->szFilePath, F_OK) == true) {
+                       int bc_level = -1;
+                       int tcs_ret = MmsPluginTcsScanFile(pMultipart->szFilePath, &bc_level);
+                       if (tcs_ret == 0) {
+                               if (bc_level > -1) {
+                                       MSG_DEBUG("This content is malware, level = %d", bc_level);
+                                       pMultipart->tcs_bc_level = bc_level;
+                                       pMultipart->malware_allow = 0;
+                               }
+                       }
+               }
 
-msg_error_t MmsPluginStorage::updateMmsAttachCount(msg_message_id_t msgId, int count)
-{
-       MSG_BEGIN();
+               if (pMultipart->tcs_bc_level < 0 || pMultipart->malware_allow) {
 
-       char sqlQuery[MAX_QUERY_LEN + 1];
+                       if (g_str_has_prefix(pMultipart->szContentType, "video")) {
+                               char thumbPath[MSG_FILEPATH_LEN_MAX+1] = {0, };
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET ATTACHMENT_COUNT = %d WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, count, msgId);
+                               if (MmsMakeMultipartThumbnailInfo(pMultipart, thumbPath) == MSG_SUCCESS)
+                                       snprintf(pMultipart->szThumbFilePath, sizeof(pMultipart->szThumbFilePath), "%s", thumbPath);
+                       }
+               }
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-               MSG_DEBUG("Fail to execute query [%s]", sqlQuery);
-               return MSG_ERR_DB_EXEC;
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s "
+                                               "(MSG_ID, CONTENT_TYPE, NAME, CONTENT_ID, CONTENT_LOCATION, FILE_PATH, TCS_LEVEL, MALWARE_ALLOW, THUMB_FILE_PATH) "
+                                               "VALUES (%d, \"%s\", \"%s\", \"%s\", \"%s\" ,\"%s\", '%d', '%d', \"%s\");",
+                                               MSGFW_MMS_MULTIPART_TABLE_NAME, msgId, pMultipart->szContentType, pMultipart->szFileName, pMultipart->szContentID, pMultipart->szContentLocation, (char *)pMultipart->szFilePath, pMultipart->tcs_bc_level, pMultipart->malware_allow, (char *)pMultipart->szThumbFilePath);
        }
+#endif
+       MSG_DEBUG("QUERY : [%s]", sqlQuery);
 
-       MSG_END();
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
 
+       MSG_END();
        return MSG_SUCCESS;
 }
 
-MmsMsgMultiStatus *MmsPluginStorage::getMultiStatus(msg_message_id_t msgId)
+msg_error_t MmsPluginStorage::updateMultipart(msg_message_id_t msgId, int allow_malware, MMS_MULTIPART_DATA_S *pMultipart)
 {
        MSG_BEGIN();
 
-       MmsMsgMultiStatus *pMultiStatus = NULL;
+       MsgDbHandler *dbHandle = getDbHandle();
 
        char sqlQuery[MAX_QUERY_LEN + 1];
-
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT B.ADDRESS_VAL, A.DELIVERY_REPORT_STATUS, A.DELIVERY_REPORT_TIME, A.READ_REPORT_STATUS, A.READ_REPORT_TIME \
-                       FROM %s A, %s B WHERE A.MSG_ID = %d AND A.CONV_ID = B.CONV_ID;",
-                       MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, msgId);
+       if (pMultipart == NULL) {
+               MSG_ERR("NULL parameter");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
-               MSG_DEBUG("MSG_ERR_DB_PREPARE");
+       if (pMultipart->type != MIME_APPLICATION_SMIL) {
+               /* make tcs_bc_level & malware_allow value */
+               pMultipart->malware_allow = allow_malware;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               pMultiStatus = (MmsMsgMultiStatus *)malloc(sizeof(MmsMsgMultiStatus));
+               if (pMultipart->tcs_bc_level >= 0 || pMultipart->malware_allow) {
 
-               memset(pMultiStatus, 0, sizeof(MmsMsgMultiStatus));
+                       if (!strcasecmp(pMultipart->szContentType, "video")) {
+                               char thumbPath[MSG_FILEPATH_LEN_MAX+1] = {0, };
 
-               if (dbHandle.columnText(0) != NULL) {
-                       strncpy(pMultiStatus->szTo, (char *)dbHandle.columnText(0), (strlen((char *)dbHandle.columnText(0)) > MAX_ADDRESS_VAL_LEN ? MAX_ADDRESS_VAL_LEN : strlen((char *)dbHandle.columnText(0))));
-                       MSG_DEBUG("### szTo = %s ###", pMultiStatus->szTo);
+                               if (MmsMakeMultipartThumbnailInfo(pMultipart, thumbPath) == MSG_SUCCESS)
+                                       snprintf(pMultipart->szThumbFilePath, sizeof(pMultipart->szThumbFilePath), "%s", thumbPath);
+                       }
                }
 
-               pMultiStatus->msgStatus = (msg_delivery_report_status_t)dbHandle.columnInt(1);
-               pMultiStatus->handledTime = dbHandle.columnInt(2);
-               pMultiStatus->readStatus = (msg_read_report_status_t)dbHandle.columnInt(3);
-               pMultiStatus->readTime = dbHandle.columnInt(4);
-       } else {
-               MSG_DEBUG("MSG_ERR_DB_STEP");
-       }
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MALWARE_ALLOW = %d, THUMB_FILE_PATH = '%s' WHERE MSG_ID = %d;",
+                       MSGFW_MMS_MULTIPART_TABLE_NAME, pMultipart->malware_allow, (char *)pMultipart->szThumbFilePath, msgId);
+
+               MSG_DEBUG("QUERY : [%s]", sqlQuery);
 
-       /* possible NULL pointer dereference*/
-       if (pMultiStatus != NULL)
-               pMultiStatus->pNext = NULL;
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_EXEC;
+
+       }
 
-       dbHandle.finalizeQuery();
 
-       return pMultiStatus;
+       MSG_END();
+       return MSG_SUCCESS;
 }
 
-
-void MmsPluginStorage::getMmsAttrib(msg_message_id_t msgId, MmsMsg *pMmsMsg)
+msg_error_t MmsPluginStorage::deleteMultipartList(int msgId)
 {
-       char sqlQuery[MAX_QUERY_LEN + 1];
+       MSG_BEGIN();
+       MsgDbHandler *dbHandle = getDbHandle();
 
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       //char filePath[MSG_FILEPATH_LEN_MAX + 1] = {0,};
+       const char * filePath = NULL;
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILE_PATH FROM %s WHERE MSG_ID = %d;",
+                       MSGFW_MMS_MULTIPART_TABLE_NAME, msgId);
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT VERSION, DATA_TYPE,  DATE, HIDE_ADDRESS, ASK_DELIVERY_REPORT, REPORT_ALLOWED, \
-                       READ_REPORT_ALLOWED_TYPE, ASK_READ_REPLY, READ, READ_REPORT_SEND_STATUS, READ_REPORT_SENT, PRIORITY, \
-                       MSG_SIZE, MSG_CLASS, EXPIRY_TIME, CUSTOM_DELIVERY_TIME, DELIVERY_TIME, MSG_STATUS FROM %s WHERE MSG_ID = %d;",
-                       MMS_PLUGIN_MESSAGE_TABLE_NAME, msgId);
-
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
-               MSG_DEBUG("MSG_ERR_DB_PREPARE");
+       MSG_DEBUG("QUERY : [%s]", sqlQuery);
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               pMmsMsg->mmsAttrib.version = dbHandle.columnInt(1);
-               pMmsMsg->mmsAttrib.dataType = (MmsDataType)dbHandle.columnInt(2);
-               pMmsMsg->mmsAttrib.date = dbHandle.columnInt(3);
-               pMmsMsg->mmsAttrib.bHideAddress = dbHandle.columnInt(4);
-               pMmsMsg->mmsAttrib.bAskDeliveryReport = dbHandle.columnInt(5);
-               pMmsMsg->mmsAttrib.bReportAllowed = dbHandle.columnInt(6);
-               pMmsMsg->mmsAttrib.readReportAllowedType = (MmsRecvReadReportType)dbHandle.columnInt(7);
-               pMmsMsg->mmsAttrib.bAskReadReply = dbHandle.columnInt(8);
-               pMmsMsg->mmsAttrib.bRead = dbHandle.columnInt(9);
-               pMmsMsg->mmsAttrib.readReportSendStatus = (MmsRecvReadReportSendStatus)dbHandle.columnInt(10);
-               pMmsMsg->mmsAttrib.bReadReportSent = dbHandle.columnInt(11);
-               pMmsMsg->mmsAttrib.priority = (MmsPriority)dbHandle.columnInt(12);
-               pMmsMsg->mmsAttrib.msgSize = dbHandle.columnInt(13);
-               pMmsMsg->mmsAttrib.msgClass = (MmsMsgClass)dbHandle.columnInt(14);
-               pMmsMsg->mmsAttrib.expiryTime.time = dbHandle.columnInt(15);
-               pMmsMsg->mmsAttrib.deliveryTime.time = dbHandle.columnInt(17);
-               pMmsMsg->mmsAttrib.msgStatus = (msg_delivery_report_status_t)dbHandle.columnInt(18);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               return MSG_ERR_DB_PREPARE;
        }
 
-       dbHandle.finalizeQuery();
-}
-
+       while (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
 
-msg_error_t MmsPluginStorage::getMmsMessageId(msg_message_id_t selectedMsgId, MmsMsg *pMmsMsg)
-{
-       msg_error_t err = MSG_SUCCESS;
+               filePath = (const char *)dbHandle->columnText(0);
+               if (filePath) {
+                       if (remove(filePath) == -1)
+                               MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+                       else
+                               MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
+               }
 
-       int rowCnt = 0;
+       }
 
-       char sqlQuery[MAX_QUERY_LEN + 1];
+       dbHandle->finalizeQuery();
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT THUMB_FILE_PATH FROM %s WHERE MSG_ID = %d;",
+                       MSGFW_MMS_MULTIPART_TABLE_NAME, msgId);
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MESSAGE_ID FROM %s WHERE MSG_ID = %d;",
-                       MMS_PLUGIN_MESSAGE_TABLE_NAME, selectedMsgId);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               return MSG_ERR_DB_PREPARE;
+       }
 
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
+       while (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
 
-       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
-               MSG_DEBUG("[Error]Failed to Get Table");
-               return MSG_ERR_DB_NORECORD;
-       }
+               filePath = (const char *)dbHandle->columnText(0);
+               if (filePath) {
+                       if (remove(filePath) == -1)
+                               MSG_SEC_DEBUG("Fail to delete file [%s]", filePath);
+                       else
+                               MSG_SEC_DEBUG("Success to delete file [%s]", filePath);
+               }
 
-       if (rowCnt != 1) {
-               dbHandle.freeTable();
-               MSG_DEBUG("[Error] MSG_ERR_DB_NORECORD");
-               return MSG_ERR_DB_NORECORD;
        }
 
-       dbHandle.getColumnToString(1, MMS_MSG_ID_LEN + 1, pMmsMsg->szMsgID);
+       dbHandle->finalizeQuery();
+
+       // Delete Data from Multipart table
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;",
+                       MSGFW_MMS_MULTIPART_TABLE_NAME, msgId);
 
-       dbHandle.freeTable();
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               return MSG_ERR_DB_EXEC;
+       }
 
+       MSG_END();
        return MSG_SUCCESS;
 }
 
-
-int MmsPluginStorage::getMmsVersion(msg_message_id_t selectedMsgId)
+msg_error_t MmsPluginStorage::getMultipartList(msg_message_id_t msgId, MMSList **multipart_list)
 {
-       msg_error_t err = MSG_SUCCESS;
-       int rowCnt = 0;
-
-       int     version = 0;
+       MSG_BEGIN();
+       MsgDbHandler *dbHandle = getDbHandle();
 
        char sqlQuery[MAX_QUERY_LEN + 1];
+       int rowCnt = 0, index = 0;
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "SELECT CONTENT_TYPE, NAME, FILE_PATH, CONTENT_ID, CONTENT_LOCATION, TCS_LEVEL, MALWARE_ALLOW, THUMB_FILE_PATH "
+                       "FROM %s WHERE MSG_ID=%d;",
+                       MSGFW_MMS_MULTIPART_TABLE_NAME, msgId);
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT VERSION FROM %s WHERE MSG_ID = %d;",
-                       MMS_PLUGIN_MESSAGE_TABLE_NAME, selectedMsgId);
+       msg_error_t err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
 
-       MSG_DEBUG("SqlQuery = %s", sqlQuery);
+       if (err == MSG_SUCCESS) {
 
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
+               for (int i = 0; i < rowCnt; i++) {
 
-       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
-               MSG_DEBUG("[Error]Failed to Get Table");
-               return version;
-       }
+                       MMS_MULTIPART_DATA_S *multipart = MsgMmsCreateMultipart();
 
-       if (rowCnt != 1) {
-               dbHandle.freeTable();
-               MSG_DEBUG("[Error]MSG_ERR_DB_NORECORD");
-               return version;
-       }
+                       dbHandle->getColumnToString(index++, sizeof(multipart->szContentType), multipart->szContentType);
 
-       version = dbHandle.getColumnToInt(1);
+                       dbHandle->getColumnToString(index++, sizeof(multipart->szFileName), multipart->szFileName);
 
-       dbHandle.freeTable();
+                       dbHandle->getColumnToString(index++, sizeof(multipart->szFilePath), multipart->szFilePath);
 
-       return version;
-}
+                       dbHandle->getColumnToString(index++, sizeof(multipart->szContentID), multipart->szContentID);
 
+                       dbHandle->getColumnToString(index++, sizeof(multipart->szContentLocation), multipart->szContentLocation);
 
-msg_error_t MmsPluginStorage::getContentLocation(MSG_MESSAGE_INFO_S *pMsgInfo)
-{
-       char sqlQuery[MAX_QUERY_LEN + 1];
+                       multipart->tcs_bc_level = dbHandle->getColumnToInt(index++);
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       multipart->malware_allow = dbHandle->getColumnToInt(index++);
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CONTENTS_LOCATION FROM %s WHERE MSG_ID = %d;",
-                       MMS_PLUGIN_MESSAGE_TABLE_NAME, pMsgInfo->msgId);
+                       dbHandle->getColumnToString(index++, sizeof(multipart->szThumbFilePath), multipart->szThumbFilePath);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
+                       multipart->type = MimeGetMimeIntFromMimeString(multipart->szContentType);
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               if (dbHandle.columnText(0) != NULL) {
-                       strncpy(pMsgInfo->msgData, (char *)dbHandle.columnText(0), (strlen((char *)dbHandle.columnText(0)) > MAX_MSG_DATA_LEN ? MAX_MSG_DATA_LEN : strlen((char *)dbHandle.columnText(0))));
-                       pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
+                       *multipart_list = g_list_append(*multipart_list, multipart);
                }
-       } else {
-               dbHandle.finalizeQuery();
-
-               return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->freeTable();
 
+       MSG_END();
        return MSG_SUCCESS;
 }
 
-
-/* reject_msg_support */
-msg_error_t MmsPluginStorage::getTrID(MSG_MESSAGE_INFO_S *pMsgInfo,char *pszTrID,int nBufferLen)
+msg_error_t MmsPluginStorage::addMmsData(msg_message_id_t msgId, const char *raw_filepath, MMS_DATA_S *pMmsData)
 {
-       char sqlQuery[MAX_QUERY_LEN + 1];
-
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       MSG_BEGIN();
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT TRANSACTION_ID FROM %s WHERE MSG_ID = %d;",
-                       MMS_PLUGIN_MESSAGE_TABLE_NAME, pMsgInfo->msgId);
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
+       char sqlQuery[MAX_QUERY_LEN + 1];
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               if (dbHandle.columnText(0) != NULL) {
-                       strncpy(pszTrID, (char *)dbHandle.columnText(0), nBufferLen - 1);
-                       pszTrID[nBufferLen-1] = '\0';
-               }
-       } else {
-               dbHandle.finalizeQuery();
+       MMS_HEADER_DATA_S *pHeader = pMmsData->header;
 
-               return MSG_ERR_DB_STEP;
+       if (pHeader == NULL) {
+               MSG_ERR("Header is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
        }
 
-       dbHandle.finalizeQuery();
-
-       return MSG_SUCCESS;
-}
-/* reject_msg_support */
-
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery)
+                       , "INSERT INTO %s "
+                       "(MSG_ID, TRANSACTION_ID, MESSAGE_ID, FWD_MESSAGE_ID, CONTENTS_LOCATION"
+                       ", FILE_PATH, VERSION, DATA_TYPE, DATE, HIDE_ADDRESS"
+                       ", ASK_DELIVERY_REPORT, REPORT_ALLOWED, READ_REPORT_ALLOWED_TYPE"
+                       ", ASK_READ_REPLY, READ, READ_REPORT_SEND_STATUS, READ_REPORT_SENT"
+                       ", PRIORITY, KEEP_COPY, MSG_SIZE, MSG_CLASS"
+                       ", EXPIRY_TIME, CUSTOM_DELIVERY_TIME, DELIVERY_TIME, MSG_STATUS) "
+                       "VALUES (%d, '%s', '%s', '%s', '%s', '%s', %d, %d, %ld, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d);"
+                       , MMS_PLUGIN_MESSAGE_TABLE_NAME
+                       , msgId, pHeader->trID, pHeader->messageID, "", pHeader->contentLocation
+                       , raw_filepath, pHeader->mmsVersion, MMS_DATATYPE_NONE, pHeader->date, pHeader->bHideAddress
+                       , pHeader->bDeliveryReport, 0 /*pMmsMsg->mmsAttrib.bReportAllowed*/, 0/*pMmsMsg->mmsAttrib.readReportAllowedType*/
+                       , pHeader->bReadReport, 0 /*pMmsMsg->mmsAttrib.bRead*/, 0/*pMmsMsg->mmsAttrib.readReportSendStatus*/, 0 /*pMmsMsg->mmsAttrib.bReadReportSent*/
+                       , pHeader->mmsPriority, true/*pMmsMsg->mmsAttrib.bLeaveCopy*/,pHeader->messageSize, pHeader->messageClass
+                       , pHeader->expiry.time, 0, pHeader->delivery.time, pHeader->mmsStatus);
+
+       msg_error_t db_err = dbHandle->execQuery(sqlQuery);
+       if (db_err != MSG_SUCCESS) {
+               MSG_ERR("execute query fail [%s], err = [%d]", sqlQuery, db_err);
+               return MSG_ERR_DB_EXEC;
+       } else {
+               MSG_DEBUG("execute query success [%s]", sqlQuery);
+       }
 
-msg_error_t MmsPluginStorage::getMmsRawFilePath(msg_message_id_t msgId, char *pFilepath)
-{
-       char sqlQuery[MAX_QUERY_LEN + 1];
+       MMS_MULTIPART_DATA_S *smil = pMmsData->smil;
+       if (smil) {
+               MSG_DEBUG("insert smil multipart to db");
+               smil->type = MIME_APPLICATION_SMIL;
+               this->insertMultipart(msgId, smil);
+       }
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       MMSList *multipart_list = pMmsData->multipartlist;
+       if (multipart_list) {
+               MSG_DEBUG("insert multipart to db");
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILE_PATH FROM %s WHERE MSG_ID = %d;",
-                       MMS_PLUGIN_MESSAGE_TABLE_NAME, msgId);
+               for (int i = 0; i < (int)g_list_length(multipart_list); i++) {
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
+                       MMS_MULTIPART_DATA_S *pMultipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(multipart_list, i);
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               if (dbHandle.columnText(0) != NULL) {
-                       strcpy(pFilepath, (char *)dbHandle.columnText(0));
+                       if (pMultipart) {
+                               this->insertMultipart(msgId, pMultipart);
+                       }
                }
-       } else {
-               dbHandle.finalizeQuery();
-
-               return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       MSG_END();
 
        return MSG_SUCCESS;
 }
 
-
-int MmsPluginStorage::searchMsgId(char *toNumber, char *szMsgID)
+msg_error_t MmsPluginStorage::getMmsData(msg_message_id_t msgId, MMS_DATA_S *pMmsData)
 {
-       int msgId = -1;
-
-       msg_folder_id_t folderId = MSG_SENTBOX_ID;
+       MsgDbHandler *dbHandle = getDbHandle();
 
        char sqlQuery[MAX_QUERY_LEN + 1];
 
-       MmsAddrUtilRemovePlmnString(toNumber);
-
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.MSG_ID FROM %s A, %s B \
-                       WHERE A.MSG_ID = B.MSG_ID AND A.FOLDER_ID = %d AND B.MESSAGE_ID LIKE '%%%s%%'",
-                       MSGFW_MESSAGE_TABLE_NAME, MMS_PLUGIN_MESSAGE_TABLE_NAME, folderId, szMsgID);
+       MMS_HEADER_DATA_S *pHeader = pMmsData->header;
 
-       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+       if (pHeader == NULL) {
+               MSG_ERR("Header is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               msgId = dbHandle.columnInt(0);
+       snprintf(sqlQuery, sizeof(sqlQuery)
+                       , "SELECT "
+                       "VERSION, DATA_TYPE,  DATE, HIDE_ADDRESS, ASK_DELIVERY_REPORT, REPORT_ALLOWED"
+                       ", READ_REPORT_ALLOWED_TYPE, ASK_READ_REPLY, READ, READ_REPORT_SEND_STATUS, READ_REPORT_SENT"
+                       ", PRIORITY,  MSG_SIZE, MSG_CLASS, EXPIRY_TIME, CUSTOM_DELIVERY_TIME, DELIVERY_TIME, MSG_STATUS"
+                       ", MESSAGE_ID, TRANSACTION_ID, CONTENTS_LOCATION, FILE_PATH "
+                       "FROM %s "
+                       "WHERE MSG_ID = %d;"
+                       , MMS_PLUGIN_MESSAGE_TABLE_NAME, msgId);
+
+       msg_error_t db_err = dbHandle->prepareQuery(sqlQuery);
+
+       if (db_err != MSG_SUCCESS) {
+               MSG_ERR("prepare query fail [%s], err = [%d]", sqlQuery, db_err);
+               //dbHandle->finalizeQuery();
+               return MSG_ERR_PLUGIN_STORAGE;
        }
 
-       dbHandle.finalizeQuery();
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               int i = 0;
+               pHeader->mmsVersion = dbHandle->columnInt(i++);
+               i++;//pMmsMsg->mmsAttrib.dataType = (MmsDataType)dbHandle->columnInt(i++);
+               pHeader->date = dbHandle->columnInt(i++);
+               pHeader->bHideAddress = dbHandle->columnInt(i++);
+               pHeader->bDeliveryReport = dbHandle->columnInt(i++);
+               i++;//pMmsMsg->mmsAttrib.bReportAllowed = dbHandle->columnInt(i++);
+               i++;//pMmsMsg->mmsAttrib.readReportAllowedType = (MmsRecvReadReportType)dbHandle->columnInt(i++);
+               pHeader->bReadReport = dbHandle->columnInt(i++);
+               i++;//pMmsMsg->mmsAttrib.bRead = dbHandle->columnInt(i++);
+               i++;//pMmsMsg->mmsAttrib.readReportSendStatus = (MmsRecvReadReportSendStatus)dbHandle->columnInt(i++);
+               i++;//pMmsMsg->mmsAttrib.bReadReportSent = dbHandle->columnInt(i++);
+               pHeader->mmsPriority = (MmsPriority)dbHandle->columnInt(i++);
+               pHeader->messageSize = dbHandle->columnInt(i++);
+               pHeader->messageClass = (MmsMsgClass)dbHandle->columnInt(i++);
+               pHeader->expiry.time = dbHandle->columnInt(i++);
+               i++;//CUSTOM_DELIVERY_TIME
+               pHeader->delivery.time = dbHandle->columnInt(i++);
+               i++;//pMmsMsg->mmsAttrib.msgStatus = (msg_delivery_report_status_t)dbHandle->columnInt(i++);
+               snprintf(pHeader->messageID, sizeof(pHeader->messageID), "%s", dbHandle->columnText(i++));
+               snprintf(pHeader->trID, sizeof(pHeader->trID), "%s", dbHandle->columnText(i++));
+               snprintf(pHeader->contentLocation, sizeof(pHeader->contentLocation), "%s", dbHandle->columnText(i++));
+               i++;//snprintf(pMmsMsg->szFileName, sizeof(pMmsMsg->szFileName), "%s", dbHandle->columnText(i++));
+       }
 
-       return msgId;
-}
+       dbHandle->finalizeQuery();
 
 
-msg_error_t MmsPluginStorage::setReadReportSendStatus(msg_message_id_t msgId, int readReportSendStatus)
-{
-       bool bReadReportSent = false;
+       MMSList *pMultipartList = NULL;
 
-       if ((MmsRecvReadReportSendStatus)readReportSendStatus == MMS_RECEIVE_READ_REPORT_SENT)
-               bReadReportSent = true;
-       else
-               bReadReportSent = false;
+       if (this->getMultipartList(msgId, &pMultipartList) == MSG_SUCCESS) {
 
-       char sqlQuery[MAX_QUERY_LEN + 1];
+               if (pMultipartList) {
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       MMS_MULTIPART_DATA_S *smil_multipart = NULL;
+                       char *content_type = NULL;
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET READ_REPORT_SEND_STATUS = %d, READ_REPORT_SENT = %d WHERE MSG_ID = %d;",
-                       MMS_PLUGIN_MESSAGE_TABLE_NAME, (MmsRecvReadReportSendStatus)readReportSendStatus, (int)bReadReportSent, msgId);
+                       MsgMmsGetSmilMultipart(pMultipartList, &smil_multipart);
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_EXEC;
+                       if (smil_multipart) {
+                               pMmsData->smil = smil_multipart ;
+                               pMultipartList = g_list_remove(pMultipartList, smil_multipart);
+                               pHeader->contentType = MIME_APPLICATION_VND_WAP_MULTIPART_RELATED;
 
-       return MSG_SUCCESS;
-}
+                               if (MsgAccessFile(smil_multipart->szFilePath, F_OK)) {
+                                       gchar *contents = NULL;
+                                       gsize length = 0;
 
+                                       g_file_get_contents (smil_multipart->szFilePath, &contents, &length, NULL);
 
-msg_error_t MmsPluginStorage::getMsgText(MMS_MESSAGE_DATA_S *pMmsMsg, char *pMsgText)
-{
-       MMS_PAGE_S *pPage = NULL;
-       MMS_MEDIA_S *pMedia = NULL;
-       char *pMmsMsgText = NULL;
-       int textLen = 0;
-       bool bText = false;
+                                       smil_multipart->pMultipartData = contents;
+                                       smil_multipart->nMultipartDataLen = length;
 
-       // Get the text data from the 1st slide.
-       for (int i = 0; i< pMmsMsg->pageCnt; ++i) {
-               pPage = _MsgMmsGetPage(pMmsMsg, i);
-
-               for (int j = 0; j < pPage->mediaCnt; ++j) {
-                       pMedia = _MsgMmsGetMedia(pPage, j);
-
-                       if (pMedia->mediatype == MMS_SMIL_MEDIA_TEXT && pMedia->szFilePath != NULL) {
-                               pMmsMsgText = MsgOpenAndReadMmsFile(pMedia->szFilePath, 0, -1, &textLen);
-                               if (pMmsMsgText)
-                                       strncpy(pMsgText, pMmsMsgText, MAX_MSG_TEXT_LEN);
-
-                               // for avoiding break character end of the string.
-                               if ((textLen >= MAX_MSG_TEXT_LEN) && pMsgText[MAX_MSG_TEXT_LEN - 1] >= 0x80) { // if it is multibyte chars by UTF8, it would be presendted by 1xxx xxxx
-                                       for (int k = 1; k < 5; k++) {
-                                               // the first byte of multi-byte chars of UTF8, should be larger than 1100 0000
-                                               // (two byte chars start with 110x xxxx, and three byte chars start with 1110 xxxx,
-                                               // four byte chars start with 1111 0xxx)
-                                               if ((pMsgText[MAX_MSG_TEXT_LEN - k] >= 0xC0)) {
-                                                       pMsgText[MAX_MSG_TEXT_LEN - k] = '\0';
-                                                       break;
-                                               }
-                                       }
+                                       memset(smil_multipart->szFilePath, 0x00, sizeof(smil_multipart->szFilePath));
                                }
 
-                               if (pMmsMsgText) {
-                                       free(pMmsMsgText);
-                                       pMmsMsgText = NULL;
-                               }
-                               bText = true;
-                               break;
+                       } else {
+                               pHeader->contentType = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED;
                        }
-               }
 
-               if (bText)
-                       break;
+                       content_type = MimeGetMimeStringFromMimeInt(pHeader->contentType);
+                       if (content_type) {
+                               snprintf(pHeader->szContentType, sizeof(pHeader->szContentType), "%s", content_type);
+                       }
+
+                       pMmsData->multipartlist = pMultipartList;
+               }
        }
 
+       MSG_END();
        return MSG_SUCCESS;
 }
 
+msg_error_t MmsPluginStorage::addMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pSerializedMms)
+{//send request or notification ind
+       MSG_BEGIN();
 
-msg_error_t MmsPluginStorage::makeThumbnail(MMS_MESSAGE_DATA_S *pMmsMsg, char *pThumbnailPath, char *szFileName)
-{
-       MMS_PAGE_S *pPage = NULL;
-       MMS_MEDIA_S *pMedia = NULL;
-
-       bool bThumbnail = false;
+       msg_error_t     err = MSG_SUCCESS;
 
-       for (int i = 0; i < pMmsMsg->pageCnt; i++) {
-               pPage = _MsgMmsGetPage(pMmsMsg, i);
-               for (int j = 0; j < pPage->mediaCnt; j++) {
-                       pMedia = _MsgMmsGetMedia(pPage, j);
+       MMS_DATA_S *pMmsData = NULL;
 
-                       MSG_DEBUG("pMedia's Name: %s", pMedia->szFilePath);
+       if (MsgDeserializeMmsData(pSerializedMms, strlen(pSerializedMms), &pMmsData) != 0) {
+               MSG_DEBUG("Fail to Deserialize Message Data");
+               goto __CATCH;
+       }
 
-                       if (pMedia->mediatype == MMS_SMIL_MEDIA_IMG) {
-                               MSG_DEBUG("Make thumbnail: image");
+       if (pMsgInfo->msgType.subType == MSG_SENDREQ_MMS || pMsgInfo->msgType.subType == MSG_SENDCONF_MMS) {
+               char raw_filepath[MSG_FILENAME_LEN_MAX+1] = {0,};
+               char working_dir[MSG_FILENAME_LEN_MAX+1] = {0,};
 
-                               char thumbPath[MSG_FILEPATH_LEN_MAX] = {0, };
+               //compose
+               MmsPluginComposer::instance()->composeSendReq(pMsgInfo, pSendOptInfo, pMmsData);
 
-                               snprintf(thumbPath, MSG_FILEPATH_LEN_MAX, MSG_THUMBNAIL_PATH"/%s.jpg", szFileName);
-                               int err = -1;
-                               err = thumbnail_request_save_to_file(pMedia->szFilePath, MEDIA_THUMB_LARGE, thumbPath);
-                               if (err < 0) {
-                                       MSG_DEBUG("Make thumbnail: image failed");
-                                       continue;
-                               }
+               //encode
+               snprintf(working_dir, sizeof(working_dir), MSG_DATA_PATH"%d.mms.dir", pMsgInfo->msgId);
 
-                               strncpy(pThumbnailPath, thumbPath, MSG_FILEPATH_LEN_MAX);
+               MsgMmsSetMultipartListData(pMmsData);//app file -> data
 
-                               bThumbnail = true;
+               MsgMmsSetMultipartListFilePath(working_dir, pMmsData);//data -> svc file
 
-                               break;
-                       } else if (pMedia->mediatype == MMS_SMIL_MEDIA_VIDEO) {
-                               MSG_DEBUG("Make thumbnail: video");
+               snprintf(raw_filepath, sizeof(raw_filepath), "%s%d.mms", MSG_DATA_PATH, pMsgInfo->msgId);
 
-                               MMHandleType content_attrs = (MMHandleType)NULL;
-                               char *err_attr_name = NULL;
+               MmsPluginEncoder::instance()->encodeMmsPdu(pMmsData, pMsgInfo->msgId, raw_filepath);
 
-                               int fileRet = 0;
+               //add to db
+               if (addMmsData(pMsgInfo->msgId, raw_filepath, pMmsData) != MSG_SUCCESS) {
+                       MSG_DEBUG("Fail to add db message");
+                       goto __CATCH;
+               }
 
-                               int trackCount = 0;
+               //set
+               if (MsgGetFileSize(raw_filepath, (int *)&pMsgInfo->dataSize) == false) {
+                       MSG_SEC_DEBUG("Fail to get mms file size [%s]", raw_filepath);
+                       goto __CATCH;
+               }
 
-                               mm_file_create_content_attrs(&content_attrs, pMedia->szFilePath);
+               {//make Preview info for APP
+                       MmsPluginAppBase appBase(pMmsData);
+                       appBase.makePreviewInfo(pMsgInfo->msgId, true, raw_filepath);
+                       appBase.getFirstPageTextFilePath(pMsgInfo->msgText, sizeof(pMsgInfo->msgText));
+               }
 
-                               fileRet = mm_file_get_attrs(content_attrs, &err_attr_name, MM_FILE_CONTENT_VIDEO_TRACK_COUNT, &trackCount, NULL);
+       } else if (pMsgInfo->msgType.subType == MSG_RETRIEVE_MMS
+                       || pMsgInfo->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS
+                       || pMsgInfo->msgType.subType ==MSG_RETRIEVE_MANUALCONF_MMS) {
 
-                               if (fileRet != 0) {
-                                       MSG_DEBUG("mm_file_get_attrs fails [%s]", err_attr_name);
-                                       if (err_attr_name) {
-                                               free(err_attr_name);
-                                               err_attr_name = NULL;
-                                       }
+               char raw_filepath[MSG_FILENAME_LEN_MAX+1] = {0,};
+               char working_dir[MSG_FILENAME_LEN_MAX+1] = {0,};
 
-                                       mm_file_destroy_content_attrs(content_attrs);
+               //compose
+               MmsPluginComposer::instance()->composeRetrieveConf(pMsgInfo, pSendOptInfo, pMmsData);
 
-                                       continue;
-                               }
+               //encode
+               snprintf(working_dir, sizeof(working_dir), MSG_DATA_PATH"%d.mms.dir", pMsgInfo->msgId);
 
-                               MSG_DEBUG("video track num: %d", trackCount);
+               MsgMmsSetMultipartListData(pMmsData);//app file -> data
 
-                               if (trackCount > 0) {
-                                       int thumbnailWidth = 0;
-                                       int thumbnailHeight = 0;
-                                       int thumbnailSize = 0;
+               MsgMmsSetMultipartListFilePath(working_dir, pMmsData);//data -> svc file
 
-                                       void *thumbnail = NULL;
+               snprintf(raw_filepath, sizeof(raw_filepath), "%s%d.mms", MSG_DATA_PATH, pMsgInfo->msgId);
 
-                                       fileRet = mm_file_get_attrs(content_attrs, &err_attr_name, MM_FILE_CONTENT_VIDEO_WIDTH, &thumbnailWidth,
-                                                                                                                       MM_FILE_CONTENT_VIDEO_HEIGHT, &thumbnailHeight,
-                                                                                                                       MM_FILE_CONTENT_VIDEO_THUMBNAIL, &thumbnail, &thumbnailSize,
-                                                                                                                       NULL);
+               MmsPluginEncoder::instance()->encodeMmsPdu(pMmsData, pMsgInfo->msgId, raw_filepath);
 
-                                       if (fileRet != 0) {
-                                               MSG_DEBUG("mm_file_get_attrs fails [%s]", err_attr_name);
-                                               if (err_attr_name) {
-                                                       free(err_attr_name);
-                                                       err_attr_name = NULL;
-                                               }
+               //add to db
+               if (addMmsData(pMsgInfo->msgId, raw_filepath, pMmsData) != MSG_SUCCESS) {
+                       MSG_DEBUG("Fail to add db message");
+                       goto __CATCH;
+               }
 
-                                               mm_file_destroy_content_attrs(content_attrs);
+               //set
+               if (MsgGetFileSize(raw_filepath, (int *)&pMsgInfo->dataSize) == false) {
+                       MSG_SEC_DEBUG("Fail to get mms file size [%s]", raw_filepath);
+                       goto __CATCH;
+               }
 
-                                               continue;
-                                       }
+               {//make Preview info for APP
+                       MmsPluginAppBase *appBase;
+                       appBase = new MmsPluginAppBase(pMmsData);
+                       appBase->makePreviewInfo(pMsgInfo->msgId, true, raw_filepath);
+                       appBase->getFirstPageTextFilePath(pMsgInfo->msgText, sizeof(pMsgInfo->msgText));
+                       delete appBase;
+               }
 
-                                       MSG_DEBUG("video width: %d", thumbnailWidth);
-                                       MSG_DEBUG("video height: %d", thumbnailHeight);
-                                       MSG_DEBUG("video thumbnail: %p", thumbnail);
+       } else if (pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS) {
 
-                                       if (thumbnail) {
-                                               char thumbPath[MSG_FILEPATH_LEN_MAX] = {0, };
+               if (pMmsData->header == NULL || pMmsData->header->messageType != MMS_MSGTYPE_NOTIFICATION_IND) {
+                       goto __CATCH;
+               }
 
-                                               snprintf(thumbPath, MSG_FILEPATH_LEN_MAX, MSG_THUMBNAIL_PATH"%s.jpg", szFileName);
+               if (addMmsData(pMsgInfo->msgId, "", pMmsData) != MSG_SUCCESS) {
+                       MSG_DEBUG("Fail to add db message");
+                       goto __CATCH;
+               }
 
-                                               fileRet = mm_util_jpeg_encode_to_file (thumbPath, thumbnail, thumbnailWidth, thumbnailHeight, MM_UTIL_JPEG_FMT_RGB888, 70);
+       } else {
+               MSG_DEBUG("Not support msg sub type [%d]", pMsgInfo->msgType.subType);
+               goto __CATCH;
+       }
 
-                                               if (fileRet != 0) {
-                                                       MSG_DEBUG("mm_util_jpeg_encode_to_file fails [%d]", fileRet);
+       MsgMmsRelease(&pMmsData);
+       MSG_END();
+       return MSG_SUCCESS;
 
-                                                       mm_file_destroy_content_attrs(content_attrs);
+__CATCH:
+       MsgMmsRelease(&pMmsData);
+       deleteMmsMessage(pMsgInfo->msgId);
 
-                                                       continue;
-                                               }
+       return err;
+}
 
-                                               memset(pThumbnailPath, 0x00, MSG_FILEPATH_LEN_MAX);
+msg_error_t MmsPluginStorage::updateMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pSerializedMms)
+{
+       MSG_BEGIN();
 
-                                               strncpy(pThumbnailPath, thumbPath, MSG_FILEPATH_LEN_MAX);
+       msg_error_t     err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
 
-                                               bThumbnail = true;
+       char sqlQuery[MAX_QUERY_LEN + 1];
 
-                                       }
+       MMS_DATA_S *pMmsData = NULL;
 
-                                       mm_file_destroy_content_attrs(content_attrs);
+       if (MsgDeserializeMmsData(pSerializedMms, strlen(pSerializedMms), &pMmsData) != 0) {
+               MSG_DEBUG("Fail to Deserialize Message Data");
+               goto __CATCH;
+       }
 
-                                       break;
-                               }
+       MSG_DEBUG("msg sub type = [%d]", pMsgInfo->msgType.subType);
 
-                               mm_file_destroy_content_attrs(content_attrs);
-                       } else if (pMedia->mediatype == MMS_SMIL_MEDIA_AUDIO) {
-                               MSG_DEBUG("Make thumbnail: %s", "audio");
+       if (pMsgInfo->msgType.subType == MSG_SENDREQ_MMS) {
+               char raw_filepath[MSG_FILENAME_LEN_MAX+1] = {0,};
+               char working_dir[MSG_FILENAME_LEN_MAX+1] = {0,};
 
-                               MMHandleType tag_attrs = (MMHandleType)NULL;
-                               char *err_attr_name = NULL;
-                               void *artwork = NULL;
-                               int artworkSize = 0;
-                               int tmpLen = 0;
-                               int fileRet = 0;
+               //compose
+               MmsPluginComposer::instance()->composeSendReq(pMsgInfo, pSendOptInfo, pMmsData);
 
-                               if (mm_file_create_tag_attrs(&tag_attrs, pMedia->szFilePath) == 0) {
+               //encode
+               snprintf(raw_filepath, sizeof(raw_filepath), "%s%d.mms", MSG_DATA_PATH, pMsgInfo->msgId);
 
+               MmsPluginEncoder::instance()->encodeMmsPdu(pMmsData, pMsgInfo->msgId, raw_filepath);
 
-                                       fileRet = mm_file_get_attrs(tag_attrs, &err_attr_name, MM_FILE_TAG_ARTWORK, &artwork, &tmpLen,
-                                                                                                               MM_FILE_TAG_ARTWORK_SIZE, &artworkSize,
-                                                                                                               NULL);
+               //add to db
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET ASK_DELIVERY_REPORT = %d, KEEP_COPY = %d, ASK_READ_REPLY = %d, EXPIRY_TIME = %d, CUSTOM_DELIVERY_TIME = %d, DELIVERY_TIME= %d, PRIORITY = %d \
+                               WHERE MSG_ID = %d;", MMS_PLUGIN_MESSAGE_TABLE_NAME, pSendOptInfo->bDeliverReq, pSendOptInfo->bKeepCopy, pSendOptInfo->option.mmsSendOptInfo.bReadReq,
+                               pSendOptInfo->option.mmsSendOptInfo.expiryTime.time, pSendOptInfo->option.mmsSendOptInfo.bUseDeliveryCustomTime, pSendOptInfo->option.mmsSendOptInfo.deliveryTime.time,
+                               pSendOptInfo->option.mmsSendOptInfo.priority, pMsgInfo->msgId);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       //CID 41997: Releasing pMmsDta in case of failure
+                       MsgMmsRelease(&pMmsData);
+                       return MSG_ERR_DB_EXEC;
+               }
 
-                                       mm_file_destroy_tag_attrs(tag_attrs);
+               snprintf(working_dir, sizeof(working_dir), MSG_DATA_PATH"%d.mms.dir", pMsgInfo->msgId);
 
-                                       if (fileRet != 0) {
-                                               MSG_DEBUG("mm_file_get_attrs fails [%s]", err_attr_name);
-                                               if (err_attr_name) {
-                                                       free(err_attr_name);
-                                                       err_attr_name = NULL;
-                                               }
+               MsgMmsSetMultipartListData(pMmsData);//app file -> data
 
-                                               continue;
-                                       }
-                               } else {
-                                       MSG_DEBUG("mm_file_create_tag_attrs fails");
-                                       continue;
-                               }
+               MmsPluginStorage::instance()->deleteMultipartList(pMsgInfo->msgId); //remove exist multipart
 
-                               MSG_DEBUG("artwork: %p", artwork);
-                               MSG_DEBUG("artwork_size: %d", artworkSize);
+               MsgMmsSetMultipartListFilePath(working_dir, pMmsData);//data -> svc file
 
-                               if (artwork) {
-                                       char thumbPath[MSG_FILEPATH_LEN_MAX] = {0, };
+               {//add multipart list
+                       if (pMmsData->smil) {
+                               pMmsData->smil->type = MIME_APPLICATION_SMIL;
+                               insertMultipart(pMsgInfo->msgId, pMmsData->smil);
+                       }
 
-                                       snprintf(thumbPath, MSG_FILEPATH_LEN_MAX, MSG_THUMBNAIL_PATH"%s.jpg", szFileName);
+                       MMSList *multipart_list = pMmsData->multipartlist;
 
-                                       FILE *tmp = MsgOpenFile(thumbPath, "wb+");
+                       if (multipart_list) {
+                               for (int i = 0; i < (int)g_list_length(multipart_list); i++) {
 
-                                       if(!tmp) {
-                                               MSG_DEBUG("MsgOpenFile file error");
-                                               return MSG_ERR_STORAGE_ERROR;
-                                       }
+                                       MMS_MULTIPART_DATA_S *pMultipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(multipart_list, i);
 
-                                       if (MsgWriteFile((char*)artwork, 1, artworkSize, tmp) != (size_t)artworkSize) {
-                                               MSG_DEBUG("MsgWriteFile error");
-                                               MsgCloseFile(tmp);
-                                               return MSG_ERR_STORAGE_ERROR;
+                                       if (pMultipart) {
+                                               insertMultipart(pMsgInfo->msgId, pMultipart);
                                        }
-                                       MsgFsync(tmp);
-                                       MsgCloseFile(tmp);
-
-                                       strncpy(pThumbnailPath, thumbPath, MSG_FILEPATH_LEN_MAX);
-
-                                       bThumbnail = true;
-
-                                       break;
                                }
                        }
                }
 
-               if (bThumbnail == true)
-                       break;
-       }
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t MmsPluginStorage::addMmsNoti(MSG_MESSAGE_INFO_S *pMsgInfo)
-{
-       MSG_BEGIN();
-
-       msg_error_t     err = MSG_SUCCESS;
+               //set
+               if (MsgGetFileSize(raw_filepath, (int *)&pMsgInfo->dataSize) == false) {
+                       MSG_SEC_DEBUG("Fail to get mms file size [%s]", raw_filepath);
+                       //CID 41997: Releasing pMmsDta in case of failure
+                       MsgMmsRelease(&pMmsData);
+                       goto __CATCH;
+               }
 
-       err = MsgInsertMmsReportToNoti(&dbHandle, pMsgInfo);
+               {//make Preview info for APP
+                       MmsPluginAppBase *appBase;
+                       appBase = new MmsPluginAppBase(pMmsData);
+                       appBase->makePreviewInfo(pMsgInfo->msgId, true, raw_filepath);
+                       appBase->getFirstPageTextFilePath(pMsgInfo->msgText, sizeof(pMsgInfo->msgText));
+                       delete appBase;
+               }
+       }
 
+       MsgMmsRelease(&pMmsData);
        MSG_END();
 
        return err;
+
+__CATCH:
+       removePreviewInfo(pMsgInfo->msgId);
+
+       THROW(MsgException::MMS_PLG_ERROR, "MMS add Error");
 }
 
-/* This API is not used anywhere now */
-msg_error_t    MmsPluginStorage::plgGetRestoreMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_MESSAGE_DATA_S *pMmsMsg, char **pDestMsg, char *filePath)
+msg_error_t MmsPluginStorage::getMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char **pSerializedMms)
 {
        MSG_BEGIN();
 
        msg_error_t     err = MSG_SUCCESS;
-       int partCnt = 0;
-       MsgType partHeader;
-       MmsAttrib pMmsAttrib;
-       char szBuf[MSG_FILEPATH_LEN_MAX] = {0, };
-       unsigned int nSize;
-       bool bMultipartRelated = false;
 
-       if (_MmsReadMsgBody(pMsg->msgId, true, true, filePath) == false) {
-               MSG_DEBUG("The MMS Message might include drm contents!!!");
+       MMS_DATA_S *pMmsData = MsgMmsCreate();
 
-#ifdef __SUPPORT_DRM__
-               if (MmsDrm2GetConvertState() == MMS_DRM2_CONVERT_REQUIRED) {
-                       bool bRetToConvert = true;
+       if (pMmsData == NULL) {
+               MSG_ERR("MsgMmsCreate Fail");
+               return MSG_ERR_NULL_POINTER;
+       }
 
-                       bRetToConvert = MmsDrm2ConvertMsgBody(mmsHeader.msgType.szOrgFilePath);
+       MMS_HEADER_DATA_S *pHeader = MsgMmsCreateHeader();
 
-                       MmsDrm2SetConvertState(MMS_DRM2_CONVERT_FINISH);
+       if (pHeader == NULL) {
+               MsgMmsRelease(&pMmsData);
+               MSG_ERR("MsgMmsCreateHeader Fail");
+               return MSG_ERR_NULL_POINTER;
+       }
 
-                       if (bRetToConvert) {
-                               remove(mmsHeader.msgType.szOrgFilePath);
-                               rename(MMS_DECODE_DRM_CONVERTED_TEMP_FILE, mmsHeader.msgType.szOrgFilePath);
+       pMmsData->header = pHeader;
 
-                               if (MmsDrm2ReadMsgConvertedBody(pMsg, true, false, NULL) == false) {
-                                       MSG_DEBUG("MmsLoadMsg:MmsDrm2ReadMsgConvertedBody() returns false\n");
-                                       goto L_CATCH;
-                               }
-                       } else {
-                               goto L_CATCH;
-                       }
-               }
-#endif
+       switch(pMsg->msgType.subType) {
+               case MSG_SENDREQ_MMS:
+                       pHeader->messageType = MMS_MSGTYPE_SEND_REQ;
+                       break;
+               case MSG_SENDCONF_MMS:
+                       pHeader->messageType = MMS_MSGTYPE_SEND_CONF;
+                       break;
+               case MSG_RETRIEVE_MMS:
+                       pHeader->messageType = MMS_MSGTYPE_RETRIEVE_CONF;
+                       break;
+               case MSG_RETRIEVE_AUTOCONF_MMS:
+                       pHeader->messageType = MMS_MSGTYPE_RETRIEVE_CONF;
+                       break;
+               case MSG_RETRIEVE_MANUALCONF_MMS:
+                       pHeader->messageType = MMS_MSGTYPE_RETRIEVE_CONF;
+                       break;
+               case MSG_NOTIFICATIONIND_MMS:
+                       pHeader->messageType = MMS_MSGTYPE_NOTIFICATION_IND;
+                       break;
+               default:
+                       break;
        }
 
-       MmsGetMsgAttrib(pMsg->msgId, &pMmsAttrib);
-
-       pMmsMsg->regionCnt = 0;
-       pMmsMsg->pageCnt = 0;
-       pMmsMsg->attachCnt = 0;
-       pMmsMsg->transitionCnt = 0;
-       pMmsMsg->metaCnt = 0;
-       memset(pMmsMsg->szSmilFilePath, 0, MSG_FILEPATH_LEN_MAX);
+       err = getMmsData(pMsg->msgId, pMmsData); // get MmsData Info from DB
 
-       if (pMmsAttrib.contentType == MIME_MULTIPART_RELATED || pMmsAttrib.contentType == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
-               char *pSmilDoc = NULL;
+       if (err == MSG_SUCCESS) {
 
-               pSmilDoc = MmsSmilGetPresentationData(pMsg->msgId);
-               if (!pSmilDoc) {
-                       goto L_CATCH;
+               if (pSendOptInfo) {
+                       pSendOptInfo->bDeliverReq = pHeader->bDeliveryReport;
+                       pSendOptInfo->option.mmsSendOptInfo.bReadReq = pHeader->bReadReport;
+                       pSendOptInfo->option.mmsSendOptInfo.priority = pHeader->mmsPriority;
+                       pSendOptInfo->option.mmsSendOptInfo.expiryTime.type = pHeader->expiry.type;
+                       pSendOptInfo->option.mmsSendOptInfo.expiryTime.time = pHeader->expiry.time;
+                       pSendOptInfo->option.mmsSendOptInfo.deliveryTime.type = pHeader->delivery.type;
+                       pSendOptInfo->option.mmsSendOptInfo.deliveryTime.time = pHeader->delivery.time;
                }
 
-               MmsSmilParseSmilDoc(pMmsMsg, pSmilDoc);
-               bMultipartRelated = true;
-       }
-
-       partCnt = MmsGetMediaPartCount(pMsg->msgId);
-       MSG_DEBUG("MmsUiGetMediaAttachInfo: partCnt=%d\n", partCnt);
+               //MsgMmsSetMultipartListData(pMmsData);
+               int mmsDataSize = MsgSerializeMms(pMmsData, pSerializedMms);
+               if (mmsDataSize > 0) {
+                       pMsg->dataSize = mmsDataSize;
+               } else {
+                       MSG_ERR("MsgSerializeMms fail");
+               }
 
-       if (partCnt < 0) {
-               MSG_DEBUG("MmsUiGetMediaAttachInfo: partCnt=%d\n", partCnt);
-               goto FREE_CATCH;
+       } else {
+               MSG_ERR("getMmsData fail, err = [%d]",  err);
        }
 
-       for (int i = 0; i < partCnt; ++i) {
-               if (!MmsGetMediaPartHeader(i, &partHeader)) {
-                       MSG_DEBUG("MmsUiGetMediaAttachInfo: MmsGetMediaPartHeader failed\n");
-                       goto FREE_CATCH;
-               }
+       //Release pMmsData
+       MsgMmsRelease(&pMmsData);
+       MSG_END();
 
-               if (partHeader.contentSize > 0) {
-                       if (!strcasecmp(partHeader.param.szFileName, "cid:")) {
-                               strncpy((char *)szBuf, &partHeader.param.szFileName[4], MSG_FILEPATH_LEN_MAX - 1);
-                       } else {
-                               strcpy((char *)szBuf, partHeader.param.szFileName);
-                       }
-                       sprintf(partHeader.param.szFileName, MSG_DATA_PATH"%s", szBuf);
+       return err;
+}
 
-                       if (!bMultipartRelated || MmsCheckAdditionalMedia(pMmsMsg, &partHeader)) {
-                               MMS_ATTACH_S *attachment = NULL;
-                               int tempType;
+msg_error_t MmsPluginStorage::updateMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
 
-                               attachment = (MMS_ATTACH_S *)calloc(sizeof(MMS_ATTACH_S), 1);
+       //update multipart list
+       MMSList *multipart_list = NULL;
+       if (MmsPluginStorage::instance()->getMultipartList(pMsgInfo->msgId, &multipart_list) != MSG_SUCCESS)
+               return -1;
 
-                               MsgGetTypeByFileName(&tempType, partHeader.param.szFileName);
-                               attachment->mediatype = (MimeType)tempType;
+       for (int i = 0; i < (int)g_list_length(multipart_list); i++) {
+               MMS_MULTIPART_DATA_S *pMultipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(multipart_list, i);
+               MmsPluginStorage::instance()->updateMultipart(pMsgInfo->msgId, true, pMultipart);
+       }
 
-                               strcpy(attachment->szFilePath, partHeader.param.szFileName);
+       //update preview
+       char szFullPath[MSG_FILEPATH_LEN_MAX] = {0, };
+       MmsMsg *mmsMsg = NULL;
+       unique_ptr<MmsMsg*, void(*)(MmsMsg**)> buf(&mmsMsg, unique_ptr_deleter);
+       mmsMsg = (MmsMsg *)new char[sizeof(MmsMsg)];
+       memset(mmsMsg, 0x00, sizeof(MmsMsg));
+
+       MmsPluginStorage::instance()->getMmsRawFilePath(pMsgInfo->msgId, szFullPath, sizeof(szFullPath));
+       MmsPluginDecoder::instance()->decodeMmsPdu(mmsMsg, pMsgInfo->msgId, szFullPath);
+       {//make Preview info for APP
+               MmsPluginAppBase *appBase;
+               appBase = new MmsPluginAppBase(mmsMsg);
+               appBase->makePreviewInfo(pMsgInfo->msgId, true, szFullPath);
+               appBase->getFirstPageTextFilePath(pMsgInfo->msgText, sizeof(pMsgInfo->msgText));
+               delete appBase;
+       }
+       MmsReleaseMmsMsg(mmsMsg);
 
-                               strncpy(attachment->szFileName, partHeader.param.szName, MSG_FILENAME_LEN_MAX - 1);
+       MSG_END();
+       return 0;
+}
 
-                               attachment->fileSize = partHeader.contentSize;
+int MmsPluginStorage::checkDuplicateNotification(char* pszTrID, char* pszContentLocation)
+{
+       MSG_BEGIN();
 
-                               _MsgMmsAddAttachment(pMmsMsg, attachment);
-                       }
-               }
-       }
+       if (!pszTrID || strlen(pszTrID) == 0)
+               return 0;
 
-       *pDestMsg = _MsgMmsSerializeMessageData(pMmsMsg, &nSize);
+       if(!pszContentLocation || strlen(pszContentLocation) == 0)
+               return 0;
 
-       __MmsReleaseMmsLists(pMmsMsg);
+       MSG_DEBUG("Trans Id = %s, Content Loc = %s", pszTrID, pszContentLocation);
 
-       MmsMsg *pStoMmsMsg;
-       MmsPluginStorage::instance()->getMmsMessage(&pStoMmsMsg);
-       _MmsInitHeader();
-       _MmsUnregisterDecodeBuffer();
-#ifdef __SUPPORT_DRM__
-       _MsgFreeDRMInfo(&pStoMmsMsg->msgType.drmInfo);
-#endif
-       _MsgFreeBody(&pStoMmsMsg->msgBody, pStoMmsMsg->msgType.type);
+       int msgId = 0;
+       msg_error_t err = MSG_SUCCESS;
+       int rowCnt = 0;
 
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       pMsg->dataSize = nSize;
+       char sqlQuery[MAX_QUERY_LEN + 1];
 
-       if (err != MSG_SUCCESS)
-               MSG_DEBUG("MmsPlgUpdateMessage : Update MMS Message Failed");
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       MSG_END();
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s \
+                       WHERE TRANSACTION_ID LIKE '%s' AND CONTENTS_LOCATION LIKE '%s'",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, pszTrID, pszContentLocation);
 
-       return err;
+       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
 
-FREE_CATCH:
-       if (bMultipartRelated) {
-               __MmsReleaseMmsLists(pMmsMsg);
+       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               dbHandle->freeTable();
+               MSG_DEBUG("[Error]Failed to Get Table");
+               return 0;
        }
 
-L_CATCH:
-       {
-               MmsMsg *pMsg;
-               MmsPluginStorage::instance()->getMmsMessage(&pMsg);
-               _MmsInitHeader();
+       if (rowCnt > 0)
+               msgId = dbHandle->getColumnToInt(1);
 
-               _MmsUnregisterDecodeBuffer();
-#ifdef __SUPPORT_DRM__
-               _MsgFreeDRMInfo(&pMsg->msgType.drmInfo);
-#endif
-               _MsgFreeBody(&pMsg->msgBody, pMsg->msgType.type);
+       dbHandle->freeTable();
 
-               return MSG_ERR_STORAGE_ERROR;
-       }
        MSG_END();
+
+       return msgId;
 }
-/* This API is not used anywhere now */
 
diff --git a/plugin/mms_plugin/MmsPluginTcs.cpp b/plugin/mms_plugin/MmsPluginTcs.cpp
new file mode 100755 (executable)
index 0000000..5a9ca7b
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include "TCSImpl.h"
+#include "TCSErrorCodes.h"
+#include "MmsPluginDebug.h"
+#include "MsgUtilFile.h"
+#include "MmsPluginTcs.h"
+
+int MmsPluginTcsScanFile(const char *filepath, int *bLevel)
+{
+       MSG_BEGIN();
+       TCSLIB_HANDLE hLib;
+       TCSScanResult result;
+       TCSDetected* pDetected;
+       int rtn, i;
+       int ret_b_level = -1;
+
+       if (MsgAccessFile(filepath, R_OK) == false) {
+               MSG_SEC_DEBUG("not exist source file [%s]", filepath);
+               return -1;
+       }
+
+       MSG_SEC_DEBUG("Scanning file name : %s\n", filepath);
+
+       hLib = TCSLibraryOpen();
+       if(hLib == INVALID_TCSLIB_HANDLE) {
+               MSG_DEBUG("TCSLibraryOpen error\n");
+               return -1;
+       }
+
+       rtn = TCSScanFile(hLib, filepath, TCS_DTYPE_UNKNOWN, TCS_SA_SCANONLY, 1, &result);
+       if(rtn == 0)
+       {
+               MSG_DEBUG("Detected malware number: %d\n", result.iNumDetected);
+               i = result.iNumDetected;
+               pDetected = result.pDList;
+               while(i && pDetected)
+               {
+                       int temp_b_level;
+                       int temp_s_class;
+                       MSG_SEC_DEBUG(" +-- Malware [%d] Name: %s\n", i, pDetected->pszName);
+                       MSG_DEBUG(" +-- Malware [%d] uAction: %u : 0x%04x\n", i, pDetected->uAction, pDetected->uAction);
+
+                       temp_b_level  = (pDetected->uAction & 0xFF00) >> 8;
+                       MSG_DEBUG(" +-- Malware [%d] Behavior level: %u\n", i, temp_b_level);
+
+                       if (ret_b_level == -1 || ret_b_level < temp_b_level) {
+                               ret_b_level = temp_b_level;
+                       }
+
+                       temp_s_class  = (pDetected->uAction & 0x00FF);
+                       MSG_DEBUG(" +-- Malware [%d] Severity class: %u\n", i, temp_s_class);
+
+                       pDetected = pDetected->pNext;
+                       i --;
+               }
+
+               result.pfFreeResult(&result);
+       } else {
+               MSG_DEBUG("TCSScanFile fail: err = %d\n", rtn);
+       }
+
+       TCSLibraryClose(hLib);
+
+       if (bLevel)
+               *bLevel = ret_b_level;
+
+       MSG_END();
+
+       return 0;
+}
diff --git a/plugin/mms_plugin/MmsPluginTextConvert.cpp b/plugin/mms_plugin/MmsPluginTextConvert.cpp
new file mode 100755 (executable)
index 0000000..bd79ac6
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include <glib.h>
+#include "MmsPluginDebug.h"
+#include "MmsPluginMIME.h"
+#include "MmsPluginCodec.h"
+#include "MmsPluginTextConvert.h"
+#include "MmsPluginUtil.h"
+
+const char *MmsPluginTextConvertGetCharSet(int MIBEnum)
+{
+       const char * result_str = NULL;
+
+       result_str = MmsGetTextByCode(MmsCodeCharSet, (unsigned short int)MIBEnum);
+       MSG_DEBUG("[MIBEnum = %d, Charset = %s]", MIBEnum, result_str);
+
+       return result_str;
+}
+
+bool MmsPluginTextConvert(const char *pToCodeSet, const char *pFromCodeset, const char *pSrc, int srcLen, char **ppDest, int *pDestLen)
+{
+       MSG_BEGIN();
+       char *pDest = NULL;
+       gsize bytes_read = 0;
+       gsize bytes_written = 0;
+       GError *error = NULL;
+
+       if (pToCodeSet == NULL || pFromCodeset == NULL) {
+               MSG_DEBUG("Error input parameter Codeset to = %s, from = %s", pToCodeSet, pFromCodeset);
+               goto __CATCH;
+       }
+
+       MSG_DEBUG("Codeset to = %s, from = %s", pToCodeSet, pFromCodeset);
+
+       if (pSrc == NULL || ppDest == NULL || pDestLen == NULL) {
+               MSG_DEBUG("Error input parameter pSrc = %p, ppDest = %p, pDestLen = %p", pSrc, ppDest, pDestLen);
+               goto __CATCH;
+       }
+
+       if (strcasecmp("utf-16", pFromCodeset) == 0) {//check utf-8 str though utf-16
+
+               MSG_DEBUG("Codeset [%s] check utf-8 type", pFromCodeset);
+
+               if (((UINT8)pSrc[0] == 0xFF && (UINT8)pSrc[1] == 0xFE) || ((UINT8)pSrc[0] == 0xFE && (UINT8)pSrc[1] == 0xFF)) {
+
+                       char *pTemp = (char *)calloc(1, srcLen + 1);
+                       if (pTemp == NULL) {
+                               MSG_DEBUG("fail to calloc");
+                               goto __CATCH;
+                       }
+
+                       memcpy(pTemp, pSrc, srcLen);
+
+                       for (int i = 0; i < srcLen - 1; i++) {
+                               if ((UINT8)pTemp[i] == 0xFF && (UINT8)pTemp[i+1] == 0xFD) {
+                                       MSG_DEBUG("exist 0xFFFD convert to 0x5F5F");
+                                       pTemp[i] = 0x5F;
+                                       pTemp[i+1] = 0x5F;
+                               }
+                       }
+
+                       if (MmsIsUtf8String((unsigned char *)pTemp+2, srcLen-2) == true) {
+                               MSG_DEBUG("UTF-8 string");
+                               pDest = (char *)calloc(1, srcLen - 2 + 1);
+                               if (pDest)
+                                       strncpy(pDest, pTemp + 2, srcLen - 2);
+                               bytes_written = srcLen - 2;
+
+                               if (pTemp) {
+                                       free(pTemp);
+                                       pTemp = NULL;
+                               }
+
+                               goto __RETURN;
+                       }
+
+                       if (pTemp) {
+                               free(pTemp);
+                               pTemp = NULL;
+                       }
+
+               }
+       }
+
+       pDest = g_convert (pSrc, srcLen,
+                       pToCodeSet, pFromCodeset,
+              &bytes_read, &bytes_written,
+              &error);
+
+       if (error != NULL) {
+               MSG_DEBUG("Error in g_convert, GError = %d:%s, pSrc = %s\n", error->code, error->message, pSrc);
+               goto __CATCH;
+       }
+
+       if (pDest == NULL || bytes_written == 0 || bytes_read == 0) {
+               MSG_DEBUG("Error in g_convert, pDest = %s, bytes_written = %d, bytes_read = %d\n", pDest, bytes_written, bytes_read);
+               goto __CATCH;
+       }
+
+__RETURN:
+       *ppDest = pDest;
+       *pDestLen = bytes_written;
+
+       MSG_END();
+       return true;
+
+__CATCH:
+       if (pDest)
+               g_free(pDest);
+
+       MSG_END();
+       return false;
+}
index 3379751..5af58cf 100755 (executable)
@@ -1,27 +1,26 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
-#include "MmsPluginEventHandler.h"
-#include "MmsPluginTransport.h"
 #include "MsgUtilFile.h"
-#include "MmsPluginCodec.h"
-#include "MmsPluginMessage.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginTypes.h"
+#include "MmsPluginTransport.h"
 #include "MmsPluginUserAgent.h"
-
+#include "MsgGconfWrapper.h"
 
 /*==================================================================================================
                                      IMPLEMENTATION OF MmsPluginTransport - Member Functions
@@ -56,6 +55,10 @@ void MmsPluginTransport::submitRequest(const MSG_REQUEST_INFO_S *pReqInfo)
 
        reqItem.isCompleted = false;
        reqItem.reqID = pReqInfo->reqId;
+       reqItem.simId = pReqInfo->msgInfo.sim_idx;
+
+       char *msisdn = NULL;
+       msisdn = MsgSettingGetString(MSG_SIM_MSISDN);
 
        MSG_DEBUG("pReqInfo->msgInfo.msgType.subType [%d]", pReqInfo->msgInfo.msgType.subType);
 
@@ -67,6 +70,7 @@ void MmsPluginTransport::submitRequest(const MSG_REQUEST_INFO_S *pReqInfo)
                reqItem.eMmsPduType = eMMS_SEND_REQ;
                reqItem.eHttpCmdType = eHTTP_CMD_POST_TRANSACTION;
                reqItem.pPostData = MsgOpenAndReadMmsFile(pReqInfo->msgInfo.msgData, 0, -1, &reqItem.postDataLen);
+               MSG_MMS_VLD_INFO("%d, MMS Send Start %s->%s, Success", pReqInfo->msgInfo.msgId, (msisdn == NULL)?"ME":msisdn, pReqInfo->msgInfo.addressList[0].addressVal);
                break;
 
        case MSG_GET_MMS:
@@ -76,18 +80,24 @@ void MmsPluginTransport::submitRequest(const MSG_REQUEST_INFO_S *pReqInfo)
                reqItem.eHttpCmdType = eHTTP_CMD_GET_TRANSACTION;
                reqItem.getDataLen = pReqInfo->msgInfo.dataSize;
                reqItem.pGetData = (char *)malloc(reqItem.getDataLen);
-               memcpy(reqItem.pGetData, pReqInfo->msgInfo.msgData, reqItem.getDataLen);
+               if (reqItem.pGetData)
+                       memcpy(reqItem.pGetData, pReqInfo->msgInfo.msgData, reqItem.getDataLen);
+               MSG_MMS_VLD_INFO("%d, MMS Receive Auto Start %s->%s, Success", pReqInfo->msgInfo.msgId, pReqInfo->msgInfo.addressList[0].addressVal, (msisdn == NULL)?"ME":msisdn);
                break;
 
-       case MSG_NOTIFYRESPIND_MMS:
+       case MSG_NOTIFYRESPIND_MMS: //reject
+       {
                MSG_DEBUG("######### MANUAL RETRIEVE : SEND NOTIFY RESPONSE IND");
                reqItem.msgId = pReqInfo->msgInfo.msgId;
                reqItem.eMmsPduType = eMMS_NOTIFYRESP_IND;
                reqItem.eHttpCmdType = eHTTP_CMD_POST_TRANSACTION;
                reqItem.pPostData = MsgOpenAndReadMmsFile(pReqInfo->msgInfo.msgData, 0, -1, &reqItem.postDataLen);
-               remove(pReqInfo->msgInfo.msgData);
+               int ret = remove(pReqInfo->msgInfo.msgData);
+               if (ret != 0) {
+                       MSG_DEBUG("remove fail\n");
+               }
                break;
-
+       }
        case MSG_RETRIEVE_MMS:
                MSG_DEBUG("######### MANUAL RETRIEVE : GET TRANSACTION");
                reqItem.msgId = pReqInfo->msgInfo.msgId;
@@ -95,42 +105,57 @@ void MmsPluginTransport::submitRequest(const MSG_REQUEST_INFO_S *pReqInfo)
                reqItem.eHttpCmdType = eHTTP_CMD_GET_TRANSACTION;
                reqItem.getDataLen = pReqInfo->msgInfo.dataSize;
                reqItem.pGetData = (char *)malloc(reqItem.getDataLen);
-               memcpy(reqItem.pGetData, pReqInfo->msgInfo.msgData, reqItem.getDataLen);
+               if (reqItem.pGetData)
+                       memcpy(reqItem.pGetData, pReqInfo->msgInfo.msgData, reqItem.getDataLen);
+               MSG_MMS_VLD_INFO("%d, MMS Receive Manual Start %s->%s, Success", pReqInfo->msgInfo.msgId, pReqInfo->msgInfo.addressList[0].addressVal, (msisdn == NULL)?"ME":msisdn);
                break;
 
        case MSG_READREPLY_MMS:
+       {
                MSG_DEBUG("######### SEND READ REPORT : POST TRANSACTION");
                reqItem.msgId = pReqInfo->msgInfo.msgId;
                reqItem.eMmsPduType = eMMS_READREPORT_REQ;
                reqItem.eHttpCmdType = eHTTP_CMD_POST_TRANSACTION;
                reqItem.pPostData = MsgOpenAndReadMmsFile(pReqInfo->msgInfo.msgData, 0, -1, &reqItem.postDataLen);
                // remove x-Read-Rec.ind file
-               remove(pReqInfo->msgInfo.msgData);
+               int ret = remove(pReqInfo->msgInfo.msgData);
+               if (ret != 0) {
+                       MSG_DEBUG("remove fail\n");
+               }
                break;
-
+       }
        case MSG_READRECIND_MMS:
+       {
                MSG_DEBUG("######### SEND READREC IND : POST TRANSACTION");
                reqItem.msgId = pReqInfo->msgInfo.msgId;
                reqItem.eMmsPduType = eMMS_READREC_IND;
                reqItem.eHttpCmdType = eHTTP_CMD_POST_TRANSACTION;
                reqItem.pPostData = MsgOpenAndReadMmsFile(pReqInfo->msgInfo.msgData, 0, -1, &reqItem.postDataLen);
                // remove x-Read-Rec.ind file
-               remove(pReqInfo->msgInfo.msgData);
+               int ret = remove(pReqInfo->msgInfo.msgData);
+               if (ret != 0) {
+                       MSG_DEBUG("remove fail\n");
+               }
                break;
-
+       }
        case MSG_FORWARD_MMS:
                MSG_DEBUG("######### SEND FORWARD MSG : POST TRANSACTION");
                reqItem.msgId = pReqInfo->msgInfo.msgId;
                reqItem.eMmsPduType = eMMS_SEND_REQ;
                reqItem.eHttpCmdType = eHTTP_CMD_POST_TRANSACTION;
                reqItem.pPostData = MsgOpenAndReadMmsFile(pReqInfo->msgInfo.msgData, 0, -1, &reqItem.postDataLen);
+               MSG_MMS_VLD_INFO("%d, MMS Send Start %s->%s, Success", pReqInfo->msgInfo.msgId, (msisdn == NULL)?"ME":msisdn, pReqInfo->msgInfo.addressList[0].addressVal);
                break;
        }
 
        MmsPluginUaManager::instance()->addMmsReqEntity(reqItem);
        MmsPluginUaManager::instance()->start();
-}
 
+       if (msisdn) {
+               free(msisdn);
+               msisdn = NULL;
+       }
+}
 
 void MmsPluginTransport::cancelRequest(msg_request_id_t reqId)
 {
index bff7fc6..41a87ea 100755 (executable)
@@ -1,33 +1,33 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#include <glib.h>
-#include <curl/curl.h>
+#include "MsgException.h"
+#include "MsgUtilFile.h"
+#include "MsgGconfWrapper.h"
+
+#include "MmsPluginDebug.h"
 #include "MmsPluginUserAgent.h"
+#include "MmsPluginHttp.h"
+#include "MmsPluginConnManWrapper.h"
 #include "MmsPluginEventHandler.h"
-#include "MsgGconfWrapper.h"
 #include "MmsPluginInternal.h"
-#include "MsgUtilFile.h"
 #include "MmsPluginCodec.h"
-#include "MsgException.h"
 #include "MmsPluginDrm.h"
 #include "MmsPluginStorage.h"
-
-
-extern MmsHeader mmsHeader;
+#include "MmsPluginUtil.h"
 
 void PRINT_PDU_TYPE(MMS_PDU_TYPE_T pduType)
 {
@@ -171,22 +171,45 @@ void updatePduType(mmsTranQEntity *qEntity)
        case eMMS_MBOX_DELETE_REQ:
                qEntity->eMmsPduType = eMMS_MBOX_DELETE_CONF;
                break;
+       default:
+               break;
+       }
 
        MSG_DEBUG("Update PDU Type:");
        PRINT_PDU_TYPE(qEntity->eMmsPduType);
+}
 
-       default:
-               break;
+bool compare_func(mmsTranQEntity const &a, mmsTranQEntity const &b)
+{
+       if (a.msgId == b.msgId) {
+               if ((a.eMmsPduType == eMMS_RETRIEVE_MANUAL || a.eMmsPduType == eMMS_RETRIEVE_AUTO)
+                               &&(b.eMmsPduType == eMMS_RETRIEVE_MANUAL || b.eMmsPduType == eMMS_RETRIEVE_AUTO)) {
+                       return true;
+               }
        }
 
+       return false;
+}
+
+bool compare_func_for_removal(mmsTranQEntity const &a, mmsTranQEntity const &b)
+{
+       if (a.reqID == b.reqID &&
+                       a.msgId == b.msgId &&
+                       a.sessionId == b.sessionId &&
+                       a.simId == b.simId) {
+                       return true;
+       }
+       return false;
 }
 
 MmsPluginUaManager *MmsPluginUaManager::pInstance = NULL;
 
 MmsPluginUaManager::MmsPluginUaManager()
 {
+       lock();
        running = false;
        mmsTranQ.clear();
+       unlock();
 }
 
 MmsPluginUaManager::~MmsPluginUaManager()
@@ -207,7 +230,7 @@ MmsPluginUaManager *MmsPluginUaManager::instance()
 
 void MmsPluginUaManager::start()
 {
-       bool bStart = true;
+//     bool bStart = true;
 
        MutexLocker lock(mx);
 
@@ -220,145 +243,203 @@ void MmsPluginUaManager::start()
 
 MMS_NET_ERROR_T MmsPluginUaManager::submitHandler(mmsTranQEntity *qEntity)
 {
+       MSG_BEGIN();
+
        MMS_NET_ERROR_T ret = eMMS_UNKNOWN;
-       int retryCount = 0;
+       http_request_info_s request_info = {};
+       char *http_url = NULL;
+       const char *home_url = NULL;
+       const char *proxy_addr = NULL;
+       const char *interfaceName = NULL;
+       bool cm_ret;
 
-       MSG_DEBUG("request Submit:");
        PRINT_PDU_TYPE(qEntity->eMmsPduType);
+
        PRINT_QUEUE_ENTITY(qEntity);
 
-       MmsPluginHttpAgent*     httpAgent = MmsPluginHttpAgent::instance();
+       cm_ret = MmsPluginCmAgent::instance()->getProxyAddr(&proxy_addr);
+       if (cm_ret == false)
+               return eMMS_EXCEPTIONAL_ERROR;
 
-       while (retryCount < RETRY_MAX) {
-               ret = httpAgent->cmdRequest(qEntity->eHttpCmdType);
+       cm_ret = MmsPluginCmAgent::instance()->getInterfaceName(&interfaceName);
+       if (cm_ret == false)
+               return eMMS_EXCEPTIONAL_ERROR;
 
-               // Process result
-               if (ret == eMMS_HTTP_SENT_SUCCESS) {
-                       MSG_DEBUG("Submit request sent");
-                       break;
-               } else if (ret == eMMS_HTTP_ERROR_NETWORK) {
-                       retryCount++;
-                       MSG_DEBUG("HTTP sent timeout and try again: %d", retryCount);
-                       continue;
-               } else {
-                       MSG_DEBUG("Unexpected Error %d", ret);
-                       break;
-               }
-       }
 
-       return ret;
-}
+       cm_ret = MmsPluginCmAgent::instance()->getHomeUrl(&home_url);
+       if (cm_ret == false)
+               return eMMS_EXCEPTIONAL_ERROR;
 
-MMS_NET_ERROR_T MmsPluginUaManager::waitingConf(mmsTranQEntity *qEntity)
-{
-       MMS_NET_ERROR_T ret = eMMS_HTTP_ERROR_UNKNOWN;
-       MmsPluginHttpAgent *pHttpAgent = MmsPluginHttpAgent::instance();
-       MMS_PLUGIN_HTTP_CONTEXT_S *pMmsPldCd = NULL;
+       memset(&request_info, 0x00, sizeof(request_info));
+
+       if (qEntity->eHttpCmdType == eHTTP_CMD_POST_TRANSACTION) {
+
+               request_info.transaction_type = MMS_HTTP_TRANSACTION_TYPE_POST;
+
+               request_info.url = home_url;
+
+               request_info.proxy = proxy_addr;
+
+               request_info.interface = interfaceName;
+
+               request_info.post_data = qEntity->pPostData;
+
+               request_info.post_data_len = qEntity->postDataLen;
+
+       } else {
+               request_info.transaction_type = MMS_HTTP_TRANSACTION_TYPE_GET;
 
-       pMmsPldCd = pHttpAgent->getMmsPldCd();
+               http_url = (char *)calloc(1, qEntity->getDataLen + 1);
 
-       if (qEntity->pGetData) {
-               free(qEntity->pGetData);
-               qEntity->pGetData = NULL;
+               if (http_url)
+                       memcpy(http_url, qEntity->pGetData, qEntity->getDataLen);
+
+               request_info.url = http_url;
+
+               request_info.proxy = proxy_addr;
+
+               request_info.interface = interfaceName;
        }
-       qEntity->getDataLen = pMmsPldCd->bufOffset;
-       qEntity->pGetData = (char *)calloc(1, pMmsPldCd->bufOffset + 1);
 
-       memcpy(qEntity->pGetData, pMmsPldCd->final_content_buf, pMmsPldCd->bufOffset);
-       free(pMmsPldCd->final_content_buf);
-       pMmsPldCd->final_content_buf = NULL;
-       pMmsPldCd->bufOffset = 0;
+       MMS_HTTP_ERROR_E http_ret;
+       MmsPluginHttpAgent*     httpAgent = MmsPluginHttpAgent::instance();
+       http_ret = httpAgent->httpRequest(request_info);
+
+       if (http_ret == MMS_HTTP_ERROR_NONE) {
+               MSG_DEBUG("Submit request sent");
+
+               if (qEntity->pGetData) {
+                       free(qEntity->pGetData);
+                       qEntity->pGetData = NULL;
+               }
 
-       MSG_DEBUG("dataLen:%d  pData:(%s)", qEntity->getDataLen, qEntity->pGetData);
+               qEntity->pGetData = request_info.response_data;
+               qEntity->getDataLen = request_info.response_data_len;
+               ret = eMMS_SUCCESS;
+       } else {
+               MSG_DEBUG("Unexpected Error http_ret = [%d]", http_ret);
+               ret = eMMS_HTTP_ERROR_NETWORK;
+       }
 
-       ret = eMMS_HTTP_CONF_SUCCESS;
+       if (http_url)
+               free(http_url);
 
+       MSG_END();
        return ret;
 }
 
+MMS_NET_ERROR_T MmsPluginUaManager::waitingConf(mmsTranQEntity *qEntity)
+{
+       return eMMS_HTTP_CONF_SUCCESS;
+}
+
 void MmsPluginUaManager::run()
 {
        MSG_BEGIN();
 
        MmsPluginCmAgent *cmAgent = MmsPluginCmAgent::instance();
-       MmsPluginHttpAgent *httpAgent = MmsPluginHttpAgent::instance();
-
-       int trId;
-       CURL *session = NULL;
-
-       int msgId;
 
        while (1) {
-               if (mmsTranQ.empty()) {
-                       lock();
+               lock();
+               while (mmsTranQ.empty()) {
                        wait();
-                       unlock();
                }
+               unlock();
 
                // Request CM Open
                if (!(cmAgent->open())) {
-                       MSG_DEBUG("Cm Open Failed");
-
+                       MSG_FATAL("Cm Open Failed");
                        // delete all request from reqQEntities
-                       goto CLEANUP;
-               }
+                       lock();
+                       int qSize = mmsTranQ.size();
+                       unlock();
+                       if (qSize > 0) {
+                               MSG_DEBUG("CLEANUP");
+                               MSG_DEBUG("clear mmsTranQ");
+
+                               mmsTranQEntity reqEntity;
+                               memset(&reqEntity, 0, sizeof(mmsTranQEntity));
+
+                               lock();
+                               mmsTranQ.front(&reqEntity);
+                               unlock();
+                               // notify send fail to APP
+                               MmsPluginEventHandler::instance()->handleMmsError(&reqEntity);
+
+                               if (reqEntity.pGetData) {
+                                       MSG_DEBUG("free pGetData");
+                                       free(reqEntity.pGetData);
+                                       reqEntity.pGetData = NULL;
+                               }
 
-               httpAgent->SetMMSProfile();
+                               if (reqEntity.pPostData) {
+                                       MSG_DEBUG("free pPostData");
+                                       free(reqEntity.pPostData);
+                                       reqEntity.pPostData = NULL;
+                               }
+                               lock();
+                               mmsTranQ.remove(reqEntity, compare_func_for_removal);
+                               //mmsTranQ.pop_front();
+                               unlock();
+                       }
+                       lock();
+                       running = false;
+                       unlock();
+                       break;
+               }
 
-               while (!mmsTranQ.empty()) {
+               bool transaction = true;
+               while (transaction) {
+                       lock();
+                       int qSize = mmsTranQ.size();
+                       unlock();
+                       if (qSize <= 0) {
+                               break;
+                       }
 
-                       MSG_DEBUG("###### mmsTranQ.size [%d]", mmsTranQ.size());
+                       MSG_DEBUG("###### mmsTranQ.size [%d]", qSize);
 
                        mmsTranQEntity reqEntity;
                        memset(&reqEntity, 0, sizeof(mmsTranQEntity));
 
+                       lock();
                        mmsTranQ.front(&reqEntity);
+                       unlock();
 
                        reqEntity.isCompleted = false;
 
                        PRINT_QUEUE_ENTITY(&reqEntity);
 
-                       if (reqEntity.eMmsPduType == eMMS_RETRIEVE_AUTO) {
-                               msgId = reqEntity.msgId;
-                               MmsPluginStorage::instance()->updateNetStatus(msgId, MSG_NETWORK_RETRIEVING);
-                       }
-
-                       if (httpAgent->cmdRequest(eHTTP_CMD_INIT_SESSION) == eMMS_HTTP_SESSION_OPEN_FAILED) {
-                               MSG_DEBUG("HTTP session open failed");
-                               // cm close
-                               cmAgent->close();
-                               // delete all request from reqQEntities
-                               goto CLEANUP;
-                       }
-
                        // MMS Transaction
                        MSG_DEBUG("\n\n ===================  MMS Transaction Start ========================");
 
                        do {
-                               httpAgent->setSession(&reqEntity);
 
-                               if (submitHandler(&reqEntity) != eMMS_HTTP_SENT_SUCCESS) {
+                               if (submitHandler(&reqEntity) != eMMS_SUCCESS) {
                                        MSG_DEBUG("Transaction Error: submit failed");
 
                                        MmsPluginEventHandler::instance()->handleMmsError(&reqEntity);
-                                       mmsTranQ.pop_front();
+                                       lock();
+                                       mmsTranQ.remove(reqEntity, compare_func_for_removal);
+                                       //mmsTranQ.pop_front();
+                                       unlock();
                                        //try to next mmsTranQ
                                        break;
                                }
 
                                MSG_DEBUG("submitHandler(&reqEntity) success.");
-                               trId = httpAgent->getHttpConfigData()->transactionId;
 
                                MSG_DEBUG("#### MMS PDU TYPE = %d ####", reqEntity.eMmsPduType);
 
                                if (reqEntity.eMmsPduType == eMMS_NOTIFYRESP_IND ||
-                                       reqEntity.eMmsPduType == eMMS_ACKNOWLEDGE_IND ||
-                                       reqEntity.eMmsPduType == eMMS_READREC_IND ||
-                                       reqEntity.eMmsPduType == eMMS_CANCEL_CONF) {
+                                               reqEntity.eMmsPduType == eMMS_ACKNOWLEDGE_IND ||
+                                               reqEntity.eMmsPduType == eMMS_READREC_IND ||
+                                               reqEntity.eMmsPduType == eMMS_CANCEL_CONF) {
                                        reqEntity.isCompleted = true;
-
-                                       mmsTranQ.pop_front();
-
+                                       lock();
+                                       mmsTranQ.remove(reqEntity, compare_func_for_removal);
+                                       //mmsTranQ.pop_front();
+                                       unlock();
                                        MSG_DEBUG("Transaction Completed");
                                        break;
                                } else {
@@ -367,9 +448,10 @@ void MmsPluginUaManager::run()
                                        updatePduType(&reqEntity);
                                        MSG_DEBUG("Waiting Conf");
                                }
-
-                               mmsTranQ.pop_front();
-
+                               lock();
+                               mmsTranQ.remove(reqEntity, compare_func_for_removal);
+                               //mmsTranQ.pop_front();
+                               unlock();
                                //////// Waiting Conf //////////////////////
                                MMS_NET_ERROR_T networkErr;
 
@@ -404,7 +486,6 @@ void MmsPluginUaManager::run()
                                        }
 
                                        MSG_DEBUG("conf received successfully");
-
                                        try {
                                                MmsPluginEventHandler::instance()->handleMmsReceivedData(&reqEntity, retrievedFilePath);
                                        } catch (MsgException& e) {
@@ -415,7 +496,7 @@ void MmsPluginUaManager::run()
                                                break;
                                        }
 
-                                       MsgSettingGetBool(MMS_RECV_DELIVERY_RECEIPT, &bReportAllowed);
+                                       MsgSettingGetBool(MMS_SEND_REPORT_ALLOWED, &bReportAllowed);
 
                                        MSG_DEBUG("conf received successfully -2");
                                        MSG_DEBUG("reqEntity.eMmsPduType [%d]", reqEntity.eMmsPduType);
@@ -453,13 +534,17 @@ void MmsPluginUaManager::run()
                                                }
 
                                                reqEntity.pPostData = MsgOpenAndReadMmsFile(filepath, 0, -1, &reqEntity.postDataLen);
-
+                                               lock();
                                                mmsTranQ.push_front(reqEntity);
-
-                                               remove(filepath);
+                                               unlock();
+                                               if (remove(filepath) != 0) {
+                                                       MSG_DEBUG("Error removing file");
+                                               }
 
                                                MSG_DEBUG("Submit Ind");
-                                       } else if (reqEntity.eMmsPduType == eMMS_RETRIEVE_MANUAL_CONF) {
+                                       }
+                                       else if (reqEntity.eMmsPduType == eMMS_RETRIEVE_MANUAL_CONF)
+                                       {
                                                /* saved msg trId should be checked  */
                                                // Send Acknowledge Ind
                                                char filepath[MAX_FULL_PATH_SIZE] = {0};
@@ -492,9 +577,9 @@ void MmsPluginUaManager::run()
                                                }
 
                                                reqEntity.pPostData = MsgOpenAndReadMmsFile(filepath, 0, -1, &reqEntity.postDataLen);
-
+                                               lock();
                                                mmsTranQ.push_front(reqEntity);
-
+                                               unlock();
                                                remove(filepath); // not ipc
 
                                                MSG_DEBUG("Submit Ack");
@@ -507,6 +592,7 @@ void MmsPluginUaManager::run()
                                        MmsPluginEventHandler::instance()->handleMmsError(&reqEntity);
                                        break;
                                }
+
                        } while (reqEntity.isCompleted == false);
 
                        MSG_DEBUG("==== MMS Transaction Completed ====\n\n");
@@ -521,8 +607,6 @@ void MmsPluginUaManager::run()
                                reqEntity.pGetData = NULL;
                        }
 
-                       // Http Session Close
-                       httpAgent->clearSession();
                }
 
                // Request CM Close
@@ -530,39 +614,6 @@ void MmsPluginUaManager::run()
 
        }
 
-CLEANUP:
-       MSG_DEBUG("CLEANUP");
-
-       while (!mmsTranQ.empty()) {
-               MSG_DEBUG("clear mmsTranQ");
-
-               mmsTranQEntity reqEntity;
-               memset(&reqEntity, 0, sizeof(mmsTranQEntity));
-
-               mmsTranQ.front(&reqEntity);
-
-               // notify send fail to APP
-               MmsPluginEventHandler::instance()->handleMmsError(&reqEntity);
-
-               if (reqEntity.pGetData) {
-                       MSG_DEBUG("free pGetData");
-                       free(reqEntity.pGetData);
-                       reqEntity.pGetData = NULL;
-               }
-
-               if (reqEntity.pPostData) {
-                       MSG_DEBUG("free pPostData");
-                       free(reqEntity.pPostData);
-                       reqEntity.pPostData = NULL;
-               }
-
-               mmsTranQ.pop_front();
-       }
-
-       mmsTranQ.clear();
-       MutexLocker locker(mx);
-       running = false;
-
        MSG_END();
 
        return;
@@ -570,89 +621,88 @@ CLEANUP:
 
 void MmsPluginUaManager::getMmsPduData(mmsTranQEntity *qEntity)
 {
+       lock();
        mmsTranQ.front(qEntity);
+       unlock();
 }
 
 void MmsPluginUaManager::addMmsReqEntity(mmsTranQEntity req)
 {
-       MSG_DEBUG("New MMS Tran Added");
-       mmsTranQ.push_back(req);
        lock();
+       if (mmsTranQ.checkExist(req, compare_func) == true) {
+               MSG_DEBUG("request Already Exist, req_id = %d", req.msgId);
+               unlock();
+               THROW(MsgException::REQ_EXIST_ERROR, "MMS request already exist");
+       }
+       mmsTranQ.push_back(req);
        signal();
        unlock();
+
+       MSG_DEBUG("New MMS Tran Added");
 }
 
 bool MmsPluginUaManager::processReceivedData(int msgId, char *pRcvdBody, int rcvdBodyLen, char *retrievedFilePath)
 {
        MSG_BEGIN();
 
+       //CID 317909 : replacing MSG_FILENAME_LEN_MAX with MAX_FULL_PATH_SIZE as the latter is max length for internal file path
+       //                              and size of retrievedFilePath in calling function is same i.e. MAX_FULL_PATH_SIZE+1
+       //CID 358483 : Making fileName smaller causes buffer overflow in MsgCreateFileName function.
+       //                      So We will keep it 1024 as before but only copy 320 out of it which is the size of retrievedFilePath buffer.
        char fileName[MSG_FILENAME_LEN_MAX] = {0};
-       FILE *pFile = NULL;
+       //char fileName[MAX_FULL_PATH_SIZE] = {0};
 
        MSG_DEBUG(":::%d :%s ", rcvdBodyLen, pRcvdBody);
 
-       _MmsInitHeader();
-       _MmsRegisterDecodeBuffer(gszMmsLoadBuf1,  gszMmsLoadBuf2, MSG_MMS_DECODE_BUFFER_MAX);
+       MmsInitHeader();
+       MmsRegisterDecodeBuffer();
 
        if (MsgCreateFileName(fileName) == false)
                return false;
 
-       snprintf(retrievedFilePath, MSG_FILEPATH_LEN_MAX, MSG_DATA_PATH"%s", fileName);
+       //CID 317909 : replacing MSG_FILENAME_LEN_MAX with MAX_FULL_PATH_SIZE as the latter is max length for internal file path
+       //                              and size of retrievedFilePath in calling function is same i.e. MAX_FULL_PATH_SIZE+1
+       //snprintf(retrievedFilePath, MSG_FILEPATH_LEN_MAX, "%s%s", MSG_DATA_PATH, fileName);
+       snprintf(retrievedFilePath, MAX_FULL_PATH_SIZE, "%s%s", MSG_DATA_PATH, fileName);
 
-       MSG_DEBUG("retrievedFilePaths [%s]", retrievedFilePath);
+       MSG_INFO("retrievedFilePaths [%s]", retrievedFilePath);
 
        // create temp file
        if (!MsgOpenCreateAndOverwriteFile(retrievedFilePath, (char *)pRcvdBody, rcvdBodyLen)) {
-               MSG_DEBUG( "_MmsUaInitMsgDecoder: creating temporary file failed(msgID=%d)\n", msgId);
+               MSG_ERR( "_MmsUaInitMsgDecoder: creating temporary file failed(msgID=%d)\n", msgId);
                return false;
        }
+#if 1 //
+       MmsMsg *pMsg;
 
-       if (_MmsReadMsgBody(msgId, true, true, retrievedFilePath) == false) {
-               MSG_DEBUG("The MMS Message might include drm contents!!!");
-
-#ifdef __SUPPORT_DRM__
-               if (MmsDrm2GetConvertState() == MMS_DRM2_CONVERT_REQUIRED) {
-                       bool bRetToConvert = true;
-                       MSG_MESSAGE_INFO_S pMsg = {0, };
+       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
 
-                       pMsg.msgId = msgId;
+       memset(pMsg, 0, sizeof(MmsMsg));
 
-                       bRetToConvert = MmsDrm2ConvertMsgBody(mmsHeader.msgType.szOrgFilePath);
+       MmsPluginDecoder::instance()->decodeMmsPdu(pMsg, msgId, retrievedFilePath);
+#else //
+       if (MmsReadMsgBody(msgId, true, true, retrievedFilePath) == false) {
+               MSG_INFO("The MMS Message might include drm contents!!!");
 
-                       MmsDrm2SetConvertState(MMS_DRM2_CONVERT_FINISH);
-
-                       if (bRetToConvert) {
-                               remove(mmsHeader.msgType.szOrgFilePath);
-                               rename(MMS_DECODE_DRM_CONVERTED_TEMP_FILE, mmsHeader.msgType.szOrgFilePath);
-
-                               if (MmsDrm2ReadMsgConvertedBody(&pMsg, true, true, retrievedFilePath) == false) {
-                                       MSG_DEBUG("MmsLoadMsg:MmsDrm2ReadMsgConvertedBody() returns false\n");
-                                       goto ERR_MMS_UA_PROCESS_CONF;
-                               }
-                       }
-               }
-#endif
-       }
-
-       MSG_END();
-
-       return true;
-
-ERR_MMS_UA_PROCESS_CONF:
-       {
                MmsMsg *pMsg;
                MmsPluginStorage::instance()->getMmsMessage(&pMsg);
 
 
-               _MmsInitHeader();
-               _MmsUnregisterDecodeBuffer();
+               MmsInitHeader();
+               MmsUnregisterDecodeBuffer();
 
-#ifdef __SUPPORT_DRM__
-               _MsgFreeDRMInfo(&pMsg->msgType.drmInfo);
-#endif
-               _MsgFreeBody(&pMsg->msgBody, pMsg->msgType.type);
+
+               MmsReleaseMsgDRMInfo(&pMsg->msgType.drmInfo);
+               MmsReleaseMsgBody(&pMsg->msgBody, pMsg->msgType.type);
+
+               MSG_END();
 
                return false;
        }
+#endif
+       MSG_END();
+
+       return true;
 }
 
+
diff --git a/plugin/mms_plugin/MmsPluginUtil.cpp b/plugin/mms_plugin/MmsPluginUtil.cpp
new file mode 100755 (executable)
index 0000000..ccbffcd
--- /dev/null
@@ -0,0 +1,457 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include <mm_file.h>
+#include <mm_util_jpeg.h>
+#include <mm_util_imgp.h>
+#include <media-thumbnail.h>
+#include <ctype.h>
+#include <errno.h>
+#include <sys/stat.h>
+#include "MsgUtilFile.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginUtil.h"
+#include <string>
+using namespace std;
+
+bool MmsMakeImageThumbnail(char *srcPath, char *dstPath)
+{
+       if (srcPath == NULL || dstPath == NULL) {
+               MSG_DEBUG(MMS_DEBUG_STR_INVALID_PARAM" src = %p, dst = %p", srcPath, dstPath);
+               return false;
+       }
+
+       if (MsgAccessFile(srcPath, R_OK) == false) {
+               MSG_DEBUG("not exist source file [%s]", srcPath);
+               return false;
+       }
+
+       int err = -1;
+       err = thumbnail_request_save_to_file(srcPath, MEDIA_THUMB_LARGE, dstPath);
+       if (err < 0) {
+               MSG_DEBUG("Make thumbnail: failed, err = %d", err);
+               return false;
+       }
+
+       if (MsgAccessFile(dstPath, F_OK) == false) {
+               MSG_DEBUG("not exist result file [%s]", dstPath);
+               return false;
+       }
+
+       MSG_DEBUG("Make thumbnail: success [%s]", dstPath);
+       return true;
+}
+
+bool MmsMakeVideoThumbnail(char *srcPath, char *dstPath)
+{
+       MMHandleType content_attrs = (MMHandleType)NULL;
+       char *err_attr_name = NULL;
+       int fileRet = 0;
+       int trackCount = 0;
+
+       if (srcPath == NULL || dstPath == NULL) {
+               MSG_DEBUG(MMS_DEBUG_STR_INVALID_PARAM" src = %p, dst = %p", srcPath, dstPath);
+               return false;
+       }
+
+       if (MsgAccessFile(srcPath, R_OK) == false) {
+               MSG_DEBUG("not exist source file [%s]", srcPath);
+               return false;
+       }
+
+       fileRet = mm_file_create_content_attrs(&content_attrs, srcPath);
+       if (fileRet != 0) {
+               mm_file_destroy_content_attrs(content_attrs);
+               MSG_DEBUG("mm_file_create_content_attrs fail [%d]", fileRet);
+               return false;
+       }
+
+       fileRet = mm_file_get_attrs(content_attrs, &err_attr_name, MM_FILE_CONTENT_VIDEO_TRACK_COUNT, &trackCount, NULL);
+       if (fileRet != 0) {
+               MSG_SEC_DEBUG("mm_file_get_attrs fails [%s]", err_attr_name);
+
+               if (err_attr_name) {
+                       free(err_attr_name);
+                       err_attr_name = NULL;
+               }
+
+               mm_file_destroy_content_attrs(content_attrs);
+
+               return false;
+       }
+
+       MSG_DEBUG("video track num: %d", trackCount);
+
+       if (trackCount <= 0) {
+               mm_file_destroy_content_attrs(content_attrs);
+               return false;
+       }
+
+
+       int thumbnailWidth = 0;
+       int thumbnailHeight = 0;
+       int thumbnailSize = 0;
+       void *thumbnail = NULL;
+
+       fileRet = mm_file_get_attrs(content_attrs, &err_attr_name, MM_FILE_CONTENT_VIDEO_WIDTH, &thumbnailWidth,
+                                                                                                                               MM_FILE_CONTENT_VIDEO_HEIGHT, &thumbnailHeight,
+                                                                                                                               MM_FILE_CONTENT_VIDEO_THUMBNAIL, &thumbnail, &thumbnailSize,
+                                                                                                                               NULL);
+
+       if (fileRet != 0) {
+               MSG_SEC_DEBUG("mm_file_get_attrs fails [%s]", err_attr_name);
+               if (err_attr_name) {
+                       free(err_attr_name);
+                       err_attr_name = NULL;
+               }
+
+               mm_file_destroy_content_attrs(content_attrs);
+               return false;
+       }
+
+       MSG_DEBUG("video width: %d", thumbnailWidth);
+       MSG_DEBUG("video height: %d", thumbnailHeight);
+       MSG_DEBUG("video thumbnail: %p", thumbnail);
+
+       if (thumbnail == NULL) {
+               mm_file_destroy_content_attrs(content_attrs);
+               return false;
+       }
+
+       fileRet = mm_util_jpeg_encode_to_file (dstPath, thumbnail, thumbnailWidth, thumbnailHeight, MM_UTIL_JPEG_FMT_RGB888, 70);
+       if (fileRet != 0) {
+               MSG_DEBUG("mm_util_jpeg_encode_to_file fails [%d]", fileRet);
+               mm_file_destroy_content_attrs(content_attrs);
+               return false;
+       }
+
+       if (MsgAccessFile(dstPath, F_OK) == false) {
+               MSG_DEBUG("not exist result file [%s]", dstPath);
+               mm_file_destroy_content_attrs(content_attrs);
+               return false;
+       }
+
+       MSG_DEBUG("Make thumbnail: success [%s]", dstPath);
+       mm_file_destroy_content_attrs(content_attrs);
+       return true;
+}
+
+FILE *MmsFileOpen(char *pFileName)
+{
+       mode_t file_mode = (S_IRUSR | S_IWUSR);
+
+       if (!pFileName) {
+               MSG_DEBUG("pFileName NULL: %s", g_strerror(errno));
+               return NULL;
+       }
+
+       MSG_DEBUG("pFileName = %s", pFileName);
+
+       FILE *pFile = MsgOpenFile(pFileName, "wb+");
+
+       if (pFile == NULL) {
+               MSG_FATAL("File Open Error: %s", g_strerror(errno));
+               return NULL;
+       }
+
+       if (MsgFseek(pFile, 0L, SEEK_CUR) < 0) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Read Error: %s", g_strerror(errno));
+               return NULL;
+       }
+
+       if (fchmod(fileno(pFile), file_mode) < 0) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File chmod Error: %s", g_strerror(errno));
+               return NULL;
+       }
+
+       return pFile;
+}
+
+
+bool MmsIsAsciiString(const char *pszText)
+{
+       if (pszText == NULL) {
+               MSG_DEBUG(MMS_DEBUG_STR_INVALID_PARAM" pszText = %p", pszText);
+               return false;
+       }
+
+       int length = strlen(pszText);
+       if (length <= 0) {
+               MSG_DEBUG("Input parameter is NULL string");
+               return false;
+       }
+
+       for (int i = 0; i < length; ++i) {
+               if (!isascii(pszText[i])) {
+                       MSG_DEBUG("It is not Ascii code");
+                       return false;
+               }
+       }
+
+       MSG_DEBUG("It is Ascii code");
+       return true;
+}
+
+void MmsRemoveLessGreaterChar(const char *szSrcID, char *szDest, int destSize)
+{
+       char szBuf[MSG_MSG_ID_LEN + 1] = {0, };
+       int cLen = strlen(szSrcID);
+
+       if (cLen > 1 && szSrcID[0] == '<' && szSrcID[cLen - 1] == '>') {
+               strncpy(szBuf, &szSrcID[1], cLen - 2);
+               szBuf[cLen - 2] = '\0';
+       } else if (cLen > 1 && szSrcID[0] == '"' && szSrcID[cLen-1] == '"') {
+               strncpy(szBuf, &szSrcID[1], cLen - 2);
+               szBuf[cLen - 2] = '\0';
+       } else {
+               strncpy(szBuf, szSrcID, cLen);
+               szBuf[cLen] = '\0';
+       }
+
+       snprintf(szDest, destSize, "%s", szBuf);
+}
+
+bool MmsRemoveMarkup(const char *src, char *dst, int dstsize)
+{
+       const int M_IN = 1;
+       const int M_OUT = 0;
+
+       int state = M_OUT;
+       const char *srcptr = NULL;
+       char *dstptr = NULL;
+
+       if (src == NULL || dst == NULL || dstsize == 0)
+               return false;
+
+       dstptr = dst;
+       srcptr = src;
+
+       while (*srcptr != '\0' && ((dstptr-dst) < dstsize)) {
+
+               if (*srcptr == '<') state = M_IN;
+               if (*srcptr == '>') state = M_OUT;
+
+               if (state == M_OUT && *srcptr != '<' && *srcptr != '>') {
+                       *dstptr = *srcptr;
+                       dstptr++;
+               }
+
+               srcptr++;
+       }
+
+       if (((dstptr-dst) < dstsize)) {
+               *dstptr = '\0';
+       } else {
+               *(dst + dstsize -1) = '\0';
+       }
+
+       return true;
+}
+
+//change character ' ' to '_'
+bool MmsReplaceSpaceChar(char *pszText)
+{
+       if (!pszText) {
+               return false;
+       }
+
+       char *spaceCharPtr = strchr(pszText, ' ');
+
+       while (spaceCharPtr) {
+
+               *spaceCharPtr = '_';
+
+               spaceCharPtr = strchr(pszText, ' ');
+       }
+
+       return true;
+}
+
+char *MmsReplaceNonAsciiUtf8(const char *szSrc, char replaceChar)
+{
+       int offset = 0;
+       int srcLen = 0;
+       const unsigned char *ptr = NULL;
+       unsigned char b1, b2, b3, b4;
+       string str;
+
+       if (szSrc == NULL) {
+               return NULL;
+       }
+
+       srcLen = strlen(szSrc);
+
+       if (srcLen == 0) {
+               return NULL;
+       }
+
+       ptr = (const unsigned char*)szSrc;
+
+       while(offset < srcLen && *(ptr) != '\0') {
+
+               b1 = *(ptr);
+
+               if ((b1 & 0x80) == 0) { //1byte : 0xxx xxxx
+                       offset += 1;
+                       ptr += 1;
+
+                       str += b1;
+               } else  if ((b1 & 0xE0) == 0xC0) { //2byte : 110x xxxx
+                       offset += 2;
+
+                       if (offset > srcLen)
+                               return NULL;
+
+                       b2 = *(ptr + 1);
+
+                       if (b2 >= 0x80) { //10xx xxxx
+                               ptr += 2;
+                               str += replaceChar;
+                       } else {
+                               return NULL;
+                       }
+
+               } else  if ((b1 & 0xF0) == 0xE0) { //3byte : 1110 xxxx
+
+                       offset += 3;
+
+                       if (offset > srcLen)
+                               return NULL;
+
+                       b2 = *(ptr + 1);
+                       b3 = *(ptr + 2);
+
+                       if (b2 >= 0x80 && b3 >= 0x80) { //10xx xxxx
+                               ptr += 3;
+                               str += replaceChar;
+                       } else {
+                               return NULL;
+                       }
+
+               } else  if ((b1 & 0xF8) == 0xF0) { //4byte : 1111 xxxx
+
+                       offset += 4;
+
+                       if (offset > srcLen)
+                               return NULL;
+
+                       b2 = *(ptr + 1);
+                       b3 = *(ptr + 2);
+                       b4 = *(ptr + 3);
+
+                       if (b2 >= 0x80 && b3 >= 0x80 && b4 >= 0x80) { //10xx xxxx
+                               ptr += 4;
+                               str += replaceChar;
+
+                       } else {
+                               return NULL;
+                       }
+               } else {
+                       return NULL;
+               }
+       }
+
+
+       if (str.empty() == true) {
+               return NULL;
+       }
+
+       MSG_DEBUG("str is UTF-8 [%s]", str.c_str());
+
+       return g_strdup(str.c_str());
+}
+
+bool MmsIsUtf8String(const unsigned char *szSrc, int nChar)
+{
+       int offset = 0;
+       int srcLen = 0;
+       const unsigned char *ptr;
+       unsigned char b1, b2, b3, b4;
+
+       if (szSrc == NULL) {
+               return false;
+       }
+
+       srcLen = nChar;
+
+       if (srcLen == 0) {
+               return true;
+       }
+
+       ptr = (const unsigned char*)szSrc;
+
+       while(offset < srcLen && *(ptr) != '\0') {
+
+               b1 = *(ptr);
+
+               if ((b1 & 0x80) == 0) { //1byte : 0xxx xxxx
+                       offset += 1;
+                       ptr += 1;
+               } else  if ((b1 & 0xE0) == 0xC0) { //2byte : 110x xxxx
+                       offset += 2;
+
+                       if (offset > srcLen)
+                               return false;
+
+                       b2 = *(ptr + 1);
+
+                       if (b2 >= 0x80) { //10xx xxxx
+                               ptr += 2;
+                       } else {
+                               return false;
+                       }
+
+               } else  if ((b1 & 0xF0) == 0xE0) { //3byte : 1110 xxxx
+
+                       offset += 3;
+
+                       if (offset > srcLen)
+                               return false;
+
+                       b2 = *(ptr + 1);
+                       b3 = *(ptr + 2);
+
+                       if (b2 >= 0x80 && b3 >= 0x80) { //10xx xxxx
+                               ptr += 3;
+                       } else {
+                               return false;
+                       }
+
+               } else  if ((b1 & 0xF8) == 0xF0) { //4byte : 1111 xxxx
+
+                       offset += 4;
+
+                       if (offset > srcLen)
+                               return false;
+
+                       b2 = *(ptr + 1);
+                       b3 = *(ptr + 2);
+                       b4 = *(ptr + 3);
+
+                       if (b2 >= 0x80 && b3 >= 0x80 && b4 >= 0x80) { //10xx xxxx
+                               ptr += 4;
+                       } else {
+                               return false;
+                       }
+               } else {
+                       return false;
+               }
+       }//while
+
+       return true;
+}
diff --git a/plugin/mms_plugin/include/MmsPluginAppBase.h b/plugin/mms_plugin/include/MmsPluginAppBase.h
new file mode 100755 (executable)
index 0000000..f1e2c28
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MMS_PLUGIN_APPBASE_H
+#define MMS_PLUGIN_APPBASE_H
+
+#include "MmsPluginTypes.h"
+
+//Set Data for Message App
+class MmsPluginAppBase {
+public:
+       MmsPluginAppBase();
+       MmsPluginAppBase(MMS_DATA_S *pMsgData);
+       MmsPluginAppBase(MmsMsg *pMmsMsg);
+       ~MmsPluginAppBase();
+
+       void setMmsData(MMS_DATA_S *pMmsData);
+       void setMmsData(MmsMsg *pMmsMsg);
+
+       void makePreviewInfo(msg_message_id_t  msgId, bool allow_malware, const char *raw_filepath);
+
+       void getFirstPageTextFilePath(char *textBuf, int textBufSize);
+private:
+       MMS_MESSAGE_DATA_S mmsMsgData;
+};
+#endif //MMS_PLUGIN_APPBASE_H
diff --git a/plugin/mms_plugin/include/MmsPluginAvCodec.h b/plugin/mms_plugin/include/MmsPluginAvCodec.h
deleted file mode 100755 (executable)
index 84ac70e..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include "MsgTypes.h"
-
-#define        FILEEXT_MAX     5
-
-typedef enum {
-       AV_CODEC_NONE                                           = 0x00000000,
-       AV_CODEC_AUDIO_REAL                                     = 0x00000001,
-       AV_CODEC_AUDIO_AMR                                      = 0x00000002,           // AMR
-       AV_CODEC_AUDIO_G723_1                           = 0x00000004,           // G723.1
-       AV_CODEC_AUDIO_MP3                                      = 0x00000008,           // MP3
-       AV_CODEC_AUDIO_AAC                                      = 0x00000010,           // AAC
-       AV_CODEC_AUDIO_MIDI                                     = 0x00000020,           // MIDI
-       AV_CODEC_AUDIO_MMF                                      = 0x00000040,           // MMF
-       AV_CODEC_AUDIO_MMF_PHRASE_L1            = 0x00000080,           // YAMAHA Phrase L1
-       AV_CODEC_AUDIO_ADPCM                            = 0x00000100,           // ADPCM
-       AV_CODEC_AUDIO_WAVE                                     = 0x00000200,           // WAVE
-       AV_CODEC_AUDIO_IMELODY                          = 0x00000400,           // IMELODY
-       AV_CODEC_AUDIO_DTMF_TONE                        = 0x00000800,           // DTMF
-       AV_CODEC_AUDIO_DTMF_TONE_ID                     = 0x00001000,
-       AV_CODEC_AUDIO_DTMF_TONE_FREQ           = 0x00002000,
-       AV_CODEC_AUDIO_DTMF_SOUND_ID            = 0x00004000,
-       AV_CODEC_AUDIO_DTMF_TONE_FLEX           = 0x00008000,           // DTMF
-       AV_CODEC_AUDIO_MPEG4                            = 0x00010000,           // MPEG4 audio
-       AV_CODEC_AUDIO_SPM                                      = 0x00020000,           // SPM(SP-MIDI)
-       AV_CODEC_AUDIO_PCM                                      = 0x00040000,
-       AV_CODEC_AUDIO_XMF                                      = 0x00080000,           // XMF
-       AV_CODEC_VIDEO_H263                                     = 0x00400000,           // H.26L
-       AV_CODEC_VIDEO_MPEG4                            = 0x02000000,           // MPEG4 video
-       AV_CODEC_VIDEO_AVI                                      = 0x04000000,           // MPEG4 video
-       AV_CODEC_VIDEO_MPEG1                            = 0x08000000,           // MPEG4 video
-       AV_CODEC_VIDEO_REAL                                     = 0x10000000,
-       AV_CODEC_VIDEO_PVX                                      = 0x20000000,            // for Fast Track .PVX type
-
-       AV_ENC_AUDIO_AMR                                        = AV_CODEC_AUDIO_AMR,           // AMR
-       AV_ENC_AUDIO_G723_1                                     = AV_CODEC_AUDIO_G723_1,        // G723.1
-       AV_ENC_AUDIO_MP3                                        = AV_CODEC_AUDIO_MP3,           // MP3
-       AV_ENC_AUDIO_AAC                                        = AV_CODEC_AUDIO_AAC,           // AAC
-       AV_ENC_AUDIO_ADPCM                                      = AV_CODEC_AUDIO_ADPCM,         // ADPCM
-       AV_ENC_AUDIO_WAVE                                       = AV_CODEC_AUDIO_WAVE,          // WAVE
-       AV_ENC_VIDEO_H263                                       = AV_CODEC_VIDEO_H263,          // H.263
-       AV_ENC_VIDEO_MPEG4                                      = AV_CODEC_VIDEO_MPEG4,         // MPEG4
-       AV_ENC_VIDEO_AVI                                        = AV_CODEC_VIDEO_AVI,           // AVI
-       AV_ENC_VIDEO_MPEG1                                      = AV_CODEC_VIDEO_MPEG1,         // MPEG1
-
-       AV_DEC_AUDIO_DTMF_TONE_FLEX                     = AV_CODEC_AUDIO_DTMF_TONE_FLEX,        // DTMF
-       AV_DEC_AUDIO_AMR                                        = AV_CODEC_AUDIO_AMR,           // AMR
-       AV_DEC_AUDIO_G723_1                                     = AV_CODEC_AUDIO_G723_1,        // G723.1
-       AV_DEC_AUDIO_MP3                                        = AV_CODEC_AUDIO_MP3,           // MP3
-       AV_DEC_AUDIO_AAC                                        = AV_CODEC_AUDIO_AAC,           // AAC
-       AV_DEC_AUDIO_MIDI                                       = AV_CODEC_AUDIO_MIDI,          // MIDI
-       AV_DEC_AUDIO_MMF                                        = AV_CODEC_AUDIO_MMF,           // MMF
-       AV_DEC_AUDIO_MMF_PHRASE_L1                      = AV_CODEC_AUDIO_MMF_PHRASE_L1,         // YAMAHA Phrase L1
-       AV_DEC_AUDIO_ADPCM                                      = AV_CODEC_AUDIO_ADPCM,         // ADPCM
-       AV_DEC_AUDIO_WAVE                                       = AV_CODEC_AUDIO_WAVE,          // WAVE
-       AV_DEC_AUDIO_IMELODY                            = AV_CODEC_AUDIO_IMELODY,               // IMELODY
-       AV_DEC_AUDIO_DTMF_TONE                          = AV_CODEC_AUDIO_DTMF_TONE,             // DTMF
-       AV_DEC_AUDIO_DTMF_TONE_ID                       = AV_CODEC_AUDIO_DTMF_TONE_ID,
-       AV_DEC_AUDIO_DTMF_TONE_FREQ                     = AV_CODEC_AUDIO_DTMF_TONE_FREQ,
-       AV_DEC_AUDIO_DTMF_SOUND_ID                      = AV_CODEC_AUDIO_DTMF_SOUND_ID,
-       AV_DEC_AUDIO_MPEG4                                      = AV_CODEC_AUDIO_MPEG4,         // MPEG4 audio
-       AV_DEC_AUDIO_SPM                                        = AV_CODEC_AUDIO_SPM,           // SPM(SP-MIDI)
-       AV_DEC_AUDIO_XMF                                        = AV_CODEC_AUDIO_XMF,           // XMF
-       AV_DEC_AUDIO_REAL                                       = AV_CODEC_AUDIO_REAL,          // MPEG4 video
-
-       AV_DEC_VIDEO_H263                                       = AV_CODEC_VIDEO_H263,          // H.26L
-       AV_DEC_VIDEO_MPEG4                                      = AV_CODEC_VIDEO_MPEG4,         // MPEG4 video
-       AV_DEC_VIDEO_AVI                                        = AV_CODEC_VIDEO_AVI,           // AVI
-       AV_DEC_VIDEO_MPEG1                                      = AV_CODEC_VIDEO_MPEG1,         // MPEG1
-
-       AV_DEC_VIDEO_REAL                                       = AV_CODEC_VIDEO_REAL,                  // REAL VIDEO DEC
-
-       AV_DEC_VIDEO_PVX                                        = AV_CODEC_VIDEO_PVX,                //for .PVX
-
-} AvCodecType;
-
-AvCodecType    AvGetFileCodecType(const char *szFileName);
index ebd8cca..0633099 100755 (executable)
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MMS_PLUGIN_CODEC_H
 #define MMS_PLUGIN_CODEC_H
 
+#include "MmsPluginCodecTypes.h"
+#include "MmsPluginCodecCommon.h"
+#include "MmsPluginEncode.h"
+#include "MmsPluginDecode.h"
 
-/*==================================================================================================
-                                                       HEADER
-==================================================================================================*/
-
-#include <glib.h>
-#include <vconf.h>
-#include "MsgMmsTypes.h"
-#include "MmsPluginMessage.h"
-#include "MsgTransportTypes.h"
-
-/*==================================================================================================
-                                                       DEFINE
-==================================================================================================*/
-
-#define        MMS_MAJOR_VERSION                       1
-
-#if defined(MMS_V1_1)
-#define        MMS_MINOR_VERSION                       1
-#define        MMS_VERSION                                     0x91
-
-#elif defined(MMS_V1_2)
-#define        MMS_MINOR_VERSION                       2
-#define        MMS_VERSION                                     0x92
-
-#else
-#define        MMS_MINOR_VERSION                       0
-#define        MMS_VERSION                                     0x90
-#endif
-
-#define        MMS_SIGN_TEXT_LEN                       100
-#define        MMS_MAX_FIELD_VALUE_COUNT       74
-#define        MMS_MAX_FIELD_TYPE_COUNT        21
-#define        MSG_MMS_ENCODE_BUFFER_MAX       (2 * 1024)
-#define        MSG_MMS_DECODE_BUFFER_MAX       (2 * 1024)
-#define        MSB                                                             0x80
-#define        QUOTE                                                   0x7F
-#define        MARK                                                    0x22    // "
-#define        NO_VALUE                                                0x00
-#define        LENGTH_QUOTE                                    0x1F
-#define        MSG_STDSTR_LONG                         0xFF
-#define        INVALID_VALUE                                   -1
-#define        MSG_INVALID_VALUE                               -1
-
-#define        MMS_MAX_FIELD_VALUE_COUNT       74
-#define        MMS_MAX_FIELD_TYPE_COUNT        21
-
-#define MSG_LOCAL_TEMP_BUF_SIZE 1024
-#define MSG_INBOX_DIRECTORY                    "/User/Msg/Inbox"
-/*==================================================================================================
-                                                       ENUMS
-==================================================================================================*/
-
-typedef enum {
-       MMS_CODE_BCC,
-       MMS_CODE_CC,
-       MMS_CODE_CONTENTLOCATION,
-       MMS_CODE_CONTENTTYPE,
-       MMS_CODE_DATE,
-       MMS_CODE_DELIVERYREPORT,
-       MMS_CODE_DELIVERYTIME,
-       MMS_CODE_EXPIRYTIME,
-       MMS_CODE_FROM,
-       MMS_CODE_MSGCLASS,
-       MMS_CODE_MSGID,
-       MMS_CODE_MSGTYPE,
-       MMS_CODE_VERSION,
-       MMS_CODE_MSGSIZE,
-       MMS_CODE_PRIORITY,
-       MMS_CODE_READREPLY,
-       MMS_CODE_REPORTALLOWED,
-       MMS_CODE_RESPONSESTATUS,
-       MMS_CODE_RETRIEVESTATUS,                /* Add by MMSENC v1.1 */
-       MMS_CODE_RESPONSETEXT,
-       MMS_CODE_RETRIEVETEXT,                  /* Add by MMSENC v1.1 */
-       MMS_CODE_SENDERVISIBILLITY,
-       MMS_CODE_MSGSTATUS,
-       MMS_CODE_SUBJECT,
-       MMS_CODE_TO,
-       MMS_CODE_TRID,
-
-       /* Add by MMSENC v1.1 */
-       MMS_CODE_READSTATUS,
-       MMS_CODE_REPLYCHARGING,
-       MMS_CODE_REPLYCHARGINGDEADLINE,
-       MMS_CODE_REPLYCHARGINGID,
-       MMS_CODE_REPLYCHARGINGSIZE,
-       MMS_CODE_PREVIOUSLYSENTBY,
-       MMS_CODE_PREVIOUSLYSENTDATE,
-
-       MMS_CODE_TRANSFERENCODING,
-       MMS_CODE_DISPOSITION,
-       MMS_CODE_CONTENT_ID
-} MmsFieldCode;
-
-enum {
-       MMS_BODYHDR_TRANSFERENCODING,
-       MMS_BODYHDR_DISPOSITION,
-       MMS_BODYHDR_CONTENTID,
-       MMS_BODYHDR_CONTENTLOCATION,
-       MMS_BODYHDR_X_OMA_DRM_SEPARATE_DELIVERY,        // DRM RO WAITING
-};
-
-typedef enum {
-       //code
-       MmsCodeFieldCode,
-       MmsCodeParameterCode,
-       MmsCodeMsgBodyHeaderCode,
-
-       //Data
-       MmsCodeMsgType,
-       MmsCodeDeliveryReport,
-       MmsCodeTimeType,
-       MmsCodeMsgClass,
-       MmsCodePriority,
-       MmsCodeResponseStatus,
-       MmsCodeRetrieveStatus,
-       MmsCodeReadReply,
-       MmsCodeReportAllowed,
-       MmsCodeSenderVisibility,
-       MmsCodeMsgStatus,
-       MmsCodeReadStatus,
-       MmsCodeAddressType,
-       MmsCodeCharSet,
-       MmsCodeReplyCharging,
-
-       MmsCodeContentType,
-
-       MmsCodeMsgDisposition,
-       MmsCodeContentTransferEncoding
-} MmsCode;
-
-typedef enum {
-       MSG_PRESENTATION_NONE = -1,
-       MSG_PRESENTATION_FIRSTPART,             //Content-type == type parameter
-       MSG_PRESENTATION_TYPE_BASE,             //Content-type == type parameter
-       MSG_PRESENTATION_LOCATION,              //Content-Location == start parameter
-       MSG_PRESENTATION_ID,                    //Content-ID == start parameter
-} MsgPresentationFactor;
-
-/*==================================================================================================
-                                                       Structures
-==================================================================================================*/
-
-typedef struct {
-       const char *szText;
-       UINT16 binary;
-} MmsField;
-
-
-typedef struct {
-       char *pData;
-       UINT32 length;
-} EncodedPData;
-
-typedef struct {
-       MsgPresentationFactor factor;
-       MsgMultipart *pPrevPart;
-       MsgMultipart *pCurPresentation;
-} MsgPresentaionInfo;
-
-// for Decoding & Encoding
-typedef struct {
-       bool bActive;
-       char *pszOwner;
-       int msgID;              // if noti.ind, msgID is -1.
-
-       MmsMsgType type;
-       char szTrID[MMS_TR_ID_LEN+1];
-       UINT8 version;
-       UINT32 date;
-
-       MsgHeaderAddress *pFrom;                //"/TYPE=PLMN", /"TYPE=IPv4", "/TYPE=IPv6"
-       MsgHeaderAddress *pTo;
-       MsgHeaderAddress *pCc;
-       MsgHeaderAddress *pBcc;
-       char szSubject[MSG_LOCALE_SUBJ_LEN + 1];
-       MmsResponseStatus responseStatus;
-       MmsRetrieveStatus retrieveStatus;
-       char szResponseText[MMS_LOCALE_RESP_TEXT_LEN + 1];
-       char szRetrieveText[MMS_LOCALE_RESP_TEXT_LEN + 1];
-
-       MmsMsgClass msgClass;
-       MmsTimeStruct expiryTime;
-       MmsTimeStruct deliveryTime;
-       MmsPriority priority;
-       MmsSenderVisible hideAddress;
-       MmsReport deliveryReport;
-       MmsReport readReply;
-       MmsReportAllowed reportAllowed;
-       char szContentLocation[MMS_LOCATION_LEN + 1];
-
-       msg_delivery_report_status_t msgStatus;
-       msg_read_report_status_t readStatus;
-
-       MmsReplyCharge replyCharge;
-
-       // only used at Decoding module
-       char szMsgID[MMS_MSG_ID_LEN + 1];
-       UINT32 msgSize;
-
-#ifdef __SUPPORT_DRM__
-       MsgDrmType drmType;
-#endif
-
-       // dependent to Client implementation
-       MsgType msgType;
-       MsgBody msgBody;
-} MmsHeader;
-
-extern const MmsField gMmsField[MMS_MAX_FIELD_TYPE_COUNT][MMS_MAX_FIELD_VALUE_COUNT];
-extern char gszMmsLoadBuf1[MSG_MMS_DECODE_BUFFER_MAX + 1];
-extern char gszMmsLoadBuf2[MSG_MMS_DECODE_BUFFER_MAX + 1];
-
-extern MmsHeader mmsHeader;
-
-/* Common */
-char *_MmsGetTextValue(MmsCode i, int j);
-char *_MmsGetTextValuebyField(int field, int value);
-int _MmsGetTextType(MmsCode i, char *pValue);
-UINT16 _MmsGetBinaryValue(MmsCode i, int j);
-int _MmsGetBinaryType(MmsCode i, UINT16 value);
-UINT8 _MmsGetVersion(MmsMsg *pMsg);
-bool _MmsSetVersion(int majorVer, int minorVer);
-
-
-/* Decoding */
-void _MmsInitHeader();
-void _MmsCleanDecodeBuff(void);
-bool _MmsDecodeInitialize(void);
-void _MmsRegisterDecodeBuffer(char *pInBuff1, char *pInBuffer2, int maxLen);
-void _MmsUnregisterDecodeBuffer(void);
-int _MmsGetDecodeOffset(void);
-
-bool MmsBinaryDecodeMsgBody(FILE *pFile, char *szFilePath, int totalLength);
-bool MmsBinaryDecodeContentType(FILE *pFile, char *szFilePath, int totalLength); // for JAVA MMS AppId
-
-bool MmsBinaryDecodeEachPart(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, int totalLength);
-int MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength);
-bool MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, int totalLength);
-bool MmsBinaryDecodePartBody(FILE *pFile, UINT32 bodyLength, int totalLength);
-bool MmsBinaryDecodeEntries(FILE *pFile, UINT32 *npEntries, int totalLength);
-bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength);
-
-bool MmsBinaryDecodeMultipart(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, int totalLength);
-
-
-/* Encoding */
-void _MmsRegisterEncodeBuffer(char *pInBuff, int maxLen);
-void _MmsUnregisterEncodeBuffer(void);
-int _MmsGetEncodeOffset(void);
-
-bool _MmsEncodeMsg(void);
-bool _MmsEncodeSendReq(FILE *pFile, MmsMsg *pMsg);
-bool _MmsEncodeTemplate(FILE *pFile, MmsMsg *pMsg);    // just encode MMS Body without any header.
-bool _MmsEncodeAckInd(FILE *pFile, char *szTrID, bool bReportAllowed);
-bool _MmsEncodeNotiRespInd(FILE *pFile, char *szTrID, msg_delivery_report_status_t iStatus, bool bReportAllowed);
-bool _MmsEncodeForwardReq(FILE *pFile, char *szContentLocation, char *szForwardTo, char *szForwardCc, char *szForwardBcc);
-bool _MmsEncodeReadReport10(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus);
-bool _MmsEncodeReadReport11(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus);
-
-
-bool MmsBinaryEncodeMsgBody(FILE *pFile, MsgType *pType, MsgBody *pBody, int nPartCount, bool bTemplate);//NEW_TEMPLATE
-
-int MmsBinaryEncodeContentTypeLen(MsgType *pType);
-bool MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength);
-int MmsBinaryEncodeContentHeaderLen(MsgContentType contentType, MsgType *pType, bool bMultipart);
-bool MmsBinaryEncodeContentHeader(FILE *pFile, MsgContentType contentType, MsgType *pType, bool bMultipart);
-bool MmsBinaryEncodeContentBody(FILE *pFile, MsgBody *pBody);
-bool MmsBinaryEncodeMsgPart(FILE *pFile, int contentType, MsgType *pType, MsgBody *pBody);
-bool MmsBinaryEncodeSendReqHdrwithinBufRegi(FILE *pFile, MmsMsg *pMsg);
-bool MsgWriteDataFromEncodeBuffer(FILE *pFile, char *pInBuffer, int *pPtr, int maxLen, int *pOffset);
-bool MsgLoadDataToDecodeBuffer(FILE *pFile, char **ppBuf, int *pPtr, int *pOffset, char *pInBuf1, char *pInBuf2, int maxLen, int *npRead, int endOfFile);
-bool MsgFreeHeaderAddress(MsgHeaderAddress *pAddr);
-bool MsgCheckFileNameHasInvalidChar(char *szName);
-bool _MsgReplaceInvalidFileNameChar(char *szInText, char replaceChar);
-char *_MsgGetStringUntilDelimiter(char *pszString, char delimiter);
-char *MsgChangeHexString(char *pOrg);
-bool _MsgParseParameter(MsgType *pType, char *pSrc);
-char *_MsgSkipWS(char *s);
-char *__MsgSkipComment(char *s, long trim);
-int _MsgGetCode(MsgHeaderField tableId, char *pStr);
-char *MsgConvertLatin2UTF8FileName(char *pSrc);
-bool _MsgChangeSpace(char *pOrg, char **ppNew);
-void _MsgRemoveFilePath(char *pSrc);
-bool MsgIsUTF8String(unsigned char *szSrc, int nChar);
-bool MsgIsPercentSign(char *pSrc);
-MsgMultipart *MsgAllocMultipart(void);
-bool _MsgInitMsgType(MsgType *pMsgType);
-bool _MsgInitMsgBody(MsgBody *pMsgBody);
-MsgPresentationFactor MsgIsPresentationEx(MsgType *multipartType, char *szStart, MsgContentType typeParam);
-void MsgConfirmPresentationPart(MsgType *pMsgType, MsgBody *pMsgBody, MsgPresentaionInfo *pPresentationInfo);
-bool MsgIsMultipartRelated(int type);
-bool MsgIsPresentablePart(int type);
-bool MsgIsText(int type);
-bool _MsgFreeBody(MsgBody *pBody, int type);
-bool MsgFreeAttrib(MmsAttrib *pAttrib);
-bool MsgResolveNestedMultipart(MsgType *pPartType, MsgBody *pPartBody);
-char *MsgResolveContentURI(char *szSrc);
-bool _MsgParsePartHeader(MsgType *pType, const char *pRawData, int nRawData);
-char *MsgRemoveQuoteFromFilename(char *pSrc);
-MmsMsg *MmsGetMsgById(MmsMsgID msgID, bool msgLock);
-bool MsgIsMultipart(int type);
-bool MsgIsHexChar(char *pSrc);
-char _MsgConvertHexValue(char *pSrc);
-int __MsgConvertCharToInt(char ch);
-bool __MsgInitMsgContentParam(MsgContentParam *pMsgContentParam);
-bool MsgCopyNestedMsgType(MsgType *pMsgType1, MsgType *pMsgType2);
-bool MsgCopyNestedMsgParam(MsgContentParam *pParam1, MsgContentParam *pParam2);
-bool MsgIsMultipartMixed(int type);
-bool MsgStrcpyWithoutCRLF(char *pOrg, char **ppNew);
-bool __MsgIsInvalidFileNameChar(char ch);
-bool MmsAddrUtilCompareAddr(char *pszAddr1, char *pszAddr2);
-bool _MmsDataUpdateLastStatus(MmsMsg *pMsg);
-
-bool _MsgEncodeBase64(void *pSrc, unsigned long srcLen, unsigned long *len, unsigned char *ret);
-void *_MsgDecodeBase64(unsigned char *pSrc, unsigned long srcLen, unsigned long *len);
-bool _MsgEncodeQuotePrintable(unsigned char *pSrc, unsigned long srcLen, unsigned long *len, unsigned char *ret);
-unsigned char *_MsgDecodeQuotePrintable(unsigned char *pSrc, unsigned long srcLen, unsigned long *len);
-bool _MsgEncode2Base64(void *pSrc, unsigned long srcLen, unsigned long *len, unsigned char *ret);
-char *_MsgDecodeText(char *pOri);
-char *MsgEncodeText(char *pOri);
-int MsgGetLatin2UTFCodeSize(unsigned char *szSrc, int nChar);
-int MsgLatin5code2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar);
-int MsgGetLatin52UTFCodeSize(unsigned char *szSrc, int nChar);
-int MsgLatin2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar);
-int MsgLatin7code2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar);
-int MsgGetLatin72UTFCodeSize(unsigned char *szSrc, int nChar);
-int MsgUnicode2UTF(unsigned char *des, int outBufSize, unsigned short *szSrc, int nChar);
-int MsgGetUnicode2UTFCodeSize(unsigned short *szSrc, int nChar);
-bool MmsAddrUtilCheckEmailAddress(char *pszAddr);
-bool MmsAddrUtilRemovePlmnString(char *pszAddr);
-int MsgCutUTFString(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar);
-void MsgMIMERemoveQuote(char *szSrc);
-bool _MmsMultipartSaveAsTempFile(MsgType *pPartType, MsgBody *pPartBody, char *pszMailboxPath, char *pszMsgFilename, int index, bool bSave);
-bool MsgGetTypeByFileName(int *type, char *szFileName);
-bool MmsGetMediaPartData(MsgType *pPartType, MsgBody *pPartBody, FILE *pFile);
-char *MmsGetBinaryUTF8Data(char *pData, int nRead, int msgEncodingValue, int msgTypeValue, int msgCharsetValue, int *npRead);
-#ifndef        __SUPPORT_DRM__
-bool MsgMakeFileName(int iMsgType, char *szFileName, int nUntitleIndex);
-#else
-bool MsgMakeFileName(int iMsgType, char *szFileName, MsgDrmType drmType, int nUntitleIndex);
-#endif
-bool MsgGetFileNameWithoutExtension(char *szOutputName, char *szName);
-int MmsGetMediaPartCount(msg_message_id_t msgId);
-bool MmsGetMediaPartHeader(int index, MsgType *pHeader);
-bool MmsGetMsgAttrib(MmsMsgID msgID, MmsAttrib *pAttrib);
-bool _MmsReadMsgBody(msg_message_id_t msgID, bool bSavePartsAsTempFiles, bool bRetrieved, char *retrievedPath);
-
-#ifdef __SUPPORT_DRM__
-void _MsgFreeDRMInfo(MsgDRMInfo *pDrmInfo);
-bool MsgCopyDrmInfo(MsgType *pPartType);
-bool MmsDrm2ConvertMsgBody(char *szOriginFilePath);
-bool MmsDrm2ReadMsgConvertedBody(MSG_MESSAGE_INFO_S *pMsg, bool bSavePartsAsTempFiles, bool bRetrieved, char *retrievedPath);
-bool MmsDrm2DecodeConvertedMsg(int msgID, char *pszFullPath);
-#endif
-
-bool MmsDebugPrintMulitpartEntry(MsgMultipart *pMultipart, int index);
-
-#endif
+#endif //MMS_PLUGIN_CODEC_H
diff --git a/plugin/mms_plugin/include/MmsPluginCodecCommon.h b/plugin/mms_plugin/include/MmsPluginCodecCommon.h
new file mode 100755 (executable)
index 0000000..4b5006b
--- /dev/null
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MMS_PLUGIN_CODEC_COMMON_H
+#define MMS_PLUGIN_CODEC_COMMON_H
+
+#include "MmsPluginCodecTypes.h"
+
+#define                MSG_CH_CR                                               '\r'
+#define                MSG_CH_LF                                               '\n'
+#define                MSG_CH_SP                                               ' '
+#define                MSG_CH_TAB                                              '\t'
+#define                MSG_CH_NULL                                             '\0'
+#define                MSG_CH_COLON                                    ':'
+#define                MSG_CH_SEMICOLON                                ';'
+#define                MSG_CH_UNDERLINE                                '_'
+#define                MSG_CH_COMMA                                    ','
+#define                MSG_CH_BASE64_LOWER                             'b'
+#define                MSG_CH_BASE64_UPPER                             'B'
+#define                MSG_CH_QPRINT_LOWER                             'Q'
+#define                MSG_CH_QPRINT_UPPER                             'q'
+
+#define                MSG_CH_QUESTION                                 '?'
+#define                MSG_CH_QUOT                                             '"'
+#define                MSG_CH_EQUAL                                    '='
+#define                MSG_CH_BRACKET_S                                '<'
+#define                MSG_CH_BRACKET_E                                '>'
+
+#define                MSG_STR_DEC_START                       "=?"
+#define                MSG_STR_DEC_END                         "?="
+#define                MSG_STR_CRLF                            "\r\n"
+#define                MSG_END_OF_HEADER                       "\r\n\r\n"
+#define                MSG_STR_DOUBLE_HYPEN            "--"
+#define                MSG_STR_BOUNDARY_DEL            "\r\n--"
+
+#define                MSG_MMS_CH_EMAIL_AT                     '@'
+
+/* character-set parameter value of content-type header field */
+enum {
+       MSG_CHARSET_US_ASCII,
+       MSG_CHARSET_UTF16,
+       MSG_CHARSET_USC2,
+       MSG_CHARSET_UTF8,
+       MSG_CHARSET_ISO_2022_KR,
+       MSG_CHARSET_KS_C_5601_1987,
+       MSG_CHARSET_EUC_KR,
+       MSG_CHARSET_ISO_2022_JP,
+       MSG_CHARSET_ISO_2022_JP_2,
+       MSG_CHARSET_ISO_8859_1,
+       MSG_CHARSET_ISO_8859_2,
+       MSG_CHARSET_ISO_8859_3,
+       MSG_CHARSET_ISO_8859_4,
+       MSG_CHARSET_ISO_8859_5,
+       MSG_CHARSET_ISO_8859_6,
+       MSG_CHARSET_ISO_8859_7,
+       MSG_CHARSET_ISO_8859_8,
+       MSG_CHARSET_ISO_8859_9,
+       MSG_CHARSET_ISO_8859_10,
+       MSG_CHARSET_ISO_8859_15,
+       MSG_CHARSET_Shift_JIS,
+       MSG_CHARSET_EUC_JP,
+       MSG_CHARSET_GB2312,
+       MSG_CHARSET_BIG5,
+       MSG_CHARSET_WIN1251,
+       MSG_CHARSET_KOI8_R,
+       MSG_CHARSET_KOI8_U,
+
+       MSG_CHARSET_NUM,
+       MSG_CHARSET_UNKNOWN
+};
+
+/* Content-Transfer-Encoding header field value */
+enum {
+       MSG_ENCODING_7BIT,
+       MSG_ENCODING_8BIT,
+       MSG_ENCODING_BINARY,
+       MSG_ENCODING_BASE64,
+       MSG_ENCODING_QUOTE_PRINTABLE,
+       MSG_ENCODING_NUM,
+       MSG_ENCODING_OTHER,
+};
+
+
+/* Content-Disposition header field value */
+enum {
+       MSG_DISPOSITION_FORMDATA,
+       MSG_DISPOSITION_ATTACHMENT,
+       MSG_DISPOSITION_INLINE,
+       MSG_DISPOSITION_NUM
+};
+
+/* MIME header field */
+enum {
+       MSG_FIELD_RETURN_PATH,
+       MSG_FIELD_MESSAGE_ID,
+       MSG_FIELD_FROM,
+       MSG_FIELD_TO,
+       MSG_FIELD_CC,
+       MSG_FIELD_SUBJECT,
+       MSG_FIELD_DATE,
+       MSG_FIELD_MIME_VERSION,
+       MSG_FIELD_CONTENT_TYPE,
+       MSG_FIELD_CONTENT_TRANSFER_ENCODING,
+       MSG_FIELD_CONTENT_DISPOSITION, //If start param is given in multipart/related, this field will be ignored
+       MSG_FIELD_CONTENT_ID,
+       MSG_FIELD_CONTENT_LOCATION,
+       MSG_FIELD_CONTENT_NAME,
+       MSG_FIELD_CONTENT_DESCRIPTION,
+       MSG_FIELD_CONTENT_VENDOR,
+       MSG_FIELD_RIGHT_ISSUER,
+
+       MSG_FIELD_RETURN_RECEIPT_TO,                    /* for Delivery confirm */
+       MSG_FIELD_DISPOSITION_NOTIFICATION_TO,  /* for Read confirm */
+
+       MSG_FILED_CONTENT_REPLACE_POS,
+       MSG_FILED_CONTENT_REPLACE_SIZE,
+       MSG_FILED_CONTENT_REPLACE_INDEX,
+
+       MSG_FIELD_DRM_CONVERTED,
+
+       MSG_FIELD_NUM,
+       MSG_FIELD_UNKNOWN,
+};
+
+/* MIME header field parameter */
+enum {
+       MSG_PARAM_CHARSET,
+       MSG_PARAM_NAME,
+       MSG_PARAM_FILENAME,
+       MSG_PARAM_TYPE,                 // only used as parameter of Content-Type: multipart/related
+       MSG_PARAM_START,                // Only if content-type is multipart/related
+       MSG_PARAM_START_INFO,   // Only if content-type is multipart/related
+       MSG_PARAM_BOUNDARY,
+       MSG_PARAM_REPORT_TYPE,  // only used as parameter of Content-Type: multipart/report; report-type=delivery-status;
+#ifdef FEATURE_JAVA_MMS
+       MSG_PARAM_APPLICATION_ID,
+       MSG_PARAM_REPLY_TO_APPLICATION_ID,
+#endif
+       MSG_PARAM_NUM,
+       MSG_PARAM_UNKNOWN,
+};
+
+const char *MmsGetTextByCode(MmsCode i, UINT16 code);
+const char *MmsGetTextValue(MmsCode i, int j);
+const char *MmsGetTextValuebyField(int field, int value);
+int MmsGetBinaryType(MmsCode i, UINT16 value);
+int MmsGetTextType(MmsCode i, char *pValue);
+UINT16 MmsGetBinaryValue(MmsCode i, int j);
+
+void *MsgDecodeBase64(unsigned char *pSrc, unsigned long srcLen, unsigned long *len);
+bool MsgEncode2Base64(void *pSrc, unsigned long srcLen, unsigned long *len, unsigned char *ret);
+unsigned char *MsgDecodeQuotePrintable(unsigned char *pSrc, unsigned long srcLen, unsigned long *len);
+
+char *MsgDecodeText(const char *pOri);
+
+const char *MmsDebugGetMimeType(MimeType mimeType);
+const char *MmsDebugGetMmsReport(MmsReport report);
+const char *MmsDebugGetMmsReportAllowed(MmsReportAllowed reportAllowed);
+const char *MmsDebugGetMmsReadStatus(msg_read_report_status_t readStatus);
+const char *MmsDebugGetMsgType(MmsMsgType msgType);
+const char *MmsDebugGetResponseStatus(MmsResponseStatus responseStatus);
+const char *MmsDebugGetRetrieveStatus(MmsRetrieveStatus retrieveStatus);
+const char *MmsDebugGetMsgStatus(msg_delivery_report_status_t msgStatus);
+const char *MmsDebugGetMsgClass(MmsMsgClass msgClass);
+const char *MmsDebugGetDataType(MmsDataType dataType);
+
+bool MmsInitMsgType(MsgType *pMsgType);
+bool MmsInitMsgBody(MsgBody *pMsgBody);
+bool MmsInitMsgContentParam(MsgContentParam *pMsgContentParam);
+bool MmsInitMsgAttrib(MmsAttrib *pAttrib);
+bool MmsInitMsgDRMInfo(MsgDRMInfo *pMsgDrmInfo);
+
+bool MmsReleaseMsgBody(MsgBody *pBody, int type);
+bool MmsReleaseMmsAttrib(MmsAttrib *pAttrib);
+void MmsReleaseMsgDRMInfo(MsgDRMInfo *pDrmInfo);
+void MmsReleaseMmsMsg(MmsMsg *pMmsMsg);
+
+bool MmsIsTextType(int type);
+bool MmsIsMultipart(int type);
+bool MmsIsVitemContent(int type, char *pszName);
+
+MsgMultipart *MmsAllocMultipart(void);
+bool MmsPrintMulitpart(MsgMultipart *pMultipart, int index);
+#endif //MMS_PLUGIN_CODEC_COMMON_H
diff --git a/plugin/mms_plugin/include/MmsPluginCodecTypes.h b/plugin/mms_plugin/include/MmsPluginCodecTypes.h
new file mode 100755 (executable)
index 0000000..0be998b
--- /dev/null
@@ -0,0 +1,470 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MMS_PLUGIN_CODEC_TYPE_H
+#define MMS_PLUGIN_CODEC_TYPE_H
+
+#include "MmsPluginTypes.h"
+
+#define        MMS_MAJOR_VERSION                       1
+
+#if defined(MMS_V1_1)
+#define        MMS_MINOR_VERSION                       1
+#define        MMS_VERSION                                     0x91
+
+#elif defined(MMS_V1_2)
+#define        MMS_MINOR_VERSION                       2
+#define        MMS_VERSION                                     0x92
+
+#else
+#define        MMS_MINOR_VERSION                       0
+#define        MMS_VERSION                                     0x90
+#endif
+
+#define        MSG_MMS_ENCODE_BUFFER_MAX       (2 * 1024)
+#define        MSG_MMS_DECODE_BUFFER_MAX       (2 * 1024)
+#define        MSB                                                             0x80
+#define        QUOTE                                                   0x7F
+#define        MARK                                                    0x22    // "
+#define        LENGTH_QUOTE                                    0x1F
+#define        MSG_STDSTR_LONG                         0xFF
+#define        INVALID_VALUE                                   -1
+
+#define        MMS_CONTENT_ID_LEN                              100
+#define        MSG_DATE_LEN                                            50
+#define        MSG_SUBJ_LEN                                            40
+#define        MSG_LOCALE_SUBJ_LEN                             (3 * MSG_SUBJ_LEN)
+#define        MSG_LOCAL_TEMP_BUF_SIZE 1024
+#define        MSG_ADDR_LEN                                            MAX_ADDRESS_VAL_LEN
+#define        MMS_LOCALE_RESP_TEXT_LEN                90
+#define        MSG_LOCALE_ADDR_LEN                             (3 * MAX_ADDRESS_VAL_LEN)
+#define        MSG_BOUNDARY_LEN                                        70
+#define        MSG_LOCALE_NAME_LEN                             150
+#define        MSG_LOCALE_FILENAME_LEN_MAX             (3 * MSG_FILENAME_LEN_MAX)
+#define        MMS_READ_REPORT_STRING_READ             "Read:"
+#define        MMS_READ_REPORT_STRING_DELETED  "Deleted:"
+
+#define        MSG_ATTACH_MAX          20
+#define        MSG_STR_ADDR_DELIMETER                  ";"
+
+#define        MMS_TEXT_LEN 2000
+#define        MSG_CH_ADDR_DELIMETER ';'
+#define        MSG_MMS_STR_ADDR_DELIMETER      MSG_STR_ADDR_DELIMETER
+#define        MSG_MMS_CH_ADDR_DELIMETER       MSG_CH_ADDR_DELIMETER
+
+
+typedef unsigned int                   UINT;
+typedef unsigned long int              UINT32;
+typedef unsigned char                  UINT8;
+typedef unsigned short int             UINT16;
+typedef unsigned long                  ULONG;
+typedef unsigned char                  UCHAR;
+typedef unsigned short                 MCHAR;
+typedef unsigned short                 USHORT;
+
+typedef struct _MsgBody                MsgBody;
+typedef struct _MsgMultipart   MsgMultipart;
+
+typedef enum {
+       MMS_CODE_BCC,
+       MMS_CODE_CC,
+       MMS_CODE_CONTENTLOCATION,
+       MMS_CODE_CONTENTTYPE,
+       MMS_CODE_DATE,
+       MMS_CODE_DELIVERYREPORT,
+       MMS_CODE_DELIVERYTIME,
+       MMS_CODE_EXPIRYTIME,
+       MMS_CODE_FROM,
+       MMS_CODE_MSGCLASS,
+       MMS_CODE_MSGID,
+       MMS_CODE_MSGTYPE,
+       MMS_CODE_VERSION,
+       MMS_CODE_MSGSIZE,
+       MMS_CODE_PRIORITY,
+       MMS_CODE_READREPLY,
+       MMS_CODE_REPORTALLOWED,
+       MMS_CODE_RESPONSESTATUS,
+       MMS_CODE_RETRIEVESTATUS,                /* Add by MMSENC v1.1 */
+       MMS_CODE_RESPONSETEXT,
+       MMS_CODE_RETRIEVETEXT,                  /* Add by MMSENC v1.1 */
+       MMS_CODE_SENDERVISIBILLITY,
+       MMS_CODE_MSGSTATUS,
+       MMS_CODE_SUBJECT,
+       MMS_CODE_TO,
+       MMS_CODE_TRID,
+
+       /* Add by MMSENC v1.1 */
+       MMS_CODE_READSTATUS,
+       MMS_CODE_REPLYCHARGING,
+       MMS_CODE_REPLYCHARGINGDEADLINE,
+       MMS_CODE_REPLYCHARGINGID,
+       MMS_CODE_REPLYCHARGINGSIZE,
+       MMS_CODE_PREVIOUSLYSENTBY,
+       MMS_CODE_PREVIOUSLYSENTDATE,
+
+       MMS_CODE_TRANSFERENCODING,
+       MMS_CODE_DISPOSITION,
+       MMS_CODE_CONTENT_ID
+} MmsFieldCode;
+
+enum {
+       MMS_BODYHDR_TRANSFERENCODING,
+       MMS_BODYHDR_DISPOSITION,
+       MMS_BODYHDR_CONTENTID,
+       MMS_BODYHDR_CONTENTLOCATION,
+       MMS_BODYHDR_X_OMA_DRM_SEPARATE_DELIVERY,        // DRM RO WAITING
+};
+
+typedef enum {
+       //code
+       MmsCodeFieldCode,
+       MmsCodeParameterCode,
+       MmsCodeMsgBodyHeaderCode,
+
+       //Data
+       MmsCodeMsgType,
+       MmsCodeDeliveryReport,
+       MmsCodeTimeType,
+       MmsCodeMsgClass,
+       MmsCodePriority,
+       MmsCodeResponseStatus,
+       MmsCodeRetrieveStatus,
+       MmsCodeReadReply,
+       MmsCodeReportAllowed,
+       MmsCodeSenderVisibility,
+       MmsCodeMsgStatus,
+       MmsCodeReadStatus,
+       MmsCodeAddressType,
+       MmsCodeCharSet,
+       MmsCodeReplyCharging,
+
+       MmsCodeContentType,
+
+       MmsCodeMsgDisposition,
+       MmsCodeContentTransferEncoding
+} MmsCode;
+
+typedef enum {
+       MMS_DATATYPE_NONE = -1,
+       MMS_DATATYPE_READ = 0,
+       MMS_DATATYPE_SENT = 1,
+       MMS_DATATYPE_NOTIFY = 2,
+       MMS_DATATYPE_UNSENT = 3,
+       MMS_DATATYPE_DRAFT = 4,
+       MMS_DATATYPE_SENDING = 6,
+       MMS_DATATYPE_RETRIEVING = 7,
+       MMS_DATATYPE_UNRETV = 8,
+       MMS_DATATYPE_TEMPLATE = 9,
+       MMS_DATATYPE_DRM_RO_WAITING = 10        // DRM RO WAITING
+} MmsDataType;
+
+typedef enum {
+       MMS_MSGTYPE_ERROR = -1, // error return in Get method
+       MMS_MSGTYPE_SEND_REQ = 0,       // default
+       MMS_MSGTYPE_SEND_CONF = 1,
+       MMS_MSGTYPE_NOTIFICATION_IND = 2,
+       MMS_MSGTYPE_NOTIFYRESP_IND = 3,
+       MMS_MSGTYPE_RETRIEVE_CONF = 4,
+       MMS_MSGTYPE_ACKNOWLEDGE_IND = 5,
+       MMS_MSGTYPE_DELIVERY_IND = 6,
+       MMS_MSGTYPE_READREC_IND = 7,
+       MMS_MSGTYPE_READORG_IND = 8,
+       MMS_MSGTYPE_FORWARD_REQ = 9,
+       MMS_MSGTYPE_FORWARD_CONF = 10,
+       MMS_MSGTYPE_READ_REPLY = 11,    // for internal use
+       MMS_MSGTYPE_MAX
+} MmsMsgType;
+
+typedef enum {
+       MMS_PRIORITY_ERROR = -1,                        // error return in Get method
+       MMS_PRIORITY_LOW = 0,                   // default
+       MMS_PRIORITY_NORMAL = 1,
+       MMS_PRIORITY_HIGH = 2
+} MmsPriority;
+
+typedef enum {
+       MMS_SENDER_VISIBLE_ERROR = -1,  // error return in Get method
+       MMS_SENDER_SHOW = 0,
+       MMS_SENDER_HIDE = 1
+} MmsSenderVisible;
+
+typedef enum {
+       MMS_REPORT_ERROR = -1,  // error return in Get method
+       MMS_REPORT_YES = 0,
+       MMS_REPORT_NO = 1
+} MmsReport;
+
+typedef enum {
+       MMS_REPORTALLOWED_ERROR = -1,   // error return in Get method
+       MMS_REPORTALLOWED_YES = 0,
+       MMS_REPORTALLOWED_NO = 1
+} MmsReportAllowed;
+
+typedef enum {
+       MMS_RECEIVE_READ_REPORT_ALLOWED,
+       MMS_RECEIVE_READ_REPORT_PROMPT,
+       MMS_RECEIVE_READ_REPORT_NOT_ALLOWED,
+} MmsRecvReadReportType ;
+
+typedef enum {
+       MMS_MSGSTATUS_NONE = -1,        // backward compatibility
+       MMS_MSGSTATUS_ERROR = -1,       // error return in Get method
+       MMS_MSGSTATUS_EXPIRED = 0,      // This value SHOULD not be used in the M-NotifyResp.ind PDU.
+       MMS_MSGSTATUS_RETRIEVED = 1,
+       MMS_MSGSTATUS_REJECTED = 2,
+       MMS_MSGSTATUS_DEFERRED = 3,
+       MMS_MSGSTATUS_UNRECOGNISED = 4, // This value SHALL not be used in the M-Delivery.ind PDU.
+       MMS_MSGSTATUS_INDETERMINATE = 5,
+       MMS_MSGSTATUS_FORWARDED = 6,
+       MMS_MSGSTATUS_UNREACHABLE = 7
+} MmsMsgStatus;
+
+typedef enum {
+       MMS_READSTATUS_NONE = -1,                       // no touch status
+       MMS_IS_READ = 0,
+       MMS_IS_DELETED = 1      // Deleted without being read
+} MmsReadStatus;
+
+typedef enum {
+       MMS_ADDRESS_PRESENT_TOKEN,
+       MMS_INSERT_ADDRESS_TOKEN
+} MmsAddressType;
+
+typedef enum {
+       MSG_PARAM_REPORT_TYPE_DELIVERY_STATUS,
+       MSG_PARAM_REPORT_TYPE_NUM,
+       MSG_PARAM_REPORT_TYPE_UNKNOWN,
+} MsgParamReportType;
+
+/* Response status */
+typedef enum {
+       MMS_RESPSTATUS_ERROR = -1,      // error return in Get method
+       MMS_RESPSTATUS_OK = 0,  // default value
+       MMS_RESPSTAUTS_ERROR_UNSPECIFIED = 1,
+       MMS_RESPSTAUTS_ERROR_SERVICEDENIED = 2,
+       MMS_RESPSTAUTS_ERROR_MESSAGEFORMATCORRUPT = 3,
+       MMS_RESPSTAUTS_ERROR_SENDINGADDRESSUNRESOLVED = 4,
+       MMS_RESPSTAUTS_ERROR_MESSAGENOTFOUND = 5,
+       MMS_RESPSTAUTS_ERROR_NETWORKPROBLEM = 6,
+       MMS_RESPSTAUTS_ERROR_CONTENTNOTACCEPTED = 7,
+       MMS_RESPSTAUTS_ERROR_UNSUPPORTEDMESSAGE = 8,
+
+       MMS_RESPSTAUTS_ERROR_TRANSIENT_FAILURE = 9,
+       MMS_RESPSTAUTS_ERROR_TRANSIENT_SENDING_ADDRESS_UNRESOLVED = 10,
+       MMS_RESPSTAUTS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND = 11,
+       MMS_RESPSTAUTS_ERROR_TRANSIENT_NETWORK_PROBLEM = 12,
+
+       MMS_RESPSTAUTS_ERROR_PERMANENT_FAILURE = 13,
+       MMS_RESPSTAUTS_ERROR_PERMANENT_SERVICE_DENIED = 14,
+       MMS_RESPSTAUTS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT = 15,
+       MMS_RESPSTAUTS_ERROR_PERMANENT_SENDING_ADDRESS_UNRESOLVED = 16,
+       MMS_RESPSTAUTS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 17,
+       MMS_RESPSTAUTS_ERROR_PERMANENT_CONTENT_NOT_ACCEPTED = 18,
+       MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_LIMITATIONS_NOT_MET = 19,
+       MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_REQUEST_NOT_ACCEPTED = 20,
+       MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_FORWARDING_DENIED = 21,
+       MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_NOT_SUPPORTED = 22
+} MmsResponseStatus;
+
+typedef enum {
+       MMS_RETRSTATUS_ERROR = -1,      // error return in Get method
+       MMS_RETRSTATUS_OK = 0,
+       MMS_RETRSTATUS_TRANSIENT_FAILURE = 1,
+       MMS_RETRSTATUS_TRANSIENT_MESSAGE_NOT_FOUND = 2,
+       MMS_RETRSTATUS_TRANSIENT_NETWORK_PROBLEM = 3,
+       MMS_RETRSTATUS_PERMANENT_FAILURE = 4,
+       MMS_RETRSTATUS_PERMANENT_SERVICE_DENIED = 5,
+       MMS_RETRSTATUS_PERMANENT_MESSAGE_NOT_FOUND = 6,
+       MMS_RETRSTATUS_PERMANENT_CONTENT_UNSUPPORT = 7
+} MmsRetrieveStatus;
+
+typedef enum {
+       MMS_REPLY_NONE = -1,    // error return in Get method
+       MMS_REPLY_REQUESTED = 0,
+       MMS_REPLY_REQUESTED_TEXT_ONLY = 1,
+       MMS_REPLY_ACCEPTED = 2,
+       MMS_REPLY_ACCEPTED_TEXT_ONLY = 3
+} MmsReplyChargeType;
+
+typedef enum {
+       MMS_MSGCLASS_ERROR = -1,        // error return in Get method
+       MMS_MSGCLASS_PERSONAL = 0,      // default
+       MMS_MSGCLASS_ADVERTISEMENT = 1,
+       MMS_MSGCLASS_INFORMATIONAL = 2,
+       MMS_MSGCLASS_AUTO = 3
+} MmsMsgClass;
+
+
+/*==================================================================================================
+                                                       Structures
+==================================================================================================*/
+
+typedef struct {
+       MmsReplyChargeType chargeType;
+       MmsTimeStruct deadLine;
+       int chargeSize;
+       char szChargeID[MMS_MSG_ID_LEN + 1];
+} MmsReplyCharge;
+
+typedef struct _MmsMsgMultiStatus {
+       char szTo[MAX_ADDRESS_VAL_LEN + 1];
+       bool bDeliveryReportIsRead;
+       bool bDeliveyrReportIsLast;
+       msg_delivery_report_status_t msgStatus;
+       UINT32 handledTime;
+       bool bReadReplyIsRead;
+       bool bReadReplyIsLast;
+       msg_read_report_status_t readStatus;
+       UINT32 readTime;
+
+       struct _MmsMsgMultiStatus *pNext;
+} MmsMsgMultiStatus;
+
+typedef struct _MMS_ATTRIB_S {
+       MimeType contentType;
+       MmsMsgType msgType;
+       MmsDataType dataType;
+       UINT32 date;
+       UINT8 version;
+
+       char szFrom[MSG_LOCALE_ADDR_LEN + 11];          //"/TYPE=PLMN", /"TYPE=IPv4", "/TYPE=IPv6"
+       char szSubject[MSG_LOCALE_SUBJ_LEN + 1];
+       char *szTo;
+       char *szCc;
+       char *szBcc;
+
+       MmsPriority priority;
+
+       MmsReplyCharge replyCharge;
+
+       bool bHideAddress;
+       bool bAskDeliveryReport;
+       bool bReportAllowed;
+       MmsRecvReadReportType readReportAllowedType;
+
+       bool bAskReadReply;
+       bool bRead;//FIXME : remove this value
+
+       MmsRecvReadReportSendStatus readReportSendStatus;
+
+       bool bReadReportSent;
+
+       bool bLeaveCopy;
+
+       int msgSize;
+       MmsMsgClass msgClass;
+       MmsTimeStruct expiryTime;
+       MmsTimeStruct deliveryTime;
+
+       //for ReadMsg, When Sending notifyResp.ind
+       msg_delivery_report_status_t msgStatus;
+
+       MmsResponseStatus responseStatus;
+       MmsRetrieveStatus retrieveStatus;
+       char szResponseText[MMS_LOCALE_RESP_TEXT_LEN + 1];
+       char szRetrieveText[MMS_LOCALE_RESP_TEXT_LEN + 1];
+
+       MmsMsgMultiStatus *pMultiStatus;
+
+} MmsAttrib;
+
+typedef struct _MsgContentParam {
+       int charset;
+       char szBoundary[MSG_BOUNDARY_LEN + 1];
+       char szFileName[MSG_FILENAME_LEN_MAX + 1];
+       char szName[MSG_LOCALE_FILENAME_LEN_MAX + 1];
+
+#ifdef FEATURE_JAVA_MMS
+       char *szApplicationID;
+       char *szReplyToApplicationID;
+#endif
+
+       int type;
+       void *pPresentation;
+       char szStart[MSG_MSG_ID_LEN + 1];
+       char szStartInfo[MSG_MSG_ID_LEN + 1];
+
+       MsgParamReportType reportType; //only used as parameter of Content-Type: multipart/report; report-type=delivery-status;
+} MsgContentParam;
+
+typedef struct _MsgDRMInfo {
+       MsgDrmType drmType;
+       MimeType contentType;
+       char *szContentURI;
+       char *szContentName;
+       char *szContentDescription;
+       char *szContentVendor;
+       char *szRightIssuer;
+       char *szDrm2FullPath;
+       int roWaitingTimerMax;          // DRM RO WAITING
+       bool bFwdLock;
+       char *pszContentType;
+       bool bNoRingTone;
+       bool bNoScreen;
+} MsgDRMInfo;
+
+typedef struct _MsgType {
+       int offset;
+       int size;
+       int contentSize;
+       int section;
+       int type;
+
+       MsgDRMInfo drmInfo;
+
+       int encoding;
+       int disposition;
+       char szContentID[MSG_MSG_ID_LEN + 1];
+       char szContentLocation[MSG_MSG_ID_LEN + 1];
+       char szOrgFilePath[MSG_FILEPATH_LEN_MAX + 1];
+
+       MsgContentParam param;
+} MsgType;
+
+struct _MsgBody {
+       int offset;
+       int size;
+       char szOrgFilePath[MSG_FILEPATH_LEN_MAX + 1];
+       MsgType presentationType;
+       MsgBody *pPresentationBody;
+
+       union {
+               char *pText;
+               MsgMultipart *pMultipart;
+       } body;
+};
+
+struct _MsgMultipart {
+       MsgType type;
+       MsgBody *pBody;
+       MsgMultipart *pNext;
+};
+
+typedef struct _MMS_MESSAGE_S {
+       MmsAttrib mmsAttrib;
+       msg_message_id_t msgID;
+       int mailbox;            // mailbox type,MMS_MAILBOX_XXX
+       char szFileName[MSG_FILENAME_LEN_MAX];
+       char szTrID[MMS_TR_ID_LEN + 1];
+       char szMsgID[MMS_MSG_ID_LEN + 1];
+       char szForwardMsgID[MMS_MSG_ID_LEN + 1];
+       char szContentLocation[MMS_LOCATION_LEN + 1];
+       int nPartCount;
+       MsgType msgType;
+       MsgBody msgBody;
+} MmsMsg;
+
+#endif //MMS_PLUGIN_CODEC_TYPE_H
diff --git a/plugin/mms_plugin/include/MmsPluginComposer.h b/plugin/mms_plugin/include/MmsPluginComposer.h
new file mode 100755 (executable)
index 0000000..c354d28
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MMS_PLUGIN_COMPOSER_H
+#define MMS_PLUGIN_COMPOSER_H
+
+#include "MmsPluginTypes.h"
+#include "MmsPluginCodec.h"
+
+//make MMS_DATA_S for DB & Encoding
+class MmsPluginComposer {
+public:
+       static MmsPluginComposer *instance();
+
+       void composeNotiInd();
+       void composeDeliveryInd();
+       void composeReadOriInd();
+       void composeRetrieveConf(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_DATA_S *pMmsData){};
+
+       void composeSendReq(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_DATA_S *pMmsData);
+
+       void composeReadReport();
+       void composeAckInd();
+       void composeNotiRespInd();
+
+private:
+       static MmsPluginComposer *pInstance;
+
+       MmsPluginComposer();
+       ~MmsPluginComposer();
+
+};
+#endif //MMS_PLUGIN_COMPOSER_H
index f2bf4c8..f8402d1 100755 (executable)
@@ -1,73 +1,67 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#ifndef MMSPLUGINCONNMANWRAPPER_H
-#define MMSPLUGINCONNMANWRAPPER_H
+#ifndef MMS_PLUGIN_CONNMAN_H
+#define MMS_PLUGIN_CONNMAN_H
 
-#include <network-cm-intf.h>
-#include <network-pm-intf.h>
-
-#include "MsgDebug.h"
-
-#include "MmsPluginTypes.h"
 #include "MsgMutex.h"
+#include "net_connection.h"
 
+typedef enum {
+       MSG_CM_ERR_NONE = 0,
+       MSG_CM_ERR_UNKNOWN,
+ } cm_error_e;
 
 class MmsPluginCmAgent
 {
 public:
        static MmsPluginCmAgent *instance();
 
-       /* open and close are occasionally called when transaction begins and ends */
        bool open();
        void close();
 
        bool getCmStatus() { return isCmOpened; }
 
-       void processCBdatas(net_event_info_t *event_cb, void *user_data);
-
-       bool getDeviceName(char *deviceName);
-       bool getHomeURL(char *homeURL);
-       bool getProxyAddr(char *proxyAddr);
-       int getProxyPort();
-
+       void connection_profile_open_callback(connection_error_e result, void* user_data);
+       void connection_profile_close_callback(connection_error_e result, void* user_data);
+       void connection_profile_state_changed_cb(connection_profile_state_e state, void* user_data);
+       bool getInterfaceName(const char **deviceName);
+       bool getProxyAddr(const char **proxyAddr);
+       bool getHomeUrl(const char **homeURL);
 private:
        MmsPluginCmAgent();
        ~MmsPluginCmAgent();
 
        static MmsPluginCmAgent *pInstance;
 
-       /* register/deregister is called once at initialization/finalization of MMS plugin */
-       bool registration();
-       void deregistration();
-
-
        void lock() { mx.lock(); }
        void unlock() { mx.unlock(); }
        void signal() { cv.signal(); }
+
        void setCmStatus() { isCmOpened = true; }
        void resetCmStatus() { isCmOpened = false; }
 
-       // shared variable between CmAgent and Dnet callback
-       bool isCmOpened;
+       bool isCmOpened; //connection & profile connect
+       bool waitProfileOpen;
+       char *home_url;
+       char *interface_name;
+       char *proxy_address;
        Mutex mx;
        CndVar cv;
 
-       net_profile_info_t mmsProfile;
 };
 
-#endif
-
+#endif //MMS_PLUGIN_CONNMAN_H
diff --git a/plugin/mms_plugin/include/MmsPluginData.h b/plugin/mms_plugin/include/MmsPluginData.h
deleted file mode 100755 (executable)
index e15a223..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#define        MMS_INVALID_MSG_ID      -1
-
-/* Mailbox type */
-#define MSG_UI_MAILBOX_MY_FOLDER_MAX   10
-
-typedef enum {
-       MSG_MAILBOX_ROOT                = -1,
-       MSG_MAILBOX_WRITE               = 0,
-       MSG_MAILBOX_INBOX               = 1,
-       MSG_MAILBOX_DRAFT               = 2,
-       MSG_MAILBOX_SENT                = 3,
-       MSG_MAILBOX_MAILBOX             = 4,
-#ifdef _MSG_DB_INCLUDE_OUTBOX
-       MSG_MAILBOX_OUTBOX              = 5,
-#endif
-       MSG_MAILBOX_TEMPLATE            = 6,            //NEW_TEMPLATE
-       MSG_MAILBOX_MYFOLDER            = 7,
-       MSG_MAILBOX_MYFOLDER_LIST       = 8,
-
-
-       MSG_MAILBOX_PRESET                      = (MSG_MAILBOX_MYFOLDER_LIST  + MSG_UI_MAILBOX_MY_FOLDER_MAX),
-
-       MSG_MAILBOX_NONE
-
-} MsgMailboxType;
-
index a6613a5..d77485e 100755 (executable)
@@ -1,65 +1,28 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MMS_PLUGIN_DEBUG_H
-#define        MMS_PLUGIN_DEBUG_H
+#define MMS_PLUGIN_DEBUG_H
 
-const char *MmsDebugGetMimeType(MimeType mimeType);
-const char *MmsDebugGetMmsReport(MmsReport report);
-const char *MmsDebugGetMmsReportAllowed(MmsReportAllowed reportAllowed);
-const char *MmsDebugGetMmsReadStatus(msg_read_report_status_t readStatus);
-const char *MmsDebugGetMsgType(MmsMsgType msgType);
-const char *MmsDebugGetResponseStatus(MmsResponseStatus responseStatus);
-const char *MmsDebugGetRetrieveStatus(MmsRetrieveStatus retrieveStatus);
-const char *MmsDebugGetMsgStatus(msg_delivery_report_status_t msgStatus);
-const char *MmsDebugGetMsgClass(MmsMsgClass msgClass);
-const char *MmsDebugGetDataType(MmsDataType dataType);
-#ifdef MMS_PLUGIN_DEBUG_ENABLE
-bool MmsDebugPrintMsgAttributes(char *pszFunc, MmsAttrib *pAttrib, bool bAll);
-char *MmsDebugGetMsgDrmType(MsgDrmType drmType);
-char *MmsDebugGetDrmDeliveryMode(DrmDeliveryMode deliveryMode);
-char *MmsDebugGetDrmRightState(DrmRightState rightState);
-bool MmsDebugPrintDrmRight(DrmRight *pDrmRight);
-char *MmsDebugPrintMsgDRMStatus(MsgDRMStatus status);
-bool MmsDebugPrintMulitpartEntry(MsgMultipart *pMultipart, int index);
-char *DebugPrintGetRmResultInd(MmsRmResultInd indType);
-char *DebugPrintHttpStatusCode(int status);
-char *DebugPrintRmMethodType(MmsRmMethodType method);
-char *DebugPrintGetMmsRmNetState(MmsRmNetState state);
-char *DebugPrintGetMmsRmEntityState(MmsRmExEntityState stateEx);
-char *MmsDebugPrintMmsRmResult(MmsRmResult result);
-void MmsDebugPrintReqEntityInfo(MmsRmRequest *pEntity);
-char *MmsDebugPrintHttpErrorCode(int errCode);
-char *MmsDebugPrintProtoErrorCode(int errCode);
-char *DebugPrintWspResult(WspResult wspResult);
-char *DebugPrintWspState(MmsRmWapState wspState);
-char *MmsDebugPrintRmPduType(MmsRmPduType pduType);
-char *MmsDebugPrintMailboxType(MsgMailboxType mailboxType);
-#endif
+#include "MsgDebug.h"
 
-typedef enum {
-       MMS_DEBUG_EV_NONE,
-       MMS_DEBUG_EV_MMS,
-       MMS_DEBUG_EV_SMS,
-       MMS_DEBUG_EV_COMMON,
-       MMS_DEBUG_EV_EMAIL
+#define MMS_DEBUG_STR_FAILED "Failed"
+#define MMS_DEBUG_STR_SUCCESS "Success"
+#define MMS_DEBUG_STR_INVALID_PARAM "Invalid Parameter"
+#define MMS_DEBUG_STR_FILE_NOT_EXIST "File not exist"
 
-} MmsDebugEvType;
-
-bool MmsDebugPrintCurrentEventHandler(char *pszFunc, MmsDebugEvType evType);
 
 #endif //MMS_PLUGIN_DEBUG_H
-
diff --git a/plugin/mms_plugin/include/MmsPluginDecode.h b/plugin/mms_plugin/include/MmsPluginDecode.h
new file mode 100755 (executable)
index 0000000..ddd3b3e
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MMS_PLUGIN_DECODE_H
+#define MMS_PLUGIN_DECODE_H
+
+#include "MmsPluginTypes.h"
+#include "MmsPluginCodecTypes.h"
+
+typedef struct _MsgHeaderAddress       MsgHeaderAddress;
+
+typedef int MmsMsgID;
+
+typedef enum {
+       MSG_PRESENTATION_NONE = -1,
+       MSG_PRESENTATION_FIRSTPART,             //Content-type == type parameter
+       MSG_PRESENTATION_TYPE_BASE,             //Content-type == type parameter
+       MSG_PRESENTATION_LOCATION,              //Content-Location == start parameter
+       MSG_PRESENTATION_ID,                    //Content-ID == start parameter
+} MsgPresentationFactor;
+
+typedef struct {
+       MsgPresentationFactor factor;
+       MsgMultipart *pPrevPart;
+       MsgMultipart *pCurPresentation;
+} MsgPresentaionInfo;
+
+struct _MsgHeaderAddress {
+       char *szAddr;
+       MsgHeaderAddress *pNext;
+};
+
+// for Decoding & Encoding
+typedef struct {
+       MmsMsgType type;
+       char szTrID[MMS_TR_ID_LEN+1];
+       UINT8 version;
+       UINT32 date;
+
+       MsgHeaderAddress *pFrom;                //"/TYPE=PLMN", /"TYPE=IPv4", "/TYPE=IPv6"
+       MsgHeaderAddress *pTo;
+       MsgHeaderAddress *pCc;
+       MsgHeaderAddress *pBcc;
+       char szSubject[MSG_LOCALE_SUBJ_LEN + 1];
+       MmsResponseStatus responseStatus;
+       MmsRetrieveStatus retrieveStatus;
+       char szResponseText[MMS_LOCALE_RESP_TEXT_LEN + 1];
+       char szRetrieveText[MMS_LOCALE_RESP_TEXT_LEN + 1];
+
+       MmsMsgClass msgClass;
+       MmsTimeStruct expiryTime;
+       MmsTimeStruct deliveryTime;
+       MmsPriority priority;
+       MmsSenderVisible hideAddress;
+       MmsReport deliveryReport;
+       MmsReport readReply;
+       MmsReportAllowed reportAllowed;
+       char szContentLocation[MMS_LOCATION_LEN + 1];
+
+       msg_delivery_report_status_t msgStatus;
+       msg_read_report_status_t readStatus;
+
+       MmsReplyCharge replyCharge;
+
+       // only used at Decoding module
+       char szMsgID[MMS_MSG_ID_LEN + 1];
+       UINT32 msgSize;
+
+       MsgDrmType drmType;
+
+       // dependent to Client implementation
+       MsgType msgType;
+       MsgBody msgBody;
+} MmsHeader;
+
+extern __thread MmsHeader mmsHeader;
+
+/* Decoding */
+void MmsInitHeader();
+void MmsReleaseHeader(MmsHeader *mms);
+void MmsRegisterDecodeBuffer();
+void MmsUnregisterDecodeBuffer(void);
+bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength);
+bool MmsBinaryDecodeMsgBody(FILE *pFile, char *szFilePath, int totalLength);
+bool MmsReadMsgBody(msg_message_id_t msgID, bool bSavePartsAsTempFiles, bool bRetrieved, char *retrievedPath);
+
+
+char *MsgChangeHexString(char *pOrg);
+char *MsgResolveContentURI(char *szSrc);
+char *MsgRemoveQuoteFromFilename(char *pSrc);
+bool MsgIsMultipart(int type);
+bool MmsAddrUtilRemovePlmnString(char *pszAddr);
+bool MmsAddrUtilCheckEmailAddress(char *pszAddr);
+bool MsgGetFileNameWithoutExtension(char *szOutputName, char *szName);
+bool MsgGetFileName(char *szFilePath, char *szFileName, int size);
+bool MmsGetMediaPartHeader(int index, MsgType *pHeader);
+
+class MmsPluginDecoder {
+public:
+       static MmsPluginDecoder *instance();
+
+       void decodeMmsPdu(MmsMsg *pMmsMsg, msg_message_id_t msgID, const char *pduFilePath);
+private:
+       static MmsPluginDecoder *pInstance;
+
+       MmsPluginDecoder();
+       ~MmsPluginDecoder();
+
+};
+#endif //MMS_PLUGIN_DECODE_H
index 6044337..f40112b 100755 (executable)
@@ -1,39 +1,24 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#include "MsgMmsTypes.h"
-#include "MmsPluginMessage.h"
+#ifndef MMS_PLUGIN_DRM_H
+#define MMS_PLUGIN_DRM_H
 
-#ifdef __SUPPORT_DRM__
+#include "MmsPluginCodecTypes.h"
 
-#define        MMS_DECODE_DRM_CONVERTED_TEMP_FILE MSG_DATA_PATH"Mms_Decode_Drm_Converted"
-#define        MMS_MIMETYPELENGTH 50
+bool MmsPluginDrmGetInfo(const char *szFilePath, MsgType *pMsgType);
 
-typedef        enum {
-       MMS_DRM2_CONVERT_NONE,
-       MMS_DRM2_CONVERT_NOT_FIXED,
-       MMS_DRM2_CONVERT_REQUIRED,
-       MMS_DRM2_CONVERT_FINISH
-} MmsDrm2ConvertState;
-
-MsgDrmType MsgGetDRMType(MsgType *pMsgType, MsgBody *pMsgBody);
-void MmsDrm2SetConvertState(MmsDrm2ConvertState newConvertState);
-MmsDrm2ConvertState MmsDrm2GetConvertState(void);
-bool MsgDRM2GetDRMInfo(char *szFilePath, MsgType *pMsgType);
-bool MsgDRMIsForwardLockType(MsgDrmType drmType);
-bool MsgChangeDrm2FileName(char *szFileName);
-bool MsgIsDCFFile(char *szFilePath);
-#endif
+#endif //MMS_PLUGIN_DRM_H
diff --git a/plugin/mms_plugin/include/MmsPluginEncode.h b/plugin/mms_plugin/include/MmsPluginEncode.h
new file mode 100755 (executable)
index 0000000..235b45b
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MMS_PLUGIN_ENCODE_H
+#define MMS_PLUGIN_ENCODE_H
+
+#include <stdio.h>
+#include "MmsPluginCodecTypes.h"
+#include "MmsPluginCodecCommon.h"
+#include "MmsPluginMessage.h"
+
+/* Encoding */
+void MmsRegisterEncodeBuffer(char *pInBuff, int maxLen);
+void MmsUnregisterEncodeBuffer(void);
+
+bool MmsEncodeSendReq(FILE *pFile, MmsMsg *pMsg);
+bool MmsEncodeTemplate(FILE *pFile, MmsMsg *pMsg);
+bool MmsEncodeAckInd(FILE *pFile, char *szTrID, bool bReportAllowed);
+bool MmsEncodeNotiRespInd(FILE *pFile, char *szTrID, msg_delivery_report_status_t iStatus, bool bReportAllowed);
+
+bool MmsEncodeReadReport10(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus);
+bool MmsEncodeReadReport11(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus);
+
+class MmsPluginEncoder {
+public:
+       static MmsPluginEncoder *instance();
+
+       void encodeMmsPdu(MMS_DATA_S *pMmsData, msg_message_id_t msgID, const char *pduFilePath);
+       void encodeMmsPdu(MmsMsg *pMmsMsg, msg_message_id_t msgID, const char *pduFilePath);
+private:
+       static MmsPluginEncoder *pInstance;
+
+       MmsPluginEncoder();
+       ~MmsPluginEncoder();
+
+};
+#endif //MMS_PLUGIN_ENCODE_H
index 884c5b5..2aa676b 100755 (executable)
@@ -1,40 +1,31 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MMS_PLUGIN_EVENT_HANDLER_H
 #define MMS_PLUGIN_EVENT_HANDLER_H
 
-
-/*==================================================================================================
-                                                       INCLUDE FILES
-==================================================================================================*/
 #include "MsgPluginInterface.h"
 #include "MmsPluginTypes.h"
-#include "MmsPluginMessage.h"
 
-/*==================================================================================================
-                                                       CLASS DEFINITIONS
-==================================================================================================*/
 class MmsPluginEventHandler
 {
 public:
        static MmsPluginEventHandler *instance();
 
        void registerListener(MSG_PLUGIN_LISTENER_S *pListener);
-       void handleSentStatus(int TapiReqId, msg_network_status_t NetStatus);
        void handleMmsReceivedData(mmsTranQEntity *pRequest, char *pRetrivedFilePath);
        void handleMmsError(mmsTranQEntity *pRequest);
 
@@ -48,4 +39,3 @@ private:
 };
 
 #endif //MMS_PLUGIN_EVENT_HANDLER_H
-
index 920a231..2292337 100755 (executable)
@@ -1,55 +1,91 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#ifndef MMSPLUGINHTTP_H
-#define MMSPLUGINHTTP_H
+#ifndef MMS_PLUGIN_HTTP_H
+#define MMS_PLUGIN_HTTP_H
 
 #include <map>
-
-#include "MsgDebug.h"
 #include "MmsPluginTypes.h"
 #include "MsgMutex.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
+#define MSG_MMS_HH_CONTENT_TYPE     "application/vnd.wap.mms-message"
+#define MSG_MMS_HH_ACCEPT           "application/vnd.wap.mms-message, */*"
+#define MSG_MMS_HH_CHARSET          "utf-8"
+#define MSG_MMS_HH_LANGUAGE         "zh-cn, en"
+#define MSG_MMS_HH_ENCODING         "deflate,gzip"
 
+#define MSG_MMS_HH_USER_AGENT          "Mozilla/5.0 (Linux; Tizen 2.3) AppleWebKit/537.3 (KHTML, like Gecko) Version/2.2 Mobile Safari/537.3"
 
-#ifdef __cplusplus
-}
-#endif
+typedef unsigned int MMS_HTTP_HEADER_FIELD_T;
 
+typedef enum _MMS_HTTP_HEADER_FIELD_E {
+       MMS_HH_CONTENT_TYPE,
+       MMS_HH_HOST,
+       MMS_HH_ACCEPT,
+       MMS_HH_ACCEPT_CHARSET,
+       MMS_HH_ACCEPT_LANGUAGE,
+       MMS_HH_ACCEPT_ENCODING,
+       MMS_HH_USER_AGENT,
+       MMS_HH_UA_PROFILE,
+#if defined(FEATURE_SMS_CDMA)
+       MMS_HH_MDN
+#endif
+} MMS_HTTP_HEADER_FIELD_E;
+
+typedef enum _MMS_HTTP_TRANSACTION_TYPE_E {
+       MMS_HTTP_TRANSACTION_TYPE_UNKNOWN = 0,
+       MMS_HTTP_TRANSACTION_TYPE_GET,
+       MMS_HTTP_TRANSACTION_TYPE_POST,
+} MMS_HTTP_TRANSACTION_TYPE_E;
+
+typedef enum _MMS_HTTP_ERROR_E {
+       MMS_HTTP_ERROR_NONE = 0,
+       MMS_HTTP_ERROR_ABORT,
+       MMS_HTTP_ERROR_TRANSACTION_TYPE,
+       MMS_HTTP_ERROR_TRANSACTION,
+       MMS_HTTP_ERROR_SESSION,
+} MMS_HTTP_ERROR_E;
+
+typedef struct _http_session_info_s {
+       MMS_HTTP_TRANSACTION_TYPE_E transaction_type;
+       const char *url;
+       const char *proxy;
+       const char *interface;
+       const char *post_data;
+       unsigned int post_data_len;
+       char *response_data;
+       unsigned int response_data_len;
+} http_request_info_s;
 
 class MmsPluginHttpAgent
 {
        public:
                static MmsPluginHttpAgent *instance();
 
-               int cmdRequest(MMS_HTTP_CMD_TYPE_T cmdType);
-
-               int setSession(mmsTranQEntity *qEntity);
-
-               void clearSession();
+               MMS_HTTP_ERROR_E httpRequest(http_request_info_s &request_info);
 
-               void SetMMSProfile();
+               void setAbortFlag(){
+                       MutexLocker locker(mx);
+                       abort = true;
+               };
 
-               MMS_PLUGIN_HTTP_DATA_S *getHttpConfigData();
-               MMS_PLUGIN_HTTP_CONTEXT_S *getMmsPldCd();
-
-               MMS_PLUGIN_HTTP_DATA_S httpConfigData;
+               bool getAbortFlag(){
+                       MutexLocker locker(mx);
+                       return abort;
+               };
 
        private:
                static MmsPluginHttpAgent *pInstance;
@@ -57,32 +93,24 @@ class MmsPluginHttpAgent
                MmsPluginHttpAgent();
                ~MmsPluginHttpAgent();
 
-               MMS_PLUGIN_HTTP_CONTEXT_S mmsPlgCd;
-
-               std::map<MMS_HTTP_CMD_TYPE_T,int(*)(MMS_PLUGIN_HTTP_DATA_S *)> httpCmdHandler;
-};
+               void initSession();
+               MMS_HTTP_ERROR_E setSession(http_request_info_s &request_info);
+               MMS_HTTP_ERROR_E startTransaction();
+               void clearSession();
 
+               void initAbortFlag(){
+                       MutexLocker locker(mx);
+                       abort = false;
+               };
 
-#define MSG_MMS_HH_CONTENT_TYPE     "application/vnd.wap.mms-message"
-#define MSG_MMS_HH_ACCEPT           "application/vnd.wap.mms-message, */*"
-#define MSG_MMS_HH_CHARSET          "utf-8"
-#define MSG_MMS_HH_LANGUAGE         "zh-cn, en"
-#define MSG_MMS_HH_ENCODING         "deflate,gzip"
+               MMS_HTTP_TRANSACTION_TYPE_E transaction_type;
 
-#define MSG_MMS_HH_USER_AGENT          "Tizen", "Mozilla/5.0 (Linux; U; Tizen 1.0; en-us) AppleWebKit/534.46 (KHTML, like Gecko) Mobile Tizen Browser/1.0"
-#define MSG_MMS_WAP_PROFILE         ""
+               void *session_header;
+               void *session_option;
 
-typedef unsigned int MMS_HTTP_HEADER_FIELD_T;
-
-enum _MMS_HTTP_HEADER_FIELD_E {
-       MMS_HH_CONTENT_TYPE,
-       MMS_HH_HOST,
-       MMS_HH_ACCEPT,
-       MMS_HH_ACCEPT_CHARSET,
-       MMS_HH_ACCEPT_LANGUAGE,
-       MMS_HH_ACCEPT_ENCODING,
-       MMS_HH_USER_AGENT,
-       MMS_HH_WAP_PROFILE
+               FILE *respfile;
+               bool abort;
+               Mutex mx;
 };
 
-#endif
+#endif //MMS_PLUGIN_HTTP_H
index ada68bb..53550f3 100755 (executable)
@@ -1,34 +1,25 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MMS_PLUGIN_INTERNAL_H
 #define MMS_PLUGIN_INTERNAL_H
 
-/*==================================================================================================
-                                                       INCLUDE FILES
-==================================================================================================*/
-#include "MsgStorageTypes.h"
-#include "MsgTypes.h"
-#include "MsgTransportTypes.h"
-#include "MmsPluginMessage.h"
 #include "MmsPluginTypes.h"
+#include "MmsPluginCodecTypes.h"
 
-/*==================================================================================================
-                                                       CLASS DEFINITIONS
-==================================================================================================*/
 class MmsPluginInternal
 {
        public:
@@ -51,8 +42,10 @@ class MmsPluginInternal
                void processDeliveryInd(MSG_MESSAGE_INFO_S *pMsgInfo);
                void processReadOrgInd(MSG_MESSAGE_INFO_S *pMsgInfo);
                bool checkRejectNotiInd(int roamState, bool bReportAllowed, char *pSendFilePath);
+               bool checkFilterMmsBody(MMS_DATA_S *pMmsData);
                bool getMmsReport(MmsReport mmsReport);
                const char *getMmsDeliveryStatus(msg_delivery_report_status_t deliveryStatus);
                const char *getMmsReadStatus(msg_read_report_status_t readStatus);
 };
-#endif
+
+#endif //MMS_PLUGIN_INTERNAL_H
index 29cefa9..fe53ff8 100755 (executable)
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#ifndef _UTY_MIME_H_
-#define _UTY_MIME_H_
+#ifndef MMS_PLUGIN_MIME_H
+#define MMS_PLUGIN_MIME_H
 
-#include "MsgMmsTypes.h"
+#include "MmsPluginTypes.h"
 
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#define                MSG_CH_CR                                               '\r'
-#define                MSG_CH_LF                                               '\n'
-#define                MSG_CH_SP                                               ' '
-#define                MSG_CH_TAB                                              '\t'
-#define                MSG_CH_NULL                                             '\0'
-#define                MSG_CH_COLON                                    ':'
-#define                MSG_CH_SEMICOLON                                ';'
-#define                MSG_CH_UNDERLINE                                '_'
-#define                MSG_CH_COMMA                                    ','
-#define                MSG_CH_BASE64_LOWER                             'b'
-#define                MSG_CH_BASE64_UPPER                             'B'
-#define                MSG_CH_QPRINT_LOWER                             'Q'
-#define                MSG_CH_QPRINT_UPPER                             'q'
-
-#define                MSG_CH_QUESTION                                 '?'
-#define                MSG_CH_QUOT                                             '"'
-#define                MSG_CH_EQUAL                                    '='
-#define                MSG_CH_BRACKET_S                                '<'
-#define                MSG_CH_BRACKET_E                                '>'
-
-#define                MSG_STR_DEC_START                       "=?"
-#define                MSG_STR_DEC_END                         "?="
-#define                MSG_STR_CRLF                            "\r\n"
-#define                MSG_END_OF_HEADER                       "\r\n\r\n"
-#define                MSG_STR_DOUBLE_HYPEN            "--"
-#define                MSG_STR_BOUNDARY_DEL            "\r\n--"
-
-#define                MSG_MMS_STR_ADDR_DELIMETER      MSG_STR_ADDR_DELIMETER
-#define                MSG_MMS_CH_ADDR_DELIMETER       MSG_CH_ADDR_DELIMETER
-#define                MSG_MMS_CH_EMAIL_AT                     '@'
-
-
-/* character-set parameter value of content-type header field */
-enum {
-       MSG_CHARSET_US_ASCII,                   //0
-       MSG_CHARSET_UTF16,
-       MSG_CHARSET_USC2,
-       MSG_CHARSET_UTF8,
-       /* MIME character-set value */
-
-       MSG_CHARSET_ISO_2022_KR,
-       MSG_CHARSET_KS_C_5601_1987,
-       MSG_CHARSET_EUC_KR,     // KS_C5861-1992
-       MSG_CHARSET_ISO_2022_JP,
-       MSG_CHARSET_ISO_2022_JP_2,
-       MSG_CHARSET_ISO_8859_1,                 //Latin1
-       MSG_CHARSET_ISO_8859_2,
-       MSG_CHARSET_ISO_8859_3,
-       MSG_CHARSET_ISO_8859_4,
-       MSG_CHARSET_ISO_8859_5,
-       MSG_CHARSET_ISO_8859_6,
-       MSG_CHARSET_ISO_8859_6_E,
-       MSG_CHARSET_ISO_8859_6_I,
-       MSG_CHARSET_ISO_8859_7,
-       MSG_CHARSET_ISO_8859_8,
-       MSG_CHARSET_ISO_8859_8_I,
-       MSG_CHARSET_ISO_8859_9,
-       MSG_CHARSET_ISO_8859_10,
-       MSG_CHARSET_ISO_8859_15,
-       MSG_CHARSET_Shift_JIS,
-       MSG_CHARSET_EUC_JP,
-       MSG_CHARSET_GB2312,
-       MSG_CHARSET_BIG5,
-       MSG_CHARSET_WIN1251,
-       MSG_CHARSET_WINDOW_1251,
-       MSG_CHARSET_WINDOWS_1251, // same: WIN1251, WINDOW-1251, WINDOWS-1251
-       MSG_CHARSET_KOI8_R,
-       MSG_CHARSET_KOI8_U,
-
-       MSG_CHARSET_NUM,
-       MSG_CHARSET_UNKNOWN
-};
-
-/* Content-Transfer-Encoding header field value */
-enum {
-       MSG_ENCODING_7BIT,
-       MSG_ENCODING_8BIT,
-       MSG_ENCODING_BINARY,
-       MSG_ENCODING_BASE64,
-       MSG_ENCODING_QUOTE_PRINTABLE,
-       MSG_ENCODING_NUM,
-       MSG_ENCODING_OTHER,
-};
-
-
-/* Content-Disposition header field value */
-enum {
-       MSG_DISPOSITION_FORMDATA,
-       MSG_DISPOSITION_ATTACHMENT,
-       MSG_DISPOSITION_INLINE,
-       MSG_DISPOSITION_NUM
-};
-
-#define                UNDEFINED_BINARY        0xFF
-#define                MSG_UNKNOWN_TYPE_STRING         "unknown"
+#define UNDEFINED_BINARY       0xFF
 
 typedef enum _MimeMainType {
+       MIME_MAINTYPE_UNKNOWN = -1,
        MIME_MAINTYPE_APPLICATION,
        MIME_MAINTYPE_AUDIO,
        MIME_MAINTYPE_IMAGE,
@@ -131,154 +34,20 @@ typedef enum _MimeMainType {
        MIME_MAINTYPE_ETC
 } MimeMainType;
 
-typedef enum _MimeAppType {
-       MIME_APPLICATION_NONE,
-
-       MIME_APPLICATION_CAMERA,
-       MIME_APPLICATION_VIDEORECORDER,
-
-       MIME_APPLICATION_IMAGEVIEWER,
-       MIME_APPLICATION_FLASHVIEWER,
-       MIME_APPLICATION_IMAGEEDITOR,
-       MIME_APPLICATION_THEMEVIEWER,
-
-       MIME_APPLICATION_SOUNDPLAYER,
-       MIME_APPLICATION_MEDIAPLAYER,
-       MIME_APPLICATION_VOICEMEMO,
-
-       MIME_APPLICATION_PICSELVIEWER,
-
-       MIME_APPLICATION_CONTACT,
-       MIME_APPLICATION_ORGANIZER,
-
-       MIME_APPLICATION_MAX
-} MimeAppType;
-
-
-typedef struct _MimeTable {
-       const char *szMIME;
-       const char *szExt;
-       bool bDownloadable;
-       MimeType mime;                  /* index of mime type */
-       MimeType contentType;   /* representative mime type */
-       MimeAppType appType;
-       MimeMainType mainType;
-       int binary;
-} MimeTable;
-
-typedef struct _ExtTable {
-       const char *szExt;
-       MimeType mimeType;
-} ExtTable;
-
-/* MIME string table ID */
-typedef enum {
-       MSG_ENCODING,
-       MSG_DISPOSITION,
-       MSG_FIELD,
-       MSG_PARAM,
-       MSG_TYPE,
-       MSG_CHARSET,
-       MSG_ADDR_TYPE,
-} MsgHeaderField;
-
-typedef enum {
-       MSG_ADDR_TYPE_ERROR = -1,               // error return in Get method
-       MSG_ADDR_TYPE_PHONE = 0,
-       MSG_ADDR_TYPE_EMAIL = 1,
-       MSG_ADDR_TYPE_IPV4  = 2,
-       MSG_ADDR_TYPE_IPV6  = 3,
-       MSG_ADDR_TYPE_ALIAS = 4,
-       MSG_ADDR_TYPE_NUM   = 5,
-} MsgAddrType;
-
-/* MIME header field */
-enum {
-       MSG_FIELD_RETURN_PATH,
-       MSG_FIELD_MESSAGE_ID,
-       MSG_FIELD_FROM,
-       MSG_FIELD_TO,
-       MSG_FIELD_CC,
-       MSG_FIELD_SUBJECT,
-       MSG_FIELD_DATE,
-       MSG_FIELD_MIME_VERSION,
-       MSG_FIELD_CONTENT_TYPE,
-       MSG_FIELD_CONTENT_TRANSFER_ENCODING,
-       MSG_FIELD_CONTENT_DISPOSITION, //If start param is given in multipart/related, this field will be ignored
-       MSG_FIELD_CONTENT_ID,
-       MSG_FIELD_CONTENT_LOCATION,
-       MSG_FIELD_CONTENT_NAME,
-       MSG_FIELD_CONTENT_DESCRIPTION,
-       MSG_FIELD_CONTENT_VENDOR,
-       MSG_FIELD_RIGHT_ISSUER,
-
-       MSG_FIELD_RETURN_RECEIPT_TO,                    /* for Delivery confirm */
-       MSG_FIELD_DISPOSITION_NOTIFICATION_TO,  /* for Read confirm */
-
-       MSG_FILED_CONTENT_REPLACE_POS,
-       MSG_FILED_CONTENT_REPLACE_SIZE,
-       MSG_FILED_CONTENT_REPLACE_INDEX,
-#ifdef __SUPPORT_DRM__
-       MSG_FIELD_DRM_CONVERTED,
-#endif
-       MSG_FIELD_NUM,
-       MSG_FIELD_UNKNOWN,
-};
-
-/* MIME header field parameter */
-enum {
-       MSG_PARAM_CHARSET,
-       MSG_PARAM_NAME,
-       MSG_PARAM_FILENAME,
-       MSG_PARAM_TYPE,                 // only used as parameter of Content-Type: multipart/related
-       MSG_PARAM_START,                // Only if content-type is multipart/related
-       MSG_PARAM_START_INFO,   // Only if content-type is multipart/related
-       MSG_PARAM_BOUNDARY,
-       MSG_PARAM_REPORT_TYPE,  // only used as parameter of Content-Type: multipart/report; report-type=delivery-status;
-#ifdef FEATURE_JAVA_MMS
-       MSG_PARAM_APPLICATION_ID,
-       MSG_PARAM_REPLY_TO_APPLICATION_ID,
-#endif
-       MSG_PARAM_NUM,
-       MSG_PARAM_UNKNOWN,
-};
-
-/********************          API definition           ************************/
-
-bool MimeIsDownloadableInt(MimeType mime);
-bool MimeIsDownloadableString(const char *szMime);
 char *MimeGetExtFromMimeInt(MimeType mime);
-char *MimeGetExtFromMimeString(const char *szMime);
-char *MimeGetMimeFromExtString(const char *szExt);
-MimeType MimeGetMimeFromExtInt(const char *szExt);
-MimeMainType MimeGetMainTypeInt(MimeType mime);
-MimeMainType MimeGetMainTypeString(const char *szMime);
-MimeType MimeGetMimeIntFromBi(int binCode);
-char *MimeGetMimeStringFromBi(int binCode);
-int MimeGetBinaryValueFromMimeInt(MimeType mime);
-int MimeGetBinaryValueFromMimeString(const char *szMime);
 
-// Append the functions on MimeAppType
-MimeAppType MimeGetAppTypeFromInt(MimeType mime);
-MimeAppType MimeGetAppTypeFromString(const char *szMime);
-MimeAppType MimeGetAppTypeFromExtString(const char *szExt);
+MimeMainType MimeGetMainTypeInt(MimeType mime);
 
-// Append the functions returning index and content type
+MimeType MimeGetMimeIntFromBi(int binCode);
 
-MimeType MimeGetContentTypeFromInt(MimeType mime);
-MimeType MimeGetContentTypeFromString(const char *szMime);
-MimeType MimeGetMimeTypeFromString(const char *szMime);
+int MimeGetBinaryValueFromMimeInt(MimeType mime);
 
 MimeType MimeGetMimeIntFromMimeString(char *szMimeStr);
-char *MimeGetMimeStringFromMimeInt(int mimeType);
 
-char *MsgGetString(MsgHeaderField tableId, int code);
-char *_MsgSkipWS3(char *s);
-int    _MsgGetCode(MsgHeaderField tableId, char *pStr);
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
+char *MimeGetMimeStringFromMimeInt(int mimeType);
 
-#endif // _UTY_MIME_H_
+bool MmsGetMimeTypeFromExt(MimeMainType mainType, const char *pExt, MimeType *pMimeType, const char **ppszMimeType);
 
+bool MmsGetMimeTypeFromFileName(MimeMainType mainType, const char *pFileName, MimeType *pMimeType, const char **ppszMimeType);
 
+#endif // MMS_PLUGIN_MIME_H
index c01ec76..527dff8 100755 (executable)
@@ -1,26 +1,23 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MMS_PLUGIN_MAIN_H
 #define MMS_PLUGIN_MAIN_H
 
-/*==================================================================================================
-                                                       INCLUDE FILES
-==================================================================================================*/
-#include "MsgTypes.h"
+#include "MmsPluginTypes.h"
 #include "MsgPluginInterface.h"
 
 #ifdef __cplusplus
@@ -29,9 +26,6 @@ extern "C"
 {
 #endif
 
-/*==================================================================================================
-                                                       FUNCTION PROTOTYPES
-==================================================================================================*/
 msg_error_t MmsInitialize();
 
 msg_error_t MmsFinalize();
@@ -46,7 +40,7 @@ msg_error_t MmsProcessReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST_INFO
 
 msg_error_t MmsUpdateMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData);
 
-msg_error_t MmsGetMmsMessage(MSG_MESSAGE_INFO_S *pMsg,  MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_MESSAGE_DATA_S *pMmsMsg, char **pDestMsg);
+msg_error_t MmsGetMmsMessage(MSG_MESSAGE_INFO_S *pMsg,  MSG_SENDINGOPT_INFO_S *pSendOptInfo, char **pDestMsg);
 
 msg_error_t MmsUpdateRejectStatus(MSG_MESSAGE_INFO_S *pMsgInfo);
 
@@ -54,6 +48,8 @@ msg_error_t MmsComposeReadReport(MSG_MESSAGE_INFO_S *pMsgInfo);
 
 msg_error_t MmsRestoreMsg(MSG_MESSAGE_INFO_S *pMsgInfo, char *pRcvBody, int rcvdBodyLen, char *filePath);
 
+msg_error_t MmsDeleteMessage(msg_message_id_t msgId);
+
 #ifdef __cplusplus
 }
 #endif
index 2969908..a12ad04 100755 (executable)
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MMS_PLUGIN_MESSAGE_H
 #define MMS_PLUGIN_MESSAGE_H
 
+#include "MmsPluginTypes.h"
+#include "MmsPluginCodec.h"
 
-/*==================================================================================================
-                                                       INCLUDE FILES
-==================================================================================================*/
-#include "MsgTypes.h"
-#include "MsgInternalTypes.h"
-#include "MsgMmsTypes.h"
-#include "MsgSettingTypes.h"
-#include "MmsPluginMIME.h"
-#include "MsgMmsTypes.h"
 
-/*==================================================================================================
-                                                       DEFINES
-==================================================================================================*/
-#define                MMS_CONTENT_ID_LEN                              100
-#define                MMS_LOCALE_RESP_TEXT_LEN                90
-#define                MMS_TEXT_LEN                                            2000
-#define                MMS_READ_REPORT_STRING_READ             "Read:"
-#define                MMS_READ_REPORT_STRING_DELETED  "Deleted:"
-
-#define                MSG_ATTACH_MAX          20
-#define                MSG_LINE_LEN                                            1024
-#define                MSG_SUBJ_LEN                                            40
-#define                MSG_DATE_LEN                                            50
-#define                MSG_BOUNDARY_LEN                                        70
-#define                MSG_LOCALE_NAME_LEN                             150
-#define                MSG_LOCALE_SUBJ_LEN                             (3 * MSG_SUBJ_LEN)
-#define                MSG_ADDR_LEN                                            MAX_ADDRESS_VAL_LEN
-#define                MSG_LOCALE_ADDR_LEN                             (3 * MAX_ADDRESS_VAL_LEN)
-#define                MSG_LOCALE_FILENAME_LEN_MAX             (3 * 255)
-#define                MSG_LOCALE_SIGN_LEN                                     (3 * MAX_SIGN_VAL_LEN)
-#define                MSG_MAILBOX_NAME_LEN            10
-
-#define                MsgContentType                                          MimeType
-#define                MsgRecipientType                                        msg_recipient_type_t
-#define                MMS_VERSION                                             0x92
-#define                MSG_STR_ADDR_DELIMETER                  ";"
-#define                MSG_CH_ADDR_DELIMETER                   ';'
-#ifdef __SUPPORT_DRM__
-#define                MSG_DRM_MAX_CMD                                 (2 * 1024)
-#endif
-
-#define                MSG_MMS_DECODE_BUFFER_MAX       (2 * 1024)
-#define                MSG_MMS_ENCODE_BUFFER_MAX       (2 * 1024)
-
-/*==================================================================================================
-                                                       TYPES
-==================================================================================================*/
-typedef unsigned int                   UINT;
-typedef unsigned long int              UINT32;
-typedef unsigned char                  UINT8;
-typedef unsigned short int             UINT16;
-typedef unsigned long                  ULONG;
-typedef unsigned char                  UCHAR;
-typedef unsigned short                 MCHAR;
-typedef unsigned short                 USHORT;
-
-typedef int                                            MmsMsgID;
-
-typedef        struct _MsgAddress      MsgAddress;
-typedef struct _MsgBody                MsgBody;
-typedef struct _MsgMultipart   MsgMultipart;
-typedef struct _MsgMessage     MsgMessage;
-
-typedef struct _MsgHeaderAddress       MsgHeaderAddress;
-
-/*==================================================================================================
-                                                       ENUMS
-==================================================================================================*/
-
-typedef enum {
-       MMS_DATATYPE_NONE = -1,
-       MMS_DATATYPE_READ = 0,
-       MMS_DATATYPE_SENT = 1,
-       MMS_DATATYPE_NOTIFY = 2,
-       MMS_DATATYPE_UNSENT = 3,
-       MMS_DATATYPE_DRAFT = 4,
-       MMS_DATATYPE_SENDING = 6,
-       MMS_DATATYPE_RETRIEVING = 7,
-       MMS_DATATYPE_UNRETV = 8,
-       MMS_DATATYPE_TEMPLATE = 9,
-       MMS_DATATYPE_DRM_RO_WAITING = 10        // DRM RO WAITING
-
-} MmsDataType;
-
-typedef        enum {
-       MMS_MSGTYPE_ERROR = -1, // error return in Get method
-       MMS_MSGTYPE_SEND_REQ = 0,       // default
-       MMS_MSGTYPE_SEND_CONF = 1,
-       MMS_MSGTYPE_NOTIFICATION_IND = 2,
-       MMS_MSGTYPE_NOTIFYRESP_IND = 3,
-       MMS_MSGTYPE_RETRIEVE_CONF = 4,
-       MMS_MSGTYPE_ACKNOWLEDGE_IND = 5,
-       MMS_MSGTYPE_DELIVERY_IND = 6,
-       MMS_MSGTYPE_READREC_IND = 7,
-       MMS_MSGTYPE_READORG_IND = 8,
-       MMS_MSGTYPE_FORWARD_REQ = 9,
-       MMS_MSGTYPE_FORWARD_CONF = 10,
-       MMS_MSGTYPE_READ_REPLY = 11,    // for internal use
-
-       MMS_MSGTYPE_MAX
-} MmsMsgType;
-
-typedef        enum {
-       MMS_PRIORITY_ERROR = -1,                        // error return in Get method
-       MMS_PRIORITY_LOW = 0,                   // default
-       MMS_PRIORITY_NORMAL = 1,
-       MMS_PRIORITY_HIGH = 2
-} MmsPriority;
-
-
-typedef enum {
-       MMS_SENDER_VISIBLE_ERROR = -1,  // error return in Get method
-       MMS_SENDER_SHOW = 0,
-       MMS_SENDER_HIDE = 1
-} MmsSenderVisible;
-
-
-typedef        enum {
-       MMS_REPORT_ERROR = -1,  // error return in Get method
-       MMS_REPORT_YES = 0,
-       MMS_REPORT_NO = 1
-} MmsReport;
-
-
-typedef enum {
-       MMS_REPORTALLOWED_ERROR = -1,   // error return in Get method
-       MMS_REPORTALLOWED_YES = 0,
-       MMS_REPORTALLOWED_NO = 1
-} MmsReportAllowed;
-
-
-typedef enum {
-       MMS_RECEIVE_READ_REPORT_ALLOWED,
-       MMS_RECEIVE_READ_REPORT_PROMPT,
-       MMS_RECEIVE_READ_REPORT_NOT_ALLOWED,
-} MmsRecvReadReportType ;
-
-
-typedef enum {
-       MMS_MSGSTATUS_NONE = -1,        // backward compatibility
-       MMS_MSGSTATUS_ERROR = -1,       // error return in Get method
-       MMS_MSGSTATUS_EXPIRED = 0,
-       MMS_MSGSTATUS_RETRIEVED = 1,
-       MMS_MSGSTATUS_REJECTED = 2,
-       MMS_MSGSTATUS_DEFERRED = 3,
-       MMS_MSGSTATUS_UNRECOGNISED = 4, // This value SHALL not be used in the M-Delivery.ind PDU.
-       MMS_MSGSTATUS_INDETERMINATE = 5,
-       MMS_MSGSTATUS_FORWARDED = 6,
-       MMS_MSGSTATUS_UNREACHABLE = 7
-} MmsMsgStatus;
-
-
-typedef        enum {
-       MMS_READSTATUS_NONE = -1,                       // no touch status
-       MMS_IS_READ = 0,
-       MMS_IS_DELETED = 1
-} MmsReadStatus;
-
-
-typedef enum {
-       MMS_ADDRESS_PRESENT_TOKEN,
-       MMS_INSERT_ADDRESS_TOKEN
-} MmsAddressType;
-
-typedef enum {
-       MSG_PARAM_REPORT_TYPE_DELIVERY_STATUS,
-       MSG_PARAM_REPORT_TYPE_NUM,
-       MSG_PARAM_REPORT_TYPE_UNKNOWN,
-} MsgParamReportType;
-
-/* Response status */
-typedef        enum {
-       MMS_RESPSTATUS_ERROR = -1,      // error return in Get method
-       MMS_RESPSTATUS_OK = 0,  // default value
-       MMS_RESPSTAUTS_ERROR_UNSPECIFIED = 1,
-       MMS_RESPSTAUTS_ERROR_SERVICEDENIED = 2,
-       MMS_RESPSTAUTS_ERROR_MESSAGEFORMATCORRUPT = 3,
-       MMS_RESPSTAUTS_ERROR_SENDINGADDRESSUNRESOLVED = 4,
-       MMS_RESPSTAUTS_ERROR_MESSAGENOTFOUND = 5,
-       MMS_RESPSTAUTS_ERROR_NETWORKPROBLEM = 6,
-       MMS_RESPSTAUTS_ERROR_CONTENTNOTACCEPTED = 7,
-       MMS_RESPSTAUTS_ERROR_UNSUPPORTEDMESSAGE = 8,
-
-       MMS_RESPSTAUTS_ERROR_TRANSIENT_FAILURE = 9,
-       MMS_RESPSTAUTS_ERROR_TRANSIENT_SENDING_ADDRESS_UNRESOLVED = 10,
-       MMS_RESPSTAUTS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND = 11,
-       MMS_RESPSTAUTS_ERROR_TRANSIENT_NETWORK_PROBLEM = 12,
-
-       MMS_RESPSTAUTS_ERROR_PERMANENT_FAILURE = 13,
-       MMS_RESPSTAUTS_ERROR_PERMANENT_SERVICE_DENIED = 14,
-       MMS_RESPSTAUTS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT = 15,
-       MMS_RESPSTAUTS_ERROR_PERMANENT_SENDING_ADDRESS_UNRESOLVED = 16,
-       MMS_RESPSTAUTS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 17,
-       MMS_RESPSTAUTS_ERROR_PERMANENT_CONTENT_NOT_ACCEPTED = 18,
-       MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_LIMITATIONS_NOT_MET = 19,
-       MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_REQUEST_NOT_ACCEPTED = 20,
-       MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_FORWARDING_DENIED = 21,
-       MMS_RESPSTAUTS_ERROR_PERMANENT_REPLY_CHARGING_NOT_SUPPORTED = 22
-} MmsResponseStatus;
-
-
-typedef        enum {
-       MMS_RETRSTATUS_ERROR = -1,      // error return in Get method
-       MMS_RETRSTATUS_OK = 0,
-       MMS_RETRSTATUS_TRANSIENT_FAILURE = 1,
-       MMS_RETRSTATUS_TRANSIENT_MESSAGE_NOT_FOUND = 2,
-       MMS_RETRSTATUS_TRANSIENT_NETWORK_PROBLEM = 3,
-       MMS_RETRSTATUS_PERMANENT_FAILURE = 4,
-       MMS_RETRSTATUS_PERMANENT_SERVICE_DENIED = 5,
-       MMS_RETRSTATUS_PERMANENT_MESSAGE_NOT_FOUND = 6,
-       MMS_RETRSTATUS_PERMANENT_CONTENT_UNSUPPORT = 7
-} MmsRetrieveStatus;
-
-
-typedef enum {
-       MMS_REPLY_NONE = -1,    // error return in Get method
-       MMS_REPLY_REQUESTED = 0,
-       MMS_REPLY_REQUESTED_TEXT_ONLY = 1,
-       MMS_REPLY_ACCEPTED = 2,
-       MMS_REPLY_ACCEPTED_TEXT_ONLY = 3
-} MmsReplyChargeType;
-
-
-typedef enum {
-       MMS_STATUS_ERROR = -1,  // error return in Get method
-       MMS_STATUS_INITIAL = 0,
-       MMS_STATUS_REQUESTING = 1,
-       MMS_STATUS_SUCCESS = 2,
-       MMS_STATUS_FAIL = 3,
-       MMS_STATUS_NUM = 4,
-} MmsDataStatus;
-
-
-typedef enum {
-       MMS_EDIT_STYLE_THIS_PAGE = 0,
-       MMS_EDIT_STYLE_ALL_PAGE,
-} MmsEditStyleMode;
-
-typedef enum {
-       MMS_SPECIAL_MSG_TYPE_NONE = 0,
-       MMS_SPECIAL_MSG_TYPE_SYSTEM_TEMPLATE,   // system template .
-       MMS_SPECIAL_MSG_TYPE_VOICE_MESSAGE,             //voice message service
-
-       MMS_SPECIAL_MSG_TYPE_VDF_POSTCARD,              //postcard service, or Generic Postcard Service
-       MMS_SPECIAL_MSG_TYPE_POSTCARD_EXT1,     //Stickers Service
-       MMS_SPECIAL_MSG_TYPE_POSTCARD_EXT2,     //Photo 10x15
-       MMS_SPECIAL_MSG_TYPE_POSTCARD_EXT3,     //8 Photos
-       MMS_SPECIAL_MSG_TYPE_POSTCARD_EXT4,     // 4 Photos
-} MmsSpecialMsgType;
-
-typedef enum {
-       MMS_MM_CLASS_TEXT,
-       MMS_MM_CLASS_IMAGE_BASIC,
-       MMS_MM_CLASS_IMAGE_RICH,
-       MMS_MM_CLASS_VIDEO_BASIC,
-       MMS_MM_CLASS_VIDEO_RICH,
-       MMS_MM_CLASS_MEGAPIXEL,
-       MMS_MM_CLASS_CONTENT_BASIC,
-       MMS_MM_CLASS_CONTENT_RICH,
-       MMS_MM_CLASS_OTHER
-} MmsUiMmClass;
-
-typedef enum {
-       MMS_MSGCLASS_ERROR = -1,        // error return in Get method
-       MMS_MSGCLASS_PERSONAL = 0,      // default
-       MMS_MSGCLASS_ADVERTISEMENT = 1,
-       MMS_MSGCLASS_INFORMATIONAL = 2,
-       MMS_MSGCLASS_AUTO = 3
-} MmsMsgClass;
-
-
-/*==================================================================================================
-                                                       Structures
-==================================================================================================*/
-
-typedef struct {
-       MmsReplyChargeType chargeType;
-       MmsTimeStruct deadLine;
-       int chargeSize;
-       char szChargeID[MMS_MSG_ID_LEN + 1];
-} MmsReplyCharge;
-
-
-typedef        struct _MmsMsgMultiStatus {
-       char szTo[MAX_ADDRESS_VAL_LEN + 1];
-       bool bDeliveryReportIsRead;
-       bool bDeliveyrReportIsLast;
-       msg_delivery_report_status_t msgStatus;
-       UINT32 handledTime;
-
-       bool bReadReplyIsRead;
-       bool bReadReplyIsLast;
-       msg_read_report_status_t readStatus;
-       UINT32 readTime;
-
-       struct _MmsMsgMultiStatus *pNext;
-} MmsMsgMultiStatus;
-
-typedef        struct _MMS_ATTRIB_S {
-       MsgContentType contentType;
-       MmsDataType dataType;
-       UINT32 date;
-       UINT8 version;
-
-       char szFrom[MSG_LOCALE_ADDR_LEN + 11];          //"/TYPE=PLMN", /"TYPE=IPv4", "/TYPE=IPv6"
-       char szSubject[MSG_LOCALE_SUBJ_LEN + 1];
-       char *szTo;
-       char *szCc;
-       char *szBcc;
-
-       MmsPriority priority;
-
-       MmsReplyCharge replyCharge;
-       bool bChargingMsgReplied;
-
-       bool bHideAddress;
-       bool bAskDeliveryReport;
-       bool bReportAllowed;
-       MmsRecvReadReportType readReportAllowedType;
-
-       bool bAskReadReply;
-       bool bRead;
-
-       MmsRecvReadReportSendStatus readReportSendStatus;
-
-       bool bReadReportSent;
-
-       bool bLeaveCopy;
-       bool bUseExpiryCustomTime;              // for expiry custom time
-       bool bUseDeliveryCustomTime;    // for expiry custom time
-       MmsEditStyleMode editStyleMode;                 //editStyle on All Page
-
-       MmsSpecialMsgType specialMsgType;                       // instead of bPostcard
-
-#ifdef __SUPPORT_DRM__
-       MsgDrmType drmType;
-       int roWaitingTimerMax;          // DRM RO WAITING
-       char *pszDrmData;                       // DRM Data to draw mailbox icon
-#endif
-
-       int msgSize;
-       MmsMsgClass msgClass;
-       MmsTimeStruct expiryTime;
-       MmsTimeStruct expiryCustomTime;
-       MmsTimeStruct deliveryTime;
-       MmsTimeStruct deliveryCustomTime;
-
-       //for ReadMsg, When Sending notifyResp.ind
-       msg_delivery_report_status_t msgStatus;
-
-       MmsResponseStatus responseStatus;
-       MmsRetrieveStatus retrieveStatus;
-       char szResponseText[MMS_LOCALE_RESP_TEXT_LEN + 1];
-       char szRetrieveText[MMS_LOCALE_RESP_TEXT_LEN + 1];
-
-       MmsMsgMultiStatus *pMultiStatus;
-       bool bRetrieveNow;
-} MmsAttrib;
-
-
-typedef struct _MsgContentParam {
-       int charset;
-       char szBoundary[MSG_BOUNDARY_LEN + 1];
-       char szFileName[MSG_FILENAME_LEN_MAX + 1];
-       char szName[MSG_LOCALE_FILENAME_LEN_MAX + 1];
-
-#ifdef FEATURE_JAVA_MMS
-       char *szApplicationID;
-       char *szReplyToApplicationID;
-#endif
-
-       int type;
-       void *pPresentation;
-       char szStart[MSG_MSG_ID_LEN + 1];
-       char szStartInfo[MSG_MSG_ID_LEN + 1];
-
-       MsgParamReportType reportType; //only used as parameter of Content-Type: multipart/report; report-type=delivery-status;
-} MsgContentParam;
-
-#ifdef __SUPPORT_DRM__
-typedef struct _MsgDRMInfo {
-       MsgDrmType drmType;
-       MsgContentType contentType;
-       char *szContentURI;
-       char *szContentName;
-       char *szContentDescription;
-       char *szContentVendor;
-       char *szRightIssuer;
-       char *szDrm2FullPath;
-       int roWaitingTimerMax;          // DRM RO WAITING
-       bool bFwdLock;
-       char *pszContentType;
-       bool bNoRingTone;
-       bool bNoScreen;
-} MsgDRMInfo;
-#endif
-
-typedef struct _MsgType {
-       int offset;
-       int size;
-       int contentSize;
-       int section;
-       int type;
-#ifdef __SUPPORT_DRM__
-       MsgDRMInfo drmInfo;
-#endif
-       int encoding;
-       int disposition;
-       char szContentID[MSG_MSG_ID_LEN + 1];
-       char szContentLocation[MSG_MSG_ID_LEN + 1];
-       char szOrgFilePath[MSG_FILEPATH_LEN_MAX];
-
-       char szContentRepPos[30];
-       char szContentRepSize[30];
-       char szContentRepIndex[8];
-#ifdef __SUPPORT_DRM__
-       int nDrmConvertedStatus;
-#endif
-
-       MsgContentParam param;
-} MsgType;
-
-struct _MsgAddress {
-       int type;                                       //MSG_ADDR_TYPE_PHONE/EMAIL/IPV4/IPV6
-       MsgRecipientType recipientType;                 // TO, CC, BCC
-       char szName[MSG_LOCALE_NAME_LEN + 1];
-       char szAddr[MSG_ADDR_LEN + 1];
-       MsgAddress *pNext;
-       bool bDoNotShow;                                // temporary clip
-
-       // sorting
-       ULONG uLastRecentTime;          // last recent time save item
-       ULONG uMostUseCount;                    // most use count item.
-       int index;                                      // index sorting..
-};
-
-typedef struct _MsgHeader {
-       MsgAddress *pFrom;
-       MsgAddress *pTo;
-       MsgAddress *pCC;
-       char szReturnPath[MSG_ADDR_LEN + 1];
-       char szDate[MSG_DATE_LEN];
-       char szSubject[MSG_LOCALE_SUBJ_LEN + 1];
-       char szMsgID[MSG_MSG_ID_LEN + 1];
-} MsgHeader;
-
-
-struct _MsgBody {
-       int offset;
-       int size;
-       char szOrgFilePath[MSG_FILEPATH_LEN_MAX];
-       MsgType presentationType;
-       MsgBody *pPresentationBody;
-
-       union {
-               char *pText;
-               void *pBinary;
-               MsgMultipart *pMultipart;
-               MsgMessage *pMessage;
-       } body;
-};
+void MmsComposeNotiMessage(MmsMsg *pMmsMsg, msg_message_id_t msgID);
 
-struct _MsgMultipart {
-       MsgType type;
-       MsgBody *pBody;
-       MsgMultipart *pNext;
-};
+void MmsComposeReadReportMessage(MmsMsg *pMmsMsg, const MSG_MESSAGE_INFO_S *pMsgInfo, msg_message_id_t selectedMsgId);
 
-struct _MsgMessage {
-       MsgHeader header;
-       MsgType type;
-       MsgBody *pBody;
-};
+//int MmsUpdatePreviewData(MSG_MESSAGE_INFO_S *pMsgInfo);
+//
+//int MmsUpdateMultipartList(MSG_MESSAGE_INFO_S *pMsgInfo);
 
+//void MmsPrintFileInfoForVLD(MMS_MESSAGE_DATA_S *pMmsMsg);
+//
+//bool MmsChangeFileNameToAscii(MMS_MESSAGE_DATA_S *pMsgData);
 
-typedef        struct _MMS_MESSAGE_S {
-       MmsAttrib mmsAttrib;
-       msg_message_id_t msgID;
-       int mailbox;            // mailbox type,MMS_MAILBOX_XXX
-       char szFileName[MSG_FILENAME_LEN_MAX];
-       char szTrID[MMS_TR_ID_LEN + 1];
-       char szMsgID[MMS_MSG_ID_LEN + 1];
-       char szForwardMsgID[MMS_MSG_ID_LEN + 1];
-       char szContentLocation[MMS_LOCATION_LEN + 1];
-       int nPartCount;
-       MsgType msgType;
-       MsgBody msgBody;
-} MmsMsg;
+bool MmsConvertMsgData(MmsMsg *pMsg, MMS_MESSAGE_DATA_S *pMmsMsg);
 
-struct _MsgHeaderAddress {
-       char *szAddr;
-       MsgHeaderAddress *pNext;
-};
+bool MmsConvertMmsData(MmsMsg *pMsg, MMS_DATA_S *pMmsData);//temp func for supporting new mmsdata
 
+bool MmsConvertMmsMsg(MmsMsg *pMmsMsg, MMS_DATA_S *pMsgData);
 
-bool MmsInitMsgType(MsgType *pMsgType);
-bool MmsInitMsgBody(MsgBody *pMsgBody);
-bool MmsInitMsgContentParam(MsgContentParam *pMsgContentParam);
-bool MmsInitMsgAttrib(MmsAttrib *pAttrib);
-bool MmsSetMsgAddressList(MmsAttrib *pAttrib, const MSG_MESSAGE_INFO_S *pMsgInfo);
-char *MmsComposeAddress(const MSG_MESSAGE_INFO_S *pMsgInfo, int recipientType);
-bool MmsGetMsgBodyfromMsgInfo(const MSG_MESSAGE_INFO_S *pMsgInfo, MMS_MESSAGE_DATA_S *pMsgBody, char *pFileData);
-bool MmsGetSmilRawData(MMS_MESSAGE_DATA_S *pMsgBody, char *pRawData, int *nSize);
-bool MmsInsertPresentation(MmsMsg *pMsg, MsgContentType mimeType, char *pData, int size);
-bool MmsInsertPartFromFile(MmsMsg *pMsg, char *szTitleName, char *szOrgFilePath, char *szContentID);
-bool MmsIsMultipart(int type);
-bool MmsGetTypeByFileName(int *type, char *szFileName);
-MsgMultipart *MmsMakeMultipart(MsgContentType mimeType, char *szTitleName, char *szOrgFilePath, void *pData, int offset, int size, char *szContentID);
-bool MmsIsText(int type);
-bool MmsIsVitemContent(int type, char *pszName);
-bool MmsComposeMessage(MmsMsg *pMmsMsg, MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_MESSAGE_DATA_S *pMsgData, char *pFileData);
-void MmsComposeNotiMessage(MmsMsg *pMmsMsg, msg_message_id_t msgID);
-bool MmsGetMmsMessageBody(MmsMsg *pMmsMsg, char *retrievedFilePath);
-bool MmsComposeForwardHeader(MmsMsg *pMmsMsg, const MSG_MESSAGE_INFO_S *pMsgInfo);
-bool MmsComposeForwardMessage(MmsMsg *pMmsMsg, char *retrievedFilePath);
-#ifdef MMS_DELIEVERY_IND_ENABLED
-MmsMsgMultiStatus *MmsComposeDeliveryIndMessage(MmsMsg *pMmsMsg, msg_message_id_t msgId);
-#endif
-void MmsComposeReadReportMessage(MmsMsg *pMmsMsg, const MSG_MESSAGE_INFO_S *pMsgInfo, msg_message_id_t selectedMsgId);
-MmsMsgMultiStatus *MmsGetMultiStatus(msg_message_id_t msgId);
-int MmsSearchMsgId(char *toNumber, char *szMsgID);
-void MmsUpdateDeliveryReport(msg_message_id_t msgId, MmsMsgMultiStatus *pStatus);
-void MmsUpdateReadReport(msg_message_id_t msgId, MmsMsgMultiStatus *pStatus);
-MsgMultipart *MmsAllocMultipart(void);
-bool _MsgIsASCII(char *pszText);
-bool _MsgReplaceNonAscii(char *szInText, char **szOutText, char replaceChar);
-bool _MsgIsSpace(char *pszText);
-bool _MsgReplaceSpecialChar(char *szInText, char **szOutText, char specialChar);
-char *MsgStrAppend(char *szInputStr1, char *szInputStr2);
-char *MsgStrCopy(const char *string);
-char *MsgStrNCopy(const char *string, int length);
-int    MsgStrlen(char *pStr);
-bool _MsgConvertCharToHex(char pSrc, char *pDest);
-msg_error_t MmsAddAttachment(MMS_MESSAGE_DATA_S *pMsgData, MMS_MEDIA_S *pMedia);
-bool MmsCheckAdditionalMedia(MMS_MESSAGE_DATA_S *pMsgData, MsgType *partHeader);
-#ifdef __SUPPORT_DRM__
-bool __MsgInitMsgDRMInfo(MsgDRMInfo *pMsgDrmInfo);
-#endif
+msg_error_t MmsMakeMultipartThumbnailInfo(MMS_MULTIPART_DATA_S *pMultipart, char *thumbnail_path);
 
-#endif
+#endif //MMS_PLUGIN_MESSAGE_H
diff --git a/plugin/mms_plugin/include/MmsPluginSMILValidate.h b/plugin/mms_plugin/include/MmsPluginSMILValidate.h
deleted file mode 100755 (executable)
index 2ec4174..0000000
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#ifndef MMS_PLUGIN_SMIL_VALIDATE_H
-#define MMS_PLUGIN_SMIL_VALIDATE_H
-
-
-/*==================================================================================================
- *                                     HEADER
- *==================================================================================================*/
-#include "MsgTypes.h"
-#include "MsgMmsTypes.h"
-#include "MmsPluginMessage.h"
-
-/*==================================================================================================
- *                                     DEFINE
- *==================================================================================================*/
-/**
- *     @brief  Represents the default values of SMIL root layout. \n
- */
-#define MSG_SMIL_ROOT_LAYOUT_WIDTH     (100)
-#define MSG_SMIL_ROOT_LAYOUT_HEIGHT    (100)
-#define MSG_SMIL_ROOT_LAYOUT_IN_PERCENT        (true)
-#define MSG_SMIL_ROOT_LAYOUT_BG_COLOR  "#FFFFFF"
-
-/**
- *     @brief  Represents the default values of SMIL Region \n
- */
-#define MSG_SMIL_DEFAULT_TXT_REG       "text"
-#define MSG_SMIL_DEFAULT_IMG_REG       "image"
-#define MSG_SMIL_DEFAULT_FULL_REG      "full"
-#define MSG_SMIL_REG_FIT_TYPE          "meet"
-#define MSG_SMIL_REG_BG_COLOR          "#FFFFFF"
-
-#define MSG_SMIL_FULL_REG_LEFT                         (0)
-#define MSG_SMIL_FULL_REG_TOP                          (0)
-#define MSG_SMIL_FULL_REG_WIDTH                                (100)
-#define MSG_SMIL_FULL_REG_HEIGHT                       (100)
-
-#define MSG_SMIL_FIRST_REG_LEFT                                (0)
-#define MSG_SMIL_FIRST_REG_TOP                         (0)
-#define MSG_SMIL_FIRST_REG_WIDTH                       (100)
-#define MSG_SMIL_FIRST_REG_HEIGHT                      (50)
-
-#define MSG_SMIL_SECOND_REG_LEFT                       (0)
-#define MSG_SMIL_SECOND_REG_TOP                                (50)
-#define MSG_SMIL_SECOND_REG_WIDTH                      (100)
-#define MSG_SMIL_SECOND_REG_HEIGHT                     (50)
-
-/**
- *     @brief  Represents the default values of SMIL Media \n
- */
-#define MSG_SMIL_REG_POSITION_IS_DEFAULT       (true)
-#define MSG_SMIL_TEXT_ON_TOP                           (true)
-
-
-/*==================================================================================================
- *                                     ENUMS
- *==================================================================================================*/
-
-/**
- *     @brief  Represents the values of an smil error code. \n
- *     Success code is zero, but all error codes SHOULD be negative and smaller than MSG_SMIL_ERR_BEGIN. \n
- */
-enum MSG_SMIL_ERR_E {
-       MSG_SMIL_SUCCESS = 0,
-       MSG_SMIL_ERR_UNKNOWN = -255,
-       MSG_SMIL_ERR_INVALID_ROOTLAYOUT,
-       MSG_SMIL_ERR_INVALID_REGION_INFO,
-       MSG_SMIL_ERR_SIMILAR_MEDIA_EXISTS,
-       MSG_SMIL_ERR_INVALID_SMIL_FILE_PATH,
-       MSG_SMIL_ERR_INVALID_PAGE_INFO,
-       MSG_SMIL_ERR_INVALID_PAGE_DUR,
-       MSG_SMIL_ERR_INVALID_PARAM,
-};
-
-/*==================================================================================================
- *                                     FUNCTIONS
- *==================================================================================================*/
-
-/**    @fn             MSG_SMIL_ERR_E MsgMMSCreateSMIL(MMS_MESSAGE_DATA_S *pMsgData)
- *     @brief  Creates a SMIL buffer based on the Message handle.
- *     @param  pMsgData is Message handle. \n
- *     @param  pError is a pointer to a SMIL error type. \n
- *     @return MSG_SMIL_ERR_E \n
- *     @retval MSG_SMIL_SUCCESS                Success in operation. \n
- *     @retval MSG_SMIL_ERR_UNKNOWN                            Encoding failed \n
- *     @retval MSG_SMIL_ERR_INVALID_ROOTLAYOUT         Invalid Root Layout \n
-  *    @retval MSG_SMIL_ERR_INVALID_REGION_INFO        Invalid Region \n
- *     @retval MSG_SMIL_ERR_SIMILAR_MEDIA_EXISTS       Duplicate media \n
- *     @retval MSG_SMIL_ERR_INVALID_SMIL_FILE_PATH     Invalid Smil Path \n
- *     @retval MSG_SMIL_ERR_INVALID_PAGE_INFO          Invalid Page Info \n
- *     @retval MSG_SMIL_ERR_INVALID_PAGE_DUR           Invalid Page Duration \n
- *     @retval MSG_SMIL_ERR_INVALID_PARAM                      Invalid Parameter \n
- */
-MSG_SMIL_ERR_E MsgMMSCreateSMIL(MMS_MESSAGE_DATA_S *pMsgData);
-
-/**    @fn             MSG_SMIL_ERR_E _MsgMMSValidateSMILRootLayout(MMS_MESSAGE_DATA_S *pMsgData)
- *     @brief  Validates the Root layout information present in the Message handle.
- *     @param  pMsgData is Message handle. \n
- *     @return MSG_SMIL_ERR_E \n
- *     @retval MSG_SMIL_SUCCESS                                                Success in operation. \n
- *     @retval MSG_SMIL_ERR_INVALID_ROOTLAYOUT                 Failure in operation. \n
- */
-MSG_SMIL_ERR_E _MsgMMSValidateSMILRootLayout(MMS_MESSAGE_DATA_S *pMsgData);
-
-/**    @fn             MSG_SMIL_ERR_E _MsgMMSAddDefaultSMILRegions(MMS_MESSAGE_DATA_S *pMsgData)
- *     @brief  Adds the default Region information based on the Message handle.
- *     @param  pMsgData is Message handle. \n
- *     @return MSG_SMIL_ERR_E \n
- *     @retval MSG_SMIL_SUCCESS                                                Success in operation. \n
- *     @retval MSG_SMIL_ERR_INVALID_ROOTLAYOUT                 Failure in operation. \n
- */
-MSG_SMIL_ERR_E _MsgMMSAddDefaultSMILRootLayout(MMS_MESSAGE_DATA_S *pMsgData);
-
-/**    @fn             MSG_SMIL_ERR_E _MsgMMSValidateSMILRegion(MMS_MESSAGE_DATA_S *pMsgData, bool *pbRegAdded)
- *     @brief  Validates the Region information present in the Message handle.
- *     @param  pMsgData is Message handle. \n
- *     @return MSG_SMIL_ERR_E \n
- *     @retval MSG_SMIL_SUCCESS                                                Success in operation. \n
- *     @retval MSG_SMIL_ERR_INVALID_REGION_INFO                Failure in operation. \n
- *     @retval MSG_SMIL_ERR_INVALID_PAGE_INFO                  Failure in operation. \n
- */
-MSG_SMIL_ERR_E _MsgMMSValidateSMILRegion(MMS_MESSAGE_DATA_S *pMsgData, bool *pbRegAdded);
-
-/**    @fn             MSG_SMIL_ERR_E _MsgMMSAddDefaultFirstSMILRegion(MMS_MESSAGE_DATA_S *pMsgData, bool bTextReg)
- *     @brief  Adds the default first Region information when two regions are present in a page based on the Message handle.
- *     @param  pMsgData is Message handle. \n
- *     @return MSG_SMIL_ERR_E \n
- *     @retval MSG_SMIL_SUCCESS                                                Success in operation. \n
- *     @retval MSG_SMIL_ERR_INVALID_REGION_INFO                Failure in operation. \n
- */
-MSG_SMIL_ERR_E _MsgMMSAddDefaultFirstSMILRegion(MMS_MESSAGE_DATA_S *pMsgData, bool bTextReg);
-
-/**    @fn             MSG_SMIL_ERR_E _MsgMMSAddDefaultSecondSMILRegion(MMS_MESSAGE_DATA_S *pMsgData, bool bTextReg)
- *     @brief  Adds the default second Region information when two regions are present in a page based on the Message handle.
- *     @param  pMsgData is Message handle. \n
- *     @return MSG_SMIL_ERR_E \n
- *     @retval MSG_SMIL_SUCCESS                                                Success in operation. \n
- *     @retval MSG_SMIL_ERR_INVALID_REGION_INFO                Failure in operation. \n
- */
-MSG_SMIL_ERR_E _MsgMMSAddDefaultSecondSMILRegion(MMS_MESSAGE_DATA_S *pMsgData, bool bTextReg);
-
-/**    @fn             MSG_SMIL_ERR_E _MsgMMSAddDefaultFullSMILRegion(MMS_MESSAGE_DATA_S *pMsgData)
- *     @brief  Adds the default full Region information when only region is present in a page based on the Message handle.
- *     @param  pMsgData is Message handle. \n
- *     @return MSG_SMIL_ERR_E \n
- *     @retval MSG_SMIL_SUCCESS                                                Success in operation. \n
- *     @retval MSG_SMIL_ERR_INVALID_REGION_INFO                Failure in operation. \n
- */
-MSG_SMIL_ERR_E _MsgMMSAddDefaultFullSMILRegion(MMS_MESSAGE_DATA_S *pMsgData);
-
-/**    @fn             MSG_SMIL_ERR_E _MsgMMSValidateSMILPage(MMS_MESSAGE_DATA_S *pMsgData, bool bRegAdded)
- *     @brief  Validates the Page information present in the Message handle.
- *     @param  pMsgData is Message handle. \n
- *     @return MSG_SMIL_ERR_E \n
- *     @retval MSG_SMIL_SUCCESS                                                Success in operation. \n
- *     @retval MSG_SMIL_ERR_INVALID_PAGE_INFO                  Failure in operation. \n
- *     @retval MSG_SMIL_ERR_SIMILAR_MEDIA_EXISTS               Same Kind of Media Exists in SMIL page. \n
- *     @retval MSG_SMIL_ERR_INVALID_REGION_INFO                Failure in operation. \n
- */
-MSG_SMIL_ERR_E _MsgMMSValidateSMILPage(MMS_MESSAGE_DATA_S *pMsgData, bool bRegAdded);
-
-#endif // MMS_PLUGIN_SMIL_ENCODE_H
diff --git a/plugin/mms_plugin/include/MmsPluginSetup.h b/plugin/mms_plugin/include/MmsPluginSetup.h
deleted file mode 100755 (executable)
index 1e9db28..0000000
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include "MmsPluginMessage.h"
-
-#define MSG_STDSTR_SHORT                       0x7F
-
-/*
- * structures for setup
- */
-
-typedef enum {
-       MMS_RECEIVE_AUTO,
-       MMS_RECEIVE_MANUAL,
-       MMS_RECEIVE_RESTRICT,
-       MMS_RECEIVE_REJECT,
-       MMS_RECEIVE_CNT,
-} MmsRecvType;
-
-typedef enum {
-       MMS_RESTRICTED_MODE,
-       MMS_WARNING_MODE,
-       MMS_FREE_MODE
-} MmsUiMsgCreationMode;
-
-typedef        enum {
-       MMS_OPCO_DEFAULT        = 0,
-       MMS_OPCO_FRANCE         = 1,
-       MMS_OPCO_GERMAN         = 2,
-       MMS_OPCO_GREECE         = 3,
-       MMS_OPCO_IRELANDS       = 4,
-       MMS_OPCO_ITALY          = 5,
-       MMS_OPCO_NETHERLANDS = 6,
-       MMS_OPCO_PORTUGAL       = 7,
-       MMS_OPCO_SPAIN          = 8,
-       MMS_OPCO_SWEDEN         = 9,
-       MMS_OPCO_SWISS          = 10,
-       MMS_OPCO_UK                     = 11,
-       MMS_OPCO_AUSTRIA        = 12,
-       MMS_OPCO_BELGIUM        = 13,
-       MMS_OPCO_HUNGARY        = 14,
-       MMS_OPCO_NUM
-} MmsOpCo;
-
-typedef        struct {
-       bool bHideAddress;
-       bool bAskDeliveyReport;
-       bool bAskReadReply;
-       MmsPriority priority;
-       char szFrom[MSG_LOCALE_ADDR_LEN + 10];
-       MmsMsgClass msgClass;
-       MmsTimeStruct expiryTime;
-       MmsTimeStruct deliveryTime;
-       bool bLeaveCopy;
-       bool bAttachVcard;
-       bool bAttachSign;
-       bool bExpiryUseCustomTime;
-
-       bool bDeliveryUseCustomTime;
-
-       MmsTimeStruct expiryCustomTime;
-       MmsTimeStruct deliveryCustomTime;
-
-       char szSign[MSG_LOCALE_SIGN_LEN + 1];
-
-       //MMS_V1_1
-       MmsReplyCharge replyCharge;
-
-       int creationMode; // Creation Mode
-} MmsSendSetup;
-
-typedef struct {
-       bool bSendDeliveryReport;
-       bool bSendReadReply;
-       bool bAnonymousReject;
-       bool bRejectAdvertisement;
-       MmsRecvType recvHomeNetwork;
-       MmsRecvType recvRoamingNetwork;
-} MmsRecvSetup;
-
-typedef        struct {
-       bool bUserSettingMsgMaxSize;
-       int msgMmsMaxSize;
-} MmsMsgSizeSetup;
-
-
-typedef struct {
-       MmsUiMsgCreationMode creationMode;
-} MmsCreationModeSetup;
-
-
-typedef struct {
-       bool bCustomTime;
-       int slideIntervalTime;
-       int customTime;
-} MmsSlideSetup;
-
-typedef struct {
-       int     postcardName;
-       int     postcardAdditionalInfo;
-       int     postcardStreet;
-       int     postcardZip;
-       int     postcardCity;
-       int     postcardStateNProvince;
-       int     postcardCountry;
-} MmsPostcardSetup;
-
-typedef struct {
-       MmsSendSetup sendSetup;
-       MmsRecvSetup recvSetup;
-       MmsMsgSizeSetup msgSizeSetup;
-       MmsPostcardSetup postcardSetup[5];                                                                      // ref) POSTCARD_EDIT_TYPE_EXTENDED4
-
-       MmsCreationModeSetup creationModeSetup;
-
-       int autoResizeSize;
-
-       /* UI not-visible fields ------------------------------------ */
-
-       MmsOpCo nOpCo;
-       int maxSendSize;
-       char szPostcardOffice[MSG_STDSTR_SHORT + 1];                            // Only Privosioning can change this field
-       char szPostcardOfficeExtend01[MSG_STDSTR_SHORT + 1];
-       char szPostcardOfficeExtend02[MSG_STDSTR_SHORT + 1];
-       char szPostcardOfficeExtend03[MSG_STDSTR_SHORT + 1];
-       char szPostcardOfficeExtend04[MSG_STDSTR_SHORT + 1];
-       bool bPostcardAvailable;                                                                        // Only Privosioning can change this field
-       char szMmlUrl[MSG_STDSTR_SHORT + 1];                                    //MML Home Url
-       char szMmlPhoneNumber[MSG_STDSTR_SHORT + 1];                    //MML Upload phonenumber
-
-       char szMmsTmplDownloadURL[MSG_STDSTR_SHORT + 1];        //  for MMS More Templates
-
-} MmsSetup;
-
-/* global Setting */
-extern MmsSetup gMmsSetup;
-
diff --git a/plugin/mms_plugin/include/MmsPluginSmil.h b/plugin/mms_plugin/include/MmsPluginSmil.h
deleted file mode 100755 (executable)
index af94847..0000000
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include <stdio.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <libxml/parser.h>
-#include <libxml/tree.h>
-#include "MsgTypes.h"
-#include "MsgMmsTypes.h"
-#include "MmsPluginCodec.h"
-
-#ifndef MMS_PLUGIN_SMIL_H
-#define MMS_PLUGIN_SMIL_H
-
-typedef enum _SMIL_ELEMENT_T {
-       ELEMENT_SMIL,
-       ELEMENT_HEAD,
-       ELEMENT_LAYOUT,
-       ELEMENT_ROOTLAYOUT,
-       ELEMENT_REGION,
-       ELEMENT_TRANSITION,
-       ELEMENT_META,
-       ELEMENT_BODY,
-       ELEMENT_PAR,
-       ELEMENT_PARAM,
-       ELEMENT_TEXT,
-       ELEMENT_IMG,
-       ELEMENT_AUDIO,
-       ELEMENT_VIDEO,
-       ELEMENT_REF,
-       ELEMENT_ANIMATE,
-       ELEMENT_MAX,
-} SMIL_ELEMENT_T;
-
-typedef        int     HMmsSmil;                       // SmilDoc Handle
-
-#define MMS_SMIL_MAX_DOC       1
-#define MMS_SMIL_COLOR_SIZE    10
-#define INVALID_HOBJ   -1
-#define SP_NO_COLOR_SET        -1
-#define SP_BLACK       0
-
-/* Structures */
-/**
- *     @brief  Represents Smil Doc Information. \n
- */
-typedef struct _MmsSmilDoc {
-       xmlDocPtr pSmilDoc;
-       xmlNodePtr pstRootNode;
-} MmsSmilDoc;
-
-typedef enum _SMIL_ATTRIBUTE_T {
-       ATTRIBUTE_UNKNOWN = -1,
-       ATTRIBUTE_ID,
-       ATTRIBUTE_TOP,
-       ATTRIBUTE_LEFT,
-       ATTRIBUTE_WIDTH,
-       ATTRIBUTE_HEIGHT,
-       ATTRIBUTE_FIT,
-       ATTRIBUTE_BGCOLOR,
-       ATTRIBUTE_DUR,
-       ATTRIBUTE_SRC,
-       ATTRIBUTE_COLOR,
-       ATTRIBUTE_BOLD,
-       ATTRIBUTE_UNDERLINE,
-       ATTRIBUTE_ITALIC,
-       ATTRIBUTE_REVERSE,
-       ATTRIBUTE_DIRECTION,
-       ATTRIBUTE_SIZE,
-       ATTRIBUTE_FONT,
-       ATTRIBUTE_REGION,
-       ATTRIBUTE_NAME,
-       ATTRIBUTE_VALUE,
-       ATTRIBUTE_ALT,
-       ATTRIBUTE_TYPE,
-       ATTRIBUTE_SUBTYPE,
-       ATTRIBUTE_CONTENT,
-       ATTRIBUTE_FGCOLOR,
-       ATTRIBUTE_TEXTFORMAT,
-       ATTRIBUTE_TRANSIN,
-       ATTRIBUTE_TRANSOUT,
-       ATTRIBUTE_BEGIN,
-       ATTRIBUTE_END,
-       ATTRIBUTE_REPEAT_COUNT,
-} SMIL_ATTRIBUTE_T;
-
-char *MmsSmilGetPresentationData(msg_message_id_t msgId);
-bool MmsSmilParseSmilDoc(MMS_MESSAGE_DATA_S *pMmsMsg, char *pSmilDoc);
-void MmsSmilGetElement(MMS_MESSAGE_DATA_S *pMmsMsg, xmlNode *a_node);
-int MmsSmilGetColorValue(xmlChar *content);
-int MmsSmilGetTime(char *pValue);
-int MmsSmilAtoIHexa(char *pInput);
-#ifndef __SUPPORT_DRM__
-int MmsSmilGetMediaSrcForNormalMsg(char *szOutbuf, char *szInBuf, MsgMultipart *pPart);
-#else
-int MmsSmilGetMediaSrcForNormalMsg(char *szOutbuf, char *szInBuf, MsgMultipart *pPart, MMS_MEDIA_S *pMedia);
-#endif
-int MmsSmilGetElementID(char *pString);
-int MmsSmilGetAttrID(char *pString);
-bool MmsSmilGetFontAttrib(char *pString);
-MmsTextDirection MmsSmilGetFontDirection(char *pString);
-int MmsSmilGetFontSizeValue(char *pString);
-MmsSmilFontType MmsSmilGetFontTypeValue(char *pString);
-bool MmsSmilGetMediaFilePath(MMS_MEDIA_S *pMedia, char *pszTemp, int msgID);
-bool __MmsGetRealFileName(MmsSmilMediaType mediaType, char *pszSrc, char *pszName, int msgID);
-/**    @fn             bool MMSGenerateSmilBuffer(MMS_MESSAGE_DATA_S *pstMsgBody)
- *     @brief  Forms Smil Buffer using pstMsgBody. \n
- *     @param[in/out]  pstMsgBody is Message handle. \n
- *     @retval TRUE                            In case of Success. \n
- *     @retval FALSE                           In case of failure. \n
- */
-bool MMSGenerateSmilBuffer(MMS_MESSAGE_DATA_S *pstMsgBody);
-
-/**    @fn             HMmsSmil MmsSmilCreateEmptySmilDoc(void)
- *     @brief  Creates default Smil Doc based on input gszEmptyRawDoc. \n
- *     @retval Returns Smil Document number. \n
- */
-HMmsSmil MmsSmilCreateEmptySmilDoc(void);
-
- /**   @fn                     HMmsSmil MmsSmilCreateSmilDoc(char *pszRawData)
- *     @brief          Creates Smil Doc based on input pszRawData. \n
- *     @param[in]      pszRawData is smil buffer. \n
- *     @retval         Returns Smil Document number. \n
- */
-HMmsSmil MmsSmilCreateSmilDoc(char *pszRawData);
-
- /**   @fn                     BOOL MmsSmilDestroyDoc(HMmsSmil hSmilDoc)
- *     @brief          Destroys Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @retval TRUE                            In case of Success. \n
- *     @retval FALSE                           In case of failure. \n
- */
-bool MmsSmilDestroyDoc(HMmsSmil hSmilDoc);
-
-/**    @fn                     static bool IsValidSmilDocNo(int nSmilDocNo)
- *     @brief          Form Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @retval         Returns Smil Buffer     In case of success. \n
- *     @retval         Returns NULL                    In case of failure. \n
- */
-bool IsValidSmilDocNo(int nSmilDocNo);
-
-/**    @fn                     static char * MmsSmilGetRawData( HMmsSmil hSmilDoc )
- *     @brief          Form Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @retval         Returns Smil Buffer             In case of success. \n
- *     @retval         Returns NULL                    In case of failure. \n
- */
-char *MmsSmilGetRawData(HMmsSmil hSmilDoc);
-
-/**    @fn                     static bool MmsSmilAddPage(HMmsSmil hSmilDoc, MMS_PAGE_S *pstSmilPage)
- *     @brief          Add Page to Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @param[in]      pstSmilPage specifies page information. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool MmsSmilAddPage(HMmsSmil hSmilDoc, MMS_PAGE_S *pstSmilPage);
-
-/**    @fn                     static bool MmsSmilAddRootLayout(HMmsSmil hSmilDoc, MMS_SMIL_ROOTLAYOUT *pstSmilRootLayout)
- *     @brief          Add Rootlayout to Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @param[in]      pstSmilRootLayout specifies RootLayout information. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool MmsSmilAddRootLayout(HMmsSmil hSmilDoc, MMS_SMIL_ROOTLAYOUT *pstSmilRootLayout);
-
-/**    @fn                     static bool MmsSmilAddRegion(HMmsSmil hSmilDoc, MMS_SMIL_REGION *pstSmilRegion)
- *     @brief          Add Region to Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @param[in]      pstSmilRegion specifies Region information. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool MmsSmilAddRegion(HMmsSmil hSmilDoc, MMS_SMIL_REGION *pstSmilRegion);
-
-/**    @fn                     static bool MmsSmilAddMedia( HMmsSmil hSmilDoc, int nPageNo, MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
- *     @brief          Add Media to Smil Doc. \n
- *     @param[in]      hSmilDoc is smil doc number. \n
- *     @param[in]      nPageNo specifies page number to which media belongs. \n
- *     @param[in]      nMediaIdx specifies medi ID. \n
- *     @param[in]      pstSmilMedia specifies Media information. \n
- *     @param[in]      pszContentID specifies Content ID of media. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool MmsSmilAddMedia(HMmsSmil hSmilDoc, int nPageNo, int nMediaIdx, MMS_MEDIA_S *pstSmilMedia, char *pszContentID);
-
-/**    @fn                     static xmlNode *__MmsCreateTextNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
- *     @brief          Create Text Element. \n
- *     @param[in]      pstSmilMedia specifies Media information. \n
- *     @param[in]      pszContentID specifies Content ID of media. \n
- *     @retval         Text Element node               In case of Success. \n
- *     @retval         NULL                            In case of failure. \n
- */
-xmlNode *__MmsCreateTextNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID);
-
-/**    @fn                     static xmlNode *__MmsCreateMMNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
- *     @brief          Create Image/Audio/Video Element. \n
- *     @param[in]      pstSmilMedia specifies Media information. \n
- *     @param[in]      pszContentID specifies Content ID of media. \n
- *     @retval         Image/Audio/Video Element node  In case of Success. \n
- *     @retval         NULL                                                    In case of failure. \n
- */
-xmlNode *__MmsCreateMMNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID);
-
-/**    @fn                     static bool __MmsInsertFirstChild(xmlNode *pstParent, xmlNode *pstCurr)
- *     @brief          Inserts first child to parent node. \n
- *     @param[in]      pstParent specifies Parent node. \n
- *     @param[in]      pstCurr specifies Child node. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool __MmsInsertFirstChild(xmlNode *pParent, xmlNode *pNode);
-
-/**    @fn                     static bool __MmsSmilInsertNode(xmlNode *pstParent, xmlNode *pstLeftSibling, xmlNode *pstCurr)
- *     @brief          Inserts node. \n
- *     @param[in]      pstParent specifies Parent node. \n
- *     @param[in]      pstLeftSibling specifies Left Sibling node. \n
- *     @param[in]      pstCurr specifies Child node. \n
- *     @retval         TRUE                            In case of Success. \n
- *     @retval         FALSE                           In case of failure. \n
- */
-bool __MmsSmilInsertNode(xmlNode *pParent, xmlNode *pLeftSibling, xmlNode *pNode);
-
-/**    @fn                     static void _MmsSmilSetAttribute(xmlNode *pNode, char *szField, char *szValue)
- *     @brief          Sets Attribute. \n
- *     @param[in]      pNode specifies node. \n
- *     @param[in]      szField specifies attribute field. \n
- *     @param[in]      szValue specifies value of field \n
- */
-void _MmsSmilSetAttribute(xmlNode *pNode, char *szField, char *szValue);
-
-/**    @fn                     static char *__MmsSmilFindColorValue(int nValue)
- *     @brief          Converts color to RGB. \n
- *     @param[in]      nValue specifies color value. \n
- *     @retval         RGB value. \n
- */
-char *__MmsSmilFindColorValue(int nValue);
-
-/**    @fn                     static xmlNodePtr UtilxmlStringGetNodeList(xmlNodePtr pstNode, char *pszValue)
- *     @brief          Get node based on pszValue. \n
- *     @param[in]      pNode specifies node. \n
- *     @param[in]      pszName specifies name field. \n
- *     @retval         RGB value. \n
- */
-xmlNodePtr UtilxmlStringGetNodeList(xmlNodePtr pstNode, char *pszName);
-
-#endif//MMS_PLUGIN_SMIL_H
-
-
index 792cc42..8086d2f 100755 (executable)
@@ -1,33 +1,25 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MMS_PLUGIN_STORAGE_H
 #define MMS_PLUGIN_STORAGE_H
 
-/*==================================================================================================
-                                                       INCLUDE FILES
-==================================================================================================*/
-#include "MsgStorageTypes.h"
 #include "MsgSqliteWrapper.h"
-#include "MmsPluginMessage.h"
+#include "MmsPluginCodecTypes.h"
 
-
-/*==================================================================================================
-                                                       CLASS DEFINITIONS
-==================================================================================================*/
 class MmsPluginStorage
 {
 public:
@@ -36,44 +28,61 @@ public:
        MmsPluginStorage();
        ~MmsPluginStorage();
 
-       void addMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData);
+       //MMS message operation
+       msg_error_t addMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pSerializedMms);
+       msg_error_t getMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char **pSerializedMms);
+       msg_error_t updateMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pSerializedMms);
+       msg_error_t updateMessage(MSG_MESSAGE_INFO_S *pMsgInfo);//malware allowed
+
+       msg_error_t deleteMmsMessage(int msgId);
+
+       //MMS message preview info
+       msg_error_t insertPreviewInfo(int msgId, int type, const char *value, int count = 0);
+       msg_error_t removePreviewInfo(int msgId);
+
+       //MMS message multipart list
+       msg_error_t insertMultipart(msg_message_id_t msgId, MMS_MULTIPART_DATA_S *pMultipart);
+       msg_error_t updateMultipart(msg_message_id_t msgId, int allow_malware, MMS_MULTIPART_DATA_S *pMultipart);
+       msg_error_t getMultipartList(msg_message_id_t msgId, MMSList **multipart_list);
+       msg_error_t deleteMultipartList(int msgId);
+
+       //MMS message report
+       msg_error_t insertDeliveryReport(msg_message_id_t msgId, char *address, MmsMsgMultiStatus *pStatus);
+       msg_error_t insertReadReport(msg_message_id_t msgId, char *address, MmsMsgMultiStatus *pStatus);
+
+       //etc
        void getMmsMessage(MmsMsg **pMmsMsg);
-       void getMmsAttrib(msg_message_id_t msgId, MmsMsg *pMmsMsg);
        msg_error_t getMmsMessageId(msg_message_id_t selectedMsgId, MmsMsg *pMmsMsg);
        void composeReadReport(MSG_MESSAGE_INFO_S *pMsgInfo);
 
        int searchMsgId(char *toNumber, char *szMsgID);
-       int     getMmsVersion(msg_message_id_t selectedMsgId);
+       int getMmsVersion(msg_message_id_t selectedMsgId);
 
-       msg_error_t     updateMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData);
-       msg_error_t     updateConfMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
-       msg_error_t     updateMmsAttrib(msg_message_id_t msgId, MmsAttrib *attrib, MSG_SUB_TYPE_T msgSubType);
+       msg_error_t updateConfMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t updateMmsAttrib(msg_message_id_t msgId, MmsAttrib *attrib, MSG_SUB_TYPE_T msgSubType);
        msg_error_t updateMmsAttachCount(msg_message_id_t msgId, int count);
-       msg_error_t     updateNetStatus(msg_message_id_t msgId, msg_network_status_t netStatus);
-       msg_error_t updateDeliveryReport(msg_message_id_t msgId, MmsMsgMultiStatus *pStatus);
-       msg_error_t     updateReadReport(msg_message_id_t msgId, MmsMsgMultiStatus *pStatus);
-       msg_error_t     setReadReportSendStatus(msg_message_id_t msgId, int readReportSendStatus);
-       msg_error_t     plgGetMmsMessage(MSG_MESSAGE_INFO_S *pMsg,  MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_MESSAGE_DATA_S *pMmsMsg, char **pDestMsg);
-       msg_error_t     getContentLocation(MSG_MESSAGE_INFO_S *pMsgInfo);
-       msg_error_t getMmsRawFilePath(msg_message_id_t msgId, char *pFilepath);
-       msg_error_t     plgGetRestoreMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_MESSAGE_DATA_S *pMmsMsg, char **pDestMsg, char *filePath);
-       /* reject_msg_support */
-       msg_error_t getTrID(MSG_MESSAGE_INFO_S *pMsgInfo, char *pszTrID, int nBufferLen);
-       /* reject_msg_support */
+
+       msg_error_t getMmsRawFilePath(msg_message_id_t msgId, char *pFilepath, size_t filePathLen);
+
+       msg_error_t getTrID(MSG_MESSAGE_INFO_S *pMsgInfo, char *pszTrID, int nBufferLen); /* reject_msg_support */
+
+       msg_error_t getAddressInfo(msg_message_id_t msgId, MSG_ADDRESS_INFO_S *pAddrInfo);
 
        msg_error_t updateMsgServerID(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo);
 
-       MmsMsgMultiStatus *getMultiStatus(msg_message_id_t msgId);
-       msg_error_t     getMsgText(MMS_MESSAGE_DATA_S *pMmsMsg, char *pMsgText);
-       msg_error_t     makeThumbnail(MMS_MESSAGE_DATA_S *pMmsMsg, char *pThumbnailPath, char *szFileName);
-       msg_error_t addMmsNoti(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t getMsgText(MMS_MESSAGE_DATA_S *pMmsMsg, char *pMsgText);
+
+       int checkDuplicateNotification(char* pszTrID, char* pszContentLocation);
 
 private:
-       msg_error_t addMmsMsgToDB(MmsMsg *pMmsMsg, const MSG_MESSAGE_INFO_S *pMsgInfo, int attachCnt = 0);
+       void getMmsFromDB(msg_message_id_t msgId, MmsMsg *pMmsMsg);
+       msg_error_t addMmsMsgToDB(MmsMsg *pMmsMsg, const char *raw_filepath);
+       msg_error_t addMmsData(msg_message_id_t msgId, const char *raw_filepath, MMS_DATA_S *pMmsData);
+       msg_error_t getMmsData(msg_message_id_t msgId, MMS_DATA_S *pMmsData);
 
-       static MmsPluginStorage *pInstance;
+       msg_error_t updateRetriveConf(msg_message_id_t msgId, MMS_DATA_S *pMmsData);
 
-       MsgDbHandler dbHandle;
+       static MmsPluginStorage *pInstance;
 
        MmsMsg mmsMsg;
 };
diff --git a/plugin/mms_plugin/include/MmsPluginTcs.h b/plugin/mms_plugin/include/MmsPluginTcs.h
new file mode 100755 (executable)
index 0000000..449a000
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MMS_PLUGIN_TCS_H
+#define MMS_PLUGIN_TCS_H
+
+//Scan content on file system.
+int MmsPluginTcsScanFile(const char *filepath, int *bLevel);
+
+#endif //MMS_PLUGIN_TCS_H
diff --git a/plugin/mms_plugin/include/MmsPluginTextConvert.h b/plugin/mms_plugin/include/MmsPluginTextConvert.h
new file mode 100755 (executable)
index 0000000..50cf1d0
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MMS_PLUGIN_TEXT_CONVERT_H
+#define MMS_PLUGIN_TEXT_CONVERT_H
+
+const char *MmsPluginTextConvertGetCharSet(int MIBEnum);
+
+bool MmsPluginTextConvert(const char *pToCodeSet, const char *pFromCodeSet, const char *pSrc, int srcLen, char **ppDest, int *pDestLen);
+
+#endif //MMS_PLUGIN_TEXT_CONVERT_H
index f619cdd..28cc34e 100755 (executable)
@@ -1,35 +1,24 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef MMS_PLUGIN_TRANSPORT_H
 #define MMS_PLUGIN_TRANSPORT_H
 
-
-/*==================================================================================================
-                                                       INCLUDE FILES
-==================================================================================================*/
-#include <map>
-
-#include "MsgTransportTypes.h"
 #include "MmsPluginTypes.h"
 
-
-/*==================================================================================================
-                                                       CLASS DEFINITIONS
-==================================================================================================*/
 class MmsPluginTransport
 {
        public:
@@ -42,12 +31,7 @@ class MmsPluginTransport
                MmsPluginTransport();
                ~MmsPluginTransport();
 
-               void submitProcess(mmsTranQEntity req);
-               MMS_NET_ERROR_T submitHandler(mmsTranQEntity *qEntity);
-               bool processReceivedData(int msgId, char *pRcvdBody, int rcvdBodyLen, char *retrievedFilePath);
-
                static MmsPluginTransport *pInstance;
 };
 
 #endif //MMS_PLUGIN_TRANSPORT_H
-
index 26b62fc..8cafe1a 100755 (executable)
@@ -1,42 +1,36 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#ifndef MMSTPDUTYPES_H
-#define MMSTPDUTYPES_H
+#ifndef MMS_PLUGIN_TYPES_H
+#define MMS_PLUGIN_TYPES_H
 
-#define        __SUPPORT_LIBCURL__
+#include "MsgTypes.h"
+#include "MsgInternalTypes.h"
 
-#include "MmsPluginMessage.h"
-#include "MsgStorageTypes.h"
-
-
-typedef enum _E_UA_STATE {
-       eUA_IDLE = 0,
-       eUA_READY,
-       eUA_WAITING
-} E_UA_STATE;
+#define IN        /*! Pfrefix*/
+#define OUT       /*! Pfrefix*/
+#define INOUT     /*! Pfrefix*/
 
+#define RETRY_MAX 1
+#define HTTP_REQUEST_LEN   1024
 
 typedef unsigned int MMS_NET_ERROR_T;
-
 typedef unsigned int MMS_PDU_TYPE_T;
-
 typedef unsigned char MMS_HTTP_CMD_TYPE_T;
 
-
 enum _MMS_NET_ERROR_E {
        eMMS_SUCCESS = 0,
        eMMS_CM_OPEN_SUCCESS,
@@ -64,12 +58,6 @@ enum _MMS_NET_ERROR_E {
        eMMS_UNKNOWN
 };
 
-typedef struct _MMS_COND_S {
-       bool valid;
-       MMS_NET_ERROR_T reason;
-
-} MMS_COND_S;
-
 enum _MMS_PDU_TYPE_E {
        eMMS_SEND_REQ = 0,
        eMMS_SEND_CONF,
@@ -113,21 +101,13 @@ enum _MMS_HTTP_CMD_TYPE_E {
        eHTTP_CMD_DELETE_TRANSACTION
 };
 
-typedef enum {
-       MSG_CHECK_ADDR_TYPE_PHONE = 0x01,
-       MSG_CHECK_ADDR_TYPE_EMAIL = 0x02,
-       MSG_CHECK_ADDR_TYPE_IPV4  = 0x04,
-       MSG_CHECK_ADDR_TYPE_IPV6  = 0x08,
-       MSG_CHECK_ADDR_TYPE_NUM   = 0x10,
-       MSG_CHECK_ADDR_TYPE_ALIAS = 0x20
-} MsgAddrCheckType;
-
 typedef struct _mmsTranQEntity {
        bool isCompleted;
        msg_request_id_t reqID;
        int msgId;
        unsigned int sessionId;
        char transactionId[MMS_TR_ID_LEN + 1];
+       unsigned int simId;
 
        MMS_PDU_TYPE_T eMmsPduType;
        MMS_HTTP_CMD_TYPE_T eHttpCmdType;
@@ -141,152 +121,5 @@ typedef struct _mmsTranQEntity {
        char *pGetData;
 } mmsTranQEntity;
 
-typedef enum {
-       MMS_RM_PDU_TYPE,
-
-       MMS_RM_SEND_REQ,
-       MMS_RM_GET_REQ_AUTO,
-       MMS_RM_GET_REQ_MANUAL,
-       MMS_RM_NOTIFY_RESP_IND,
-       MMS_RM_ACK_IND,
-
-       MMS_RM_NOTI_IND,
-       MMS_RM_RETRIEVE_CONF,
-
-       MMS_RM_READ_REPORT_V10,
-       MMS_RM_READ_REPORT_V11
-} MmsRmPduType;
-
-/// CM //////////////////////////////////////////////////////
-
-#define MAX_PROFILE_ID 1
-
-#define MAX_URL_LENGTH 1024
-#define MAX_IPV4_LENGTH 30
-
-typedef struct _MMS_NETWORK_PROFILE_S {
-       int profileId[MAX_PROFILE_ID];
-       int profileCount;
-} MMS_NETWORK_PROFILE_S;
-
-
-
-/// HTTP ////////////////////////////////////////////////////
-
-enum _E_MMS_CONNECTION_MODE {
-       eTCP_WITH_PROXY = 0,  /** Means HTTP Proxy/Gateway are available */
-       eTCP_WITHOUT_PROXY = 1   /**  Means HTTP Proxy/Gateway is not available */
-};
-
-typedef unsigned int E_MMS_CONNECTION_MODE; /**< Values from \ref  _E_MMS_CONNECTION_MODE   */
-
-enum _E_MMS_NETWORK_ACCESS_POINT {
-       eNETWORK_ACCESS_POINT_ACKTIVE = 1
-};
-
-typedef unsigned int E_MMS_NETWORK_ACCESS_POINT;
-
-typedef struct  _MMSC_CONFIG_DATA_S {
-       char mmscUrl[MAX_URL_LENGTH + 1];                       /** if break, change it to NETPM_HOME_URL_LEN_MAX   */
-       char httpProxyIpAddr[MAX_IPV4_LENGTH + 1];      /**   HTTP Proxy's URL or IP address */
-
-       unsigned int proxyPortNo;       /** MMS HTTP proxy Port number  */
-       E_MMS_CONNECTION_MODE connectionMode;   /**   Values must be from ENUM list -\ref E_MMS_CONNECTION_MODE  */
-       E_MMS_NETWORK_ACCESS_POINT networkAccessPoint;  /**   Values must be from \ref E_MMS_NETWORK_ACCESS_POINT  */
-       unsigned int bAutoRetrieveFlag; /**  Value's shall be true or false */
-       unsigned int profileId;                 /** Profile is for CM Conn open*/
-} MMSC_CONFIG_DATA_S;
-
-typedef struct _MMS_PLUGIN_HTTP_DATA_S {
-       int profileId;
-       int profileCount;
-       int currentProfileId;
-       int sessionId;
-       int transactionId;
-       void *session;
-       void *sessionHeader;
-       MMSC_CONFIG_DATA_S mmscConfig;
-} MMS_PLUGIN_HTTP_DATA_S;
-
-typedef struct _MMS_PLUGIN_HTTP_CONTEXT_S {
-       char *recv_header_buf ;
-       int header_bufsize;
-       unsigned char *final_content_buf; // Final Concatenated Buffer
-       unsigned long ulContentLength;  // Content Leght Value received in HTTP OK Header
-       unsigned long bufOffset; /** < Incremented once received Content_receiving or Content_received Event */
-} MMS_PLUGIN_HTTP_CONTEXT_S;
-
-typedef struct _MMS_PLUGIN_PROCESS_DATA_S {
-       unsigned char *pData;
-       unsigned long dataLen;
-} MMS_PLUGIN_PROCESS_DATA_S;
-
-
-///////////////////////////////////////////////////////////////
-
-#define RETRY_MAX 1
-
-typedef enum {
-       MMS_HTTP_GET = 1,               /* GET  */
-       MMS_HTTP_POST = 2               /* POST */
-} MMS_HTTP_METHOD;
-
-#define MAX_MMSC_URL_LEN       100     /**   MAX URL Length includes NULL char */
-#define MAX_HTTP_PROXY_IPADDR_LEN      100     /**   MAX  HTTP Proxy IP addres length  includes NULL char */
-
-#define HTTP_REQUEST_LEN   1024
-#define HTTP_VER     "HTTP/1.1"
-#define CRLF             "\r\n"
-#define CRLFCRLF     "\r\n\r\n"
-
-/*  URL of  IIS Server - Where CGI script located */
-#define IIS_PostURI   "/mms/post.exe"
-#define OperatorPostUrl   "/mms/"
-#define MAX_MMSC_IPADDR_LEN   512
-#define        POST_URI   OperatorPostUrl
-
-
-
-//////////////////////////////////////////////////////////
-#define HTTP_RESP_SUCCESS    200
-#define HTTP_PROB_RESP_SUCCESS    100
-
-
-#define MMS_HTTP_HDR_CONNECTION "Keep-Alive"
-
-/********* HTTP HEADER MACROS *********/
-#define MMS_HTTP_HDR_CONTENT_TYPE "application/vnd.wap.mms-message"
-
-#define MMS_HTTP_HDR_USER_AGENT "AX355"
-
-#define MMS_HTTP_HDR_ACCEPT "application/vnd.wap.mms-message"
-
-#define MMS_HTTP_HDR_ACCEPT_LANGUAGE "en"
-
-#define MMS_HTTP_HDR_ACCEPT_CHARSET "US-ASCII, ISO-8859-1, UTF-8"
-
-//  MMSC Address
-#define NOW_MMSC_URL    ""
-#define NOW_MMSC_IP      ""
-#define NOW_MMSC_PROXY   ""
-#define NOW_MMSC_PROXY_PORT
-
-#define DEFAULT_MMSC_URL               NOW_MMSC_URL
-#define DEFAULT_MMSC_IP                NOW_MMSC_IP
-#define DEFAULT_MMSC_PORT
-#define DEFAULT_HTTP_PROXY     NOW_MMSC_PROXY
-#define DEFAULT_HTTP_PROXY_PORT        NOW_MMSC_PROXY_PORT
-
-typedef struct _S_HTTP_UA_RECVING_DATA {
-       int curr_len_recv;
-       int total_data_len;
-} S_HTTP_UA_RECVING_DATA;
-
-/////////////////////////////////////////////////////
-
-#define IN        /*! Pfrefix*/
-#define OUT       /*! Pfrefix*/
-#define INOUT     /*! Pfrefix*/
-
-#endif
+#endif //MMS_PLUGIN_TYPES_H
 
index ed7f08e..3df0340 100755 (executable)
@@ -1,32 +1,26 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#ifndef MMSPLUGINUSERAGENT_H
-#define MMSPLUGINUSERAGENT_H
+#ifndef MMS_PLUGIN_USERAGENT_H
+#define MMS_PLUGIN_USERAGENT_H
 
-#include <pthread.h>
-#include <vector>
-
-#include "MsgDebug.h"
+#include "MsgThread.h"
 #include "MsgMutex.h"
 #include "MsgQueue.h"
 #include "MmsPluginTypes.h"
-#include "MmsPluginConnManWrapper.h"
-#include "MmsPluginHttp.h"
-#include "MsgThread.h"
 
 class MmsPluginUaManager: public MsgThread
 {
@@ -59,9 +53,7 @@ class MmsPluginUaManager: public MsgThread
                // condition values
                bool running;           // flag for thread running
 
-               MsgThdSafeQ <mmsTranQEntity> mmsTranQ; // transaction q for mms plugin
+               MsgSimpleQ<mmsTranQEntity> mmsTranQ; // transaction q for mms plugin
 };
 
-bool MsgOpenCreateAndOverwriteFile(char *szFullPath, char *szBuff, int totalLength);
-
-#endif // MMSPLUGINUSERAGENT_H
+#endif //MMS_PLUGIN_USERAGENT_H
diff --git a/plugin/mms_plugin/include/MmsPluginUtil.h b/plugin/mms_plugin/include/MmsPluginUtil.h
new file mode 100755 (executable)
index 0000000..1e08034
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef MMS_PLUGIN_UTIL_H
+#define MMS_PLUGIN_UTIL_H
+
+#include <stdio.h>
+
+//File Util
+bool MmsMakeImageThumbnail(char *srcPath, char *dstPath);
+
+bool MmsMakeVideoThumbnail(char *srcPath, char *dstPath);
+
+FILE *MmsFileOpen(char *pFileName);
+
+//Text Util
+bool MmsIsAsciiString(const char *szSrc);
+
+bool MmsIsUtf8String(const unsigned char *szSrc, int nChar);
+
+void MmsRemoveLessGreaterChar(const char *szSrc, char *szDest, int destSize);
+
+bool MmsRemoveMarkup(const char *szSrc, char *szDest, int dstsize);
+
+bool MmsReplaceSpaceChar(char *pszText);
+
+char *MmsReplaceNonAsciiUtf8(const char *szSrc, char replaceChar);
+
+#endif //MMS_PLUGIN_UTIL_H
diff --git a/plugin/mms_plugin/include/MmsPluginWmLngPack.h b/plugin/mms_plugin/include/MmsPluginWmLngPack.h
deleted file mode 100755 (executable)
index 114bc01..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#ifndef _MMS_PLUGIN_WM_LNG_PACK_H_
-#define _MMS_PLUGIN_WM_LNG_PACK_H_
-
-#include "MmsPluginMessage.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-
-#define LOCALCODE_BYTE_MAX     3
-
-#define WmSizeof(size)         \
-               sizeof(size)/2
-
-/* Code Convert */
-bool  WmConvert2PCode( MCHAR* pmszOutText, int outBufSize, char* szInText);
-bool  WmConvert2LCode( char* pszOutText, int outBufSize, MCHAR* mszInText);
-bool  WmConvert2PCodeN( MCHAR* pmszOutText, int outBufSize, char*  szInText, int byteCount );
-bool  WmConvert2LCodeN( char* pszOutText, int outBufSize, MCHAR* mszInText, int charCount );
-bool  WmConvertPCode2UTF( UCHAR *pszOutText, int outBufSize, MCHAR *mszInText, int charCount );
-bool  WmConvertUTF2PCode( MCHAR *pmszOutText,int outBufSize, UCHAR *szInText, int byteCount );
-int   WmGetLCodeSize( MCHAR * mszText );
-int   WmGetLCodeSizeN( MCHAR *mszText, int charCount );
-bool  WmConvertLatinCode2PCode( MCHAR* pmszOutText, int outBufSize, char*  szInText);
-bool  WmConvertLatinCode2PCodeN( MCHAR* pmszOutText, int outBufSize, char*  szInText, int charCount );
-
-
-/* latin2 <-> PCode */
-bool   WmConvertLatin2Code2PCode( MCHAR* pmszOutText, int outBufSize, char*  szInText);
-
-/* latin3 <-> PCode */
-bool   WmConvertLatin3Code2PCode( MCHAR* pmszOutText, int outBufSize, char*  szInText);
-
-/* latin4 <-> PCode */
-bool   WmConvertLatin4Code2PCode( MCHAR* pmszOutText, int outBufSize, char*  szInText);
-
-/* latin8 <-> PCode */
-bool   WmConvertLatin8Code2PCode( MCHAR* pmszOutText, int outBufSize, char*  szInText);
-
-/* latin15 <-> PCode */
-bool   WmConvertLatin15Code2PCode( MCHAR* pmszOutText, int outBufSize, char*  szInText);
-
-/* latin5 <-> PCode */
-bool   WmConvertLatin5Code2PCode( MCHAR* pmszOutText, int outBufSize, char*  szInText);
-
-/* win1251 <-> PCode */
-bool   WmConvertWin1251Code2PCode( MCHAR* pmszOutText, int outBufSize, char*  szInText);
-
-/* Koi8-r <-> PCode */
-bool   WmConvertKoi8rCode2PCode( MCHAR* pmszOutText, int outBufSize, char*  szInText);
-
-/* Koi8-u <-> PCode */
-bool   WmConvertKoi8uCode2PCode( MCHAR* pmszOutText, int outBufSize, char*  szInText);
-
-
-/* String Handling */
-int    WmStrlen( const MCHAR* mszInText );
-int    WmStrncmp( const MCHAR* mszInText1, const MCHAR* mszInText2, UINT charCount );
-
-
-int WmGetLatin32UTFCodeSize( unsigned char* szSrc, int nChar ); //ISO 8859-3
-int WmGetLatin42UTFCodeSize( unsigned char* szSrc, int nChar ); //ISO 8859-4
-int WmGetLatin82UTFCodeSize( unsigned char* szSrc, int nChar ); //ISO 8859-8
-int WmGetLatin152UTFCodeSize( unsigned char* szSrc, int nChar ); //ISO 8859-15
-int WmGetLatin52UTFCodeSize( unsigned char* szSrc, int nChar ); //ISO 8859-9
-
-
-bool __WmConvertCodeBufferSizeCheck( char* ftnName, int outBufSize, int requiredBufSize );
-bool _WmT9ChangeUniToGSMCode( MCHAR* pmszOutText, MCHAR* mszInText, int length );
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* _WM_LNG_PACK_H_ */
-
-
diff --git a/plugin/sms_cdma_plugin/CMakeLists.txt b/plugin/sms_cdma_plugin/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..539a0b4
--- /dev/null
@@ -0,0 +1,57 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT(sms-plugin CXX)
+
+SET(CMAKE_SKIP_BUILD_RPATH TRUE)
+
+IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+       SET(CMAKE_BUILD_TYPE "Release")
+ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+MESSAGE("Build type: ${CMAKE_BUILD_TYPE}")
+
+SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
+
+##########################################################
+# Define SMS Plugin
+##########################################################
+
+SET(SMS-PLUGIN-SRCS
+       ${CMAKE_SOURCE_DIR}/plugin/sms_cdma_plugin/SmsCdmaPluginCallback.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_cdma_plugin/SmsCdmaPluginCodec.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_cdma_plugin/SmsCdmaPluginEventHandler.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_cdma_plugin/SmsCdmaPluginMain.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_cdma_plugin/SmsCdmaPluginParamCodec.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_cdma_plugin/SmsCdmaPluginStorage.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_cdma_plugin/SmsCdmaPluginTransport.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_cdma_plugin/SmsCdmaPluginUAManager.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_cdma_plugin/SmsCdmaPluginSetting.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_cdma_plugin/SmsCdmaPluginWapPushHandler.cpp
+)
+
+INCLUDE_DIRECTORIES(
+    ${CMAKE_SOURCE_DIR}/include/mapi
+       ${CMAKE_SOURCE_DIR}/include/common
+       ${CMAKE_SOURCE_DIR}/include/utils
+       ${CMAKE_SOURCE_DIR}/include/externals
+       ${CMAKE_CURRENT_SOURCE_DIR}/include
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(sms_plugin_pkgs REQUIRED db-util glib-2.0 tapi libxml-2.0 libwbxml2 dlog vconf gio-2.0)
+
+FOREACH(flag ${sms_plugin_pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
+
+ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+ADD_LIBRARY(${SMS-PLUGIN-LIB} SHARED ${SMS-PLUGIN-SRCS})
+TARGET_LINK_LIBRARIES(${SMS-PLUGIN-LIB} ${sms_plugin_pkgs_LDFLAGS} ${UTILS-LIB} ${EXTERNALS-LIB})
+
+IF(_FEATURE_TELEPHONY_ENABLE)
+INSTALL(TARGETS ${SMS-PLUGIN-LIB} LIBRARY DESTINATION lib)
+ENDIF(_FEATURE_TELEPHONY_ENABLE)
+
diff --git a/plugin/sms_cdma_plugin/SmsCdmaPluginCallback.cpp b/plugin/sms_cdma_plugin/SmsCdmaPluginCallback.cpp
new file mode 100755 (executable)
index 0000000..2afe93b
--- /dev/null
@@ -0,0 +1,574 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <glib.h>
+#include <pthread.h>
+
+#include "MsgDebug.h"
+#include "MsgCppTypes.h"
+#include "MsgException.h"
+#include "MsgGconfWrapper.h"
+#include "SmsCdmaPluginEventHandler.h"
+#include "SmsCdmaPluginParamCodec.h"
+#include "SmsCdmaPluginCodec.h"
+#include "SmsCdmaPluginTransport.h"
+#include "SmsCdmaPluginSetting.h"
+#include "SmsCdmaPluginCallback.h"
+
+
+extern struct tapi_handle *pTapiHandle;
+extern bool isMemAvailable;
+
+void _dnet_state_changed_cb(keynode_t *key, void* data);
+void _TapiMdnChangedCb(keynode_t *key, void *data);
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+
+SmsPluginCallback* SmsPluginCallback::pInstance = NULL;
+
+
+SmsPluginCallback::SmsPluginCallback()
+{
+
+
+}
+
+
+SmsPluginCallback::~SmsPluginCallback()
+{
+       if (pInstance != NULL) {
+               delete pInstance;
+               pInstance = NULL;
+       }
+}
+
+
+SmsPluginCallback* SmsPluginCallback::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginCallback();
+
+       return pInstance;
+}
+
+
+void SmsPluginCallback::registerEvent()
+{
+       if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SMS_DEVICE_READY, TapiEventDeviceReady, NULL) != TAPI_API_SUCCESS)
+               MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SMS_DEVICE_READY);
+       if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SMS_INCOM_MSG, TapiEventMsgIncoming, NULL) != TAPI_API_SUCCESS)
+               MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SMS_INCOM_MSG);
+       if (tel_register_noti_event(pTapiHandle, TAPI_PROP_NETWORK_SERVICE_TYPE, TapiEventNetworkStatusChange, NULL) != TAPI_API_SUCCESS)
+               MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_PROP_NETWORK_SERVICE_TYPE);
+       if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SIM_REFRESHED, TapiEventSimRefreshed, NULL) != TAPI_API_SUCCESS)
+               MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SIM_REFRESHED);
+
+       MsgSettingRegVconfCBCommon(VCONFKEY_DNET_STATE, _dnet_state_changed_cb);
+//     MsgSettingRegVconfCBCommon(VCONFKEY_TELEPHONY_MDN, _TapiMdnChangedCb);
+}
+
+
+void SmsPluginCallback::deRegisterEvent()
+{
+
+
+}
+
+
+void TapiEventDeviceReady(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventDeviceReady is called. : noti_id = [%d]", noti_id);
+
+       try
+       {
+               // Call Event Handler
+               SmsPluginEventHandler::instance()->setDeviceStatus();
+
+               if (SmsPluginEventHandler::instance()->getNeedInitConfig() == true) {
+                       SmsPluginEventHandler::instance()->setNeedInitConfig(false);
+                       SmsPluginSetting::instance()->SimRefreshCb();
+               }
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+
+}
+
+
+void TapiEventMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
+{
+       MSG_WARN("TapiEventMsgIncoming is called. noti_id [%s]", noti_id);
+
+       if (data == NULL) {
+               MSG_DEBUG("Error. evt->pData is NULL.");
+               return;
+       }
+
+       TelSmsDatapackageInfo_t* pDataPackage = (TelSmsDatapackageInfo_t*)data;
+
+       MSG_DEBUG("pDataPackage->format = [%d]", pDataPackage->format);
+       MSG_DEBUG("pDataPackage->Sca = [%s]", pDataPackage->Sca);
+       MSG_DEBUG("pDataPackage->MsgLength = [%d]", pDataPackage->MsgLength);
+       MSG_DEBUG("pDataPackage->szData = ");
+       for (int i = 0; i < pDataPackage->MsgLength; i++) {
+               MSG_DEBUG("[%02x]", pDataPackage->szData[i]);
+       }
+
+       char tpduTmp[(pDataPackage->MsgLength*2)+1];
+       memset(tpduTmp, 0x00, sizeof(tpduTmp));
+       for (int i = 0; i < pDataPackage->MsgLength; i++) {
+               snprintf(tpduTmp+(i*2), sizeof(tpduTmp)-(i*2), "%02X", pDataPackage->szData[i]);
+       }
+       MSG_WARN("[%s]", tpduTmp);
+
+       sms_trans_msg_s sms_trans_msg;
+       memset(&sms_trans_msg, 0x00, sizeof(sms_trans_msg_s));
+
+       if (pDataPackage->format == (TelSmsNetType_t)0x03) {                            // voice mail notification
+               sms_trans_msg.data.p2p_msg.telesvc_msg.type = SMS_TYPE_DELIVER;
+               sms_trans_msg.data.p2p_msg.telesvc_id = SMS_TRANS_TELESVC_VMN_95;
+
+               int num_msg = 0;
+               for (int i = 0; i < pDataPackage->MsgLength; i++) {
+                       num_msg*=256;
+                       num_msg+=pDataPackage->szData[i];
+               }
+
+               sms_trans_msg.data.p2p_msg.telesvc_msg.data.deliver.num_msg = num_msg;
+
+               char *voiceNumber = MsgSettingGetString(VOICEMAIL_NUMBER);
+               if (voiceNumber) {
+                       snprintf(sms_trans_msg.data.p2p_msg.address.szData, sizeof(sms_trans_msg.data.p2p_msg.address.szData), "%s", voiceNumber);
+                       free(voiceNumber);
+                       voiceNumber = NULL;
+               }
+               sms_trans_msg.data.p2p_msg.address.addr_len = strlen(sms_trans_msg.data.p2p_msg.address.szData);
+       } else {
+               bool bInvalid = SmsPluginMsgCodec::checkInvalidPDU(pDataPackage->szData, pDataPackage->MsgLength);
+               if (bInvalid == true) {
+                       // Decode Incoming Message
+                       SmsPluginMsgCodec::decodeMsg(pDataPackage->szData, pDataPackage->MsgLength, &sms_trans_msg);
+
+                       if (sms_trans_msg.data.cb_msg.telesvc_msg.data.deliver.cmas_data.is_wrong_recode_type) {
+                               MSG_WARN("Invalid CMAS Record Type");
+                               return;
+                       }
+               }
+               else {
+                       MSG_WARN("Invalid PDU");
+                       return;
+               }
+       }
+
+       /// Print tpdu
+       if (sms_trans_msg.type == SMS_TRANS_P2P_MSG) {
+               MSG_DEBUG("############# SMS_TRANS_P2P_MSG Incoming decoded tpdu values ####################");
+               MSG_DEBUG("------------------------------ transport layer data -----------------------------");
+               MSG_DEBUG("sms_trans_msg.type = [%d]", sms_trans_msg.type);
+               MSG_DEBUG("sms_trans_msg.data.p2p_msg.telesvc_id = [%d]", sms_trans_msg.data.p2p_msg.telesvc_id);
+               MSG_DEBUG("sms_trans_msg.data.p2p_msg.address.digit_mode = [%d]", sms_trans_msg.data.p2p_msg.address.digit_mode);
+               MSG_DEBUG("sms_trans_msg.data.p2p_msg.address.number_mode = [%d]", sms_trans_msg.data.p2p_msg.address.number_mode);
+               MSG_DEBUG("sms_trans_msg.data.p2p_msg.address.number_plan = [%d]", sms_trans_msg.data.p2p_msg.address.number_plan);
+               MSG_DEBUG("sms_trans_msg.data.p2p_msg.address.number_type = [%d]", sms_trans_msg.data.p2p_msg.address.number_type);
+               MSG_DEBUG("sms_trans_msg.data.p2p_msg.address.addr_len = [%d]", sms_trans_msg.data.p2p_msg.address.addr_len);
+               MSG_DEBUG("sms_trans_msg.data.p2p_msg.address.szData = [%s]", sms_trans_msg.data.p2p_msg.address.szData);
+               MSG_DEBUG("sms_trans_msg.data.p2p_msg.svc_ctg = [%d]", sms_trans_msg.data.p2p_msg.svc_ctg);
+               MSG_DEBUG("----------------------- teleservice layer : deliver data -------------------------");
+               sms_telesvc_deliver_s *deliver_msg = &(sms_trans_msg.data.p2p_msg.telesvc_msg.data.deliver);
+               MSG_DEBUG("sms_trans_msg.data.p2p_msg.telesvc_msg.type = [%d]", sms_trans_msg.data.p2p_msg.telesvc_msg.type);
+               MSG_DEBUG("priority= [%d]", deliver_msg->priority);
+               MSG_DEBUG("privacy= [%d]", deliver_msg->privacy);
+               MSG_DEBUG("display_mode= [%d]", deliver_msg->display_mode);
+               MSG_DEBUG("language= [%d]", deliver_msg->language);
+               MSG_DEBUG("msg_id= [%d]", deliver_msg->msg_id);
+               MSG_DEBUG("alert_priority= [%d]", deliver_msg->alert_priority);
+               MSG_DEBUG("num_msg= [%d]", deliver_msg->num_msg);
+               MSG_DEBUG("user_data.msg_type= [%d]", deliver_msg->user_data.msg_type);
+               MSG_DEBUG("user_data.encode_type= [%d]", deliver_msg->user_data.encode_type);
+               MSG_DEBUG("user_data.data_len= [%d]", deliver_msg->user_data.data_len);
+               MSG_DEBUG("user_data.user_data= [%s]", deliver_msg->user_data.user_data);
+               MSG_DEBUG("time_stamp.year= [%d]", deliver_msg->time_stamp.year);
+               MSG_DEBUG("time_stamp.month= [%d]", deliver_msg->time_stamp.month);
+               MSG_DEBUG("time_stamp.day= [%d]", deliver_msg->time_stamp.day);
+               MSG_DEBUG("time_stamp.hours= [%d]", deliver_msg->time_stamp.hours);
+               MSG_DEBUG("time_stamp.minutes= [%d]", deliver_msg->time_stamp.minutes);
+               MSG_DEBUG("time_stamp.seconds= [%d]", deliver_msg->time_stamp.seconds);
+               MSG_DEBUG("deliver_msg->callback_number.addr_len= [%d]", deliver_msg->callback_number.addr_len);
+               MSG_DEBUG("deliver_msg->callback_number.digit_mode= [%d]", deliver_msg->callback_number.digit_mode);
+               MSG_DEBUG("deliver_msg->callback_number.number_plan= [%d]", deliver_msg->callback_number.number_plan);
+               MSG_DEBUG("deliver_msg->callback_number.number_type= [%d]", deliver_msg->callback_number.number_type);
+               MSG_DEBUG("deliver_msg->callback_number.szData= [%s]", deliver_msg->callback_number.szData);
+               MSG_DEBUG("#####################################################");
+       }
+       else if (sms_trans_msg.type == SMS_TRANS_BROADCAST_MSG) {
+               MSG_DEBUG("############# SMS_TRANS_BROADCAST_MSG Incoming decoded tpdu values ####################");
+               MSG_DEBUG("------------------------------ transport layer data -----------------------------");
+               MSG_DEBUG("sms_trans_msg.data.cb_msg.svc_ctg = [%d]", sms_trans_msg.data.cb_msg.svc_ctg);
+               MSG_DEBUG("----------------------- teleservice layer : deliver data -------------------------");
+               sms_telesvc_deliver_s *deliver_msg = &(sms_trans_msg.data.cb_msg.telesvc_msg.data.deliver);
+               MSG_DEBUG("sms_trans_msg.data.cb_msg.telesvc_msg.type = [%d]", sms_trans_msg.data.cb_msg.telesvc_msg.type);
+               MSG_DEBUG("priority= [%d]", deliver_msg->priority);
+               MSG_DEBUG("display_mode= [%d]", deliver_msg->display_mode);
+               MSG_DEBUG("language= [%d]", deliver_msg->language);
+               MSG_DEBUG("msg_id= [%d]", deliver_msg->msg_id);
+               MSG_DEBUG("msg_id.msg_id)= [%d]", deliver_msg->msg_id.msg_id);
+               MSG_DEBUG("header_ind= [%d]", deliver_msg->msg_id.header_ind);
+               MSG_DEBUG("alert_priority= [%d]", deliver_msg->alert_priority);
+               MSG_DEBUG("cmas_data.encode_type= [%d]", deliver_msg->cmas_data.encode_type);
+               MSG_DEBUG("cmas_data.data_len= [%d]", deliver_msg->cmas_data.data_len);
+               MSG_DEBUG("cmas_data.alert_text= [%s]", deliver_msg->cmas_data.alert_text);
+               MSG_DEBUG("cmas_data.response_type= [%d]", deliver_msg->cmas_data.response_type);
+               MSG_DEBUG("cmas_data.severity= [%d]", deliver_msg->cmas_data.severity);
+               MSG_DEBUG("cmas_data.urgency= [%d]", deliver_msg->cmas_data.urgency);
+               MSG_DEBUG("cmas_data.certainty= [%d]", deliver_msg->cmas_data.certainty);
+               MSG_DEBUG("cmas_data.id= [%d]", deliver_msg->cmas_data.id);
+               MSG_DEBUG("time_stamp.year= [%d]", deliver_msg->time_stamp.year);
+               MSG_DEBUG("time_stamp.month= [%d]", deliver_msg->time_stamp.month);
+               MSG_DEBUG("time_stamp.day= [%d]", deliver_msg->time_stamp.day);
+               MSG_DEBUG("time_stamp.hours= [%d]", deliver_msg->time_stamp.hours);
+               MSG_DEBUG("time_stamp.minutes= [%d]", deliver_msg->time_stamp.minutes);
+               MSG_DEBUG("time_stamp.seconds= [%d]", deliver_msg->time_stamp.seconds);
+               MSG_DEBUG("deliver_msg->callback_number.addr_len= [%d]", deliver_msg->callback_number.addr_len);
+               MSG_DEBUG("deliver_msg->callback_number.digit_mode= [%d]", deliver_msg->callback_number.digit_mode);
+               MSG_DEBUG("deliver_msg->callback_number.number_plan= [%d]", deliver_msg->callback_number.number_plan);
+               MSG_DEBUG("deliver_msg->callback_number.number_type= [%d]", deliver_msg->callback_number.number_type);
+               MSG_DEBUG("deliver_msg->callback_number.szData= [%s]", deliver_msg->callback_number.szData);
+               MSG_DEBUG("#####################################################");
+       } else if (sms_trans_msg.type == SMS_TRANS_ACK_MSG) {
+               // DLOG
+               MSG_DEBUG("#####################################################");
+       }
+
+       try
+       {
+               if (sms_trans_msg.type == SMS_TRANS_P2P_MSG) {
+                       if (sms_trans_msg.data.p2p_msg.telesvc_id == SMS_TRANS_TELESVC_WAP) {
+                               SmsPluginEventHandler::instance()->handleWapMsgIncoming(&(sms_trans_msg.data.p2p_msg));
+                       }
+                       else {
+                               SmsPluginEventHandler::instance()->handleMsgIncoming(&(sms_trans_msg.data.p2p_msg)); // Call Event Handler
+                       }
+               } else if (sms_trans_msg.type == SMS_TRANS_BROADCAST_MSG) {
+                       SmsPluginEventHandler::instance()->handleCbMsgIncoming(&(sms_trans_msg.data.cb_msg)); // Call Event Handler
+               } else if (sms_trans_msg.type == SMS_TRANS_ACK_MSG) {
+                       //SmsPluginEventHandler::instance()->handleAckMsgIncoming(&(sms_trans_msg.data.ack_msg)); // Call Event Handler
+               }
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+}
+
+
+void TapiEventNetworkStatusChange(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventNetworkStatusChange is called.");
+
+       if (data == NULL) {
+               MSG_DEBUG("Error. data is NULL.");
+               return;
+       }
+
+       TelNetworkServiceType_t *type = (TelNetworkServiceType_t *)data;
+
+       MSG_DEBUG("network status type [%d]", *type);
+
+       if(*type > TAPI_NETWORK_SERVICE_TYPE_SEARCH)
+       {
+               SmsPluginEventHandler::instance()->handleResendMessage(); // Call Event Handler
+       }
+}
+
+
+void TapiEventSimRefreshed(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSimRefreshed is called.");
+
+       SmsPluginSetting::instance()->SimRefreshCb();
+}
+
+
+void TapiEventMemoryStatus(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("Tapi result is [%d]", result);
+       if(result == TAPI_API_SUCCESS)
+       {
+               isMemAvailable = true;
+       }
+}
+
+
+void TapiEventSentStatus(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSentStatus is called. result = [%d]", result);
+
+       sms_network_status_t sentStatus;
+
+       /* Convert TAPI status -> SMS network status */
+       switch ((TelSmsResponse_t)result) {
+               case TAPI_NETTEXT_SENDSMS_SUCCESS :
+                       sentStatus = SMS_NETWORK_SEND_SUCCESS;
+                       break;
+               case TAPI_NETTEXT_INVALID_MANDATORY_INFO :
+                       sentStatus = SMS_NETWORK_SEND_FAIL_MANDATORY_INFO_MISSING;
+                       break;
+               case TAPI_NETTEXT_DESTINAITION_OUTOFSERVICE :
+               case TAPI_NETTEXT_TEMPORARY_FAILURE :
+               case TAPI_NETTEXT_CONGESTION :
+               case TAPI_NETTEXT_RESOURCES_UNAVAILABLE :
+               case TAPI_NETTEXT_MESSAGE_NOT_COMPAT_PROTOCOL :
+                       sentStatus = SMS_NETWORK_SEND_FAIL_TEMPORARY;
+                       break;
+               case TAPI_NETTEXT_DEST_ADDRESS_FDN_RESTRICTED :
+               case TAPI_NETTEXT_SCADDRESS_FDN_RESTRICTED :
+                       sentStatus = SMS_NETWORK_SEND_FAIL_FDN_RESTRICED;
+                       break;
+               default :
+                       sentStatus = SMS_NETWORK_SEND_FAIL;
+                       break;
+       }
+
+       MSG_DEBUG("SMS Network Status = [%d]", sentStatus);
+
+       if(sentStatus == SMS_NETWORK_SEND_FAIL_TEMPORARY ||
+                       sentStatus == SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_WITH_MOD ||
+                       sentStatus == SMS_NETWORK_SEND_FAIL_FDN_RESTRICED) {
+               SmsPluginTransport::instance()->setNetStatus(sentStatus);
+               return;
+       }
+
+       if(sentStatus == SMS_NETWORK_SEND_FAIL)
+       {
+               int svc_type;
+               tel_get_property_int(handle, TAPI_PROP_NETWORK_SERVICE_TYPE, &svc_type);
+               if(svc_type < TAPI_NETWORK_SERVICE_TYPE_2G){
+                       sentStatus = SMS_NETWORK_SEND_PENDING;
+               }
+       }
+
+       /* Convert SMS status -> Messaging network status */
+       msg_network_status_t netStatus;
+
+       if (sentStatus == SMS_NETWORK_SEND_SUCCESS) {
+               netStatus = MSG_NETWORK_SEND_SUCCESS;
+       } else if (sentStatus == SMS_NETWORK_SENDING) {
+               netStatus = MSG_NETWORK_SENDING;
+       } else if (sentStatus == SMS_NETWORK_SEND_PENDING) {
+               netStatus = MSG_NETWORK_SEND_PENDING;
+       } else if (sentStatus == SMS_NETWORK_SEND_FAIL_UNKNOWN_SUBSCRIBER) {
+               netStatus = MSG_NETWORK_SEND_FAIL_UNKNOWN_SUBSCRIBER;
+       } else if (sentStatus == SMS_NETWORK_SEND_FAIL_MS_DISABLED) {
+               netStatus = MSG_NETWORK_SEND_FAIL_MS_DISABLED;
+       } else if (sentStatus == SMS_NETWORK_SEND_FAIL_NETWORK_NOT_READY) {
+               netStatus = MSG_NETWORK_SEND_FAIL_NETWORK_NOT_READY;
+       } else {
+               netStatus = MSG_NETWORK_SEND_FAIL;
+       }
+
+       try
+       {
+               SmsPluginEventHandler::instance()->handleSentStatus(netStatus);
+
+               SmsPluginTransport::instance()->setNetStatus(sentStatus);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+
+}
+
+
+void TapiEventDeliveryReportCNF(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventDeliveryReportCNF is called. : result = [%d]", result);
+
+       return;
+}
+
+
+void TapiEventSetConfigData(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSetConfigData is called.");
+
+       if (data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+               return;
+       }
+
+       TelSmsSetResponse* responseType = (TelSmsSetResponse*)data;
+
+       MSG_DEBUG("responseType : [%d]", *responseType);
+
+       switch (*responseType)
+       {
+               case TAPI_NETTEXT_SETPREFERREDBEARER_RSP :
+                       MSG_DEBUG("TAPI_NETTEXT_SETPREFERREDBEARER_RSP is called");
+               break;
+
+               case TAPI_NETTEXT_SETPARAMETERS_RSP :
+                       MSG_DEBUG("TAPI_NETTEXT_SETPARAMETERS_RSP is called");
+               break;
+
+               case TAPI_NETTEXT_CBSETCONFIG_RSP :
+                       MSG_DEBUG("TAPI_NETTEXT_CBSETCONFIG_RSP is called");
+               break;
+
+               case TAPI_NETTEXT_SETMEMORYSTATUS_RSP :
+                       MSG_DEBUG("TAPI_NETTEXT_SETMEMORYSTATUS_RSP is called");
+               break;
+
+               case TAPI_NETTEXT_SETMESSAGESTATUS_RSP :
+                       MSG_DEBUG("TAPI_NETTEXT_SETMESSAGESTATUS_RSP is called");
+               break;
+
+               default :
+                       MSG_DEBUG("Unknown Response is called [%d]", *responseType);
+               break;
+       }
+
+       bool bRet = true;
+
+       MSG_DEBUG("status : [%d]", (TelSmsCause_t)result);
+
+       if ((TelSmsCause_t)result != TAPI_NETTEXT_SUCCESS) bRet = false;
+
+       SmsPluginSetting::instance()->setResultFromEvent(bRet);
+
+}
+
+
+void TapiEventGetCBConfig(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetCBConfig is called.");
+
+       MSG_CBMSG_OPT_S cbOpt = {0};
+
+       if (result != TAPI_API_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+
+               SmsPluginSetting::instance()->setCbConfigEvent(NULL, false);
+
+               return;
+       }
+
+       TelSmsCbConfig_t* pCBConfig = (TelSmsCbConfig_t*)data;
+
+       cbOpt.bReceive = (bool)pCBConfig->CBEnabled;
+
+//     cbOpt.maxSimCnt = pCBConfig->MsgIdMaxCount;
+
+//     MSG_DEBUG("Receive [%d], Max SIM Count [%d]", cbOpt.bReceive, cbOpt.maxSimCnt);
+       MSG_DEBUG("Receive [%d]", cbOpt.bReceive);
+
+       cbOpt.channelData.channelCnt = pCBConfig->MsgIdRangeCount;
+
+       if (cbOpt.channelData.channelCnt > CB_CHANNEL_MAX)
+       {
+               MSG_DEBUG("Channel Count [%d] from TAPI is over MAX", cbOpt.channelData.channelCnt);
+               cbOpt.channelData.channelCnt = CB_CHANNEL_MAX;
+       }
+
+       MSG_DEBUG("Channel Count [%d]", cbOpt.channelData.channelCnt);
+
+       for (int i = 0; i < cbOpt.channelData.channelCnt; i++)
+       {
+               cbOpt.channelData.channelInfo[i].bActivate = pCBConfig->MsgIDs[i].Net3gpp2.Selected;
+               cbOpt.channelData.channelInfo[i].ctg = pCBConfig->MsgIDs[i].Net3gpp2.CBCategory;
+               cbOpt.channelData.channelInfo[i].lang = pCBConfig->MsgIDs[i].Net3gpp2.CBLanguage;
+               memset(cbOpt.channelData.channelInfo[i].name, 0x00, CB_CHANNEL_NAME_MAX+1);
+
+               MSG_DEBUG("Channel Category [%d], Channel Language [%d] ", cbOpt.channelData.channelInfo[i].ctg, cbOpt.channelData.channelInfo[i].lang);
+       }
+
+       SmsPluginSetting::instance()->setCbConfigEvent(&cbOpt, true);
+}
+
+void TapiEventGetMsisdnInfo(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetMsisdnInfo is called.");
+
+       bool bRet = false;
+
+       if (result != TAPI_SIM_ACCESS_SUCCESS || data == NULL) {
+               MSG_DEBUG("Error. data is NULL.");
+               SmsPluginSetting::instance()->setResultFromSim(bRet);
+               return;
+       }
+
+       TelSimMsisdnList_t *list = (TelSimMsisdnList_t *)data;
+
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       int simIndex = 1;
+
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_MSISDN, simIndex);
+
+       for (int i = 0; i < list->count; i++) {
+               if (list->list[i].num[0] != '\0') {
+                       if (MsgSettingSetString(keyName, list->list[i].num) == MSG_SUCCESS) {
+                               MSG_SEC_DEBUG("Get MSISDN from SIM : [%s]", list->list[i].num);
+                               bRet = true;
+                       } else {
+                               MSG_DEBUG("Getting MSISDN is failed!");
+                       }
+                       break;
+               }
+       }
+
+       SmsPluginSetting::instance()->setResultFromSim(bRet);
+}
+
+void _dnet_state_changed_cb(keynode_t *key, void* data)
+{
+       int dnet_state = MsgSettingGetInt(VCONFKEY_DNET_STATE);
+
+       if (dnet_state > VCONFKEY_DNET_OFF) {
+               SmsPluginEventHandler::instance()->handleResendMessage(); // Call Event Handler
+       }
+}
+
+void _TapiMdnChangedCb(keynode_t *key, void *data)
+{
+       MSG_INFO("_TapiMdnChangedCb is called.");
+
+       char *mdn = vconf_get_str("db/telephony/mdn");
+
+       if (mdn) {
+               bool bNeedToUpdateVoicemail = SmsPluginSetting::instance()->getUpdateVoicemailByMdn();
+               MSG_INFO("bNeedToUpdateVoicemail:%d, mdn:[%s]", bNeedToUpdateVoicemail, mdn);
+
+               if (bNeedToUpdateVoicemail) {
+                       if (MsgSettingSetString(VOICEMAIL_NUMBER, mdn) != MSG_SUCCESS)
+                               MSG_DEBUG("MsgSettingSetInt is failed!!");
+
+                       if (MsgSettingSetString(VOICEMAIL_DEFAULT_NUMBER, mdn) != MSG_SUCCESS)
+                               MSG_DEBUG("Error to set config data [%s]", VOICEMAIL_DEFAULT_NUMBER);
+               }
+
+               free(mdn);
+       }
+}
diff --git a/plugin/sms_cdma_plugin/SmsCdmaPluginCodec.cpp b/plugin/sms_cdma_plugin/SmsCdmaPluginCodec.cpp
new file mode 100755 (executable)
index 0000000..0ae9eff
--- /dev/null
@@ -0,0 +1,2383 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+
+
+
+#include <stdio.h>
+#include <string.h>
+
+#include "MsgDebug.h"
+#include "MsgTextConvert.h"
+
+#include "SmsCdmaPluginParamCodec.h"
+#include "SmsCdmaPluginCodec.h"
+
+
+
+SmsPluginMsgCodec* SmsPluginMsgCodec::pInstance = NULL;
+
+SmsPluginMsgCodec::SmsPluginMsgCodec()
+{
+
+}
+
+
+SmsPluginMsgCodec::~SmsPluginMsgCodec()
+{
+
+}
+
+
+SmsPluginMsgCodec* SmsPluginMsgCodec::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginMsgCodec();
+
+       return pInstance;
+}
+
+
+void _shiftNBit(unsigned char *src, unsigned int n_bytes, unsigned int n_shift_bit)
+{
+       char tmp;
+
+    for (unsigned int index = 1; index < n_bytes; index++) {
+            tmp = src[index] >> (8 - n_shift_bit);
+            src[index-1] |= tmp;
+            src[index] = src[index] << n_shift_bit;
+    }
+}
+
+
+void _shiftNBit_for_decode(unsigned char *src, unsigned int n_bytes, unsigned int n_shift_bit)
+{
+     for (unsigned int index = 0; index < n_bytes; index++) {
+         src[index]<<=n_shift_bit;
+         src[index] |= (src[index+1] >> (8 - n_shift_bit));
+         }
+}
+
+
+void _copy_short_to_char(unsigned char *dest, const unsigned short *src)
+{
+       dest[0] = (0xff00 & *src) >> 8;
+       dest[1] = 0x00ff & *src;
+}
+
+
+void _copy_char_to_short(unsigned short *dest, const unsigned char *src)
+{
+     *dest = src[0]*256 + src[1];
+}
+
+
+unsigned char _convert_to_BCD(unsigned char val)
+{
+       unsigned char ret = 0x00;
+       ret = ((val/10) << 4) | (val%10);
+       return ret;
+}
+
+
+int UnpackGSM7bitData(unsigned char *src, unsigned char *dest, unsigned int dataLen)
+{
+       unsigned int srcIdx = 0, dstIdx = 0, shift = 0;
+
+       MSG_DEBUG("dataLen = %d", dataLen);
+
+       for (; dstIdx < dataLen; dstIdx++)
+       {
+               if (shift == 0)
+               {
+                       dest[dstIdx] = src[srcIdx] & 0x7F;
+
+                       shift = 7;
+                       srcIdx++;
+                       dstIdx++;
+
+                       if (dstIdx >= dataLen) break;
+               }
+
+               if (shift > 0)
+               {
+                       dest[dstIdx] = (src[srcIdx-1] >> shift) + (src[srcIdx] << (8 - shift));
+
+                       dest[dstIdx] &= 0x7F;
+
+                       shift--;
+
+                       if (shift > 0) srcIdx++;
+               }
+       }
+
+       return dstIdx;
+}
+
+
+int PackGSM7bitData(const unsigned char *pUserData, unsigned char *pPackData, int dataLen)
+{
+       int srcIdx = 0, dstIdx = 0, shift = 0;
+
+       if (shift > 0)
+               dstIdx = 1;
+
+       while (srcIdx < dataLen)
+       {
+               if (shift == 0)
+               {
+                       pPackData[dstIdx] = pUserData[srcIdx];
+
+                       shift = 7;
+                       srcIdx++;
+                       dstIdx++;
+
+                       if (srcIdx >= dataLen) break;
+               }
+
+               if (shift > 1)
+               {
+                       pPackData[dstIdx-1] |= pUserData[srcIdx] << shift;
+                       pPackData[dstIdx] = pUserData[srcIdx] >> (8-shift);
+                       shift--;
+
+                       srcIdx++;
+                       dstIdx++;
+               }
+               else if (shift == 1)
+               {
+                       pPackData[dstIdx-1] |= pUserData[srcIdx] << shift;
+
+                       srcIdx++;
+
+                       shift--;
+               }
+       }
+
+       return dstIdx;
+}
+
+
+bool SmsPluginMsgCodec::checkInvalidPDU(const unsigned char *p_pkg_str, const int p_pkg_len)
+{
+       MSG_BEGIN();
+       int offset = 0;
+
+       if (!(p_pkg_str[offset] == 0x00 || p_pkg_str[offset] == 0x01 || p_pkg_str[offset] == 0x02)) {
+               MSG_WARN("Invalid PDU : Message Type [%2x]", p_pkg_str[offset]);
+               return false;
+       }
+
+       offset++;
+
+       while (offset < p_pkg_len) {
+               switch (p_pkg_str[offset]) {
+               case 0x00 :
+               case 0x01 :
+               case 0x02 :
+               case 0x03 :
+               case 0x04 :
+               case 0x05 :
+               case 0x06 :
+               case 0x07 :
+               case 0x08 :
+                       offset += (p_pkg_str[offset+1]+2);
+                       break;
+               default:
+                       MSG_WARN("Invalid PDU : Parameter ID [%2x], offset [%d]", p_pkg_str[offset], offset);
+                       return false;
+               }
+       }
+
+       if (offset != p_pkg_len)
+               return false;
+
+       MSG_END();
+       return true;
+}
+
+
+int SmsPluginMsgCodec::encodeMsg(const sms_trans_msg_s *p_msg, unsigned char *p_pkg_str)
+{
+       MSG_BEGIN();
+
+       int encode_size = 0;
+
+       switch(p_msg->type) {
+               case SMS_TRANS_P2P_MSG:
+                       encode_size = encodeP2PMsg(&(p_msg->data.p2p_msg), p_pkg_str);
+                       break;
+               case SMS_TRANS_BROADCAST_MSG:
+                       encode_size = encodeCBMsg(&(p_msg->data.cb_msg), p_pkg_str);
+                       break;
+               case SMS_TRANS_ACK_MSG :
+                       encode_size = encodeAckMsg(&(p_msg->data.ack_msg), p_pkg_str);
+                       break;
+               default :
+                       break;
+       }
+
+
+       MSG_END();
+
+       return encode_size;
+}
+
+
+int SmsPluginMsgCodec::encodeP2PMsg(const sms_trans_p2p_msg_s *p_msg, unsigned char *p_pkg_str)
+{
+       MSG_BEGIN();
+
+       int offset = 0, encode_size = 0;
+       int addr_len = 0;
+       int index = 0, len_index = 0;
+
+       p_pkg_str[offset++] = SMS_TRANS_P2P_MSG;
+
+       // 1. teleservice id
+       p_pkg_str[offset++] = SMS_TRANS_PARAM_TELESVC_IDENTIFIER;
+       p_pkg_str[offset++] = 2; // fixed
+       //memcpy(p_pkg_str+offset, &(p_msg->telesvc_id), sizeof(sms_trans_telesvc_id_t));
+       _copy_short_to_char(p_pkg_str+offset, &(p_msg->telesvc_id));
+       offset += sizeof(sms_trans_telesvc_id_t);
+
+       // 2. Service category
+       if(p_msg->svc_ctg < SMS_TRANS_SVC_CTG_UNDEFINED) {
+               p_pkg_str[offset++] = SMS_TRANS_PARAM_SERVICE_CATEGORY;
+               p_pkg_str[offset++] = 0x02; // fixed
+               _copy_short_to_char(&p_pkg_str[offset],&(p_msg->svc_ctg));
+       }
+
+       // 3. Address
+       p_pkg_str[offset++] = SMS_TRANS_PARAM_DEST_ADDRESS;
+
+       len_index = offset++; // Will be set to param length
+
+       p_pkg_str[offset] = p_msg->address.digit_mode ? 0x80 : 0x00;
+       p_pkg_str[offset] |= (p_msg->address.number_mode ? 0x40 : 0x00);
+
+       if(p_msg->address.digit_mode == false) {
+               index = offset++;
+               p_pkg_str[offset++] = p_msg->address.addr_len;
+
+               addr_len = SmsPluginParamCodec::instance()->convertDigitToDTMF(p_msg->address.szData, p_msg->address.addr_len, 0, p_pkg_str+offset);
+
+               for (int j=0; j < addr_len; j++) {
+                       MSG_DEBUG("ADDRESS 4BIT DTMF [%d] = [%02x]", j, p_pkg_str[offset+j]);
+               }
+
+               offset += addr_len;
+
+               _shiftNBit(&p_pkg_str[index], offset-index+1, 6);
+       }
+       else if(p_msg->address.digit_mode == true) {
+               p_pkg_str[offset] |= p_msg->address.number_type << 3;
+
+               if(p_msg->address.number_mode == false) {
+                       p_pkg_str[offset++] |= p_msg->address.number_plan >> 1;
+                       p_pkg_str[offset++] |= p_msg->address.number_plan << 7;
+                       index = offset-1;
+                       p_pkg_str[offset++] = p_msg->address.addr_len;
+
+                       memcpy(p_pkg_str+offset, p_msg->address.szData, p_msg->address.addr_len);
+
+                       offset += p_msg->address.addr_len;
+
+                       _shiftNBit(&p_pkg_str[index], offset-index+1, 7);
+               }
+               else if(p_msg->address.number_mode == true) {
+                       index = offset++;
+                       p_pkg_str[offset++] = p_msg->address.addr_len;
+                       memcpy(p_pkg_str+offset, p_msg->address.szData, p_msg->address.addr_len);
+
+                       offset += p_msg->address.addr_len;
+
+                       _shiftNBit(&p_pkg_str[index], offset-index+1, 3);
+               }
+       }
+
+       p_pkg_str[len_index] = offset - len_index - 1 ;
+       MSG_DEBUG("Address subparam length field = [%d]", p_pkg_str[len_index]);
+
+       // 4. Sub address (optional)
+       if(p_msg->sub_address.addr_len > 0) {
+               p_pkg_str[offset++] = SMS_TRANS_PARAM_ORG_SUB_ADDRESS;
+               p_pkg_str[offset] = p_msg->sub_address.addr_len + 2;
+               index = offset++;
+               p_pkg_str[offset] |= p_msg->sub_address.type << 5;
+               p_pkg_str[offset++] |= (p_msg->sub_address.odd ? 0x10 : 0x00);
+               p_pkg_str[offset++] = p_msg->sub_address.addr_len;
+               memcpy(p_pkg_str+offset, p_msg->sub_address.szData, p_msg->sub_address.addr_len);
+
+               offset+=p_msg->sub_address.addr_len;
+
+               _shiftNBit(&p_pkg_str[index], offset-index+1, 4);
+       }
+
+       // 5. Bearer reply option (optional)
+       if(p_msg->reply_seq > 0) {
+               p_pkg_str[offset++] = SMS_TRANS_PARAM_BEARER_REPLY_OPTION;
+               p_pkg_str[offset++] = 1;
+               p_pkg_str[offset++] = (unsigned char)(p_msg->reply_seq << 2);
+               MSG_DEBUG("Reply sequnce number = [%d]", p_msg->reply_seq);
+       }
+
+       // 6. Bearer data
+    p_pkg_str[offset++] = SMS_TRANS_PARAM_BEARER_DATA;
+       index = offset++; // PARAMETER_LEN field should be filled at the last part.
+
+       unsigned char *encode_data = &p_pkg_str[offset];
+
+       encode_size = encodeTelesvcMsg(&(p_msg->telesvc_msg), encode_data);
+       p_pkg_str[index] = encode_size; // PARAMETER_LEN
+
+       offset += encode_size;
+
+       MSG_END();
+
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::encodeCBMsg(const sms_trans_broadcast_msg_s *p_msg, unsigned char *p_pkg_str)
+{
+       MSG_BEGIN();
+
+       int offset = 0, encode_size = 0;
+       int len_index = 0;
+
+       // 1. Service Category(Mandatory)
+       p_pkg_str[offset++] = SMS_TRANS_PARAM_SERVICE_CATEGORY;
+       p_pkg_str[offset++] = 0x02;
+       _copy_short_to_char(&p_pkg_str[offset],&p_msg->svc_ctg);
+
+
+       // 2. Bearer Data(Optional)
+       // TODO: give condition
+    p_pkg_str[offset++] = SMS_TRANS_PARAM_BEARER_DATA;
+       len_index = offset++; // PARAMETER_LEN field should be filled at the last part.
+
+       unsigned char *encode_data = &p_pkg_str[offset];
+
+       encode_size = encodeTelesvcMsg(&(p_msg->telesvc_msg), encode_data);
+       p_pkg_str[len_index] = encode_size; // PARAMETER_LEN
+
+       offset += encode_size;
+
+       MSG_END();
+
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::encodeAckMsg(const sms_trans_ack_msg_s *p_msg, unsigned char *p_pkg_str)
+{
+       MSG_BEGIN();
+
+       int offset = 0;
+       int addr_len = 0, len_index = 0;
+       int index = 0;
+
+       // 1. Address
+       p_pkg_str[offset++] = SMS_TRANS_PARAM_DEST_ADDRESS;
+
+       len_index = offset++; // Will be set to param length
+
+       p_pkg_str[offset] = p_msg->address.digit_mode ? 0x80 : 0x00;
+       p_pkg_str[offset] |= (p_msg->address.number_mode ? 0x40 : 0x00);
+
+       index = offset++;
+
+       if(p_msg->address.digit_mode == false) {
+               p_pkg_str[offset++] = p_msg->address.addr_len;
+
+               addr_len = SmsPluginParamCodec::instance()->convertDigitToDTMF(p_msg->address.szData, p_msg->address.addr_len, 0, p_pkg_str+offset);
+
+               for (int j=0; j < addr_len; j++) {
+                       MSG_DEBUG("ADDRESS 4BIT DTMF [%d] = [%02x]", j, p_pkg_str[offset+j]);
+               }
+
+               offset += addr_len;
+
+               _shiftNBit(&p_pkg_str[index], offset-index+1, 6);
+       }
+       else if(p_msg->address.digit_mode == true) {
+               p_pkg_str[offset] |= p_msg->address.number_type << 3;
+
+               if(p_msg->address.number_mode == false) {
+                       p_pkg_str[offset++] |= p_msg->address.number_plan >> 1;
+                       p_pkg_str[offset++] |= p_msg->address.number_plan << 7;
+                       index++;
+                       p_pkg_str[offset++] = p_msg->address.addr_len;
+
+                       memcpy(p_pkg_str+offset, p_msg->address.szData, p_msg->address.addr_len);
+
+                       offset += p_msg->address.addr_len;
+
+                       _shiftNBit(&p_pkg_str[index], offset-index+1, 7);
+               }
+               else if(p_msg->address.number_mode == true) {
+                       p_pkg_str[++offset] = p_msg->address.addr_len;
+                       offset++;
+                       memcpy(p_pkg_str+offset, p_msg->address.szData, p_msg->address.addr_len);
+
+                       offset += p_msg->address.addr_len;
+
+                       _shiftNBit(&p_pkg_str[index], offset-index+1, 3);
+               }
+       }
+
+       p_pkg_str[len_index] = offset - len_index - 1 ;
+       MSG_DEBUG("Address subparam length field = [%d]", p_pkg_str[len_index]);
+
+       // 2. Sub address
+       if(p_msg->sub_address.addr_len > 0) {
+               p_pkg_str[offset++] = SMS_TRANS_PARAM_ORG_SUB_ADDRESS;
+               p_pkg_str[offset] = p_msg->sub_address.addr_len + 2;
+               index = offset++;
+               p_pkg_str[offset] |= p_msg->sub_address.type << 5;
+               p_pkg_str[offset++] |= (p_msg->sub_address.odd ? 0x10 : 0x00);
+               p_pkg_str[offset++] = p_msg->sub_address.addr_len;
+               memcpy(p_pkg_str+offset, p_msg->sub_address.szData, p_msg->sub_address.addr_len);
+
+               offset+=p_msg->sub_address.addr_len;
+
+               _shiftNBit(&p_pkg_str[index], offset-index+1, 4);
+       }
+
+       // 3. Cause code
+       p_pkg_str[offset++] = SMS_TRANS_PARAM_CAUSE_CODES;
+       index = offset++;
+       p_pkg_str[offset] |= p_msg->cause_code.reply_seq << 2;
+       p_pkg_str[offset] |= p_msg->cause_code.error_class;
+       if (p_msg->cause_code.error_class != 0x0) {
+               p_pkg_str[++offset] = p_msg->cause_code.cause_code;
+       }
+       p_pkg_str[index] = offset - index;
+
+       MSG_END();
+
+       return offset;
+
+}
+
+int SmsPluginMsgCodec::encodeTelesvcMsg(const sms_telesvc_msg_s *p_msg, unsigned char *p_pkg_str)
+{
+       MSG_BEGIN();
+       int encode_size = 0;
+
+       MSG_DEBUG("Teleservice msg type = [%d]", p_msg->type);
+
+       switch(p_msg->type) {
+//             case SMS_TYPE_DELIVER :
+//                     encode_size = encodeTelesvcDeliverMsg(&(p_msg->data.delever), p_pkg_str);
+//                     break;
+               case SMS_TYPE_SUBMIT :
+                       encode_size = encodeTelesvcSubmitMsg(&(p_msg->data.submit), p_pkg_str);
+                       break;
+               case SMS_TYPE_CANCEL :
+                       encode_size = encodeTelesvcCancelMsg(&(p_msg->data.cancel), p_pkg_str);
+                       break;
+               case SMS_TYPE_USER_ACK :
+                       encode_size = encodeTelesvcUserAckMsg(&(p_msg->data.user_ack), p_pkg_str);
+                       break;
+               case SMS_TYPE_READ_ACK :
+                       encode_size = encodeTelesvcReadAckMsg(&(p_msg->data.read_ack), p_pkg_str);
+                       break;
+               case SMS_TYPE_DELIVER_REPORT :
+                       encode_size = encodeTelesvcDeliverReportMsg(&(p_msg->data.report), p_pkg_str);
+                       break;
+               default :
+                       MSG_DEBUG("No matching type for [%d]", p_msg->type);
+                       break;
+       }
+
+       MSG_END();
+       return encode_size;
+}
+
+//int SmsPluginMsgCodec::encodeTelesvcDeliverMsg(const sms_telesvc_deliver_s *p_msg, char *p_pkg_str)
+//{
+//
+//}
+
+int SmsPluginMsgCodec::encodeTelesvcReadAckMsg(const sms_telesvc_read_ack_s *p_msg, unsigned char *p_pkg_str)
+{
+       MSG_BEGIN();
+
+       int offset = 0;
+
+
+       MSG_END();
+
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::encodeTelesvcUserAckMsg(const sms_telesvc_user_ack_s *p_msg, unsigned char *p_pkg_str)
+{
+       MSG_BEGIN();
+
+       int offset = 0;
+
+       MSG_END();
+
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::encodeTelesvcDeliverReportMsg(const sms_telesvc_report_s *p_msg, unsigned char *p_pkg_str)
+{
+       MSG_BEGIN();
+
+       int offset = 0, len_index = 0, encode_size = 0;
+       bool delReservedBit = false;
+
+       // 1. Message Identifier (Mandatory)
+       p_pkg_str[offset++] = SMS_BEARER_MESSAGE_IDENTIFIER;
+       p_pkg_str[offset++] = 3;
+       _copy_short_to_char(p_pkg_str+offset+1, &(p_msg->msg_id.msg_id));
+       _shiftNBit(&p_pkg_str[offset], 3, 4);
+       p_pkg_str[offset] |= SMS_TYPE_SUBMIT << 4;
+       offset+=2;
+       p_pkg_str[offset++] |= (p_msg->msg_id.header_ind ? 0x08 : 0x00);
+
+
+       // 2. TP-Failure Cause (Conditional)
+       if(p_msg->tp_fail_cause >= 0x8000) {
+               p_pkg_str[offset++] = SMS_BEARER_TP_FAILURE_CAUSE;
+               p_pkg_str[offset++] = 1;
+               p_pkg_str[offset++] = p_msg->tp_fail_cause;
+       }
+
+       // 3. User Data (Optional)
+       if(p_msg->user_data.data_len > 0) {
+               p_pkg_str[offset++] = SMS_BEARER_USER_DATA;
+               len_index = offset;
+               offset++;
+               if(p_msg->user_data.encode_type == 0x01 || p_msg->user_data.encode_type == 0x0a)
+                       p_pkg_str[offset++] = p_msg->user_data.msg_type;
+
+               p_pkg_str[offset++] = p_msg->user_data.encode_type << 3;
+               p_pkg_str[offset++] = p_msg->user_data.data_len;
+
+               if (p_msg->user_data.encode_type == SMS_ENCODE_7BIT_ASCII || p_msg->user_data.encode_type == SMS_ENCODE_GSM7BIT) {
+                       encode_size = encodeUserData(p_msg->user_data.user_data, &p_pkg_str[offset], p_msg->user_data.data_len);
+                       offset += encode_size;
+                       if(p_msg->user_data.data_len % 8 > 4)
+                               delReservedBit = true;
+               } else {
+                       memcpy(p_pkg_str+offset, p_msg->user_data.user_data, p_msg->user_data.data_len);
+                       offset += p_msg->user_data.data_len;
+               }
+               _shiftNBit(&p_pkg_str[len_index+1], offset-len_index-1, 3);
+
+               if (delReservedBit == true)
+                       offset--;
+
+               p_pkg_str[len_index] = offset - len_index - 1;
+
+       }
+
+       // 4. Language Indicator (Optional)
+       // TODO : give condition
+//     p_pkg_str[offset++] = SMS_BEARER_ALERT_ON_MSG_DELIVERY;
+//     p_pkg_str[offset++] = 1;
+//     p_pkg_str[offset++] = p_msg->language;
+
+
+       // 5. Multiple Encoding User Data (Optional)
+       // Omitted
+
+       MSG_END();
+
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::encodeTelesvcCancelMsg(const sms_telesvc_cancel_s *p_msg, unsigned char *p_pkg_str)
+{
+       MSG_BEGIN();
+
+       int offset = 0;
+
+       // 1. Message Identifier
+       p_pkg_str[offset++] = SMS_BEARER_MESSAGE_IDENTIFIER;
+       p_pkg_str[offset++] = 3;
+       _copy_short_to_char(p_pkg_str+offset+1, &(p_msg->msg_id.msg_id));
+       _shiftNBit(&p_pkg_str[offset], 3, 4);
+       p_pkg_str[offset] |= SMS_TYPE_SUBMIT << 4;
+       offset+=2;
+       p_pkg_str[offset++] |= (p_msg->msg_id.header_ind ? 0x08 : 0x00);
+
+       MSG_END();
+
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::encodeTelesvcSubmitMsg(const sms_telesvc_submit_s *p_msg, unsigned char *p_pkg_str)
+{
+       MSG_BEGIN();
+
+       int offset = 0, len_index = 0;
+       int encode_size = 0;
+       bool delReservedBit = false;
+
+       // 1. Message Identifier
+       p_pkg_str[offset++] = SMS_BEARER_MESSAGE_IDENTIFIER;
+       p_pkg_str[offset++] = 3;
+       _copy_short_to_char(p_pkg_str+offset+1, &(p_msg->msg_id.msg_id));
+       _shiftNBit(&p_pkg_str[offset], 3, 4);
+       p_pkg_str[offset] |= SMS_TYPE_SUBMIT << 4;
+       offset+=2;
+       p_pkg_str[offset++] |= (p_msg->msg_id.header_ind ? 0x08 : 0x00);
+
+       // 2. User Data
+       if(p_msg->user_data.data_len > 0) {
+               p_pkg_str[offset++] = SMS_BEARER_USER_DATA;
+               len_index = offset;
+               offset++;
+               if(p_msg->user_data.encode_type == 0x01 || p_msg->user_data.encode_type == 0x0a)
+                       p_pkg_str[offset++] = p_msg->user_data.msg_type;
+
+               p_pkg_str[offset++] = p_msg->user_data.encode_type << 3;
+               p_pkg_str[offset++] = p_msg->user_data.data_len;
+
+               if (p_msg->user_data.encode_type == SMS_ENCODE_7BIT_ASCII) {
+                       encode_size = encodeUserData(p_msg->user_data.user_data, &p_pkg_str[offset], p_msg->user_data.data_len);
+                       offset += encode_size;
+                       if(p_msg->user_data.data_len % 8 > 4)
+                               delReservedBit = true;
+               } else if (p_msg->user_data.encode_type == SMS_ENCODE_GSM7BIT) {
+                       encode_size = PackGSM7bitData(p_msg->user_data.user_data, &p_pkg_str[offset], p_msg->user_data.data_len);
+                       offset += encode_size;
+                       if(p_msg->user_data.data_len % 8 > 4)
+                               delReservedBit = true;
+               } else if (p_msg->user_data.encode_type == SMS_ENCODE_UNICODE) {
+                       MsgTextConvert *textCvt = MsgTextConvert::instance();
+                       encode_size = textCvt->convertUTF8ToUCS2(&p_pkg_str[offset], SMS_MAX_USER_DATA_LEN, p_msg->user_data.user_data, p_msg->user_data.data_len);
+                       p_pkg_str[offset-1] = encode_size / 2;
+                       offset += encode_size;
+               } else {
+                       memcpy(p_pkg_str+offset, p_msg->user_data.user_data, p_msg->user_data.data_len);
+                       offset += p_msg->user_data.data_len;
+               }
+               _shiftNBit(&p_pkg_str[len_index+1], offset-len_index-1, 3);
+
+               if (delReservedBit == true)
+                       offset--;
+
+               p_pkg_str[len_index] = offset - len_index - 1;
+
+       }
+/* Sprint and Verizon issue
+       // 3. Validity Period
+       if (p_msg->val_period.format == SMS_TIME_RELATIVE) {
+               p_pkg_str[offset++] = SMS_BEARER_VALIDITY_PERIOD_RELATIVE;
+               p_pkg_str[offset++] = 1;
+               p_pkg_str[offset++] = p_msg->val_period.time.rel_time.rel_time;
+
+       } else if (p_msg->val_period.format == SMS_TIME_ABSOLUTE){
+               p_pkg_str[offset++] = SMS_BEARER_VALIDITY_PERIOD_ABSOLUTE;
+               p_pkg_str[offset++] = 6;
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->val_period.time.abs_time.year);
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->val_period.time.abs_time.month);
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->val_period.time.abs_time.day);
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->val_period.time.abs_time.hours);
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->val_period.time.abs_time.minutes);
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->val_period.time.abs_time.seconds);
+       }
+*/
+       // 4. Deferred Delivery Time
+       if (p_msg->defer_val_period.format == SMS_TIME_RELATIVE) {
+               p_pkg_str[offset++] = SMS_BEARER_DEFERRED_DELIVERY_TIME_RELATIVE;
+               p_pkg_str[offset++] = 1;
+               p_pkg_str[offset++] = p_msg->defer_val_period.time.rel_time.rel_time;
+
+       } else if (p_msg->defer_val_period.format == SMS_TIME_ABSOLUTE) {
+               p_pkg_str[offset++] = SMS_BEARER_DEFERRED_DELIVERY_TIME_ABSOLUTE;
+               p_pkg_str[offset++] = 6;
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->defer_val_period.time.abs_time.year);
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->defer_val_period.time.abs_time.month);
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->defer_val_period.time.abs_time.day);
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->defer_val_period.time.abs_time.hours);
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->defer_val_period.time.abs_time.minutes);
+               p_pkg_str[offset++] = _convert_to_BCD(p_msg->defer_val_period.time.abs_time.seconds);
+       }
+
+       // 5. Priority Indicator
+       if (p_msg->priority >= SMS_PRIORITY_NORMAL && p_msg->priority <=        SMS_PRIORITY_EMERGENCY) {
+               p_pkg_str[offset++] = SMS_BEARER_PRIORITY_INDICATOR;
+               p_pkg_str[offset++] = 1;
+               p_pkg_str[offset++] = p_msg->priority << 6;
+       }
+
+/* Sprint and Verizon issue
+       // 6. Privacy Indicator
+       if (p_msg->privacy >= SMS_PRIVACY_NOT_RESTRICTED && p_msg->privacy <= SMS_PRIVACY_SECRET) {
+               p_pkg_str[offset++] = SMS_BEARER_PRIVACY_INDICATOR;
+               p_pkg_str[offset++] = 1;
+               p_pkg_str[offset++] = p_msg->privacy << 6;
+       }
+*/
+       // 7. Reply Option
+       if (p_msg->reply_opt.user_ack_req | p_msg->reply_opt.deliver_ack_req | p_msg->reply_opt.read_ack_req | p_msg->reply_opt.report_req) {
+               p_pkg_str[offset++] = SMS_BEARER_REPLY_OPTION;
+               p_pkg_str[offset++] = 1;
+               p_pkg_str[offset] |= p_msg->reply_opt.user_ack_req << 7;
+               p_pkg_str[offset] |= p_msg->reply_opt.deliver_ack_req << 6;
+               p_pkg_str[offset] |= p_msg->reply_opt.read_ack_req << 5;
+               p_pkg_str[offset++] |= p_msg->reply_opt.report_req << 4;
+       }
+
+       // 8. Alert on Message Delivery
+       // TODO : give condition
+//     p_pkg_str[offset++] = SMS_BEARER_ALERT_ON_MSG_DELIVERY;
+//     p_pkg_str[offset++] = 1;
+//     p_pkg_str[offset++] = p_msg->alert_priority << 6;
+
+       // 9. Language Indicator
+       // TODO : give condition
+//     p_pkg_str[offset++] = SMS_BEARER_ALERT_ON_MSG_DELIVERY;
+//     p_pkg_str[offset++] = 1;
+//     p_pkg_str[offset++] = p_msg->language;
+
+       // 10. Call-back Number
+       if (p_msg->callback_number.addr_len > 0) {
+               p_pkg_str[offset++] = SMS_BEARER_CALLBACK_NUMBER;
+
+               int len_index = offset++;
+
+               p_pkg_str[offset] |= p_msg->callback_number.digit_mode << 7;
+
+               if(p_msg->callback_number.digit_mode == false) {
+                       p_pkg_str[offset++] |= (p_msg->callback_number.addr_len & 0xfe) >> 1;
+                       p_pkg_str[offset] |= (p_msg->callback_number.addr_len & 0x01) << 7;
+                       int addr_len = SmsPluginParamCodec::instance()->convertDigitToDTMF(p_msg->callback_number.szData, p_msg->callback_number.addr_len, 1, p_pkg_str+offset);
+                       offset += addr_len;
+               }
+               else if(p_msg->callback_number.digit_mode == true) {
+                       p_pkg_str[offset] |= p_msg->callback_number.number_type << 6;
+                       p_pkg_str[offset++] |= p_msg->callback_number.number_plan;
+                       p_pkg_str[offset++] = p_msg->callback_number.addr_len;
+                       memcpy(p_pkg_str+offset, p_msg->callback_number.szData, p_msg->callback_number.addr_len);
+                       offset += p_msg->callback_number.addr_len;
+               }
+
+               p_pkg_str[len_index] = offset- len_index - 1;
+       }
+
+       // 11. Multiple Encoding User Data
+       // Omitted
+
+       // 12. Message Deposit Index
+       // Omitted
+
+       // 13. Service Category Program Results
+       // Omitted
+
+       MSG_END();
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::decodeMsg(const unsigned char *p_pkg_str, int pkg_len, sms_trans_msg_s *p_msg)
+{
+       MSG_BEGIN();
+
+       int decodelen = 0;
+
+       char mti = p_pkg_str[0] & 0xff;
+
+       switch(mti) {
+               case SMS_TRANS_P2P_MSG:
+                       p_msg->type = SMS_TRANS_P2P_MSG;
+                       decodelen = decodeP2PMsg(p_pkg_str+1, pkg_len-1, &(p_msg->data.p2p_msg));
+                       break;
+               case SMS_TRANS_BROADCAST_MSG:
+                       p_msg->type = SMS_TRANS_BROADCAST_MSG;
+                       decodelen = decodeCBMsg(p_pkg_str+1, pkg_len-1, &(p_msg->data.cb_msg));
+                       break;
+               case SMS_TRANS_ACK_MSG:
+                       p_msg->type = SMS_TRANS_ACK_MSG;
+                       decodelen = decodeAckMsg(p_pkg_str+1, pkg_len-1, &(p_msg->data.ack_msg));
+                       break;
+               default:
+                       p_msg->type = SMS_TRANS_TYPE_RESERVED;
+                       break;
+       }
+
+       MSG_END();
+
+       return decodelen+1;
+}
+
+
+int SmsPluginMsgCodec::decodeP2PMsg(const unsigned char *p_pkg_str, int pkg_len, sms_trans_p2p_msg_s *p_p2p)
+{
+       MSG_BEGIN();
+
+       int offset = 0, tmp_len = 0;
+
+       while (offset < pkg_len) {
+               switch (p_pkg_str[offset]) {
+               case 0x00:                              // Teleservice Identifier
+                       offset += decodeTeleId(p_pkg_str+offset, pkg_len, &(p_p2p->telesvc_id));
+                       break;
+
+               case 0x01:                              // Service Category
+                       offset += decodeSvcCtg(p_pkg_str+offset, pkg_len, &(p_p2p->svc_ctg));
+                       break;
+
+               case 0x02:
+               case 0x04:                              // Address
+                       offset += decodeAddress(p_pkg_str+offset, pkg_len, &(p_p2p->address));
+                       break;
+
+               case 0x03:
+               case 0x05:                              // Subaddress
+                       offset += decodeSubAddress(p_pkg_str+offset, pkg_len, &(p_p2p->sub_address));
+                       break;
+
+               case 0x06:                              // Bearer Reply Option
+                       offset+=2;
+                       p_p2p->reply_seq = (sms_trans_reply_seq_t)(p_pkg_str[offset] >> 2);
+                       offset++;
+                       break;
+
+               case 0x08:                              // Bearer Data
+                       tmp_len = p_pkg_str[++offset];
+                       decodeP2PTelesvcMsg(p_pkg_str+offset+1, tmp_len, &p_p2p->telesvc_msg);
+                       offset+=(tmp_len+1);
+                       break;
+
+               default:
+                       break;
+               }
+       }
+
+       MSG_END();
+
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::decodeCBMsg(const unsigned char *p_pkg_str, int pkg_len, sms_trans_broadcast_msg_s *p_cb)
+{
+       MSG_BEGIN();
+
+       int offset = 0, tmp_len = 0;
+
+       while(offset < pkg_len) {
+               if(p_pkg_str[offset] == 0x01) {                 // Service Category
+                       offset += decodeTeleId(p_pkg_str+offset, pkg_len, &(p_cb->svc_ctg));
+               }
+               else if(p_pkg_str[offset] == 0x08) {                                                    // Bearer Data
+                       tmp_len = p_pkg_str[++offset];
+                       if(p_cb->svc_ctg >= SMS_TRANS_SVC_CTG_CMAS_PRESIDENTIAL && p_cb->svc_ctg <= SMS_TRANS_SVC_CTG_CMAS_TEST) {
+                               decodeCBBearerData(p_pkg_str+offset+1, tmp_len, &(p_cb->telesvc_msg), true);
+                       }
+                       else {
+                               decodeCBBearerData(p_pkg_str+offset+1, tmp_len, &(p_cb->telesvc_msg), false);
+                       }
+
+                       offset+=(tmp_len+1);
+               }
+       }
+
+       MSG_END();
+
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::decodeAckMsg(const unsigned char *p_pkg_str, int pkg_len, sms_trans_ack_msg_s *p_ack)
+{
+       MSG_BEGIN();
+
+       int offset = 0;
+
+       while (offset < pkg_len) {
+               if(p_pkg_str[offset] == 0x04) {                                 // Destination Address
+                       offset += decodeAddress(p_pkg_str+offset, pkg_len, &(p_ack->address));
+               }
+               else if(p_pkg_str[offset] == 0x05) {                                    // Destination Subaddress
+                       offset += decodeSubAddress(p_pkg_str+offset, pkg_len, &(p_ack->sub_address));
+               }
+               else if(p_pkg_str[offset] == 0x07) {                                    // Cause Codes
+                       offset+=2;
+                       p_ack->cause_code.reply_seq = (sms_trans_reply_seq_t)p_pkg_str[offset] >> 2;
+                       switch(p_pkg_str[offset++] & 0x03) {
+                       case 0x00:
+                               p_ack->cause_code.error_class = SMS_TRANS_ERR_CLASS_NONE;
+                               break;
+                       case 0x01:
+                               break;
+                       case 0x10:
+                               p_ack->cause_code.error_class = SMS_TRANS_ERR_CLASS_TEMPORARY;
+                               break;
+                       case 0x11:
+                               p_ack->cause_code.error_class = SMS_TRANS_ERR_CLASS_PERMANENT;
+                               break;
+                       }
+
+                       if(p_ack->cause_code.error_class != SMS_TRANS_ERR_CLASS_NONE) {
+                               p_ack->cause_code.cause_code = (sms_trans_cause_code_t)p_pkg_str[offset++];
+                       }
+               }
+       }
+
+       MSG_END();
+
+       return offset;
+}
+
+
+void SmsPluginMsgCodec::decodeP2PTelesvcMsg(const unsigned char *p_pkg_str, int pkg_len, sms_telesvc_msg_s *p_telesvc)
+{
+       MSG_BEGIN();
+
+       p_telesvc->type = findMsgType(p_pkg_str, pkg_len);
+
+       MSG_DEBUG("Msg Type = [%d]", p_telesvc->type);
+
+       switch (p_telesvc->type) {
+       case SMS_TYPE_DELIVER:
+               decodeP2PDeliverMsg(p_pkg_str, pkg_len, &p_telesvc->data.deliver);
+               break;
+       case SMS_TYPE_SUBMIT:
+               decodeP2PSubmitMsg(p_pkg_str, pkg_len, &p_telesvc->data.submit);
+               break;
+       case SMS_TYPE_DELIVERY_ACK:
+               decodeP2PDeliveryAckMsg(p_pkg_str, pkg_len, &p_telesvc->data.delivery_ack);
+               break;
+       case SMS_TYPE_USER_ACK:
+               decodeP2PUserAckMsg(p_pkg_str, pkg_len, &p_telesvc->data.user_ack);
+               break;
+       case SMS_TYPE_READ_ACK:
+               decodeP2PReadAckMsg(p_pkg_str, pkg_len, &p_telesvc->data.read_ack);
+               break;
+       case SMS_TYPE_SUBMIT_REPORT:
+//             decodeP2PSubmitReportMsg(p_pkg_str, pkg_len, &p_telesvc->data.report);
+               break;
+       default:
+               break;
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginMsgCodec::decodeP2PDeliverMsg(const unsigned char *p_pkg_str, int pkg_len, sms_telesvc_deliver_s *p_del)
+{
+       MSG_BEGIN();
+
+       int offset = 0, tmp_len, tmp_off;
+       unsigned short tmp_param_s;
+       unsigned char tmp_str[pkg_len+1];
+
+       while (offset < pkg_len) {
+               MSG_DEBUG("current offset = [%d] [%x]", offset, p_pkg_str[offset]);
+
+               switch (p_pkg_str[offset])
+               {
+                       case 0x00:                              // Message Identifier
+                               offset += decodeMsgId(p_pkg_str+offset, 5, &(p_del->msg_id));
+                               break;
+
+                       case 0x01:                              // User Data
+                               offset += 2;
+                               tmp_len = p_pkg_str[offset-1];
+                               memset(tmp_str, 0x00, sizeof(tmp_str));
+                               memcpy(tmp_str, p_pkg_str+offset, tmp_len);
+                               decodeUserData(tmp_str, tmp_len, &(p_del->user_data));
+                               offset += tmp_len;
+                               break;
+
+                       case 0x03:                              // Message Center Time Stamp
+                               offset+=2;
+                               offset += decodeAbsTime(p_pkg_str+offset, &(p_del->time_stamp));
+                               break;
+
+                       case 0x04:                              // Validity Period - Absolute
+                               offset+=2;
+                               p_del->val_period.format = SMS_TIME_ABSOLUTE;
+                               offset += decodeAbsTime(p_pkg_str+offset, &(p_del->val_period.time.abs_time));
+                               break;
+
+                       case 0x05:                              // Validity Period - Relative
+                               offset+=2;
+                               p_del->val_period.format = SMS_TIME_RELATIVE;
+                               p_del->val_period.time.rel_time.rel_time = (sms_relative_time_t)p_pkg_str[offset++];
+                               break;
+
+                       case 0x08:                              // Priority Indicator
+                               offset+=2;
+                               p_del->priority = (sms_priority_indicator_t)((p_pkg_str[offset++] & 0xc0) >> 6);
+                               break;
+
+                       case 0x09:                              // Privacy Indicator
+                               offset+=2;
+                               p_del->privacy = (sms_privacy_indicator_t)((p_pkg_str[offset++] & 0xc0) >> 6);
+                               break;
+
+                       case 0x0a:                              // Reply Option
+                               offset+=2;
+
+                               if(p_pkg_str[offset] & 0x80)
+                                       p_del->reply_opt.user_ack_req = true;
+                               else
+                                       p_del->reply_opt.user_ack_req = false;
+
+                               if(p_pkg_str[offset] & 0x40)
+                                       p_del->reply_opt.deliver_ack_req = true;
+                               else
+                                       p_del->reply_opt.deliver_ack_req = false;
+
+                               if(p_pkg_str[offset] & 0x20)
+                                       p_del->reply_opt.read_ack_req = true;
+                               else
+                                       p_del->reply_opt.read_ack_req = false;
+
+                               if(p_pkg_str[offset] & 0x10)
+                                       p_del->reply_opt.report_req = true;
+                               else
+                                       p_del->reply_opt.report_req = false;
+
+                               offset++;
+                               break;
+
+                       case 0x0b:                              // Number of Message
+                               offset+=2;
+                               p_del->num_msg = (((p_pkg_str[offset] & 0xf0) >> 4) * 10) + (p_pkg_str[offset] & 0x0f);
+                               offset++;
+                               break;
+
+                       case 0x0c:                              // Alert on Message Delivery
+                               offset+=2;
+                               tmp_len = p_pkg_str[offset-1];
+                               if (tmp_len > 0)
+                                       p_del->alert_priority = (sms_alert_priority_t)((p_pkg_str[offset] & 0xc0) >> 6);
+                               offset+=tmp_len;
+                               break;
+
+                       case 0x0d:                              // Language Indicator
+                               offset+=2;
+                               p_del->language = (sms_language_type_t)p_pkg_str[offset++];
+                               break;
+
+                       case 0x0e:                              // Call-Back Number
+                               offset+=2;
+                               tmp_len = p_pkg_str[offset-1];
+
+                               decodeCallBackNum(&p_pkg_str[offset], tmp_len, &(p_del->callback_number));
+
+                               offset+=tmp_len;
+                               break;
+
+                       case 0x0f:                              // Message Display Mode
+                               offset+=2;
+
+                               p_del->display_mode = (sms_display_mode_t)((p_pkg_str[offset++] & 0xc0) >> 6);
+                               break;
+
+                       case 0x10:                              // Multiple Encoding User Data
+                               offset+=2;
+                               tmp_len = p_pkg_str[offset-1];
+
+
+                               // TODO
+
+
+
+                               offset+=tmp_len;
+                               break;
+
+                       case 0x11:                              // Message Deposit Index
+                               offset+=2;
+
+                               memset(&tmp_param_s, 0x00, sizeof(unsigned short));
+                               _copy_char_to_short(&tmp_param_s, p_pkg_str+offset);
+                               p_del->deposit_id = tmp_param_s;
+
+                               offset+=2;
+                               break;
+
+                       case 0x16:                              // Enhanced VMN
+                               offset++;
+                               tmp_len = p_pkg_str[offset++];
+                               memset(tmp_str, 0x00, sizeof(tmp_str));
+                               memcpy(tmp_str, p_pkg_str+offset, tmp_len);
+                               tmp_off = 0;
+
+                               p_del->enhanced_vmn.priority = (sms_priority_indicator_t)(p_pkg_str[offset] >> 6);
+                               p_del->enhanced_vmn.password_req = p_pkg_str[offset] & 0x20 ? true : false;
+                               p_del->enhanced_vmn.setup_req = p_pkg_str[offset] & 0x10 ? true : false;
+                               p_del->enhanced_vmn.pw_change_req = p_pkg_str[offset] & 0x08 ? true : false;
+                               _shiftNBit_for_decode(tmp_str, tmp_len, 5);
+
+                               if(p_del->enhanced_vmn.setup_req || p_del->enhanced_vmn.pw_change_req) {
+                                       p_del->enhanced_vmn.min_pw_len = tmp_str[tmp_off] >> 4;
+                                       p_del->enhanced_vmn.max_pw_len = tmp_str[tmp_off++] & 0x0f;
+                               }
+
+                               p_del->enhanced_vmn.vm_num_unheard_msg = tmp_str[tmp_off++];
+                               p_del->enhanced_vmn.vm_mailbox_alm_full = tmp_str[tmp_off] & 0x80 ? true : false;
+                               p_del->enhanced_vmn.vm_mailbox_full = tmp_str[tmp_off] & 0x40 ? true : false;
+                               p_del->enhanced_vmn.reply_allowed = tmp_str[tmp_off] & 0x20 ? true : false;
+                               p_del->enhanced_vmn.fax_included = tmp_str[tmp_off] & 0x10 ? true : false;
+                               p_del->enhanced_vmn.vm_len = ((tmp_str[tmp_off] >> 0x0f) << 8) | tmp_str[tmp_off+1];
+                               tmp_off+=2;
+                               p_del->enhanced_vmn.vm_ret_day = tmp_str[tmp_off] >> 1;
+                               _shiftNBit_for_decode(tmp_str, tmp_len, 7);
+                               p_del->enhanced_vmn.vm_msg_id = (tmp_str[tmp_off] << 8) | tmp_str[tmp_off+1];
+                               tmp_off+=2;
+                               p_del->enhanced_vmn.vm_mailbox_id = (tmp_str[tmp_off] << 8) | tmp_str[tmp_off+1];
+                               tmp_off+=2;
+
+                               p_del->enhanced_vmn.an_digit_mode = (sms_digit_mode_t)(tmp_str[tmp_off] & 0x80 ? true : false);
+                               p_del->enhanced_vmn.an_number_type = (sms_number_type_t)((tmp_str[tmp_off] & 0x70) >> 4);
+                               if (p_del->enhanced_vmn.an_digit_mode) {
+                                       p_del->enhanced_vmn.an_number_plan = (sms_number_plan_t)(tmp_str[tmp_off++] & 0x0f);
+                                       p_del->enhanced_vmn.an_num_field = tmp_str[tmp_off++];
+                                       for(int i=0; i<p_del->enhanced_vmn.an_num_field; i++) {
+                                               switch(tmp_str[tmp_off] & 0xf0)
+                                               {
+                                                       case 0x10:
+                                                       case 0x20:
+                                                       case 0x30:
+                                                       case 0x40:
+                                                       case 0x50:
+                                                       case 0x60:
+                                                       case 0x70:
+                                                       case 0x80:
+                                                       case 0x90:
+                                                               p_del->enhanced_vmn.an_char[i] = ((tmp_str[tmp_off] & 0xf0) >> 4) + '0';
+                                                               break;
+                                                       case 0xa0:
+                                                               p_del->enhanced_vmn.an_char[i] = '0';
+                                                               break;
+                                                       case 0xb0:
+                                                               p_del->enhanced_vmn.an_char[i] = '*';
+                                                               break;
+                                                       case 0xc0:
+                                                               p_del->enhanced_vmn.an_char[i] = '#';
+                                                               break;
+                                                       default:
+                                                               break;
+                                               }
+
+                                               _shiftNBit_for_decode(tmp_str, tmp_len, 4);
+                                       }
+                               }
+                               else {
+                                       _shiftNBit_for_decode(tmp_str, tmp_len, 4);
+                                       p_del->enhanced_vmn.an_num_field = tmp_str[tmp_off++];
+                                       memset(p_del->enhanced_vmn.an_char, 0x00, sizeof(p_del->enhanced_vmn.an_char));
+                                       memcpy(p_del->enhanced_vmn.an_char, tmp_str+tmp_off, p_del->enhanced_vmn.an_num_field);
+                                       tmp_off+=p_del->enhanced_vmn.an_num_field;
+                               }
+
+                               p_del->enhanced_vmn.cli_digit_mode = (sms_digit_mode_t)(tmp_str[offset] & 0x80 ? true : false);
+                               p_del->enhanced_vmn.cli_number_type = (sms_number_type_t)(tmp_str[offset] & 0x70 >> 4);
+                               if (p_del->enhanced_vmn.cli_digit_mode) {
+                                       p_del->enhanced_vmn.cli_number_plan = (sms_number_plan_t)(tmp_str[tmp_off++] & 0x0f);
+                                       p_del->enhanced_vmn.cli_num_field = tmp_str[tmp_off++];
+                                       for(int i=0; i<p_del->enhanced_vmn.cli_num_field; i++) {
+                                               switch(tmp_str[tmp_off] & 0xf0)
+                                               {
+                                                       case 0x10:
+                                                       case 0x20:
+                                                       case 0x30:
+                                                       case 0x40:
+                                                       case 0x50:
+                                                       case 0x60:
+                                                       case 0x70:
+                                                       case 0x80:
+                                                       case 0x90:
+                                                               p_del->enhanced_vmn.cli_char[i] = ((tmp_str[tmp_off] & 0xf0) >> 4) + '0';
+                                                               break;
+                                                       case 0xa0:
+                                                               p_del->enhanced_vmn.cli_char[i] = '0';
+                                                               break;
+                                                       case 0xb0:
+                                                               p_del->enhanced_vmn.cli_char[i] = '*';
+                                                               break;
+                                                       case 0xc0:
+                                                               p_del->enhanced_vmn.cli_char[i] = '#';
+                                                               break;
+                                                       default:
+                                                               break;
+                                               }
+
+                                               _shiftNBit_for_decode(tmp_str, tmp_len, 4);
+                                       }
+                               }
+                               else {
+                                       _shiftNBit_for_decode(tmp_str, tmp_len, 4);
+                                       p_del->enhanced_vmn.cli_num_field = tmp_str[tmp_off++];
+                                       memset(p_del->enhanced_vmn.cli_char, 0x00, sizeof(p_del->enhanced_vmn.cli_char));
+                                       memcpy(p_del->enhanced_vmn.cli_char, tmp_str+tmp_off, p_del->enhanced_vmn.cli_num_field);
+                                       tmp_off+=p_del->enhanced_vmn.cli_num_field;
+                               }
+
+                               offset+=tmp_len;
+                               break;
+
+                       case 0x17:                              // Enhanced VMN Ack
+                               offset++;
+                               tmp_len = p_pkg_str[offset++];
+                               memset(tmp_str, 0x00, sizeof(tmp_str));
+                               memcpy(tmp_str, p_pkg_str+offset, tmp_len);
+                               p_del->enhanced_vmn_ack.vm_mailbox_id = tmp_str[offset] << 8 | tmp_str[offset+1];
+                               offset+=2;
+                               p_del->enhanced_vmn_ack.vm_num_unheard_msg = tmp_str[offset++];
+                               p_del->enhanced_vmn_ack.num_delete_ack = tmp_str[offset] >> 5;
+                               p_del->enhanced_vmn_ack.num_play_ack = (tmp_str[offset] & 0x1c) >> 2;
+                               _shiftNBit_for_decode(tmp_str, tmp_len, 6);
+                               for(int i=0; i<p_del->enhanced_vmn_ack.num_delete_ack; i++) {
+                                       p_del->enhanced_vmn_ack.da_vm_msg_id[i] = tmp_str[offset] << 8 | tmp_str[offset+1];
+                                       offset+=2;
+                               }
+                               for(int i=0; i<p_del->enhanced_vmn_ack.num_play_ack; i++) {
+                                       p_del->enhanced_vmn_ack.pa_vm_msg_id[i] = tmp_str[offset] << 8 | tmp_str[offset+1];
+                                       offset+=2;
+                               }
+                               break;
+
+                       default:
+                               /* skip unrecognized sub parameters */
+                               offset++;
+                               tmp_len = p_pkg_str[offset++];
+                               offset += tmp_len;
+                               break;
+               }
+
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginMsgCodec::decodeP2PSubmitMsg(const unsigned char *p_pkg_str, int pkg_len, sms_telesvc_submit_s *p_sub)
+{
+       int offset = 0, tmp_len;
+       unsigned short tmp_param_s;
+       unsigned char tmp_str[pkg_len+1];
+
+       while (offset < pkg_len) {
+               if(p_pkg_str[offset] == 0x00) {                                 // Message Identifier
+                       offset += decodeMsgId(p_pkg_str+offset, 5, &(p_sub->msg_id));
+               }
+
+               else if(p_pkg_str[offset] == 0x01) {                                    // User Data
+                       offset += 2;
+                       tmp_len = p_pkg_str[offset-1];
+                       memset(tmp_str, 0x00, sizeof(tmp_str));
+                       memcpy(tmp_str, p_pkg_str+offset, tmp_len);
+
+                       decodeUserData(tmp_str, tmp_len, &(p_sub->user_data));
+
+                       offset += tmp_len;
+               }
+
+               else if(p_pkg_str[offset] == 0x04) {                            // Validity Period - Absolute
+                       offset+=2;
+                       p_sub->val_period.format = SMS_TIME_ABSOLUTE;
+                       offset += decodeAbsTime(p_pkg_str+offset, &(p_sub->val_period.time.abs_time));
+               }
+
+               else if(p_pkg_str[offset] == 0x05) {                            // Validity Period - Relative
+                       offset+=2;
+                       p_sub->val_period.format = SMS_TIME_RELATIVE;
+                       p_sub->val_period.time.rel_time.rel_time = (sms_relative_time_t)p_pkg_str[offset++];
+               }
+
+               else if(p_pkg_str[offset] == 0x06) {                            // Deferred Delivery Time - Absolute
+                       offset+=2;
+                       p_sub->defer_val_period.format = SMS_TIME_ABSOLUTE;
+                       offset += decodeAbsTime(p_pkg_str+offset, &(p_sub->defer_val_period.time.abs_time));
+               }
+
+               else if(p_pkg_str[offset] == 0x07) {                            // Deferred Delivery Time - Relative
+                       offset+=2;
+                       p_sub->defer_val_period.format = SMS_TIME_RELATIVE;
+                       p_sub->defer_val_period.time.rel_time.rel_time = (sms_relative_time_t)p_pkg_str[offset++];
+               }
+
+               else if(p_pkg_str[offset] == 0x08) {                            // Priority indicator
+                       offset+=2;
+                       p_sub->priority = (sms_priority_indicator_t)((p_pkg_str[offset++] & 0xc0) >> 6);
+               }
+
+               else if(p_pkg_str[offset] == 0x09) {                            // Privacy indicator
+                       offset+=2;
+                       p_sub->privacy = (sms_privacy_indicator_t)((p_pkg_str[offset++] & 0xc0) >> 6);
+               }
+
+               else if(p_pkg_str[offset] == 0x0a) {                            // Reply Option
+                       offset+=2;
+
+                       if(p_pkg_str[offset] & 0x80)
+                               p_sub->reply_opt.user_ack_req = true;
+                       else
+                               p_sub->reply_opt.user_ack_req = false;
+
+                       if(p_pkg_str[offset] & 0x40)
+                               p_sub->reply_opt.deliver_ack_req = true;
+                       else
+                               p_sub->reply_opt.deliver_ack_req = false;
+
+                       if(p_pkg_str[offset] & 0x20)
+                               p_sub->reply_opt.read_ack_req = true;
+                       else
+                               p_sub->reply_opt.read_ack_req = false;
+
+                       if(p_pkg_str[offset] & 0x10)
+                               p_sub->reply_opt.report_req = true;
+                       else
+                               p_sub->reply_opt.report_req = false;
+
+                       offset++;
+               }
+
+               else if(p_pkg_str[offset] == 0x0c) {                            // Alert on Message Delivery
+                       offset+=2;
+
+                       p_sub->alert_priority = (sms_alert_priority_t)((p_pkg_str[offset++] & 0xc0) >> 6);
+               }
+
+               else if(p_pkg_str[offset] == 0x0d) {                            // Language Indicator
+                       offset+=2;
+
+                       p_sub->language = (sms_language_type_t)p_pkg_str[offset++];
+               }
+
+               else if(p_pkg_str[offset] == 0x0e) {                            // Call-Back Number
+                       offset+=2;
+                       tmp_len = p_pkg_str[offset-1];
+
+                       decodeCallBackNum(&p_pkg_str[offset], tmp_len, &(p_sub->callback_number));
+
+                       offset+=tmp_len;
+               }
+
+               else if(p_pkg_str[offset] == 0x10) {                            // Multiple Encoding User Data
+                       offset+=2;
+                       tmp_len = p_pkg_str[offset-1];
+
+
+                       // TODO
+
+
+
+                       offset+=tmp_len;
+               }
+
+               else if(p_pkg_str[offset] == 0x11) {                            // Message Deposit Index
+                       offset+=2;
+
+                       memset(&tmp_param_s, 0x00, sizeof(unsigned short));
+                       _copy_char_to_short(&tmp_param_s, p_pkg_str+offset);
+                       p_sub->deposit_id = tmp_param_s;
+
+                       offset+=2;
+               }
+       }
+
+}
+
+
+void SmsPluginMsgCodec::decodeP2PUserAckMsg(const unsigned char *p_pkg_str, int pkg_len, sms_telesvc_user_ack_s *p_user_ack)
+{
+       MSG_BEGIN();
+
+       int offset = 0, tmp_len;
+       unsigned short tmp_param_s;
+       unsigned char tmp_str[pkg_len+1];
+
+       while (offset < pkg_len) {
+               if(p_pkg_str[offset] == 0x00) {                                 // Message Identifier
+                       offset += decodeMsgId(p_pkg_str+offset, 5, &(p_user_ack->msg_id));
+               }
+
+               else if(p_pkg_str[offset] == 0x01) {                                    // User Data
+                       offset += 2;
+                       tmp_len = p_pkg_str[offset-1];
+                       memset(tmp_str, 0x00, sizeof(tmp_str));
+                       memcpy(tmp_str, p_pkg_str+offset, tmp_len);
+
+                       decodeUserData(tmp_str, tmp_len, &(p_user_ack->user_data));
+
+                       offset += tmp_len;
+               }
+
+               else if(p_pkg_str[offset] == 0x02) {                            // User Response Code
+                       offset += 2;
+                       p_user_ack->resp_code = p_pkg_str[offset++];
+               }
+
+               else if(p_pkg_str[offset] == 0x03) {                            // Message Center Time Stamp
+                       offset+=2;
+                       offset += decodeAbsTime(p_pkg_str+offset, &(p_user_ack->time_stamp));
+               }
+
+               else if(p_pkg_str[offset] == 0x10) {                            // Multiple Encoding User Data
+                       offset+=2;
+                       tmp_len = p_pkg_str[offset-1];
+
+
+                       // TODO
+
+
+
+                       offset+=tmp_len;
+               }
+
+               else if(p_pkg_str[offset] == 0x11) {                            // Message Deposit Index
+                       offset+=2;
+
+                       memset(&tmp_param_s, 0x00, sizeof(unsigned short));
+                       _copy_char_to_short(&tmp_param_s, p_pkg_str+offset);
+                       p_user_ack->deposit_id = tmp_param_s;
+
+                       offset+=2;
+               }
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginMsgCodec::decodeP2PReadAckMsg(const unsigned char *p_pkg_str, int pkg_len, sms_telesvc_read_ack_s *p_read_ack)
+{
+       MSG_BEGIN();
+
+       int offset = 0, tmp_len;
+       unsigned short tmp_param_s;
+       unsigned char tmp_str[pkg_len+1];
+
+       while (offset < pkg_len) {
+               if(p_pkg_str[offset] == 0x00) {                                 // Message Identifier
+                       offset += decodeMsgId(p_pkg_str+offset, 5, &(p_read_ack->msg_id));
+               }
+
+               else if(p_pkg_str[offset] == 0x01) {                                    // User Data
+                       offset += 2;
+                       tmp_len = p_pkg_str[offset-1];
+                       memset(tmp_str, 0x00, sizeof(tmp_str));
+                       memcpy(tmp_str, p_pkg_str+offset, tmp_len);
+
+                       decodeUserData(tmp_str, tmp_len, &(p_read_ack->user_data));
+
+                       offset += tmp_len;
+               }
+
+               else if(p_pkg_str[offset] == 0x03) {                            // Message Center Time Stamp
+                       offset+=2;
+                       offset += decodeAbsTime(p_pkg_str+offset, &(p_read_ack->time_stamp));
+               }
+
+               else if(p_pkg_str[offset] == 0x10) {                            // Multiple Encoding User Data
+                       offset+=2;
+                       tmp_len = p_pkg_str[offset-1];
+
+
+                       // TODO
+
+
+
+                       offset+=tmp_len;
+               }
+
+               else if(p_pkg_str[offset] == 0x11) {                            // Message Deposit Index
+                       offset+=2;
+
+                       memset(&tmp_param_s, 0x00, sizeof(unsigned short));
+                       _copy_char_to_short(&tmp_param_s, p_pkg_str+offset);
+                       p_read_ack->deposit_id = tmp_param_s;
+
+                       offset+=2;
+               }
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginMsgCodec::decodeP2PSubmitReportMsg(const unsigned char *p_pkg_str, int pkg_len, sms_telesvc_report_s *p_sub_report)
+{
+       MSG_BEGIN();
+
+       int offset = 0, tmp_len;
+       unsigned char tmp_str[pkg_len+1];
+
+       while (offset < pkg_len) {
+               switch (p_pkg_str[offset]) {
+               case 0x00:                                      // Message Identifier
+                       offset += decodeMsgId(p_pkg_str+offset, 5, &(p_sub_report->msg_id));
+                       break;
+
+               case 0x01:                                      // User Data
+                       offset += 2;
+                       tmp_len = p_pkg_str[offset-1];
+                       memset(tmp_str, 0x00, sizeof(tmp_str));
+                       memcpy(tmp_str, p_pkg_str+offset, tmp_len);
+                       decodeUserData(tmp_str, tmp_len, &(p_sub_report->user_data));
+                       offset += tmp_len;
+                       break;
+
+               case 0x0d:                                      // Language Indicator
+                       offset+=2;
+                       p_sub_report->language = (sms_language_type_t)p_pkg_str[offset++];
+                       break;
+
+               case 0x10:                                      // Multiple Encoding User Data
+                       offset+=2;
+                       tmp_len = p_pkg_str[offset-1];
+
+
+                       // TODO
+
+
+
+                       offset+=tmp_len;
+                       break;
+
+               case 0x15:                                      // TP-Failure Cause
+                       offset += 2;
+                       p_sub_report->tp_fail_cause = p_pkg_str[offset++];
+                       break;
+
+               default:
+                       break;
+               }
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginMsgCodec::decodeP2PDeliveryAckMsg(const unsigned char *p_pkg_str, int pkg_len, sms_telesvc_deliver_ack_s *p_del_ack)
+{
+       MSG_BEGIN();
+
+       int offset = 0, tmp_len;
+       unsigned char tmp_str[pkg_len+1];
+
+       while(offset < pkg_len) {
+               switch (p_pkg_str[offset]) {
+               case 0x00:                                      // Message Identifier
+                       offset += decodeMsgId(p_pkg_str+offset, 5, &(p_del_ack->msg_id));
+                       break;
+
+               case 0x01:                                      // User Data
+                       offset += 2;
+                       tmp_len = p_pkg_str[offset-1];
+                       memset(tmp_str, 0x00, sizeof(tmp_str));
+                       memcpy(tmp_str, p_pkg_str+offset, tmp_len);
+
+                       decodeUserData(tmp_str, tmp_len, &(p_del_ack->user_data));
+
+                       offset += tmp_len;
+                       break;
+
+               case 0x03:                                      // Message Center Time Stamp
+                       offset+=2;
+                       offset += decodeAbsTime(p_pkg_str+offset, &(p_del_ack->time_stamp));
+                       break;
+
+               case 0x10:                                      // Multiple Encoding User Data
+                       offset+=2;
+                       tmp_len = p_pkg_str[offset-1];
+
+
+                       // TODO
+
+
+
+                       offset+=tmp_len;
+                       break;
+
+               case 0x14:                                      // Message Status
+                       offset+=2;
+                       p_del_ack->msg_status = (sms_status_code_t)p_pkg_str[offset++];
+                       break;
+
+               default:
+                       break;
+               }
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginMsgCodec::decodeCBBearerData(const unsigned char *p_pkg_str, int pkg_len, sms_telesvc_msg_s *p_telesvc, bool isCMAS)
+{
+       MSG_BEGIN();
+
+       int offset = 0, tmp_len;
+       unsigned char tmp_str[pkg_len+1];
+
+       while (offset < pkg_len) {
+               if(p_pkg_str[offset] == 0x00) {                                 // Message Identifier
+                       p_telesvc->type = SMS_TYPE_DELIVER;
+                       offset += decodeMsgId(p_pkg_str+offset, 5, &(p_telesvc->data.deliver.msg_id));
+               }
+
+               else if(p_pkg_str[offset] == 0x01) {                                    // User Data
+                       offset += 2;
+                       tmp_len = p_pkg_str[offset-1];
+                       memset(tmp_str, 0x00, sizeof(tmp_str));
+                       memcpy(tmp_str, p_pkg_str+offset, tmp_len);
+
+                       if(isCMAS)
+                               decodeCMASData(tmp_str, tmp_len, &(p_telesvc->data.deliver.cmas_data));
+                       else
+                               decodeUserData(tmp_str, tmp_len, &(p_telesvc->data.deliver.user_data));
+
+                       offset += tmp_len;
+               }
+
+               else if(p_pkg_str[offset] == 0x03) {                            // Message Center Time Stamp
+                       offset += 2;
+                       offset += decodeAbsTime(p_pkg_str+offset, &(p_telesvc->data.deliver.time_stamp));
+               }
+
+               else if(p_pkg_str[offset] == 0x04) {                            // Validity Period - Absolute
+                       offset += 2;
+                       p_telesvc->data.deliver.val_period.format = SMS_TIME_ABSOLUTE;
+                       offset += decodeAbsTime(p_pkg_str+offset, &(p_telesvc->data.deliver.val_period.time.abs_time));
+               }
+
+               else if(p_pkg_str[offset] == 0x05) {                            // Validity Period - Relative
+                       offset+=2;
+                       p_telesvc->data.deliver.val_period.format = SMS_TIME_RELATIVE;
+                       p_telesvc->data.deliver.val_period.time.rel_time.rel_time = (sms_relative_time_t)p_pkg_str[offset++];
+               }
+
+               else if(p_pkg_str[offset] == 0x08) {                            // Priority indicator
+                       offset+=2;
+                       p_telesvc->data.deliver.priority = (sms_priority_indicator_t)((p_pkg_str[offset++] & 0xc0) >> 6);
+               }
+
+               else if(p_pkg_str[offset] == 0x0c) {                            // Alert on Message Delivery
+                       offset+=2;
+
+                       p_telesvc->data.deliver.alert_priority = (sms_alert_priority_t)((p_pkg_str[offset++] & 0xc0) >> 6);
+               }
+
+               else if(p_pkg_str[offset] == 0x0d) {                            // Language Indicator
+                       offset+=2;
+
+                       p_telesvc->data.deliver.language = (sms_language_type_t)p_pkg_str[offset++];
+               }
+
+               else if(p_pkg_str[offset] == 0x0e) {                            // Call-Back Number
+                       offset+=2;
+                       tmp_len = p_pkg_str[offset-1];
+
+                       decodeCallBackNum(&p_pkg_str[offset], tmp_len, &(p_telesvc->data.deliver.callback_number));
+
+                       offset+=tmp_len;
+               }
+
+               else if(p_pkg_str[offset] == 0x0f) {                            // Message Display Mode
+                       offset+=2;
+
+                       p_telesvc->data.deliver.display_mode = (sms_display_mode_t)((p_pkg_str[offset++] & 0xc0) >> 6);
+               }
+
+               else if(p_pkg_str[offset] == 0x10) {                            // Multiple Encoding User Data
+                       offset+=2;
+                       tmp_len = p_pkg_str[offset-1];
+
+
+                       // TODO
+
+
+
+                       offset+=tmp_len;
+               }
+       }
+
+       MSG_END();
+}
+
+
+int SmsPluginMsgCodec::decodeTeleId(const unsigned char *p_pkg_str, int pkg_len, sms_trans_telesvc_id_t *tele_id)
+{
+       int offset = 0;
+       unsigned short tmp_param_s;
+
+       offset+=2;
+
+    _copy_char_to_short(&tmp_param_s, &p_pkg_str[offset]);
+
+       switch(tmp_param_s) {
+               case SMS_TRANS_TELESVC_CMT_91:
+                       *tele_id = SMS_TRANS_TELESVC_CMT_91;
+                       break;
+               case SMS_TRANS_TELESVC_CPT_95:
+                       *tele_id = SMS_TRANS_TELESVC_CPT_95;
+                       break;
+               case SMS_TRANS_TELESVC_CMT_95:
+                       *tele_id = SMS_TRANS_TELESVC_CMT_95;
+                       break;
+               case SMS_TRANS_TELESVC_VMN_95:
+                       *tele_id = SMS_TRANS_TELESVC_VMN_95;
+                       break;
+               case SMS_TRANS_TELESVC_WAP:
+                       *tele_id = SMS_TRANS_TELESVC_WAP;
+                       break;
+               case SMS_TRANS_TELESVC_WEMT:
+                       *tele_id = SMS_TRANS_TELESVC_WEMT;
+                       break;
+               case SMS_TRANS_TELESVC_SCPT:
+                       *tele_id = SMS_TRANS_TELESVC_SCPT;
+                       break;
+               case SMS_TRANS_TELESVC_CATPT:
+                       *tele_id = SMS_TRANS_TELESVC_CATPT;
+                       break;
+               default:
+                       *tele_id = SMS_TRANS_TELESVC_RESERVED;
+                       break;
+       }
+
+       return offset+2;
+}
+
+
+int SmsPluginMsgCodec::decodeSvcCtg(const unsigned char *p_pkg_str, int pkg_len, sms_trans_svc_ctg_t *svc_ctg)
+{
+       int offset = 0;
+       unsigned short tmp_param_s;
+
+       offset+=2;
+
+       _copy_char_to_short(&tmp_param_s, &p_pkg_str[offset]);
+       if((tmp_param_s >= SMS_TRANS_SVC_CTG_UNKNOWN && tmp_param_s <= SMS_TRANS_SVC_CTG_KDDI_CORP_MAX1)
+               || (tmp_param_s >= SMS_TRANS_SVC_CTG_KDDI_CORP_MIN2 && tmp_param_s <= SMS_TRANS_SVC_CTG_KDDI_CORP_MAX2)
+               || (tmp_param_s >= SMS_TRANS_SVC_CTG_KDDI_CORP_MIN3 && tmp_param_s <= SMS_TRANS_SVC_CTG_KDDI_CORP_MAX3)) {
+               *svc_ctg = (sms_trans_svc_ctg_t)tmp_param_s;
+       }
+       else {
+               *svc_ctg = SMS_TRANS_SVC_CTG_RESERVED;
+       }
+
+       return offset+2;
+}
+
+
+int SmsPluginMsgCodec::decodeAddress(const unsigned char *p_pkg_str, int pkg_len, sms_trans_addr_s *addr)
+{
+       int offset = 0, tmp_len = 0;
+       unsigned char tmp_str[pkg_len+1];
+
+       tmp_len = p_pkg_str[++offset];
+
+       memset(tmp_str, 0x00, sizeof(tmp_str));
+       memcpy(tmp_str, p_pkg_str+offset+1, tmp_len);
+
+       offset += (tmp_len+1);
+
+       if(tmp_str[0] & 0x80)
+               addr->digit_mode = true;
+       else
+               addr->digit_mode = false;
+
+       if(tmp_str[0] & 0x40)
+               addr->number_mode = true;
+       else
+               addr->number_mode = false;
+
+       _shiftNBit_for_decode(tmp_str, tmp_len, 2);
+
+       if(addr->digit_mode == false) {
+               addr->addr_len = tmp_str[0];
+
+               memset(addr->szData, 0x00, sizeof(addr->szData));
+
+               for(unsigned int i = 0; i < addr->addr_len; i++) {
+                       switch(tmp_str[1] & 0xf0) {
+                               case 0x10:
+                               case 0x20:
+                               case 0x30:
+                               case 0x40:
+                               case 0x50:
+                               case 0x60:
+                               case 0x70:
+                               case 0x80:
+                               case 0x90:
+                                       addr->szData[i] = ((tmp_str[1] & 0xf0) >> 4) + '0';
+                                       break;
+                               case 0x00://sprint issue
+                               case 0xa0:
+                                       addr->szData[i] = '0';
+                                       break;
+                               case 0xb0:
+                                       addr->szData[i] = '*';
+                                       break;
+                               case 0xc0:
+                                       addr->szData[i] = '#';
+                                       break;
+                               default:
+                                       break;
+                       }
+
+                       _shiftNBit_for_decode(tmp_str, tmp_len, 4);
+               }
+       }
+       else if(addr->digit_mode == true) {
+               if(addr->number_mode == false) {                                                // digit mode = 1, number mode = 0
+                       switch(tmp_str[0] & 0xe0) {
+                               case 0x00:
+                                       addr->number_type = SMS_NUMBER_TYPE_UNKNOWN;
+                                       break;
+                               case 0x20:
+                                       addr->number_type = SMS_NUMBER_TYPE_INTERNATIONAL;
+                                       break;
+                               case 0x40:
+                                       addr->number_type = SMS_NUMBER_TYPE_NATIONAL;
+                                       break;
+                               case 0x60:
+                                       addr->number_type = SMS_NUMBER_TYPE_NETWORK_SPECIFIC;
+                                       break;
+                               case 0x80:
+                                       addr->number_type = SMS_NUMBER_TYPE_SUBSCRIBER;
+                                       break;
+                               case 0xa0:
+                                       addr->number_type = SMS_NUMBER_TYPE_RESERVED_5;
+                                       break;
+                               case 0xc0:
+                                       addr->number_type = SMS_NUMBER_TYPE_ABBREVIATED;
+                                       break;
+                               case 0xe0:
+                                       addr->number_type = SMS_NUMBER_TYPE_RESERVED_7;
+                                       break;
+                       }
+
+                       _shiftNBit_for_decode(tmp_str, tmp_len, 3);
+
+                       switch(tmp_str[0] & 0xf0) {
+                               case 0x00:
+                                       addr->number_plan = SMS_NPI_UNKNOWN;
+                                       break;
+                               case 0x10:
+                                       addr->number_plan = SMS_NPI_ISDN;
+                                       break;
+                               case 0x30:
+                                       addr->number_plan = SMS_NPI_DATA;
+                                       break;
+                               case 0x40:
+                                       addr->number_plan = SMS_NPI_TELEX;
+                                       break;
+                               case 0x90:
+                                       addr->number_plan = SMS_NPI_PRIVATE;
+                                       break;
+                               default:
+                                       addr->number_plan = SMS_NPI_RESERVED;
+                                       break;
+                       }
+
+                       _shiftNBit_for_decode(tmp_str, tmp_len, 4);
+               }
+               else if(addr->number_mode == true) {                                            // digit mode = 1, number mode = 1
+                       switch(tmp_str[0] & 0xe0) {
+                               case 0x00:
+                                       addr->number_type = SMS_TRANS_DNET_UNKNOWN;
+                                       break;
+                               case 0x20:
+                                       addr->number_type = SMS_TRANS_DNET_INTERNET_PROTOCOL;
+                                       break;
+                               case 0x40:
+                                       addr->number_type = SMS_TRANS_DNET_INTERNET_MAIL_ADDR;
+                                       break;
+                               default:
+                                       addr->number_type = SMS_TRANS_DNET_RESERVED;
+                                       break;
+                       }
+
+                       _shiftNBit_for_decode(tmp_str, tmp_len, 3);
+               }
+
+               addr->addr_len = tmp_str[0];
+
+               memset(addr->szData, 0x00, sizeof(addr->szData));
+               memcpy(addr->szData, &tmp_str[1], addr->addr_len);
+       }
+
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::decodeSubAddress(const unsigned char *p_pkg_str, int pkg_len, sms_trans_sub_addr_s *sub_addr)
+{
+       int offset = 0, tmp_len = 0;
+       unsigned char tmp_str[pkg_len+1];
+
+       tmp_len = p_pkg_str[++offset];
+       memset(tmp_str, 0x00, sizeof(tmp_str));
+       memcpy(tmp_str, p_pkg_str+offset+1, tmp_len);
+
+       offset += (tmp_len+1);
+
+       switch(tmp_str[0] & 0xe0) {
+               case 0x00:
+                       sub_addr->type = SMS_TRANS_SUB_ADDR_NSAP;
+                       break;
+               case 0x20:
+                       sub_addr->type = SMS_TRANS_SUB_ADDR_USER;
+                       break;
+               default:
+                       sub_addr->type = SMS_TRANS_SUB_ADDR_RESERVED;
+                       break;
+       }
+
+       if(tmp_str[0] & 0x10)
+               sub_addr->odd = true;
+       else
+               sub_addr->odd = false;
+
+       _shiftNBit_for_decode(tmp_str, tmp_len, 4);
+       memset(sub_addr->szData, 0x00, sizeof(sub_addr->szData));
+       memcpy(sub_addr->szData, tmp_str+1, tmp_str[0]);
+
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::decodeMsgId(const unsigned char *p_pkg_str, int pkg_len, sms_trans_msg_id_s *p_msg_id)
+{
+       int offset = 0;
+       unsigned short tmp_param_s;
+       unsigned char tmp_str[pkg_len+1];
+
+       memset(tmp_str, 0x00, sizeof(tmp_str));
+       memcpy(tmp_str, &p_pkg_str[offset+2], 3);
+
+       _shiftNBit_for_decode(tmp_str, 3, 4);
+
+       memset(&tmp_param_s, 0x00, sizeof(unsigned short));
+       _copy_char_to_short(&tmp_param_s, tmp_str);
+
+       p_msg_id->msg_id = tmp_param_s;
+       if(tmp_str[2] & 0x80)
+               p_msg_id->header_ind = true;
+       else
+               p_msg_id->header_ind = false;
+
+       offset+=5;
+
+       return offset;
+}
+
+
+void SmsPluginMsgCodec::decodeCallBackNum(const unsigned char *p_pkg_str, int pkg_len, sms_telesvc_addr_s *p_callback)
+{
+       int offset = 0;
+       unsigned char tmp_str[pkg_len+1];
+
+       if(p_pkg_str[offset] & 0x80) {
+               p_callback->digit_mode = true;
+
+               switch(p_pkg_str[offset] & 0x70) {
+                       case 0x00:
+                               p_callback->number_type = SMS_NUMBER_TYPE_UNKNOWN;
+                               break;
+                       case 0x10:
+                               p_callback->number_type = SMS_NUMBER_TYPE_INTERNATIONAL;
+                               break;
+                       case 0x20:
+                               p_callback->number_type = SMS_NUMBER_TYPE_NATIONAL;
+                               break;
+                       case 0x30:
+                               p_callback->number_type = SMS_NUMBER_TYPE_NETWORK_SPECIFIC;
+                               break;
+                       case 0x40:
+                               p_callback->number_type = SMS_NUMBER_TYPE_SUBSCRIBER;
+                               break;
+                       case 0x50:
+                               p_callback->number_type = SMS_NUMBER_TYPE_RESERVED_5;
+                               break;
+                       case 0x60:
+                               p_callback->number_type = SMS_NUMBER_TYPE_ABBREVIATED;
+                               break;
+                       case 0x70:
+                               p_callback->number_type = SMS_NUMBER_TYPE_RESERVED_7;
+                               break;
+                       default:
+                               break;
+               }
+
+               switch(p_pkg_str[offset++] & 0x0f) {
+               case 0x00:
+                       p_callback->number_plan = SMS_NPI_UNKNOWN;
+                       break;
+               case 0x01:
+                       p_callback->number_plan = SMS_NPI_ISDN;
+                       break;
+               case 0x03:
+                       p_callback->number_plan = SMS_NPI_DATA;
+                       break;
+               case 0x04:
+                       p_callback->number_plan = SMS_NPI_TELEX;
+                       break;
+               case 0x09:
+                       p_callback->number_plan = SMS_NPI_PRIVATE;
+                       break;
+               case 0x0f:
+               default:
+                       p_callback->number_plan = SMS_NPI_RESERVED;
+                       break;
+               }
+
+               p_callback->addr_len = p_pkg_str[offset++];
+               memset(p_callback->szData, 0x00, sizeof(p_callback->szData));
+
+               if (p_callback->number_type == SMS_NUMBER_TYPE_INTERNATIONAL) {
+                       memcpy(&(p_callback->szData[1]), p_pkg_str+offset, p_callback->addr_len);
+                       if(p_callback->szData[1] != '\0') {
+                               p_callback->szData[0] = '+';
+                       }
+               }
+               else {
+                       memcpy(p_callback->szData, p_pkg_str+offset, p_callback->addr_len);
+               }
+       }
+       else {
+               p_callback->digit_mode = false;
+
+               memset(tmp_str, 0x00, sizeof(tmp_str));
+               memcpy(tmp_str, p_pkg_str+offset, pkg_len);
+
+               _shiftNBit_for_decode(tmp_str, pkg_len, 1);
+
+               p_callback->addr_len = tmp_str[0];
+
+               memset(p_callback->szData, 0x00, sizeof(p_callback->szData));
+
+               for(unsigned int i = 0; i < p_callback->addr_len; i++) {
+                       switch(tmp_str[1] & 0xf0) {
+                               case 0x10:
+                               case 0x20:
+                               case 0x30:
+                               case 0x40:
+                               case 0x50:
+                               case 0x60:
+                               case 0x70:
+                               case 0x80:
+                               case 0x90:
+                                       p_callback->szData[i] = ((tmp_str[1] & 0xf0) >> 4) + '0';
+                                       break;
+                               case 0xa0:
+                                       p_callback->szData[i] = '0';
+                                       break;
+                               case 0xb0:
+                                       p_callback->szData[i] = '*';
+                                       break;
+                               case 0xc0:
+                                       p_callback->szData[i] = '#';
+                                       break;
+                               default :
+                                       break;
+                       }
+
+                       _shiftNBit_for_decode(tmp_str, pkg_len, 4);
+               }
+       }
+
+
+}
+
+
+int SmsPluginMsgCodec::decodeAbsTime(const unsigned char *p_pkg_str, sms_time_abs_s *p_time_abs)
+{
+       int offset = 0;
+
+       p_time_abs->year = (((p_pkg_str[offset] & 0xf0) >> 4) * 10) + (p_pkg_str[offset] & 0x0f);
+       offset++;
+       p_time_abs->month = (((p_pkg_str[offset] & 0xf0) >> 4) * 10) + (p_pkg_str[offset] & 0x0f);
+       offset++;
+       p_time_abs->day = (((p_pkg_str[offset] & 0xf0) >> 4) * 10) + (p_pkg_str[offset] & 0x0f);
+       offset++;
+       p_time_abs->hours = (((p_pkg_str[offset] & 0xf0) >> 4) * 10) + (p_pkg_str[offset] & 0x0f);
+       offset++;
+       p_time_abs->minutes = (((p_pkg_str[offset] & 0xf0) >> 4) * 10) + (p_pkg_str[offset] & 0x0f);
+       offset++;
+       p_time_abs->seconds = (((p_pkg_str[offset] & 0xf0) >> 4) * 10) + (p_pkg_str[offset] & 0x0f);
+       offset++;
+
+       return offset;
+}
+
+
+int SmsPluginMsgCodec::encodeUserData(const unsigned char* src, unsigned char *dest, int src_size)
+{
+       int i, j;
+       int shift = 0;
+
+       unsigned char *tmp = (unsigned char *)calloc(1, src_size+1);
+       for (i = 0; i < src_size; i++) {
+               tmp[i] = src[i] << 1;
+       }
+
+       j = 0;
+       for (i = 0; i < src_size; i++) {
+               shift = j % 7;
+               dest[j++] = (tmp[i] << shift) + (tmp[i+1] >> (7-shift));
+               if(shift == 6) {
+                       i++;
+               }
+       }
+
+       if (tmp) {
+               free(tmp);
+               tmp = NULL;
+       }
+
+       return j;
+}
+
+
+void SmsPluginMsgCodec::decodeCMASData(unsigned char *p_pkg_str, int pkg_len, sms_telesvc_cmasdata_s *p_cmas)
+{
+       MSG_BEGIN();
+
+       int offset = 0, tmp_len = 0;
+       unsigned char tmp_str[pkg_len+1];
+
+       if ((p_pkg_str[offset] & 0xf8) != 0x00) {
+               MSG_ERR("Wrong Encode Type = [%d]!! The type must be 0", (p_pkg_str[offset]&0xf8)>>3);
+               return;
+       }
+       else {
+               _shiftNBit_for_decode(p_pkg_str, pkg_len, 5);
+
+               offset++;
+
+               if (p_pkg_str[offset++] != 0x00) {
+                       MSG_ERR("Wrong protocol version = [%d]!! This field must be 0", p_pkg_str[offset-1]);
+                       p_cmas->is_wrong_recode_type  = TRUE;
+                       return;
+               }
+
+               while (offset < pkg_len - 1) {
+                       if (p_pkg_str[offset] == 0x00) {
+                               MSG_DEBUG("Type 0 Decode!");
+                               offset++;
+                               tmp_len = p_pkg_str[offset++];
+                               MSG_DEBUG("Type 0 length = [%d]", tmp_len);
+                               memset(tmp_str, 0x00, sizeof(tmp_str));
+                               memcpy(tmp_str, p_pkg_str+offset, tmp_len);
+
+                               switch(tmp_str[0] & 0xf8) {
+                                       case 0x00:
+                                               p_cmas->encode_type = SMS_ENCODE_OCTET;
+                                               break;
+                                       case 0x08:
+                                               p_cmas->encode_type = SMS_ENCODE_EPM;
+                                               break;
+                                       case 0x10:
+                                               p_cmas->encode_type = SMS_ENCODE_7BIT_ASCII;
+                                               break;
+                                       case 0x18:
+                                               p_cmas->encode_type = SMS_ENCODE_IA5;
+                                               break;
+                                       case 0x20:
+                                               p_cmas->encode_type = SMS_ENCODE_UNICODE;
+                                               break;
+                                       case 0x28:
+                                               p_cmas->encode_type = SMS_ENCODE_SHIFT_JIS;
+                                               break;
+                                       case 0x30:
+                                               p_cmas->encode_type = SMS_ENCODE_KOREAN;
+                                               break;
+                                       case 0x38:
+                                               p_cmas->encode_type = SMS_ENCODE_LATIN_HEBREW;
+                                               break;
+                                       case 0x40:
+                                               p_cmas->encode_type = SMS_ENCODE_LATIN;
+                                               break;
+                                       case 0x48:
+                                               p_cmas->encode_type = SMS_ENCODE_GSM7BIT;
+                                               break;
+                                       case 0x50:
+                                               p_cmas->encode_type = SMS_ENCODE_GSMDCS;
+                                               break;
+                                       case 0x80:              // reserved value, but SKT use this value for KSC5601
+                                               p_cmas->encode_type = SMS_ENCODE_EUCKR;
+                                               break;
+                                       default :
+                                               p_cmas->encode_type = SMS_ENCODE_RESERVED;
+                                               break;
+                               }
+                               _shiftNBit_for_decode(tmp_str, tmp_len, 5);
+
+                               switch(p_cmas->encode_type) {
+                                       case SMS_ENCODE_7BIT_ASCII:
+                                       case SMS_ENCODE_IA5:
+                                       case SMS_ENCODE_GSM7BIT:
+                                               memset(p_cmas->alert_text, 0x00, sizeof(p_cmas->alert_text));
+                                               p_cmas->data_len = (tmp_len*8-5) / 7;
+                                               for(unsigned int i = 0; i < p_cmas->data_len; i++) {
+                                                       p_cmas->alert_text[i] = tmp_str[0] >> 1;
+                                                       _shiftNBit_for_decode(tmp_str, tmp_len, 7);
+                                               }
+                                               break;
+                                       case SMS_ENCODE_EPM:
+                                               break;
+                                       case SMS_ENCODE_GSMDCS:
+                                               break;
+                                       default:
+                                               p_cmas->data_len = tmp_len - 1;
+                                               memset(p_cmas->alert_text, 0x00, sizeof(p_cmas->alert_text));
+                                               memcpy(p_cmas->alert_text, tmp_str+offset, tmp_len-1);
+                                               break;
+                               }
+
+                               offset+=tmp_len;
+                       }
+
+                       else if (p_pkg_str[offset] == 0x01) {
+                               MSG_DEBUG("Type 1 Decode!");
+                               offset+=2;
+                               tmp_len = p_pkg_str[offset-1];
+                               MSG_DEBUG("Type 1 length = [%d]", tmp_len);
+                               p_cmas->category = (sms_cmae_category_t)p_pkg_str[offset++];
+                               p_cmas->response_type = (sms_cmae_response_type_t)p_pkg_str[offset++];
+                               p_cmas->severity = (sms_cmae_severity_t)(p_pkg_str[offset] >> 4);
+                               p_cmas->urgency = (sms_cmae_urgency_t)(p_pkg_str[offset++] & 0x0f);
+                               p_cmas->certainty = (sms_cmae_certainty_t)(p_pkg_str[offset++] >> 4);
+                       }
+
+                       else if (p_pkg_str[offset] == 0x02) {
+                               MSG_DEBUG("Type 2 Decode!");
+                               offset+=2;
+                               tmp_len = p_pkg_str[offset-1];
+                               MSG_DEBUG("Type 2 length = [%d]", tmp_len);
+                               _copy_char_to_short(&(p_cmas->id), p_pkg_str+offset);
+                               offset+=2;
+                               p_cmas->alert_handle = (sms_cmae_alert_handle_t)p_pkg_str[offset++];
+                               offset += decodeAbsTime(p_pkg_str+offset, &(p_cmas->expires));
+                               p_cmas->language = (sms_language_type_t)p_pkg_str[offset++];
+                       }
+
+                       MSG_DEBUG("offset = [%d], pkg_len = [%d]", offset, pkg_len);
+               }
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginMsgCodec::decodeUserData(unsigned char *p_pkg_str, int pkg_len, sms_telesvc_userdata_s *p_user)
+{
+       switch(p_pkg_str[0] & 0xf8) {
+               case 0x00:
+                       p_user->encode_type = SMS_ENCODE_OCTET;
+                       break;
+               case 0x08:
+                       p_user->encode_type = SMS_ENCODE_EPM;
+                       break;
+               case 0x10:
+                       p_user->encode_type = SMS_ENCODE_7BIT_ASCII;
+                       break;
+               case 0x18:
+                       p_user->encode_type = SMS_ENCODE_IA5;
+                       break;
+               case 0x20:
+                       p_user->encode_type = SMS_ENCODE_UNICODE;
+                       break;
+               case 0x28:
+                       p_user->encode_type = SMS_ENCODE_SHIFT_JIS;
+                       break;
+               case 0x30:
+                       p_user->encode_type = SMS_ENCODE_KOREAN;
+                       break;
+               case 0x38:
+                       p_user->encode_type = SMS_ENCODE_LATIN_HEBREW;
+                       break;
+               case 0x40:
+                       p_user->encode_type = SMS_ENCODE_LATIN;
+                       break;
+               case 0x48:
+                       p_user->encode_type = SMS_ENCODE_GSM7BIT;
+                       break;
+               case 0x50:
+                       p_user->encode_type = SMS_ENCODE_GSMDCS;
+                       break;
+               case 0x80:              // reserved value, but SKT use this value for KSC5601
+                       p_user->encode_type = SMS_ENCODE_EUCKR;
+                       break;
+               default :
+                       p_user->encode_type = SMS_ENCODE_RESERVED;
+                       break;
+       }
+
+       _shiftNBit_for_decode(p_pkg_str, pkg_len, 5);
+
+       if(p_user->encode_type == SMS_ENCODE_EPM || p_user->encode_type == SMS_ENCODE_GSMDCS) {
+               p_user->msg_type = p_pkg_str[0];
+               _shiftNBit_for_decode(p_pkg_str, pkg_len, 8);
+       }
+
+       p_user->data_len = p_pkg_str[0];
+       switch(p_user->encode_type) {
+               case SMS_ENCODE_7BIT_ASCII:
+                       memset(p_user->user_data, 0x00, sizeof(p_user->user_data));
+                       for(unsigned int i = 0; i < p_user->data_len; i++) {
+                               p_user->user_data[i] = p_pkg_str[1] >> 1;
+                               _shiftNBit_for_decode(p_pkg_str, pkg_len, 7);
+                       }
+                       break;
+               case SMS_ENCODE_IA5:
+               case SMS_ENCODE_GSM7BIT:
+                       memset(p_user->user_data, 0x00, sizeof(p_user->user_data));
+                       UnpackGSM7bitData(&(p_pkg_str[1]), p_user->user_data, p_user->data_len);
+                       break;
+               case SMS_ENCODE_EPM:
+                       break;
+               case SMS_ENCODE_GSMDCS:
+                       break;
+               case SMS_ENCODE_UNICODE:
+                       p_user->data_len*=2;
+                       memset(p_user->user_data, 0x00, sizeof(p_user->user_data));
+                       memcpy(p_user->user_data, p_pkg_str+1, p_user->data_len);
+                       break;
+               default:
+                       memset(p_user->user_data, 0x00, sizeof(p_user->user_data));
+                       memcpy(p_user->user_data, p_pkg_str+1, p_user->data_len);
+                       break;
+       }
+
+}
+
+
+sms_message_type_t SmsPluginMsgCodec::findMsgType(const unsigned char *p_pkg_str, int pkg_len)
+{
+       int offset = 0;
+       while(offset < pkg_len) {
+               if(p_pkg_str[offset] == 0x00) {
+                       return (sms_message_type_t)((p_pkg_str[offset+2]&0xf0)>>4);
+               }
+               offset+=(p_pkg_str[offset+1]+2);
+       }
+
+       return SMS_TYPE_MAX_VALUE;
+}
diff --git a/plugin/sms_cdma_plugin/SmsCdmaPluginEventHandler.cpp b/plugin/sms_cdma_plugin/SmsCdmaPluginEventHandler.cpp
new file mode 100755 (executable)
index 0000000..a21d9b9
--- /dev/null
@@ -0,0 +1,1210 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <time.h>
+
+#include "MsgDebug.h"
+#include "MsgUtilFile.h"
+#include "MsgUtilFunction.h"
+#include "MsgUtilStorage.h"
+#include "MsgCppTypes.h"
+#include "MsgContact.h"
+#include "MsgGconfWrapper.h"
+
+#ifndef MSG_NOTIFICATION_NOT_SUPPORTED
+#include "MsgNotificationWrapper.h"
+#endif
+
+#include "SmsCdmaPluginTransport.h"
+#include "SmsCdmaPluginStorage.h"
+#include "SmsCdmaPluginSetting.h"
+#include "SmsCdmaPluginEventHandler.h"
+#include "SmsCdmaPluginWapPushHandler.h"
+
+
+
+SmsPluginEventHandler* SmsPluginEventHandler::pInstance = NULL;
+
+
+SmsPluginEventHandler::SmsPluginEventHandler()
+{
+       /**  Initialize global parameters */
+       memset(&listener, 0x00, sizeof(MSG_PLUGIN_LISTENER_S));
+       memset(&sentInfo, 0x00, sizeof(sms_sent_info_s));
+       devStatus = false;
+}
+
+
+SmsPluginEventHandler::~SmsPluginEventHandler()
+{
+
+}
+
+
+SmsPluginEventHandler* SmsPluginEventHandler::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginEventHandler();
+
+       return pInstance;
+}
+
+void SmsPluginEventHandler::registerListener(MSG_PLUGIN_LISTENER_S *pListener)
+{
+       listener = *pListener;
+}
+
+
+void SmsPluginEventHandler::convertTpduToMsginfo(sms_trans_p2p_msg_s *p_p2p_msg, MSG_MESSAGE_INFO_S *p_msg_info)
+{
+       MSG_BEGIN();
+
+       // Address
+       if (p_p2p_msg->telesvc_msg.data.deliver.callback_number.szData[0] != '\0')
+               p_msg_info->nAddressCnt = 2;
+       else
+               p_msg_info->nAddressCnt = 1;
+
+       p_msg_info->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S) * p_msg_info->nAddressCnt];
+
+       if (p_msg_info->addressList) {
+               switch (p_msg_info->nAddressCnt) {
+                       case 2 :
+                               memset(p_msg_info->addressList[1].addressVal, 0x00, MAX_ADDRESS_VAL_LEN+1);
+                       case 1 :
+                               memset(p_msg_info->addressList[0].addressVal, 0x00, MAX_ADDRESS_VAL_LEN+1);
+                               break;
+                       default :
+                               MSG_ERR("Invalid case");
+                               memset(p_msg_info->addressList[0].addressVal, 0x00, MAX_ADDRESS_VAL_LEN+1);
+               }
+       }
+
+       if (p_p2p_msg->address.szData[0] != '\0') {
+               p_msg_info->addressList[0].addressType = MSG_ADDRESS_TYPE_UNKNOWN;
+               memcpy(p_msg_info->addressList[0].addressVal, p_p2p_msg->address.szData, MAX_ADDRESS_VAL_LEN);
+               p_msg_info->addressList[0].recipientType = MSG_RECIPIENTS_TYPE_TO;
+       }
+
+
+       // Teleservice message
+       switch(p_p2p_msg->telesvc_msg.type)
+       {
+               case SMS_TYPE_DELIVER :
+                       p_msg_info->msgType.subType = MSG_NORMAL_SMS;
+                       p_msg_info->folderId = MSG_INBOX_ID;
+
+                       convertDeliverMsgToMsgInfo(&(p_p2p_msg->telesvc_msg.data.deliver), p_msg_info);
+                       break;
+               case SMS_TYPE_DELIVERY_ACK :
+                       convertAckMsgToMsgInfo(&(p_p2p_msg->telesvc_msg.data.delivery_ack), p_msg_info);
+                       break;
+               case SMS_TYPE_SUBMIT_REPORT :
+                       convertReportMsgToMsgInfo(&(p_p2p_msg->telesvc_msg.data.report), p_msg_info);
+                       break;
+               default :
+                       MSG_DEBUG("No matching type = [%d]", p_p2p_msg->telesvc_msg.type);
+                       break;
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginEventHandler::convertTpduToMsginfo(sms_trans_broadcast_msg_s *p_cb_msg, MSG_MESSAGE_INFO_S *p_msg_info)
+{
+       MSG_BEGIN();
+
+       // Address
+       p_msg_info->nAddressCnt = 0;
+       p_msg_info->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+
+       if (p_msg_info->addressList) {
+               memset(p_msg_info->addressList[0].addressVal, 0x00, MAX_ADDRESS_VAL_LEN+1);
+       }
+
+       // Bearer Data
+       if(p_cb_msg->telesvc_msg.type == SMS_TYPE_DELIVER) {
+               p_msg_info->msgType.subType = MSG_CB_SMS;
+               p_msg_info->folderId = MSG_CBMSGBOX_ID;
+
+               if (p_cb_msg->svc_ctg >= SMS_TRANS_SVC_CTG_CMAS_PRESIDENTIAL && p_cb_msg->svc_ctg <= SMS_TRANS_SVC_CTG_CMAS_TEST)
+                       convertCMASMsgToMsgInfo(&(p_cb_msg->telesvc_msg.data.deliver), p_msg_info);
+               else
+                       convertDeliverMsgToMsgInfo(&(p_cb_msg->telesvc_msg.data.deliver), p_msg_info);
+       }
+       else {
+               MSG_DEBUG("No matching type = [%d]", p_cb_msg->telesvc_msg.type);
+       }
+
+       if (p_msg_info->nAddressCnt == 0) {
+               p_msg_info->nAddressCnt = 1;
+               p_msg_info->addressList[0].addressType = MSG_ADDRESS_TYPE_UNKNOWN;
+               p_msg_info->addressList[0].recipientType = MSG_RECIPIENTS_TYPE_TO;
+
+               if (p_cb_msg->svc_ctg == SMS_TRANS_SVC_CTG_CMAS_PRESIDENTIAL)
+                       snprintf(p_msg_info->addressList[0].addressVal, MAX_ADDRESS_VAL_LEN, "Presidential Alert");
+               else if (p_cb_msg->svc_ctg == SMS_TRANS_SVC_CTG_CMAS_EXTREME)
+                       snprintf(p_msg_info->addressList[0].addressVal, MAX_ADDRESS_VAL_LEN, "Extreme Alert");
+               else if (p_cb_msg->svc_ctg == SMS_TRANS_SVC_CTG_CMAS_SEVERE)
+                       snprintf(p_msg_info->addressList[0].addressVal, MAX_ADDRESS_VAL_LEN, "Severe Alert");
+               else if (p_cb_msg->svc_ctg == SMS_TRANS_SVC_CTG_CMAS_AMBER)
+                       snprintf(p_msg_info->addressList[0].addressVal, MAX_ADDRESS_VAL_LEN, "AMBER Alert");
+               else if (p_cb_msg->svc_ctg == SMS_TRANS_SVC_CTG_CMAS_TEST)
+                       snprintf(p_msg_info->addressList[0].addressVal, MAX_ADDRESS_VAL_LEN, "Emergency Alert");
+               else
+                       snprintf(p_msg_info->addressList[0].addressVal, MAX_ADDRESS_VAL_LEN, "CB Message");
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginEventHandler::convertCMASMsgToMsgInfo(sms_telesvc_deliver_s *p_deliver, MSG_MESSAGE_INFO_S *p_msg_info)
+{
+       MSG_BEGIN();
+
+       p_msg_info->msgType.mainType = MSG_SMS_TYPE;
+
+       p_msg_info->msgType.classType = MSG_CLASS_NONE;
+       p_msg_info->networkStatus = MSG_NETWORK_RECEIVED;
+       p_msg_info->bRead = false;
+       p_msg_info->bProtected = false;
+       p_msg_info->direction = MSG_DIRECTION_TYPE_MT;
+       p_msg_info->bTextSms = true;
+
+       if (p_deliver->callback_number.szData[0] != '\0') {                     // If callback number is in received pdu, replace the address value.
+               memset(p_msg_info->addressList[0].addressVal, 0x00, MAX_ADDRESS_VAL_LEN+1);
+               p_msg_info->nAddressCnt = 1;
+               p_msg_info->addressList[0].addressType = MSG_ADDRESS_TYPE_UNKNOWN;
+               snprintf(p_msg_info->addressList[0].addressVal, MAX_ADDRESS_VAL_LEN, "%s", p_deliver->callback_number.szData);
+               p_msg_info->addressList[0].recipientType = MSG_RECIPIENTS_TYPE_TO;
+       }
+
+       time_t rawtime = 0;
+       p_msg_info->storageId = MSG_STORAGE_PHONE;
+
+#if 0 // Save Timestamp of message center.
+               char displayTime[32];
+               struct tm * timeTM;
+
+               struct tm timeinfo;
+               memset(&timeinfo, 0x00, sizeof(tm));
+
+               if (p_deliver->time_stamp.year > 95)
+                       timeinfo.tm_year = (p_deliver->time_stamp.year + 1900);
+               else
+                       timeinfo.tm_year = (p_deliver->time_stamp.year + 2000);
+
+               timeinfo.tm_mon = (p_deliver->time_stamp.month - 1);
+               timeinfo.tm_mday = p_deliver->time_stamp.day;
+               timeinfo.tm_hour = p_deliver->time_stamp.hour;
+               timeinfo.tm_min = p_deliver->time_stamp.minute;
+               timeinfo.tm_sec = p_deliver->time_stamp.second;
+               timeinfo.tm_isdst = 0;
+
+               rawtime = mktime(&timeinfo);
+
+               MSG_DEBUG("tzname[0] [%s]", tzname[0]);
+               MSG_DEBUG("tzname[1] [%s]", tzname[1]);
+               MSG_DEBUG("timezone [%d]", timezone);
+               MSG_DEBUG("daylight [%d]", daylight);
+
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", &timeinfo);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= (pTpdu->timeStamp.time.absolute.timeZone * (3600/4));
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= timezone;
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+       }
+#else
+       rawtime = time(NULL);
+#endif
+
+       p_msg_info->displayTime = rawtime;
+
+
+       if (p_deliver->priority == SMS_PRIORITY_URGENT || p_deliver->priority == SMS_PRIORITY_EMERGENCY)
+               p_msg_info->priority = MSG_MESSAGE_PRIORITY_HIGH;
+       else
+               p_msg_info->priority = MSG_MESSAGE_PRIORITY_NORMAL;
+
+
+       memset(p_msg_info->subject, 0x00, MAX_SUBJECT_LEN+1);
+
+       p_msg_info->msgPort.valid = false;
+       p_msg_info->msgPort.dstPort = 0;
+       p_msg_info->msgPort.srcPort = 0;
+
+       p_msg_info->encodeType = getEncodeType(p_deliver->cmas_data.encode_type);
+
+       if (p_deliver->cmas_data.data_len <= 0) {
+               memset(p_msg_info->msgText, 0x00, sizeof(p_msg_info->msgText));
+               p_msg_info->dataSize = 0;
+       } else if (p_deliver->cmas_data.data_len > MAX_MSG_TEXT_LEN) {
+               sprintf(p_msg_info->msgText, "[Broken Message]");
+               p_msg_info->dataSize = strlen(p_msg_info->msgData);
+               return;
+       } else {
+               if(p_msg_info->encodeType == MSG_ENCODE_UCS2) {
+                       MSG_DEBUG("Encode Type = UCS2");
+                       MsgTextConvert *textCvt = MsgTextConvert::instance();
+                       p_msg_info->dataSize = textCvt->convertUCS2ToUTF8((unsigned char*)&p_msg_info->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)&p_deliver->cmas_data.alert_text, p_deliver->cmas_data.data_len);
+               }
+               else if(p_msg_info->encodeType == MSG_ENCODE_EUCKR) {
+                       MSG_DEBUG("Encode Type = EUCKR");
+                       MsgTextConvert *textCvt = MsgTextConvert::instance();
+                       p_msg_info->dataSize = textCvt->convertEUCKRToUTF8((unsigned char*)&p_msg_info->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)&p_deliver->cmas_data.alert_text, p_deliver->cmas_data.data_len);
+               }
+               else if(p_msg_info->encodeType == MSG_ENCODE_SHIFT_JIS) {
+                       MSG_DEBUG("Encode Type = Shift-JIS");
+                       MsgTextConvert *textCvt = MsgTextConvert::instance();
+                       p_msg_info->dataSize = textCvt->convertSHIFTJISToUTF8((unsigned char*)&p_msg_info->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)&p_deliver->cmas_data.alert_text, p_deliver->cmas_data.data_len);
+               }
+               else if(p_msg_info->encodeType == MSG_ENCODE_GSM7BIT) {
+                       MSG_DEBUG("Encode Type = GSM7BIT");
+                       MSG_LANG_INFO_S langinfo = {0,};
+                       MsgTextConvert *textCvt = MsgTextConvert::instance();
+                       p_msg_info->dataSize = textCvt->convertGSM7bitToUTF8((unsigned char*)&p_msg_info->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)&p_deliver->cmas_data.alert_text, p_deliver->cmas_data.data_len, &langinfo);
+               }
+               else {
+                       snprintf(p_msg_info->msgText, sizeof(p_msg_info->msgText), "%s", p_deliver->cmas_data.alert_text);
+                       p_msg_info->dataSize = p_deliver->cmas_data.data_len;
+               }
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginEventHandler::convertDeliverMsgToMsgInfo(sms_telesvc_deliver_s *p_deliver, MSG_MESSAGE_INFO_S *p_msg_info)
+{
+       MSG_BEGIN();
+
+       p_msg_info->msgType.mainType = MSG_SMS_TYPE;
+//     p_msg_info->msgType.subType = MSG_NORMAL_SMS;
+
+//     p_msg_info->folderId = MSG_INBOX_ID;
+
+       p_msg_info->msgType.classType = MSG_CLASS_NONE;
+       p_msg_info->networkStatus = MSG_NETWORK_RECEIVED;
+       p_msg_info->bRead = false;
+       p_msg_info->bProtected = false;
+       p_msg_info->direction = MSG_DIRECTION_TYPE_MT;
+       p_msg_info->bTextSms = true;
+
+       if (p_deliver->callback_number.szData[0] != '\0') {                     // If callback number is in received pdu, replace the address value.
+               memset(p_msg_info->addressList[1].addressVal, 0x00, MAX_ADDRESS_VAL_LEN+1);
+               p_msg_info->addressList[1].addressType = MSG_ADDRESS_TYPE_UNKNOWN;
+               memcpy(p_msg_info->addressList[1].addressVal, p_deliver->callback_number.szData, MAX_ADDRESS_VAL_LEN);
+               p_msg_info->addressList[1].recipientType = MSG_RECIPIENTS_TYPE_TO;
+       }
+
+       time_t rawtime = 0;
+       p_msg_info->storageId = MSG_STORAGE_PHONE;
+
+#if 0 // Save Timestamp of message center.
+               char displayTime[32];
+               struct tm * timeTM;
+
+               struct tm timeinfo;
+               memset(&timeinfo, 0x00, sizeof(tm));
+
+               if (p_deliver->time_stamp.year > 95)
+                       timeinfo.tm_year = (p_deliver->time_stamp.year + 1900);
+               else
+                       timeinfo.tm_year = (p_deliver->time_stamp.year + 2000);
+
+               timeinfo.tm_mon = (p_deliver->time_stamp.month - 1);
+               timeinfo.tm_mday = p_deliver->time_stamp.day;
+               timeinfo.tm_hour = p_deliver->time_stamp.hour;
+               timeinfo.tm_min = p_deliver->time_stamp.minute;
+               timeinfo.tm_sec = p_deliver->time_stamp.second;
+               timeinfo.tm_isdst = 0;
+
+               rawtime = mktime(&timeinfo);
+
+               MSG_DEBUG("tzname[0] [%s]", tzname[0]);
+               MSG_DEBUG("tzname[1] [%s]", tzname[1]);
+               MSG_DEBUG("timezone [%d]", timezone);
+               MSG_DEBUG("daylight [%d]", daylight);
+
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", &timeinfo);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= (pTpdu->timeStamp.time.absolute.timeZone * (3600/4));
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= timezone;
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+       }
+#else
+       rawtime = time(NULL);
+#endif
+
+       p_msg_info->displayTime = rawtime;
+
+
+       if (p_deliver->priority == SMS_PRIORITY_URGENT || p_deliver->priority == SMS_PRIORITY_EMERGENCY)
+               p_msg_info->priority = MSG_MESSAGE_PRIORITY_HIGH;
+       else
+               p_msg_info->priority = MSG_MESSAGE_PRIORITY_NORMAL;
+
+
+       memset(p_msg_info->subject, 0x00, MAX_SUBJECT_LEN+1);
+
+       p_msg_info->msgPort.valid = false;
+       p_msg_info->msgPort.dstPort = 0;
+       p_msg_info->msgPort.srcPort = 0;
+
+       p_msg_info->encodeType = getEncodeType(p_deliver->user_data.encode_type);
+
+       if (p_deliver->user_data.data_len <= 0) {
+               memset(p_msg_info->msgText, 0x00, sizeof(p_msg_info->msgText));
+               p_msg_info->dataSize = 0;
+       } else if (p_deliver->user_data.data_len > MAX_MSG_TEXT_LEN) {
+               sprintf(p_msg_info->msgText, "[Broken Message]");
+               p_msg_info->dataSize = strlen(p_msg_info->msgData);
+               return;
+       } else {
+               if(p_msg_info->encodeType == MSG_ENCODE_UCS2) {
+                       MSG_DEBUG("Encode Type = UCS2");
+                       MsgTextConvert *textCvt = MsgTextConvert::instance();
+                       p_msg_info->dataSize = textCvt->convertUCS2ToUTF8((unsigned char*)&p_msg_info->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)&p_deliver->user_data.user_data, p_deliver->user_data.data_len);
+               }
+               else if(p_msg_info->encodeType == MSG_ENCODE_EUCKR) {
+                       MSG_DEBUG("Encode Type = EUCKR");
+                       MsgTextConvert *textCvt = MsgTextConvert::instance();
+                       p_msg_info->dataSize = textCvt->convertEUCKRToUTF8((unsigned char*)&p_msg_info->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)&p_deliver->user_data.user_data, p_deliver->user_data.data_len);
+               }
+               else if(p_msg_info->encodeType == MSG_ENCODE_SHIFT_JIS) {
+                       MSG_DEBUG("Encode Type = Shift-JIS");
+                       MsgTextConvert *textCvt = MsgTextConvert::instance();
+                       p_msg_info->dataSize = textCvt->convertSHIFTJISToUTF8((unsigned char*)&p_msg_info->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)&p_deliver->user_data.user_data, p_deliver->user_data.data_len);
+               }
+               else if(p_msg_info->encodeType == MSG_ENCODE_GSM7BIT) {
+                       MSG_DEBUG("Encode Type = GSM7BIT");
+                       MSG_LANG_INFO_S langinfo = {0,};
+                       MsgTextConvert *textCvt = MsgTextConvert::instance();
+                       p_msg_info->dataSize = textCvt->convertGSM7bitToUTF8((unsigned char*)&p_msg_info->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)&p_deliver->user_data.user_data, p_deliver->user_data.data_len, &langinfo);
+               }
+               else {
+                       snprintf(p_msg_info->msgText, sizeof(p_msg_info->msgText), "%s", p_deliver->user_data.user_data);
+                       p_msg_info->dataSize = p_deliver->user_data.data_len;
+               }
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginEventHandler::convertAckMsgToMsgInfo(sms_telesvc_deliver_ack_s *p_deliver, MSG_MESSAGE_INFO_S *p_msg_info)
+{
+
+}
+
+
+void SmsPluginEventHandler::convertReportMsgToMsgInfo(sms_telesvc_report_s *p_deliver, MSG_MESSAGE_INFO_S *p_msg_info)
+{
+
+}
+
+
+void SmsPluginEventHandler::SetSentInfo(sms_sent_info_s *pSentInfo)
+{
+       memset(&sentInfo, 0x00, sizeof(sms_sent_info_s));
+       memcpy(&sentInfo, pSentInfo, sizeof(sms_sent_info_s));
+
+       MSG_DEBUG("sentInfo.reqId : %d", sentInfo.reqInfo.reqId);
+       MSG_DEBUG("sentInfo.bLast : %d", sentInfo.bLast);
+}
+
+
+
+void SmsPluginEventHandler::handleSentStatus(msg_network_status_t NetStatus)
+{
+       MSG_DEBUG("NetStatus[%d]", NetStatus);
+
+       if (sentInfo.bLast == true || NetStatus != MSG_NETWORK_SEND_SUCCESS) {
+               /** Update Msg Status */
+               if (sentInfo.reqInfo.msgInfo.msgPort.valid == false) {
+
+                       sentInfo.reqInfo.msgInfo.networkStatus = NetStatus;
+
+                       if (NetStatus == MSG_NETWORK_SEND_SUCCESS) {
+                               MSG_DEBUG("Add phone log");
+                               MsgAddPhoneLog(&(sentInfo.reqInfo.msgInfo));
+                               sentInfo.reqInfo.msgInfo.folderId = MSG_SENTBOX_ID;
+                       } else {
+                               sentInfo.reqInfo.msgInfo.bRead = false;
+                       }
+
+                       callbackStorageChange(MSG_STORAGE_CHANGE_UPDATE, &(sentInfo.reqInfo.msgInfo));
+               }
+
+               MSG_DEBUG("sentInfo.reqInfo.sendOptInfo.bSetting [%d]", sentInfo.reqInfo.sendOptInfo.bSetting);
+               MSG_DEBUG("sentInfo.reqInfo.sendOptInfo.bKeepCopy [%d]", sentInfo.reqInfo.sendOptInfo.bKeepCopy);
+               /** Check sending options */
+               if (sentInfo.reqInfo.sendOptInfo.bSetting && !sentInfo.reqInfo.sendOptInfo.bKeepCopy && NetStatus == MSG_NETWORK_SEND_SUCCESS) {
+                       callbackStorageChange(MSG_STORAGE_CHANGE_DELETE, &(sentInfo.reqInfo.msgInfo));
+               }
+
+               /** Callback to MSG FW */
+               MSG_SENT_STATUS_S msgStatus;
+
+               msgStatus.reqId = sentInfo.reqInfo.reqId;
+               msgStatus.status = NetStatus;
+
+               MSG_DEBUG("sentStatus.reqId : %d", msgStatus.reqId);
+               MSG_DEBUG("sentStatus.status : %d", msgStatus.status);
+
+               listener.pfSentStatusCb(&msgStatus);
+       }
+}
+
+
+void SmsPluginEventHandler::handleMsgIncoming(sms_trans_p2p_msg_s *p_p2p_msg)
+{
+
+       /** Make MSG_MESSAGE_INFO_S */
+       MSG_MESSAGE_INFO_S msgInfo;
+
+       /** initialize msgInfo */
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       /** convert to msgInfo */
+       convertTpduToMsginfo(p_p2p_msg, &msgInfo);
+
+       if (p_p2p_msg->telesvc_id == SMS_TRANS_TELESVC_RESERVED) {
+               MSG_DEBUG("This Incoming Message has Unknown Teleservice ID");
+               SmsPluginTransport::instance()->sendDeliverReport(MSG_ERR_INVALID_MSG_TYPE, p_p2p_msg);
+               return;
+       }
+
+       /** Check for Voice Mail Notification */
+       if (p_p2p_msg->telesvc_id == SMS_TRANS_TELESVC_VMN_95) {
+               if (p_p2p_msg->telesvc_msg.data.deliver.enhanced_vmn.fax_included)
+                       msgInfo.msgType.subType = MSG_MWI_FAX_SMS;
+               else
+                       msgInfo.msgType.subType = MSG_MWI_VOICE_SMS;
+
+               if (p_p2p_msg->telesvc_msg.data.deliver.num_msg < 0)
+                       p_p2p_msg->telesvc_msg.data.deliver.num_msg = 0;
+
+               int voice_cnt = MsgSettingGetInt(VOICEMAIL_COUNT);
+
+               // repeated msg check for voicemail
+               if (voice_cnt == p_p2p_msg->telesvc_msg.data.deliver.num_msg) {
+                       SmsPluginTransport::instance()->sendDeliverReport(MSG_SUCCESS, p_p2p_msg);
+                       return;
+               }
+
+               SmsPluginSetting::instance()->setMwiInfo(msgInfo.msgType.subType, p_p2p_msg->telesvc_msg.data.deliver.num_msg);
+
+               memset(msgInfo.msgText, 0x00, sizeof(msgInfo.msgText));
+
+               snprintf(msgInfo.msgText, sizeof(msgInfo.msgText), "%d", p_p2p_msg->telesvc_msg.data.deliver.num_msg);
+               msgInfo.dataSize = strlen(msgInfo.msgText);
+       }
+       /** Check for EMS(Unsupported) */
+       else if (p_p2p_msg->telesvc_id == SMS_TRANS_TELESVC_WEMT) {
+               char *msg_text = getTranslateText(MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR, "IDS_MSGF_POP_ERROR_UNSUPPORTED_MSG");
+               memset(msgInfo.msgText, 0x00, sizeof(msgInfo.msgText));
+               snprintf(msgInfo.msgText, sizeof(msgInfo.msgText), "%s", msg_text);
+               msgInfo.dataSize = strlen(msgInfo.msgText);
+
+               if (msg_text) {
+                       free(msg_text);
+                       msg_text = NULL;
+               }
+       }
+
+       /** Print MSG_MESSAGE_INFO_S */
+       MSG_DEBUG("############# Convert  tpdu values to Message Info values ####################");
+       MSG_DEBUG("msgInfo.nAddressCnt : %d", msgInfo.nAddressCnt);
+       MSG_DEBUG("msgInfo.addressList[0].addressType : %d", msgInfo.addressList[0].addressType);
+       MSG_DEBUG("msgInfo.addressList[0].addressVal : %s", msgInfo.addressList[0].addressVal);
+       MSG_DEBUG("msgInfo.addressList[0].displayName : %s", msgInfo.addressList[0].displayName);
+       MSG_DEBUG("msgInfo.priority : %d", msgInfo.priority);
+       MSG_DEBUG("msgInfo.bProtected : %d", msgInfo.bProtected);
+       MSG_DEBUG("msgInfo.bRead : %d", msgInfo.bRead);
+       MSG_DEBUG("msgInfo.bTextSms : %d", msgInfo.bTextSms);
+       MSG_DEBUG("msgInfo.bStore : %d", msgInfo.bStore);
+       MSG_DEBUG("msgInfo.direction : %d", msgInfo.direction);
+       MSG_DEBUG("msgInfo.msgType.mainType : %d", msgInfo.msgType.mainType);
+       MSG_DEBUG("msgInfo.msgType.subType : %d", msgInfo.msgType.subType);
+       MSG_DEBUG("msgInfo.msgType.classType : %d", msgInfo.msgType.classType);
+       MSG_DEBUG("msgInfo.displayTime : %s", ctime(&msgInfo.displayTime));
+       MSG_DEBUG("msgInfo.msgPort.valid : %d", msgInfo.msgPort.valid);
+       MSG_DEBUG("msgInfo.encodeType : %d", msgInfo.encodeType);
+       MSG_DEBUG("msgInfo.dataSize : %d", msgInfo.dataSize);
+
+       if (msgInfo.bTextSms == true) {
+               MSG_DEBUG("msgInfo.msgText : %s", msgInfo.msgText);
+       } else {
+               MSG_DEBUG("msgInfo.msgData : %s", msgInfo.msgData);
+       }
+
+       MSG_DEBUG("###############################################################");
+
+       msg_error_t err = MSG_SUCCESS;
+       bool isUnique = true;
+       MSG_UNIQUE_INDEX_S unq_ind;
+       memset(&unq_ind, 0x00, sizeof(MSG_UNIQUE_INDEX_S));
+
+       if (msgInfo.msgType.subType == MSG_STATUS_REPORT_SMS) {
+//             /** Status Report Message */
+//             err = SmsPluginStorage::instance()->updateMsgDeliverStatus(&msgInfo, pTpdu->data.statusRep.msgRef);
+//
+//             if (err == MSG_SUCCESS)
+//                     err = listener.pfMsgIncomingCb(&msgInfo);
+//             else
+//                     MSG_DEBUG("updateMsgDeliverStatus is failed [%d]", err);
+//
+//             /** Handling of Fail Case ?? */
+//             SmsPluginTransport::instance()->sendDeliverReport(MSG_SUCCESS);
+       } else { /** SMS Deliver */
+
+               /** Add message to DB */
+               if (msgInfo.msgPort.valid == false) {
+                       if (p_p2p_msg->telesvc_id != SMS_TRANS_TELESVC_VMN_95) {
+                               memcpy(unq_ind.address, p_p2p_msg->address.szData, sizeof(p_p2p_msg->address.szData));
+                               memcpy(unq_ind.sub_address, p_p2p_msg->sub_address.szData, sizeof(p_p2p_msg->sub_address.szData));
+                               unq_ind.tele_msgId = p_p2p_msg->telesvc_msg.data.deliver.msg_id.msg_id;
+                               snprintf(unq_ind.time_stamp, sizeof(unq_ind.time_stamp), "%02d%02d%02d%02d%02d%02d",
+                                               p_p2p_msg->telesvc_msg.data.deliver.time_stamp.year, p_p2p_msg->telesvc_msg.data.deliver.time_stamp.month,
+                                               p_p2p_msg->telesvc_msg.data.deliver.time_stamp.day, p_p2p_msg->telesvc_msg.data.deliver.time_stamp.hours,
+                                               p_p2p_msg->telesvc_msg.data.deliver.time_stamp.minutes, p_p2p_msg->telesvc_msg.data.deliver.time_stamp.seconds);
+                               unq_ind.telesvc_id = p_p2p_msg->telesvc_id;
+                               isUnique = listener.pfCheckUniquenessCb(&unq_ind, 0, false);
+                       }
+               }
+
+               if (isUnique) {
+                       err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
+               }
+               else {
+                       SmsPluginTransport::instance()->sendDeliverReport(MSG_SUCCESS, p_p2p_msg);
+                       return;
+               }
+
+               /** Callback to MSG FW */
+               if (err == MSG_SUCCESS) {
+                       MSG_DEBUG("callback to msg fw");
+                       err = listener.pfMsgIncomingCb(&msgInfo);
+               } else {
+                       if (msgInfo.msgType.classType == MSG_CLASS_0) {
+                               MSG_DEBUG("callback for class0 message to msg fw");
+                               if (listener.pfMsgIncomingCb(&msgInfo) != MSG_SUCCESS)
+                                       MSG_DEBUG("listener.pfMsgIncomingCb is failed!");
+                       }
+               }
+
+               if (err == MSG_SUCCESS && p_p2p_msg->telesvc_id != SMS_TRANS_TELESVC_VMN_95)
+                       listener.pfCheckUniquenessCb(&unq_ind, msgInfo.msgId, true);
+
+               /** Send Deliver Report */
+               if (p_p2p_msg->telesvc_id == SMS_TRANS_TELESVC_WEMT) {
+                       SmsPluginTransport::instance()->sendDeliverReport(MSG_ERR_INVALID_MSG_TYPE, p_p2p_msg);
+               } else {
+                       SmsPluginTransport::instance()->sendDeliverReport(err, p_p2p_msg);
+               }
+
+               // Tizen Validation System
+               char *msisdn = NULL;
+               char keyName[MAX_VCONFKEY_NAME_LEN];
+               int simIndex = 1;
+
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_MSISDN, simIndex);
+
+               msisdn = MsgSettingGetString(keyName);
+
+               MSG_SMS_VLD_INFO("%d, SMS Receive, %s->%s, %s", msgInfo.msgId, \
+                                                                                                               msgInfo.addressList[0].addressVal, \
+                                                                                                               (msisdn == NULL)?"ME":msisdn, \
+                                                                                                               (err == MSG_SUCCESS)?"Success":"Fail");
+
+               MSG_SMS_VLD_TXT("%d, [%s]", msgInfo.msgId, msgInfo.msgText);
+
+               if (msisdn) {
+                       free(msisdn);
+                       msisdn = NULL;
+               }
+       }
+}
+
+
+void SmsPluginEventHandler::handleCbMsgIncoming(sms_trans_broadcast_msg_s *p_cb_msg)
+{
+       MSG_BEGIN();
+
+       if (p_cb_msg->telesvc_msg.data.deliver.cmas_data.encode_type == SMS_ENCODE_KOREAN
+               || p_cb_msg->telesvc_msg.data.deliver.cmas_data.encode_type == SMS_ENCODE_GSMDCS) {
+               MSG_DEBUG("This encode type is not supported [%d]", p_cb_msg->telesvc_msg.data.deliver.cmas_data.encode_type);
+               return;
+       }
+
+       /** Make MSG_MESSAGE_INFO_S */
+       MSG_MESSAGE_INFO_S msgInfo;
+
+       /** initialize msgInfo */
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       /** convert to msgInfo */
+       convertTpduToMsginfo(p_cb_msg, &msgInfo);
+       msgInfo.msgId = p_cb_msg->telesvc_msg.data.deliver.msg_id.msg_id;
+
+       /** Print MSG_MESSAGE_INFO_S */
+       MSG_DEBUG("############# Convert  tpdu values to Message Info values ####################");
+       MSG_DEBUG("msgInfo.priority : %d", msgInfo.priority);
+       MSG_DEBUG("msgInfo.bProtected : %d", msgInfo.bProtected);
+       MSG_DEBUG("msgInfo.bRead : %d", msgInfo.bRead);
+       MSG_DEBUG("msgInfo.bTextSms : %d", msgInfo.bTextSms);
+       MSG_DEBUG("msgInfo.bStore : %d", msgInfo.bStore);
+       MSG_DEBUG("msgInfo.direction : %d", msgInfo.direction);
+       MSG_DEBUG("msgInfo.msgType.mainType : %d", msgInfo.msgType.mainType);
+       MSG_DEBUG("msgInfo.msgType.subType : %d", msgInfo.msgType.subType);
+       MSG_DEBUG("msgInfo.msgType.classType : %d", msgInfo.msgType.classType);
+       MSG_DEBUG("msgInfo.displayTime : %s", ctime(&msgInfo.displayTime));
+       MSG_DEBUG("msgInfo.msgPort.valid : %d", msgInfo.msgPort.valid);
+       MSG_DEBUG("msgInfo.encodeType : %d", msgInfo.encodeType);
+       MSG_DEBUG("msgInfo.dataSize : %d", msgInfo.dataSize);
+       MSG_DEBUG("msgInfo.msgId : %d", msgInfo.msgId);
+
+       if (msgInfo.bTextSms == true) {
+               MSG_DEBUG("msgInfo.msgText : %s", msgInfo.msgText);
+       } else {
+               MSG_DEBUG("msgInfo.msgData : %s", msgInfo.msgData);
+       }
+
+       MSG_DEBUG("###############################################################");
+
+       msg_error_t err = MSG_SUCCESS;
+
+       /** Add message to DB */
+       if (msgInfo.msgPort.valid == false) {
+               err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
+       }
+
+       if (!checkCbOpt(p_cb_msg->svc_ctg))
+       {
+               MSG_DEBUG("The CB Msg is not supported by option.");
+               return;
+       }
+
+       /** Callback to MSG FW */
+       if (err == MSG_SUCCESS) {
+
+#if 1
+               MSG_CB_MSG_S cbOutMsg = {0, };
+               bool is_duplicate = false;
+
+               switch (p_cb_msg->svc_ctg) {
+                       case SMS_TRANS_SVC_CTG_CMAS_PRESIDENTIAL :
+                               msgInfo.msgType.subType = MSG_CMAS_PRESIDENTIAL;
+                               break;
+                       case SMS_TRANS_SVC_CTG_CMAS_EXTREME :
+                               msgInfo.msgType.subType = MSG_CMAS_EXTREME;
+                               break;
+                       case SMS_TRANS_SVC_CTG_CMAS_SEVERE :
+                               msgInfo.msgType.subType = MSG_CMAS_SEVERE;
+                               break;
+                       case SMS_TRANS_SVC_CTG_CMAS_AMBER :
+                               msgInfo.msgType.subType = MSG_CMAS_AMBER;
+                               break;
+                       case SMS_TRANS_SVC_CTG_CMAS_TEST :
+                               msgInfo.msgType.subType = MSG_CMAS_TEST;
+                               break;
+                       default :
+                               msgInfo.msgType.subType = MSG_CB_SMS;
+                               break;
+               }
+
+               cbOutMsg.type = msgInfo.msgType.subType;
+               cbOutMsg.receivedTime = msgInfo.displayTime;
+               cbOutMsg.serialNum = 0;//encodeCbSerialNum (CbMsgPage.pageHeader.serialNum);
+               cbOutMsg.messageId = msgInfo.msgId;
+//             cbOutMsg.dcs = CbMsgPage.pageHeader.dcs.rawData;
+               memset (cbOutMsg.cbText, 0x00, sizeof(cbOutMsg.cbText));
+
+               cbOutMsg.cbTextLen= msgInfo.dataSize;
+               memset(cbOutMsg.language_type, 0x00, sizeof(cbOutMsg.language_type));
+//             memcpy(cbOutMsg.language_type, CbMsgPage.pageHeader.dcs.iso639Lang, 3);
+
+               if (!is_duplicate)
+               {
+                       MSG_DEBUG("callback to msg fw");
+                       err = listener.pfCBMsgIncomingCb(&cbOutMsg, &msgInfo);
+
+                       if (err != MSG_SUCCESS)
+                       {
+                               MSG_WARN("callbackMsgIncoming() Error !! [%d]", err);
+                       }
+               }
+               else
+               {
+                       MSG_WARN("duplicate cb serialNum[%d] messageId[%d]", cbOutMsg.serialNum, cbOutMsg.messageId);
+               }
+
+#else
+               err = listener.pfMsgIncomingCb(&msgInfo);
+#endif
+       }
+
+       /** Send Deliver Report */
+//     SmsPluginTransport::instance()->sendDeliverReport(err, p_cb_msg);
+
+       // Tizen Validation System
+       char *msisdn = NULL;
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       int simIndex = 1;
+
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_MSISDN, simIndex);
+
+       msisdn = MsgSettingGetString(keyName);
+
+       MSG_SMS_VLD_INFO("%d, SMS Receive, %s->%s, %s", msgInfo.msgId, \
+                                                                                                       msgInfo.addressList[0].addressVal, \
+                                                                                                       (msisdn == NULL)?"ME":msisdn, \
+                                                                                                       (err == MSG_SUCCESS)?"Success":"Fail");
+
+       MSG_SMS_VLD_TXT("%d, [%s]", msgInfo.msgId, msgInfo.msgText);
+
+       if (msisdn) {
+               free(msisdn);
+               msisdn = NULL;
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginEventHandler::handleWapMsgIncoming(sms_trans_p2p_msg_s *p_p2p_msg)
+{
+       MSG_BEGIN();
+
+       sms_wap_msg_s msg;
+       memset(&msg, 0x00, sizeof(sms_wap_msg_s));
+
+       msg.msgId = p_p2p_msg->telesvc_msg.data.deliver.msg_id.msg_id;
+       msg.totalSeg = p_p2p_msg->telesvc_msg.data.deliver.user_data.user_data[1];
+       msg.segNum = p_p2p_msg->telesvc_msg.data.deliver.user_data.user_data[2];
+
+       char tmpUserText[SMS_MAX_USER_DATA_LEN+1] = {0,};
+       sms_telesvc_userdata_s tmpUserData;
+       memset(&tmpUserData, 0x00, sizeof(sms_telesvc_userdata_s));
+
+       tmpUserData.data_len = p_p2p_msg->telesvc_msg.data.deliver.user_data.data_len - 3;
+       memcpy(tmpUserText, &(p_p2p_msg->telesvc_msg.data.deliver.user_data.user_data[3]), tmpUserData.data_len);
+       memcpy(tmpUserData.user_data, tmpUserText, sizeof(tmpUserData.user_data));
+
+       unsigned char segCnt = checkWapMsg(&msg, &tmpUserData);
+
+       MSG_DEBUG("segNum [%d]", msg.segNum);
+       MSG_DEBUG("segCnt [%d]", segCnt);
+       MSG_DEBUG("msg.totalSeg [%d]", msg.totalSeg);
+
+       if (segCnt == msg.totalSeg) {
+               MSG_DEBUG("RECEIVED LAST WAP : %d", segCnt);
+
+               unsigned short srcPort = 0, dstPort = 0;
+               int dataSize = 0;
+               char* pUserData = NULL;
+               char* pTmpUserData = NULL;
+               unique_ptr<char*, void(*)(char**)> dataBuf(&pUserData, unique_ptr_deleter);
+               unique_ptr<char*, void(*)(char**)> dataBuf1(&pTmpUserData, unique_ptr_deleter);
+
+               MSG_MESSAGE_INFO_S msgInfo = {0,};
+
+               msgInfo.addressList = NULL;
+               unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+               dataSize = MakeWapUserData(msg.msgId, &pUserData);
+
+               pTmpUserData = new char[dataSize];
+
+               memcpy(pTmpUserData, pUserData, dataSize);
+               memset(pUserData, 0x00, dataSize);
+
+               srcPort = pTmpUserData[0] << 8  | pTmpUserData[1];
+               dstPort = pTmpUserData[2] << 8 | pTmpUserData[3];
+
+#ifndef FEATURE_OMADM_DUPLICATE_PORT_WAPPUSH
+               dataSize -= 4;
+               memcpy(pUserData, &pTmpUserData[4], dataSize);
+#else
+               if ((srcPort == 0x23f0 && dstPort == 0x0b84) &&
+                       ((pTmpUserData[4] << 8 | pTmpUserData[5]) == 0x23f0) &&
+                       ((pTmpUserData[6] << 8 | pTmpUserData[7]) == 0x0b84)) {
+                       dataSize -= 8;
+                       memcpy(pUserData, &pTmpUserData[8], dataSize);
+               }
+               else {
+                       dataSize -= 4;
+                       memcpy(pUserData, &pTmpUserData[4], dataSize);
+               }
+#endif
+
+               if (dataSize > 0) {
+                       MSG_DEBUG("dataSize = %d", dataSize);
+                       for (int i = 0; i < dataSize; i++)
+                               MSG_DEBUG("UserData[%d] = [%c] [%02x]", i, pUserData[i], pUserData[i]);
+
+                       if      (SmsPluginWapPushHandler::instance()->IsWapPushMsg(dstPort) == true) {
+                               msgInfo.msgType.mainType = MSG_SMS_TYPE;
+                               SmsPluginWapPushHandler::instance()->copyDeliverData(&(p_p2p_msg->address));
+                               SmsPluginWapPushHandler::instance()->handleWapPushMsg(pUserData, dataSize);
+                       }
+                       else {
+                               MSG_DEBUG("not supported wap push port [%x]", dstPort);
+                       }
+               }
+
+               // remove from waplist
+               for (int index = wapList.size()-1; index >= 0 ; index--) {
+                       if (wapList[index].msgId == msg.msgId) {
+                               MSG_DEBUG("remove waplist of the index [%d]", index);
+                               wapList.erase(wapList.begin()+index);
+                               break;
+                       }
+               }
+       }
+
+       /** Send Deliver Report */
+       SmsPluginTransport::instance()->sendDeliverReport(MSG_SUCCESS, p_p2p_msg);
+
+       MSG_END();
+}
+
+
+void SmsPluginEventHandler::handleResendMessage(void)
+{
+       listener.pfResendMessageCb();
+}
+
+
+msg_error_t SmsPluginEventHandler::callbackMsgIncoming(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       /** Callback to MSG FW */
+       err = listener.pfMsgIncomingCb(pMsgInfo);
+
+       MSG_END();
+
+       return err;
+}
+
+
+msg_error_t SmsPluginEventHandler::callbackStorageChange(msg_storage_change_type_t storageChangeType, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       /** Callback to MSG FW */
+       listener.pfStorageChangeCb(storageChangeType, pMsgInfo);
+
+       return MSG_SUCCESS;
+}
+
+
+void SmsPluginEventHandler::setDeviceStatus()
+{
+       mx.lock();
+       devStatus = true;
+       cv.signal();
+       mx.unlock();
+}
+
+
+bool SmsPluginEventHandler::getDeviceStatus()
+{
+       int ret = 0;
+
+       mx.lock();
+
+       ret = cv.timedwait(mx.pMutex(), 25);
+
+       if (ret == ETIMEDOUT) {
+               MSG_DEBUG("WARNING: DEVICE STATUS TIME-OUT");
+               devStatus = false;
+               bNeedInitConfig = true;
+       }
+       mx.unlock();
+       return devStatus;
+}
+
+void SmsPluginEventHandler::setNeedInitConfig(bool bNeeded)
+{
+       bNeedInitConfig = bNeeded;
+}
+
+bool SmsPluginEventHandler::getNeedInitConfig()
+{
+       return bNeedInitConfig;
+}
+
+msg_encode_type_t SmsPluginEventHandler::getEncodeType(sms_encoding_type_t encode_type)
+{
+       switch(encode_type) {
+               case SMS_ENCODE_IA5 :
+               case SMS_ENCODE_GSM7BIT :
+                       return MSG_ENCODE_GSM7BIT;
+               case SMS_ENCODE_KOREAN :
+               case SMS_ENCODE_EUCKR :
+                       return MSG_ENCODE_EUCKR;
+               case SMS_ENCODE_7BIT_ASCII :
+               case SMS_ENCODE_LATIN_HEBREW :
+               case SMS_ENCODE_LATIN :
+               case SMS_ENCODE_OCTET :
+                       return MSG_ENCODE_8BIT;
+               case SMS_ENCODE_SHIFT_JIS :
+                       return MSG_ENCODE_SHIFT_JIS;
+//             case SMS_ENCODE_EPM :
+//             case SMS_ENCODE_UNICODE :
+//             case SMS_ENCODE_GSMDCS :
+               default :
+                       return MSG_ENCODE_UCS2;
+       }
+
+       return MSG_ENCODE_UCS2;
+}
+
+
+unsigned short SmsPluginEventHandler::checkWapMsg(sms_wap_msg_s *pMsg, sms_telesvc_userdata_s *pUserdata)
+{
+       unsigned char currSegNum = 0;
+
+       bool bFind = false;
+
+       for (unsigned int i = 0; i < wapList.size(); i++) {
+               if (wapList[i].msgId == pMsg->msgId) {
+                       if (wapList[i].data.count(pMsg->segNum) != 0) {
+                               MSG_DEBUG("The Segment Number already exists [%d]", pMsg->segNum);
+                               return 0;
+                       }
+                       wap_data_s wapData = {0};
+
+                       memcpy(wapData.data, pUserdata->user_data, pUserdata->data_len);
+                       wapData.length = pUserdata->data_len;
+
+                       pair<unsigned char, wap_data_s> newData(pMsg->segNum, wapData);
+                       wapList[i].data.insert(newData);
+
+                       MSG_DEBUG("MSG DATA : %s", pUserdata->user_data);
+                       MSG_DEBUG("PAIR DATA [%d] : %s", newData.first, newData.second.data);
+                       MSG_DEBUG("DATA SIZE [%d]", pUserdata->data_len);
+
+                       wapList[i].segNum++;
+                       wapList[i].totalSize += pUserdata->data_len;
+                       currSegNum = wapList[i].segNum;
+
+                       bFind = true;
+
+                       break;
+               }
+       }
+
+       /** New Wap Push Msg */
+       if (bFind == false) {
+               sms_wap_info_s tmpInfo;
+               tmpInfo.msgId = pMsg->msgId;
+               tmpInfo.totalSeg = pMsg->totalSeg;
+               tmpInfo.segNum = 1;
+
+               tmpInfo.totalSize = pUserdata->data_len;
+
+               wap_data_s wapData = {0};
+
+               memcpy(wapData.data, pUserdata->user_data, pUserdata->data_len);
+               wapData.length = pUserdata->data_len;
+
+               pair<unsigned char, wap_data_s> newData(pMsg->segNum, wapData);
+               tmpInfo.data.insert(newData);
+
+               MSG_DEBUG("MSG DATA : %s", pUserdata->user_data);
+               MSG_DEBUG("PAIR DATA [%d] : %s", newData.first, newData.second.data);
+               MSG_DEBUG("DATA SIZE [%d]", pUserdata->data_len);
+
+               wapList.push_back(tmpInfo);
+
+               currSegNum = tmpInfo.segNum;
+       }
+
+       return currSegNum;
+}
+
+
+int SmsPluginEventHandler::MakeWapUserData(unsigned short msgId, char **ppTotalData)
+{
+       wapDataMap::iterator it;
+
+       int totalSize = 0, offset = 0;
+
+       for (unsigned int i = 0; i < wapList.size(); i++) {
+               if (wapList[i].msgId == msgId) {
+                       totalSize = wapList[i].totalSize;
+
+                       if (totalSize <= 0) {
+                               MSG_DEBUG("Size Error : totalSize <= 0");
+                               return 0;
+                       }
+
+                       MSG_DEBUG("totalSize [%d]", totalSize);
+
+                       *ppTotalData = new char[totalSize];
+
+                       for (it = wapList[i].data.begin(); it != wapList[i].data.end(); it++) {
+                               memcpy(*ppTotalData+offset, it->second.data, it->second.length);
+                               offset += it->second.length;
+                       }
+               }
+       }
+
+       return totalSize;
+
+}
+
+
+void SmsPluginEventHandler::handleSyncMLMsgIncoming(msg_syncml_message_type_t msgType, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen)
+{
+       MSG_SYNCML_MESSAGE_DATA_S syncMLData;
+
+       memset(&syncMLData, 0x00, sizeof(MSG_SYNCML_MESSAGE_DATA_S));
+
+       /** set syncML data */
+       syncMLData.syncmlType = msgType;
+
+       syncMLData.pushBodyLen = PushBodyLen;
+       memcpy(syncMLData.pushBody, pPushBody, PushBodyLen);
+
+       syncMLData.wspHeaderLen= WspHeaderLen;
+       memcpy(syncMLData.wspHeader, pWspHeader, WspHeaderLen);
+
+       /** Callback to MSG FW */
+       listener.pfSyncMLMsgIncomingCb(&syncMLData);
+}
+
+
+void SmsPluginEventHandler::handleLBSMsgIncoming(char* pPushHeader, char* pPushBody, int pushBodyLen)
+{
+       MSG_LBS_MESSAGE_DATA_S lBSData;
+
+       memset(&lBSData, 0x00, sizeof(MSG_LBS_MESSAGE_DATA_S));
+
+       /** set LBA data */
+       memcpy(lBSData.pushHeader, pPushHeader, strlen(pPushHeader));
+
+       lBSData.pushBodyLen = pushBodyLen;
+       memcpy(lBSData.pushBody, pPushBody, pushBodyLen);
+
+       /** Callback to MSG FW */
+       listener.pfLBSMsgIncomingCb(&lBSData);
+}
+
+
+void SmsPluginEventHandler::handlePushMsgIncoming(char* pPushHeader, char* pPushBody, int pushBodyLen, char *application_id, char *content_type)
+{
+       MSG_PUSH_MESSAGE_DATA_S pushData;
+
+       memset(&pushData, 0x00, sizeof(MSG_PUSH_MESSAGE_DATA_S));
+
+       /** set PUSH data */
+       memcpy(pushData.pushHeader, pPushHeader, strlen(pPushHeader));
+
+       pushData.pushBodyLen = pushBodyLen;
+       memcpy(pushData.pushBody, pPushBody, pushBodyLen);
+
+       memcpy(pushData.pushAppId, application_id, MAX_WAPPUSH_ID_LEN);
+       memcpy(pushData.pushContentType, content_type, MAX_WAPPUSH_CONTENT_TYPE_LEN);
+
+       /** Callback to MSG FW */
+       listener.pfPushMsgIncomingCb(&pushData);
+}
+
+
+bool SmsPluginEventHandler::checkCbOpt(sms_trans_svc_ctg_t svc_ctg)
+{
+       bool bReceive = false;
+       MsgSettingGetBool(CB_RECEIVE, &bReceive);
+
+       // Receive CB Msg = FALSE
+       if (!bReceive)
+       {
+               MSG_DEBUG("RECEIVE CB = FALSE");
+               return false;
+       }
+
+       if (svc_ctg >= SMS_TRANS_SVC_CTG_CMAS_PRESIDENTIAL && svc_ctg <= SMS_TRANS_SVC_CTG_CMAS_TEST) {
+               bool bActivate = false;
+               short Category = 0;
+               MSG_CB_CHANNEL_S cbChannelInfo = {0,};
+               msg_error_t err = MSG_SUCCESS;
+               MsgDbHandler *dbHandle = getDbHandle();
+
+               err = MsgStoGetCBChannelInfo(dbHandle, &cbChannelInfo);
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("Error value of MsgStoGetCBChannelInfo [%d]", err);
+                       return false;
+               }
+
+               for (int i = 0; i < cbChannelInfo.channelCnt; i++)
+               {
+                       bActivate = cbChannelInfo.channelInfo[i].bActivate;
+                       Category = cbChannelInfo.channelInfo[i].ctg;
+
+                       if (bActivate == true && svc_ctg == Category)
+                       {
+                               MSG_DEBUG("FIND CHANNEL = [%d]", svc_ctg);
+                               return true;
+                       }
+               }
+
+               return false;
+       }
+
+       return true;
+}
diff --git a/plugin/sms_cdma_plugin/SmsCdmaPluginMain.cpp b/plugin/sms_cdma_plugin/SmsCdmaPluginMain.cpp
new file mode 100755 (executable)
index 0000000..22c3b4b
--- /dev/null
@@ -0,0 +1,442 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <errno.h>
+
+#include "MsgDebug.h"
+#include "MsgException.h"
+#include "MsgGconfWrapper.h"
+
+#include "MsgMutex.h"
+#include "SmsCdmaPluginTransport.h"
+#include "SmsCdmaPluginStorage.h"
+#include "SmsCdmaPluginCallback.h"
+#include "SmsCdmaPluginEventHandler.h"
+#include "SmsCdmaPluginUAManager.h"
+#include "SmsCdmaPluginSetting.h"
+#include "SmsCdmaPluginMain.h"
+#include <gio/gio.h>
+
+extern "C"
+{
+       #include <tapi_common.h>
+       #include <TelSms.h>
+       #include <TapiUtility.h>
+       #include <ITapiSim.h>
+       #include <ITapiNetText.h>
+}
+
+#define BUS_NAME "org.tizen.system.deviced"
+#define PATH_NAME "/Org/Tizen/System/DeviceD/Lowmem"
+#define INTERFACE_NAME BUS_NAME".lowmem"
+#define MEMBER_NAME "Full"
+
+struct tapi_handle *pTapiHandle = NULL;
+bool isMemAvailable = true;
+
+GDBusConnection *gdbus_conn = NULL;
+GDBusProxy *gdbus_proxy = NULL;
+gint subs_id = 0;
+
+Mutex mx;
+CndVar cv;
+
+
+void MsgResourceMonitorInit(void);
+void MsgResourceMonitorDeinit(void);
+
+/*==================================================================================================
+                                FUNCTION IMPLEMENTATION
+==================================================================================================*/
+
+static void MsgTapiInitCB(keynode_t *key, void* data)
+{
+       MSG_DEBUG("MsgTapiInitCB is called.");
+       mx.lock();
+       cv.signal();
+       mx.unlock();
+}
+
+msg_error_t MsgPlgCreateHandle(MSG_PLUGIN_HANDLER_S *pPluginHandle)
+{
+       if (pPluginHandle == NULL)
+       {
+               MSG_DEBUG("SMS plugin: create handler error ");
+               return MSG_ERR_NULL_POINTER;
+       }
+       else
+       {
+               pPluginHandle->pfInitialize = SmsPlgInitialize;
+               pPluginHandle->pfFinalize = SmsPlgFinalize;
+               pPluginHandle->pfRegisterListener = SmsPlgRegisterListener;
+               pPluginHandle->pfSubmitRequest = SmsPlgSubmitRequest;
+               pPluginHandle->pfSaveSimMessage = SmsPlgSaveSimMessage;
+               pPluginHandle->pfDeleteSimMessage = SmsPlgDeleteSimMessage;
+               pPluginHandle->pfSetReadStatus = SmsPlgSetReadStatus;
+               pPluginHandle->pfSetMemoryStatus = SmsPlgSetMemoryStatus;
+               pPluginHandle->pfSetConfigData = SmsPlgSetConfigData;
+               pPluginHandle->pfGetConfigData = SmsPlgGetConfigData;
+               pPluginHandle->pfAddMessage = SmsPlgAddMessage;
+
+               MSG_DEBUG("SMS plugin: create handler OK");
+               MSG_DEBUG ("SMS plugin %p", pPluginHandle);
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgPlgDestroyHandle(MSG_PLUGIN_HANDLER_S *pPluginHandle)
+{
+       if (pPluginHandle != NULL)
+       {
+               free(pPluginHandle);
+               pPluginHandle = NULL;
+       }
+
+       MSG_DEBUG("SMS plugin: destory handler OK");
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgInitialize()
+{
+       MSG_BEGIN();
+
+       bool bReady = false;
+
+       for (int i = 0; i < 100; i++) {
+               MsgSettingGetBool(VCONFKEY_TELEPHONY_READY, &bReady);
+               MSG_DEBUG("Get VCONFKEY_TELEPHONY_READY [%d].", bReady ? 1 : 0);
+
+               if(bReady)
+                       break;
+
+               sleep(1);
+       }
+
+       if (!bReady) {
+               MSG_DEBUG("Fail to wait telephony init complete.");
+               return MSG_ERR_PLUGIN_TAPIINIT;
+       }
+
+       pTapiHandle = tel_init(NULL);
+
+       if (pTapiHandle) {
+               // register event.
+               SmsPluginCallback::instance()->registerEvent();
+
+               // set sim change status.
+               MSG_DEBUG("Try to initialize SIM on init");
+               SmsPluginSetting::instance()->setSimChangeStatus();
+
+               // set resource monitor
+               MsgResourceMonitorInit();
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgFinalize()
+{
+       MSG_BEGIN();
+
+       MsgResourceMonitorDeinit();
+
+       if (!pTapiHandle)
+               return MSG_ERR_PLUGIN_TAPIINIT;
+
+       SmsPluginCallback::instance()->deRegisterEvent();
+
+       tel_deinit(pTapiHandle);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgRegisterListener(MSG_PLUGIN_LISTENER_S *pListener)
+{
+       MSG_BEGIN();
+
+       SmsPluginEventHandler::instance()->registerListener(pListener);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgSubmitRequest(MSG_REQUEST_INFO_S *pReqInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       // Add Submit SMS into DB
+       if (pReqInfo->msgInfo.msgId == 0) {
+               if (pReqInfo->msgInfo.msgPort.valid == false) {
+
+                       err = SmsPluginStorage::instance()->checkMessage(&(pReqInfo->msgInfo));
+
+                       if (err != MSG_SUCCESS) {
+                               MSG_DEBUG("########  checkMessage Fail !! [err=%d]", err);
+                               return MSG_ERR_PLUGIN_STORAGE;
+                       }
+
+                       err = SmsPluginStorage::instance()->addSmsMessage(&(pReqInfo->msgInfo));
+                       if (err != MSG_SUCCESS) {
+                               MSG_DEBUG("########  addSmsMessage Fail !! [err=%d]", err);
+                               return MSG_ERR_PLUGIN_STORAGE;
+                       }
+
+                       if (SmsPluginStorage::instance()->addSmsSendOption(&(pReqInfo->msgInfo), &(pReqInfo->sendOptInfo)) != MSG_SUCCESS) {
+                               MSG_DEBUG("########  addSmsSendOption Fail !!");
+                               return MSG_ERR_PLUGIN_STORAGE;
+                       }
+               }
+       }
+
+       // Check SIM is present or not
+//     MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
+//
+//     if (simStatus == MSG_SIM_STATUS_NOT_FOUND)
+//     {
+//             MSG_DEBUG("SIM is not present..");
+//
+//             // Update Msg Status
+//             if (pReqInfo->msgInfo.msgPort.valid == false)
+//                     SmsPluginStorage::instance()->updateSentMsg(&(pReqInfo->msgInfo), MSG_NETWORK_SEND_FAIL);
+//
+//             return MSG_ERR_NO_SIM;
+//     }
+
+       sms_request_info_s *request = NULL;
+
+       request = (sms_request_info_s *)calloc(1, sizeof(sms_request_info_s));
+
+       if (request != NULL) {
+               request->reqId = pReqInfo->reqId;
+
+               memcpy(&(request->msgInfo), &(pReqInfo->msgInfo), sizeof(MSG_MESSAGE_INFO_S));
+               memcpy(&(request->sendOptInfo), &(pReqInfo->sendOptInfo), sizeof(MSG_SENDINGOPT_INFO_S));
+
+               /* Add Request into Queue and Start UA Manger */
+               SmsPluginUAManager::instance()->addReqEntity(request);
+
+               free(request);
+       }
+
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgSaveSimMessage(const MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList)
+{
+       MSG_DEBUG("CDMA does not support sim card operations.");
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgDeleteSimMessage(msg_sim_id_t SimMsgId)
+{
+       MSG_DEBUG("CDMA does not support sim card operations.");
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgSetReadStatus(msg_sim_id_t SimMsgId)
+{
+       MSG_DEBUG("CDMA does not support sim card operations.");
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgSetMemoryStatus(msg_error_t Error)
+{
+
+       int tapiRet = TAPI_API_SUCCESS;
+       int status = TAPI_NETTEXT_PDA_MEMORY_STATUS_AVAILABLE;
+
+       if (Error == MSG_ERR_SIM_STORAGE_FULL || Error == MSG_ERR_MESSAGE_COUNT_FULL)
+       {
+               status = TAPI_NETTEXT_PDA_MEMORY_STATUS_FULL;
+       }
+
+       MSG_DEBUG("Set Status : [%d]", status);
+
+       tapiRet = tel_set_sms_memory_status(pTapiHandle, status, TapiEventMemoryStatus, NULL);
+
+       if (tapiRet == TAPI_API_SUCCESS)
+       {
+               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
+       }
+       else
+       {
+               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! return : [%d] #######", tapiRet);
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgSetConfigData(const MSG_SETTING_S *pSetting)
+{
+       try
+       {
+               SmsPluginSetting::instance()->setConfigData(pSetting);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_SETTING;
+       }
+       catch (exception& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_SETTING;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgGetConfigData(MSG_SETTING_S *pSetting)
+{
+       try
+       {
+               SmsPluginSetting::instance()->getConfigData(pSetting);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_SETTING;
+       }
+       catch (exception& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_SETTING;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgAddMessage(MSG_MESSAGE_INFO_S *pMsgInfo,  MSG_SENDINGOPT_INFO_S* pSendOptInfo, char* pFileData)
+{
+       MSG_DEBUG("CDMA does not support sim card operations.");
+       return MSG_SUCCESS;
+}
+
+static void on_change_received(GDBusConnection *connection, const gchar *sender_name,
+               const gchar *object_path, const gchar *interface_name, const gchar *signal_name,
+               GVariant *parameters, gpointer user_data)
+{
+       MSG_DEBUG("signal_name = [%s]", signal_name);
+
+       if (g_strcmp0(signal_name, MEMBER_NAME) == 0) {
+               gint memStatus;
+               g_variant_get(parameters, "(i)", &memStatus);
+               MSG_DEBUG("memStatus = [%d]", memStatus);
+               if(memStatus == 0) {
+                       SmsPlgSetMemoryStatus(MSG_SUCCESS);
+               }
+       }
+}
+
+void MsgResourceMonitorInit(void)
+{
+    MSG_BEGIN();
+
+       GError *error = NULL;
+
+       if (gdbus_conn) {
+               g_object_unref(gdbus_conn);
+               gdbus_conn = NULL;
+       }
+
+       gdbus_conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
+       if (error) {
+               MSG_FATAL("g_bus_get_sync() failed : %s", error->message);
+               g_error_free(error);
+               error = NULL;
+               goto _DBUS_ERROR;
+       }
+
+       if (gdbus_proxy) {
+               g_object_unref(gdbus_proxy);
+               gdbus_proxy = NULL;
+       }
+
+       gdbus_proxy = g_dbus_proxy_new_sync(gdbus_conn, G_DBUS_PROXY_FLAGS_NONE,
+                                                       NULL, BUS_NAME, PATH_NAME, INTERFACE_NAME, NULL, &error);
+       if (error) {
+               MSG_FATAL("g_dbus_proxy_new_sync() failed : %s", error->message);
+               g_error_free(error);
+               error = NULL;
+               goto _DBUS_ERROR;
+       }
+
+       subs_id = g_dbus_connection_signal_subscribe(gdbus_conn, NULL,
+                                                       INTERFACE_NAME, MEMBER_NAME, PATH_NAME,
+                                                       NULL, G_DBUS_SIGNAL_FLAGS_NONE,
+                                                       on_change_received,
+                                                       NULL, NULL);
+       MSG_END();
+       return;
+
+_DBUS_ERROR:
+       if (gdbus_conn) {
+               g_object_unref(gdbus_conn);
+               gdbus_conn = NULL;
+       }
+
+       if (gdbus_proxy) {
+               g_object_unref(gdbus_proxy);
+               gdbus_proxy = NULL;
+       }
+
+       MSG_END();
+       return;
+
+}
+
+
+void MsgResourceMonitorDeinit(void)
+{
+       MSG_BEGIN();
+
+       if (subs_id) {
+               g_dbus_connection_signal_unsubscribe(gdbus_conn, subs_id);
+               subs_id = 0;
+       }
+
+       if (gdbus_conn) {
+               g_object_unref(gdbus_conn);
+               gdbus_conn = NULL;
+       }
+
+       if (gdbus_proxy) {
+               g_object_unref(gdbus_proxy);
+               gdbus_proxy = NULL;
+       }
+
+       MSG_END();
+}
diff --git a/plugin/sms_cdma_plugin/SmsCdmaPluginParamCodec.cpp b/plugin/sms_cdma_plugin/SmsCdmaPluginParamCodec.cpp
new file mode 100755 (executable)
index 0000000..e1885b2
--- /dev/null
@@ -0,0 +1,240 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <stdio.h>
+#include <string.h>
+
+#include "SmsCdmaPluginParamCodec.h"
+
+
+/*==================================================================================================
+                               IMPLEMENTATION OF SmsCdmaPluginParamCodec - Member Functions
+==================================================================================================*/
+SmsPluginParamCodec* SmsPluginParamCodec::pInstance = NULL;
+
+
+SmsPluginParamCodec::SmsPluginParamCodec()
+{
+
+
+}
+
+
+SmsPluginParamCodec::~SmsPluginParamCodec()
+{
+
+
+}
+
+SmsPluginParamCodec* SmsPluginParamCodec::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginParamCodec();
+
+       return pInstance;
+}
+
+
+
+/*==================================================================================================
+                                     Util Functions
+==================================================================================================*/
+int SmsPluginParamCodec::convertDigitToBcd(char *pDigit, int DigitLen, unsigned char *pBcd)
+{
+       int offset = 0;
+       unsigned char temp;
+
+       for (int i = 0; i < DigitLen; i++) {
+               if (pDigit[i] == '*')
+                       temp = 0x0A;
+               else if (pDigit[i] == '#')
+                       temp = 0x0B;
+               else if (pDigit[i] == 'P' || pDigit[i] == 'p')
+                       temp = 0x0C;
+               else
+                       temp = pDigit[i] - '0';
+
+               if ((i % 2) == 0)
+                       pBcd[offset] = temp & 0x0F;
+               else
+                       pBcd[offset++] |= ((temp & 0x0F) << 4);
+       }
+
+       if ((DigitLen % 2) == 1) {
+               pBcd[offset++] |= 0xF0;
+       }
+
+       return offset;
+}
+
+int SmsPluginParamCodec::convertBcdToDigit(const unsigned char *pBcd, int BcdLen, char *pDigit)
+{
+       int offset = 0;
+       unsigned char temp;
+
+       for (int i = 0; i < BcdLen; i++) {
+               temp = pBcd[i] & 0x0F;
+
+               if (temp == 0x0A)
+                       pDigit[offset++] = '*';
+               else if (temp == 0x0B)
+                       pDigit[offset++] = '#';
+               else if (temp == 0x0C)
+                       pDigit[offset++] = 'P';
+               else
+                       pDigit[offset++] = temp + '0';
+
+               temp = (pBcd[i] & 0xF0) >> 4;
+
+               if (temp == 0x0F) {
+                       pDigit[offset] = '\0';
+                       return offset;
+               }
+
+               if (temp == 0x0A)
+                       pDigit[offset++] = '*';
+               else if (temp == 0x0B)
+                       pDigit[offset++] = '#';
+               else if (temp == 0x0C)
+                       pDigit[offset++] = 'P';
+               else
+                       pDigit[offset++] = temp + '0';
+       }
+
+       pDigit[offset] = '\0';
+
+       return offset;
+}
+
+int SmsPluginParamCodec::convertDigitToDTMF(const char *pDigit, int DigitLen, int startBit, unsigned char *pDtmf)
+{
+       int shift = startBit;
+       int offset = 0;
+       int srcIdx = 0;
+       unsigned char temp;
+
+       if (shift > 7) {
+               MSG_DEBUG("Invalid Param value shift : %d", shift);
+               return 0;
+       }
+       /* shift 1 and shift 2 are supported in this spec. */
+       if (shift >= 4) {
+               MSG_DEBUG("Invalid Param value shift : %d", shift);
+               return 0;
+       }
+
+       for (int i = 0; i < DigitLen; i++) {
+               if (pDigit[srcIdx] == '*')
+                       temp = 0x0B;
+               else if (pDigit[srcIdx] == '#')
+                       temp = 0x0C;
+               else if (pDigit[srcIdx] == '0')
+                       temp = 0x0A;
+               else
+                       temp = pDigit[srcIdx] - '0';
+
+               temp &= 0x0F;
+
+               if (shift == 0) {
+                       if (i % 2 == 1) {
+                               pDtmf[offset] |= temp;
+                               offset++;
+                       } else {
+                               pDtmf[offset] |= temp << 4;
+                       }
+               } else if (shift >= 1 && shift < 4) {
+                       if (i % 2 == 1) {
+                               pDtmf[offset] |= (temp >> shift);
+                               pDtmf[offset + 1] = temp << (8 - shift);
+                               offset++;
+                       } else {
+                               pDtmf[offset] |= (temp << (8 - shift - 4));
+                       }
+               }
+
+               srcIdx++;
+       }
+
+       return offset;
+}
+
+int SmsPluginParamCodec::convertDTMFToDigit(const unsigned char *pDtmf, int DtmfLen, int startBit, char *pDigit)
+{
+       int shift = startBit;
+       int offset = 0;
+       int srcIdx = 0;
+       unsigned char temp = 0;
+
+       if (shift > 7) {
+               MSG_DEBUG("Invalid Param value shift : %d", shift);
+               return 0;
+       }
+       /* shift 1 and shift 2 are supported in this spec. */
+       if (shift >= 4) {
+               MSG_DEBUG("Invalid Param value shift : %d", shift);
+               return 0;
+       }
+
+       for (int i = 0; i < DtmfLen; i++) {
+               if (shift == 0) {
+                       if (i % 2 == 1) {
+                               temp = pDtmf[srcIdx] & 0x0F;
+                               srcIdx++;
+                       } else {
+                               temp = (pDtmf[srcIdx] >> 4) & 0x0F;
+                       }
+               } else if (shift >= 1 && shift < 4) {
+                       if (i % 2 == 1) {
+                               temp = ((pDtmf[srcIdx] << shift) & 0x0F) + (pDtmf[srcIdx + 1] >> (8 - shift));
+                               srcIdx++;
+                       } else {
+                               temp = (pDtmf[srcIdx] >> (8 - shift - 4)) & 0x0F;
+                       }
+               }
+
+               if (temp == 0x0A)
+                       pDigit[offset++] = '0';
+               else if (temp == 0x0B)
+                       pDigit[offset++] = '*';
+               else if (temp == 0x0C)
+                       pDigit[offset++] = '#';
+               else
+                       pDigit[offset++] = temp + '0';
+       }
+
+       pDigit[offset] = '\0';
+
+       return offset;
+}
+
+bool SmsPluginParamCodec::isDtmfNumber(const char *pDigit, int DigitLen)
+{
+       bool isDtmf = true;
+
+       for (int i = 0; i < DigitLen; i++) {
+               if (!((pDigit[i] >= '0' && pDigit[i] <= '9') ||
+                       pDigit[i] == '*' ||
+                       pDigit[i] == '#')) {
+                       isDtmf = false;
+                       break;
+               }
+       }
+
+       return isDtmf;
+}
+
+
+
diff --git a/plugin/sms_cdma_plugin/SmsCdmaPluginSetting.cpp b/plugin/sms_cdma_plugin/SmsCdmaPluginSetting.cpp
new file mode 100755 (executable)
index 0000000..14b1cbb
--- /dev/null
@@ -0,0 +1,683 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <errno.h>
+#include <pthread.h>
+
+#include "MsgDebug.h"
+#include "MsgCppTypes.h"
+#include "MsgException.h"
+#include "MsgGconfWrapper.h"
+
+#ifndef MSG_NOTIFICATION_NOT_SUPPORTED
+#include "MsgNotificationWrapper.h"
+#endif
+
+#include "MsgSoundPlayer.h"
+#include "MsgContact.h"
+#include "MsgUtilStorage.h"
+#include "MsgTextConvert.h"
+
+#include "SmsCdmaPluginParamCodec.h"
+#include "SmsCdmaPluginCallback.h"
+#include "SmsCdmaPluginEventHandler.h"
+#include "SmsCdmaPluginMain.h"
+#include "SmsCdmaPluginSetting.h"
+
+
+extern "C"
+{
+       #include <tapi_common.h>
+       #include <TelSms.h>
+       #include <TapiUtility.h>
+       #include <ITapiNetText.h>
+       #include <ITapiSim.h>
+       #include <ITapiModem.h>
+}
+
+extern struct tapi_handle *pTapiHandle;
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginSetting - Member Functions
+==================================================================================================*/
+SmsPluginSetting* SmsPluginSetting::pInstance = NULL;
+
+
+SmsPluginSetting::SmsPluginSetting()
+{
+       // Initialize member variables
+       memset(&cbOpt, 0x00, sizeof(MSG_CBMSG_OPT_S));
+       memset(&meImei, 0x00, sizeof(meImei));
+
+       bTapiResult = false;
+       bUpdateVoicemailByMdn = false;
+}
+
+
+SmsPluginSetting::~SmsPluginSetting()
+{
+
+
+}
+
+
+SmsPluginSetting* SmsPluginSetting::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginSetting();
+
+       return pInstance;
+}
+
+
+void* SmsPluginSetting::initSimInfo(void *data)
+{
+       MSG_BEGIN();
+
+       int tapiRet = TAPI_API_SUCCESS;
+
+       // Get IMSI
+       char imsi[17];
+       memset(imsi, 0x00, sizeof(imsi));
+
+       // Get IMSI
+       TelSimImsiInfo_t imsiInfo;
+       memset(&imsiInfo, 0x00, sizeof(TelSimImsiInfo_t));
+
+       tapiRet = tel_get_sim_imsi(pTapiHandle, &imsiInfo);
+
+       if (tapiRet == TAPI_API_SUCCESS) {
+               MSG_SEC_DEBUG("tel_get_sim_imsi() Success - MCC [%s], MNC [%s], MSIN [%s]", imsiInfo.szMcc, imsiInfo.szMnc, imsiInfo.szMsin);
+               snprintf(imsi, sizeof(imsi), "%03d%03d%s", atoi(imsiInfo.szMcc), atoi(imsiInfo.szMnc), imsiInfo.szMsin);
+               MSG_SEC_DEBUG("IMSI [%s]", imsi);
+       } else {
+               MSG_DEBUG("tel_get_sim_imsi() Error![%d]", tapiRet);
+               MsgSettingSetBool(MSG_NATIONAL_SIM, false);
+       }
+
+       MsgSettingSetString(MSG_SIM_IMSI, imsi);
+
+       instance()->updateSimStatus();
+
+       MSG_END();
+       return NULL;
+}
+
+void SmsPluginSetting::updateSimStatus()
+{
+       MSG_BEGIN();
+
+       if (!pTapiHandle) {
+               MSG_DEBUG("pTapiHandle is NULL.");
+               return;
+       }
+
+       int status = 0;
+       int tapiRet = TAPI_API_SUCCESS;
+
+       tapiRet = tel_check_sms_device_status(pTapiHandle, &status);
+
+       if (tapiRet != TAPI_API_SUCCESS) {
+               MSG_DEBUG("tel_check_sms_device_status() Error! [%d], Status [%d]", tapiRet, status);
+               return;
+       }
+
+       if (status == 1 || status == 2) {
+               MSG_DEBUG("Device Is Ready, status = %d", status);
+               SmsPluginEventHandler::instance()->setNeedInitConfig(false);
+       } else if (status == 0) {
+               MSG_DEBUG("Device Is Not Ready.. Waiting For Ready Callback");
+
+               if (SmsPluginEventHandler::instance()->getDeviceStatus() == true) {
+                       MSG_DEBUG("Device Is Ready");
+               } else {
+                       MSG_DEBUG("Device Is Not Ready.");
+                       return;
+               }
+       }
+
+       // init config data.
+       initConfigData();
+
+       MSG_END();
+
+       return;
+}
+
+
+void SmsPluginSetting::setSimChangeStatus()
+{
+       MSG_BEGIN();
+
+       pthread_t thd;
+
+       if(pthread_create(&thd, NULL, &initSimInfo, NULL) < 0) {
+               MSG_DEBUG("pthread_create() error");
+       }
+
+       pthread_detach(thd);
+
+       MSG_END();
+}
+
+
+
+void SmsPluginSetting::initConfigData()
+{
+       MSG_BEGIN();
+
+       msg_error_t     err = MSG_SUCCESS;
+
+#if 1
+       /*==================== CB configuration ====================*/
+//     if (simStatus != MSG_SIM_STATUS_NOT_FOUND)
+//     {
+//             MSG_DEBUG("simStatus == [%d]", simStatus);
+
+               MSG_CBMSG_OPT_S cbMsgOpt = {0,};
+
+               if (getCbConfig(&cbMsgOpt) == true) {
+                       err = addCbOpt(&cbMsgOpt);
+
+                       if (err == MSG_SUCCESS) {
+                               MSG_DEBUG("########  Add CB Option Success !!! #######");
+                               MSG_SETTING_S cbSetting;
+                               cbSetting.type = MSG_CBMSG_OPT;
+                               getCbOpt(&cbSetting);
+                               setCbConfig(&(cbSetting.option.cbMsgOpt));
+                       } else {
+                               MSG_DEBUG("########  Add CB Option Fail !!! return : %d #######", err);
+                       }
+               } else {
+                       MSG_DEBUG("########  getCbConfig Fail !!! #######");
+#endif
+
+#if 0
+                       // CSC doesn't support CB Info any longer
+                       if (MsgCscGetCBInfo(&cbMsgOpt) == true) {
+                               err = addCbOpt(&cbMsgOpt);
+
+                               if (err == MSG_SUCCESS) {
+                                       MSG_DEBUG("########  Add CB Option From CSC Success !!! #######");
+                               } else {
+                                       MSG_DEBUG("########  Add CB Option from CSC Fail !!! return : %d #######", err);
+                               }
+                       } else {
+                               MSG_DEBUG("########  MsgCscGetCBInfo Fail !!! #######");
+                       }
+#endif
+               }
+
+               /*==================== MSISDN update ====================*/
+               if (getMsisdnInfo() == true) {
+                       MSG_DEBUG("########  getMsisdnInfo Success !!! #######");
+               } else {
+                       MSG_DEBUG("########  getMsisdnInfo Fail !!! #######");
+               }
+#if 1
+               /*==================== Default Voice mail Setting ====================*/
+               char *num = MsgSettingGetString(VOICEMAIL_DEFAULT_NUMBER);
+
+               if (num) {
+                       MSG_DEBUG("Voicemail Default Number [%s]", num);
+                       if (MsgSettingSetString(VOICEMAIL_NUMBER, num) != MSG_SUCCESS)
+                               MSG_DEBUG("MsgSettingSetInt is failed!!");
+                       free(num);
+                       num = NULL;
+               }
+               else {
+                       MSG_DEBUG("Voicemail Default Number is NULL");
+                       if (MsgSettingSetString(VOICEMAIL_NUMBER, "") != MSG_SUCCESS)
+                               MSG_DEBUG("MsgSettingSetInt is failed!!");
+               }
+
+               char *voiceNumber = MsgSettingGetString(VOICEMAIL_NUMBER);
+
+               if (!voiceNumber || (voiceNumber && voiceNumber[0] == '\0')) {
+                       MSG_DEBUG("Voice Number is Empty");
+               }
+
+               if (voiceNumber) {
+                       free(voiceNumber);
+                       voiceNumber = NULL;
+               }
+
+               if (MsgSettingSetString(VOICEMAIL_ALPHA_ID, VOICEMAIL_DEFAULT_ALPHA_ID) != MSG_SUCCESS)
+                       MSG_DEBUG("MsgSettingSetString is failed!!");
+#endif
+
+       MSG_END();
+}
+
+
+void SmsPluginSetting::SimRefreshCb()
+{
+       pthread_t thd;
+
+       if(pthread_create(&thd, NULL, &init_config_data, NULL) < 0) {
+               MSG_DEBUG("pthread_create() error");
+       }
+
+       pthread_detach(thd);
+
+}
+
+
+void* SmsPluginSetting::init_config_data(void *data)
+{
+       instance()->initConfigData();
+       return NULL;
+}
+
+
+void SmsPluginSetting::setConfigData(const MSG_SETTING_S *pSetting)
+{
+       MSG_DEBUG("Setting Type : [%d]", pSetting->type);
+
+       switch (pSetting->type)
+       {
+#if 0
+               case MSG_SMS_SENDOPT :
+                       setNetworkMode(&pSetting->option.smsSendOpt);
+                       break;
+               case MSG_SMSC_LIST :
+                       setParamList(&pSetting->option.smscList);
+                       break;
+#endif
+               case MSG_VOICEMAIL_OPT:
+                       setVoiceMailInfo(&pSetting->option.voiceMailOpt);
+                       break;
+
+               case MSG_CBMSG_OPT :
+                       setCbConfig(&pSetting->option.cbMsgOpt);
+                       break;
+               default :
+                       THROW(MsgException::SMS_PLG_ERROR, "The Setting type is not supported. [%d]", pSetting->type);
+                       break;
+       }
+}
+
+
+void SmsPluginSetting::getConfigData(MSG_SETTING_S *pSetting)
+{
+       MSG_DEBUG("Setting Type : [%d]", pSetting->type);
+
+       switch (pSetting->type)
+       {
+#if 0
+               case MSG_SMSC_LIST :
+                       getParamList(&pSetting->option.smscList);
+               break;
+#endif
+               case MSG_CBMSG_OPT :
+                       getCbConfig(&pSetting->option.cbMsgOpt);
+               break;
+
+               default :
+                       THROW(MsgException::SMS_PLG_ERROR, "The Setting type is not supported. [%d]", pSetting->type);
+               break;
+       }
+}
+
+
+msg_error_t SmsPluginSetting::addCbOpt(MSG_CBMSG_OPT_S *pCbOpt)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+//     MSG_DEBUG("Receive [%d], Max SIM Count [%d]", pCbOpt->bReceive, pCbOpt->maxSimCnt);
+
+       MSG_DEBUG("Receive [%d], Channel Count [%d]", pCbOpt->bReceive, pCbOpt->channelData.channelCnt);
+
+       for (int i = 0; i < pCbOpt->channelData.channelCnt; i++)
+       {
+               MSG_DEBUG("Channel Category [%d], Channel Language [%d]", pCbOpt->channelData.channelInfo[i].ctg, pCbOpt->channelData.channelInfo[i].lang);
+       }
+
+#if 0
+       // Set Setting Data into Vconf
+       if (MsgSettingSetBool(CB_RECEIVE, pCbOpt->bReceive) != MSG_SUCCESS) {
+               MSG_DEBUG("Error to set config data [%s]", CB_RECEIVE);
+               return MSG_ERR_SET_SETTING;
+       }
+#endif
+
+#if 0
+       if (MsgSettingSetInt(CB_MAX_SIM_COUNT, pCbOpt->maxSimCnt) != MSG_SUCCESS) {
+               MSG_DEBUG("Error to set config data [%s]", CB_MAX_SIM_COUNT);
+               return MSG_ERR_SET_SETTING;
+       }
+#endif
+
+#if 0
+       MsgDbHandler dbHandle;
+       err = MsgStoAddCBChannelInfo(&dbHandle, &pCbOpt->channelData);
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("MsgStoGetCBChannelInfo is failed [%d]", err);
+               return MSG_ERR_SET_SETTING;
+       }
+#endif
+
+       return err;
+}
+
+
+void SmsPluginSetting::getCbOpt(MSG_SETTING_S *pSetting)
+{
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler dbHandle;
+
+       memset(&(pSetting->option.cbMsgOpt), 0x00, sizeof(MSG_CBMSG_OPT_S));
+
+       MsgSettingGetBool(CB_RECEIVE, &pSetting->option.cbMsgOpt.bReceive);
+
+//     pSetting->option.cbMsgOpt.maxSimCnt = MsgSettingGetInt(CB_MAX_SIM_COUNT);
+
+       err = MsgStoGetCBChannelInfo(&dbHandle, &pSetting->option.cbMsgOpt.channelData);
+       MSG_DEBUG("MsgStoAddCBChannelInfo : err=[%d]", err);
+
+#if 0
+       char keyName[128];
+
+       for (int i = MSG_CBLANG_TYPE_ALL; i < MSG_CBLANG_TYPE_MAX; i++) {
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", CB_LANGUAGE, i);
+
+               MsgSettingGetBool(keyName, &pSetting->option.cbMsgOpt.bLanguage[i]);
+       }
+#endif
+
+}
+
+void SmsPluginSetting::setVoiceMailInfo(const MSG_VOICEMAIL_OPT_S *pVoiceOpt)
+{
+       bUpdateVoicemailByMdn = false;
+
+       return;
+}
+
+bool SmsPluginSetting::setCbConfig(const MSG_CBMSG_OPT_S *pCbOpt)
+{
+       int ret = TAPI_API_SUCCESS;
+
+#if 1
+       TelSmsCbConfig_t cbConfig = {};
+
+       cbConfig.CBEnabled = (int)pCbOpt->bReceive;
+       cbConfig.Net3gppType = TAPI_NETTEXT_NETTYPE_3GPP2;
+//     cbConfig.MsgIdMaxCount = pCbOpt->maxSimCnt;
+       cbConfig.MsgIdRangeCount = pCbOpt->channelData.channelCnt;
+
+       for (int i = 0; i < cbConfig.MsgIdRangeCount; i++) {
+               cbConfig.MsgIDs[i].Net3gpp2.Selected = (unsigned short)pCbOpt->channelData.channelInfo[i].bActivate;
+               cbConfig.MsgIDs[i].Net3gpp2.CBCategory = (unsigned short)pCbOpt->channelData.channelInfo[i].ctg;
+               cbConfig.MsgIDs[i].Net3gpp2.CBLanguage = (unsigned short)pCbOpt->channelData.channelInfo[i].lang;
+
+               MSG_DEBUG("Category: %d, Language: %d", cbConfig.MsgIDs[i].Net3gpp2.CBCategory, cbConfig.MsgIDs[i].Net3gpp2.CBLanguage);
+       }
+       MSG_DEBUG("CBEnabled: %d, range_count: %d", cbConfig.CBEnabled, cbConfig.MsgIdRangeCount);
+
+       ret = tel_set_sms_cb_config(pTapiHandle, &cbConfig, TapiEventSetConfigData, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_set_sms_cb_config() Success !!! #######");
+       } else {
+               MSG_DEBUG("######## tel_set_sms_cb_config() Fail !!! return : %d #######", ret);
+               return false;
+       }
+
+#if 0
+       if (getResultFromSim() == true) {
+               MSG_DEBUG("######## Set Cb Config was Successful !!! #######");
+       } else {
+               MSG_DEBUG("######## Set Cb Config was Failed !!! #######");
+               return false;
+       }
+#endif
+#endif
+       return true;
+}
+
+
+bool SmsPluginSetting::getCbConfig(MSG_CBMSG_OPT_S *pCbOpt)
+{
+       int ret = TAPI_API_SUCCESS;
+#if 1
+       ret = tel_get_sms_cb_config(pTapiHandle, TapiEventGetCBConfig, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_get_sms_cb_config() Success !!! #######");
+       } else {
+               MSG_DEBUG("######## tel_get_sms_cb_config() Fail !!! return : %d #######", ret);
+               return false;
+       }
+
+       if (getCbConfigEvent(pCbOpt) == true) {
+               MSG_DEBUG("######## Get Cb Config was Successful !!! #######");
+       } else {
+               MSG_DEBUG("######## Get Cb Config was Failed !!! #######");
+               return false;
+       }
+#endif
+       return true;
+}
+
+
+void SmsPluginSetting::getMeImei(char *pImei)
+{
+#if 0
+       int ret = TAPI_API_SUCCESS;
+       ret = tel_get_misc_me_imei(pTapiHandle, TapiEventGetMeImei, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_SEC_DEBUG("######## tel_get_misc_me_imei() Success !!! #######");
+
+               if (getResultImei(pImei) == true) {
+                       MSG_SEC_DEBUG("######## Get ME IMEI was Successful !!! #######");
+               } else {
+                       MSG_SEC_DEBUG("######## Get ME IMEI was Failed !!! #######");
+               }
+       } else {
+               MSG_SEC_DEBUG("######## tel_get_misc_me_imei() Fail !!! return : %d #######", ret);
+       }
+#endif
+}
+
+bool SmsPluginSetting::getUpdateVoicemailByMdn()
+{
+       return bUpdateVoicemailByMdn;
+}
+
+void SmsPluginSetting::setCbConfigEvent(const MSG_CBMSG_OPT_S *pCbOpt, bool bSuccess)
+{
+       mx.lock();
+
+       bTapiResult = bSuccess;
+
+       memset(&cbOpt, 0x00, sizeof(MSG_CBMSG_OPT_S));
+
+       if (bTapiResult == true) {
+               MSG_DEBUG("Success to get cb config data");
+
+               memcpy(&cbOpt, pCbOpt, sizeof(MSG_CBMSG_OPT_S));
+       }
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+
+bool SmsPluginSetting::getCbConfigEvent(MSG_CBMSG_OPT_S *pCbOpt)
+{
+       int ret = 0;
+
+       mx.lock();
+
+       bTapiResult = false;
+       ret = cv.timedwait(mx.pMutex(), 25);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT) {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return false;
+       }
+
+       memset(pCbOpt, 0x00, sizeof(MSG_CBMSG_OPT_S));
+
+       if (bTapiResult == true) {
+               memcpy(pCbOpt, &cbOpt, sizeof(MSG_CBMSG_OPT_S));
+       }
+
+       return bTapiResult;
+}
+
+
+void SmsPluginSetting::setResultImei(bool bResult, char *pImei)
+{
+       mx.lock();
+
+       bTapiResult = bResult;
+
+       memset(&meImei, 0x00, sizeof(meImei));
+
+       if (bTapiResult == true && pImei) {
+               snprintf(meImei, sizeof(meImei), "%s", pImei);
+       }
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+
+bool SmsPluginSetting::getResultImei(char *pImei)
+{
+       int ret = 0;
+
+       mx.lock();
+
+       ret = cv.timedwait(mx.pMutex(), 25);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT) {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return false;
+       }
+
+       if (bTapiResult == true && pImei) {
+               snprintf(pImei, sizeof(meImei), "%s", meImei);
+       }
+
+       return bTapiResult;
+}
+
+
+void SmsPluginSetting::setResultFromEvent(bool bResult)
+{
+       mx.lock();
+
+       bTapiResult = bResult;
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+
+void SmsPluginSetting::setMwiInfo(MSG_SUB_TYPE_T type, int count)
+{
+       MSG_DEBUG("SET MWI INFO, type=[%d]", type);
+       MSG_DEBUG("SET MWI INFO, count=[%d]", count);
+
+       if (MsgSettingSetInt(VOICEMAIL_COUNT, count) != MSG_SUCCESS)
+               MSG_DEBUG("MsgSettingSetInt is failed!!");
+
+//     if (count == 0) {
+//             MsgStoClearUniquenessTable();
+//     }
+
+//     if(count <= 0) {
+//             if (type == MSG_MWI_VOICE_SMS)
+//                     MsgCleanAndResetNotification(MSG_NOTI_TYPE_VOICE_1);
+//             else if (type == MSG_MWI_VOICE2_SMS)
+//                     MsgCleanAndResetNotification(MSG_NOTI_TYPE_VOICE_2);
+//     }
+
+//     if (bMbdnEnable == false) {
+//             MSG_DEBUG("MBDN service is disable.");
+//             return;
+//     }
+
+       return;
+}
+
+
+bool SmsPluginSetting::getMsisdnInfo(void)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_get_sim_msisdn(pTapiHandle, TapiEventGetMsisdnInfo, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_get_sim_msisdn() Success !!! #######");
+       } else {
+               MSG_DEBUG("######## tel_get_sim_msisdn() Fail !!! return : %d #######", ret);
+               return false;
+       }
+
+       if (getResultFromSim() == true) {
+               MSG_DEBUG("######## Get Sim msisdn was Successful !!! #######");
+       } else {
+               MSG_DEBUG("######## Get Sim msisdn was Failed !!! #######");
+               return false;
+       }
+
+       return true;
+}
+
+
+void SmsPluginSetting::setResultFromSim(bool bResult)
+{
+       mx.lock();
+
+       bTapiResult = bResult;
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+
+bool SmsPluginSetting::getResultFromSim()
+{
+       int ret = 0;
+
+       mx.lock();
+
+       ret = cv.timedwait(mx.pMutex(), 25);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT) {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return false;
+       }
+
+       return bTapiResult;
+}
+
diff --git a/plugin/sms_cdma_plugin/SmsCdmaPluginStorage.cpp b/plugin/sms_cdma_plugin/SmsCdmaPluginStorage.cpp
new file mode 100755 (executable)
index 0000000..fb7e693
--- /dev/null
@@ -0,0 +1,672 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include <errno.h>
+
+#include "MsgDebug.h"
+#include "MsgCppTypes.h"
+#include "MsgException.h"
+#include "MsgContact.h"
+#include "MsgUtilFile.h"
+#include "MsgUtilStorage.h"
+#include "MsgUtilFunction.h"
+#include "MsgGconfWrapper.h"
+
+#ifndef MSG_NOTIFICATION_NOT_SUPPORTED
+#include "MsgNotificationWrapper.h"
+#endif
+
+#include "SmsCdmaPluginMain.h"
+#include "SmsCdmaPluginStorage.h"
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginStorage - Member Functions
+==================================================================================================*/
+SmsPluginStorage* SmsPluginStorage::pInstance = NULL;
+
+
+SmsPluginStorage::SmsPluginStorage()
+{
+
+}
+
+
+SmsPluginStorage::~SmsPluginStorage()
+{
+
+}
+
+
+SmsPluginStorage* SmsPluginStorage::instance()
+{
+       if (!pInstance) {
+               MSG_DEBUG("pInstance is NULL. Now creating instance.");
+               pInstance = new SmsPluginStorage();
+       }
+
+       return pInstance;
+}
+
+
+msg_error_t SmsPluginStorage::insertMsgRef(MSG_MESSAGE_INFO_S *pMsg, unsigned char msgRef, int index)
+{
+       MSG_BEGIN();
+
+       time_t curTime = time(NULL);
+
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
+       char *normalNum = NULL;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       normalNum = msg_normalize_number(pMsg->addressList[index].addressVal);
+
+       MSG_SEC_DEBUG("Insert MsgID=[%d], Address=[%s], MsgRef=[%d], Time=[%d]", \
+                       pMsg->msgId, normalNum, (int)msgRef, (int)curTime);
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %s, %d, 0, -1, %d);",
+                       MSGFW_SMS_REPORT_TABLE_NAME, pMsg->msgId, normalNum, (int)msgRef, (int)curTime);
+
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgExecQuery() : [%s]", sqlQuery);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+
+}
+
+
+msg_error_t SmsPluginStorage::updateMsgDeliverStatus(MSG_MESSAGE_INFO_S *pMsgInfo, unsigned char msgRef)
+{
+       MSG_BEGIN();
+
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       msg_message_id_t msgId = 0;
+       int rowCnt = 0;
+       char *normalNum = NULL;
+
+       normalNum = msg_normalize_number(pMsgInfo->addressList[0].addressVal);
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE ADDRESS_VAL = %s AND MSG_REF > 0 ORDER BY TIME ASC;",
+                       MSGFW_SMS_REPORT_TABLE_NAME, normalNum);
+       MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW)
+               msgId = dbHandle->columnInt(0);
+
+       dbHandle->finalizeQuery();
+
+       pMsgInfo->msgId = msgId;
+
+       /** Update Status - MSG_MESSAGE_TABLE */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT * FROM %s WHERE MSG_ID = %d AND MSG_REF > 0;",
+                       MSGFW_SMS_REPORT_TABLE_NAME, msgId);
+
+       if (dbHandle->getTable(sqlQuery, &rowCnt, NULL) != MSG_SUCCESS)
+               return MSG_ERR_DB_GETTABLE;
+
+       MSG_DEBUG("Selected row count = [%d]", rowCnt);
+
+       if (rowCnt == 1 && pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_SUCCESS) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET NETWORK_STATUS = %d WHERE MSG_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, (int)pMsgInfo->networkStatus, msgId);
+               MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+                       return MSG_ERR_DB_EXEC;
+               }
+       }
+
+       /** Update Status - MSG_REPORT_TABLE */
+       if (pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_SUCCESS) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MSG_REF = -1, STATUS = %d, TIME = %d WHERE MSG_ID = %d and ADDRESS_VAL = '%s';",
+                               MSGFW_SMS_REPORT_TABLE_NAME, 1, (int)pMsgInfo->displayTime, msgId, normalNum);
+               MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+                       return MSG_ERR_DB_EXEC;
+               }
+       } else if(pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_EXPIRED) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MSG_REF = -1, STATUS = %d, TIME = %d WHERE MSG_ID = %d and ADDRESS_VAL = '%s';",
+                               MSGFW_SMS_REPORT_TABLE_NAME, 0, (int)pMsgInfo->displayTime, msgId, normalNum);
+               MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+                       return MSG_ERR_DB_EXEC;
+               }
+       } else if(pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_PENDING) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MSG_REF = -1, STATUS = %d, TIME = %d WHERE MSG_ID = %d and ADDRESS_VAL = '%s';",
+                               MSGFW_SMS_REPORT_TABLE_NAME, 3, (int)pMsgInfo->displayTime, msgId, normalNum);
+               MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+                       return MSG_ERR_DB_EXEC;
+               }
+       } else if(pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_FAIL) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MSG_REF = -1, STATUS = %d, TIME = %d WHERE MSG_ID = %d and ADDRESS_VAL = '%s';",
+                               MSGFW_SMS_REPORT_TABLE_NAME, 8, (int)pMsgInfo->displayTime, msgId, normalNum);
+               MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+                       return MSG_ERR_DB_EXEC;
+               }
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPluginStorage::updateSentMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_network_status_t status)
+{
+       MSG_BEGIN();
+
+       if (!pMsgInfo || (pMsgInfo && pMsgInfo->msgId <= 0)) {
+               MSG_DEBUG("Invalid message id");
+               return MSG_ERR_INVALID_MESSAGE_ID;
+       }
+
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       MSG_DEBUG("Update Msg ID : [%d], Network Status : [%d] ", pMsgInfo->msgId, status);
+
+       /** Move Msg to SENTBOX */
+       if (status == MSG_NETWORK_SEND_SUCCESS) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET NETWORK_STATUS = %d, FOLDER_ID = %d WHERE MSG_ID = %d;",
+                                       MSGFW_MESSAGE_TABLE_NAME, status, MSG_SENTBOX_ID, pMsgInfo->msgId);
+       } else {
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET NETWORK_STATUS = %d, READ_STATUS = 0 WHERE MSG_ID = %d;",
+                                       MSGFW_MESSAGE_TABLE_NAME, status, pMsgInfo->msgId);
+       }
+
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgExecQuery() : [%s]", sqlQuery);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       if (status == MSG_NETWORK_SEND_SUCCESS) {
+               MSG_DEBUG("MsgAddPhoneLog() : folderId [%d]", pMsgInfo->folderId);
+               MsgAddPhoneLog(pMsgInfo);
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPluginStorage::checkMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       /**  Check whether storage is full or not */
+       err = checkStorageStatus(pMsgInfo);
+
+       if (err != MSG_SUCCESS) {
+               if (pMsgInfo->msgType.classType == MSG_CLASS_0) {
+                       pMsgInfo->folderId = 0;
+                       err = MSG_SUCCESS;
+               }
+//             else if(pMsgInfo->msgType.classType == MSG_CLASS_2 &&
+//                             (pMsgInfo->msgType.subType == MSG_NORMAL_SMS || pMsgInfo->msgType.subType == MSG_REJECT_SMS)) {
+//                     err = addClass2Message(pMsgInfo);
+//             }
+               else if (pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS){
+                       err = MSG_SUCCESS;
+               }
+               return err;
+       }
+
+       /**  Amend message information for type **/
+       if (pMsgInfo->msgType.subType == MSG_NORMAL_SMS || pMsgInfo->msgType.subType == MSG_REJECT_SMS) {
+               MSG_DEBUG("Normal SMS");
+
+               if (pMsgInfo->msgType.classType == MSG_CLASS_2) {
+//                     err = addClass2Message(pMsgInfo);
+               } else if (pMsgInfo->msgType.classType == MSG_CLASS_0) {
+                       /** Class 0 Msg should be saved in hidden folder */
+                       pMsgInfo->folderId = 0;
+               }
+
+       } else if ((pMsgInfo->msgType.subType >= MSG_REPLACE_TYPE1_SMS) && (pMsgInfo->msgType.subType <= MSG_REPLACE_TYPE7_SMS)) {
+               MSG_DEBUG("Replace SM Type [%d]", pMsgInfo->msgType.subType-3);
+
+               if (pMsgInfo->msgType.classType == MSG_CLASS_2) {
+//                     err = addClass2Message(pMsgInfo);
+               } else if (pMsgInfo->msgType.classType == MSG_CLASS_0) {
+                       /** Class 0 Msg should be saved in hidden folder */
+                       pMsgInfo->folderId = 0;
+                       pMsgInfo->msgType.subType = MSG_NORMAL_SMS;
+               }
+
+       } else if ((pMsgInfo->msgType.subType >= MSG_MWI_VOICE_SMS) && (pMsgInfo->msgType.subType <= MSG_MWI_OTHER_SMS)) {
+               if (pMsgInfo->bStore == true) {
+                       MSG_DEBUG("MWI Message");
+
+//                     if (pMsgInfo->msgType.classType == MSG_CLASS_2) {
+//                             err = addClass2Message(pMsgInfo);
+//                     }
+               }
+       } else {
+               MSG_DEBUG("No matching type [%d]", pMsgInfo->msgType.subType);
+       }
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Success to check message !!");
+       } else {
+               MSG_DEBUG("fail to check message !! : [%d]", err);
+       }
+
+       return err;
+}
+
+
+msg_error_t SmsPluginStorage::addSmsMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       unsigned int rowId = 0;
+       msg_thread_id_t convId = 0;
+
+       MsgDbHandler *dbHandle = getDbHandle();
+       dbHandle->beginTrans();
+
+       if (pMsgInfo->nAddressCnt > 0) {
+
+               err = MsgStoAddAddress(dbHandle, pMsgInfo, &convId);
+
+               if (err != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return err;
+               }
+
+               pMsgInfo->threadId = convId;
+       }
+
+       /**  Add Message Table */
+       rowId = MsgStoAddMessageTable(dbHandle, pMsgInfo);
+
+       if (rowId <= 0) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_ROW;
+       }
+
+       /** Update conversation table */
+       err = MsgStoUpdateConversation(dbHandle, convId);
+
+       if (err != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return err;
+       }
+
+       err = dbHandle->endTrans(true);
+       if (err != MSG_SUCCESS) {
+               return err;
+       }
+
+       pMsgInfo->msgId = (msg_message_id_t)rowId;
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPluginStorage::deleteSmsMessage(msg_message_id_t msgId)
+{
+       MSG_BEGIN();
+
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+        /**  Get SUB_TYPE, STORAGE_ID */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MAIN_TYPE, SUB_TYPE, FOLDER_ID, CONV_ID, SIM_INDEX \
+                       FROM %s WHERE MSG_ID = %d;",
+                       MSGFW_MESSAGE_TABLE_NAME, msgId);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       MSG_MESSAGE_TYPE_S msgType;
+       msg_folder_id_t folderId;
+
+       msg_thread_id_t convId;
+       int simIndex;
+
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               msgType.mainType = dbHandle->columnInt(0);
+               msgType.subType = dbHandle->columnInt(1);
+               folderId = dbHandle->columnInt(2);
+               convId = dbHandle->columnInt(3);
+               simIndex = dbHandle->columnInt(4);
+
+               MSG_DEBUG("Main Type:[%d] SubType:[%d] FolderId:[%d] ConversationId:[%d] simIndex:[%d]", msgType.mainType, msgType.subType, folderId, convId, simIndex);
+       } else {
+               MSG_DEBUG("MsgStepQuery() Error [%s]", sqlQuery);
+               dbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle->finalizeQuery();
+
+       dbHandle->beginTrans();
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_SMS_SENDOPT_TABLE_NAME, msgId);
+
+       /**  Delete SMS Send Option */
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       if (msgType.subType == MSG_CB_SMS || msgType.subType == MSG_JAVACB_SMS) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_CB_MSG_TABLE_NAME, msgId);
+
+               /** Delete Push Message from push table */
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
+       } else if (msgType.subType >= MSG_WAP_SI_SMS && msgType.subType <= MSG_WAP_CO_SMS) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_PUSH_MSG_TABLE_NAME, msgId);
+
+               /**  Delete Push Message from push table */
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
+       } else if (msgType.subType == MSG_SYNCML_CP) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_SYNCML_MSG_TABLE_NAME, msgId);
+
+               /**  Delete SyncML Message from syncML table */
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
+       }
+
+       /** Delete Message from msg table */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, msgId);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       /** Delete Message from msg_report table */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_SMS_REPORT_TABLE_NAME, msgId);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       /** Delete Message from msg_sim table */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_SIM_MSG_TABLE_NAME, msgId);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       /**  Clear Conversation table */
+       if (MsgStoClearConversationTable(dbHandle) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       /**  Update conversation table.*/
+       if (MsgStoUpdateConversation(dbHandle, convId) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       dbHandle->endTrans(true);
+
+       if (folderId == MSG_INBOX_ID) {
+               msgType.classType = MSG_CLASS_NONE;
+
+               /**  Set memory status in SIM */
+               if (MsgStoCheckMsgCntFull(dbHandle, &msgType, folderId) == MSG_SUCCESS) {
+                       MSG_DEBUG("Set Memory Status");
+                       SmsPlgSetMemoryStatus(MSG_SUCCESS);
+               }
+       }
+
+//     MsgRefreshAllNotification(true, false, false);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPluginStorage::addSmsSendOption(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo)
+{
+       MSG_BEGIN();
+
+       MsgDbHandler *dbHandle = getDbHandle();
+       msg_error_t err = MSG_SUCCESS;
+
+       if (pSendOptInfo->bSetting == false) {
+               MsgSettingGetBool(SMS_SEND_DELIVERY_REPORT, &pSendOptInfo->bDeliverReq);
+               MsgSettingGetBool(SMS_SEND_REPLY_PATH, &pSendOptInfo->option.smsSendOptInfo.bReplyPath);
+
+//             if (pSendOptInfo->bDeliverReq || pSendOptInfo->option.smsSendOptInfo.bReplyPath) {
+//                     pSendOptInfo->bSetting = true;
+                       MsgSettingGetBool(MSG_KEEP_COPY, &pSendOptInfo->bKeepCopy);
+//             }
+       }
+
+//     if (pSendOptInfo->bSetting == true) {
+               char sqlQuery[MAX_QUERY_LEN+1];
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, %d);",
+                               MSGFW_SMS_SENDOPT_TABLE_NAME, pMsg->msgId, pSendOptInfo->bDeliverReq,
+                               pSendOptInfo->bKeepCopy, pSendOptInfo->option.smsSendOptInfo.bReplyPath, pMsg->encodeType);
+
+               MSG_DEBUG("Query = [%s]", sqlQuery);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       err = MSG_ERR_DB_EXEC;
+               }
+//     }
+
+       MSG_END();
+
+       return err;
+}
+
+
+msg_error_t SmsPluginStorage::checkStorageStatus(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       MsgDbHandler *dbHandle = getDbHandle();
+       err = MsgStoCheckMsgCntFull(dbHandle, &(pMsgInfo->msgType), pMsgInfo->folderId);
+
+       if (err != MSG_SUCCESS) {
+
+               if (err == MSG_ERR_MESSAGE_COUNT_FULL) {
+                       bool bAutoErase = false;
+
+                       MsgSettingGetBool(MSG_AUTO_ERASE, &bAutoErase);
+
+                       MSG_DEBUG("bAutoErase: %d", bAutoErase);
+
+                       if (bAutoErase == true) {
+                               msg_message_id_t msgId;
+
+                               /** Find the oldest message's msgId */
+                               err = MsgStoGetOldestMessage(dbHandle, pMsgInfo, &msgId);
+
+                               if (err != MSG_SUCCESS)
+                                       return err;
+
+                               /** Delete the corresponding message. */
+                               err = deleteSmsMessage(msgId);
+                       }
+               }
+
+               return err;
+       }
+
+       return err;
+}
+
+
+msg_error_t SmsPluginStorage::getRegisteredPushEvent(char* pPushHeader, int *count, char *application_id, int app_id_len, char *content_type, int content_type_len)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int rowCnt = 0, index = 0;
+
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       char sqlQuery[MAX_QUERY_LEN+1] = {0, };
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CONTENT_TYPE, APP_ID, APPCODE FROM %s", MSGFW_PUSH_CONFIG_TABLE_NAME);
+
+       err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+       MSG_DEBUG("rowCnt: %d", rowCnt);
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               dbHandle->freeTable();
+               return MSG_SUCCESS;
+       }
+       else if ( err != MSG_SUCCESS) {
+               dbHandle->freeTable();
+               return err;
+       }
+
+       char contentType[MAX_WAPPUSH_CONTENT_TYPE_LEN + 1] = {0,};
+       char appId[MAX_WAPPUSH_ID_LEN + 1] = {0,};
+       int appcode = 0, default_appcode = 0;
+       bool found = false;
+       char *_content_type = NULL, *_app_id = NULL;
+       *count = 0;
+
+
+       for (int i = 0; i < rowCnt; i++) {
+               memset(contentType, 0, MAX_WAPPUSH_CONTENT_TYPE_LEN);
+               memset(appId, 0, MAX_WAPPUSH_ID_LEN);
+
+               dbHandle->getColumnToString(index++, MAX_WAPPUSH_CONTENT_TYPE_LEN + 1, contentType);
+               dbHandle->getColumnToString(index++, MAX_WAPPUSH_ID_LEN + 1, appId);
+               appcode = dbHandle->getColumnToInt(index++);
+
+               //MSG_DEBUG("content_type: %s, app_id: %s", content_type, app_id);
+               _content_type = strcasestr(pPushHeader, contentType);
+               if(_content_type) {
+                       _app_id = strcasestr(pPushHeader, appId);
+                       if(appcode)
+                               default_appcode = appcode;
+
+                       if(_app_id) {
+                               PUSH_APPLICATION_INFO_S pInfo = {0, };
+                               pInfo.appcode = appcode;
+                               MSG_SEC_DEBUG("appcode: %d, app_id: %s", pInfo.appcode, appId);
+                               snprintf(application_id, app_id_len, "%s", appId);
+                               snprintf(content_type, content_type_len, "%s", contentType);
+                               pushAppInfoList.push_back(pInfo);
+                               (*count)++;
+                               found = true;
+                       }
+               }
+       }
+
+       if(!found && default_appcode != SMS_WAP_APPLICATION_LBS)
+       {
+               // perform default action.
+               PUSH_APPLICATION_INFO_S pInfo = {0, };
+               pInfo.appcode = default_appcode;
+               memset(appId, 0, MAX_WAPPUSH_ID_LEN + 1);
+               snprintf(application_id, app_id_len, "%s", appId);
+               snprintf(content_type, content_type_len, "%s", contentType);
+               pushAppInfoList.push_back(pInfo);
+               *count = 1;
+       }
+       dbHandle->freeTable();
+
+       return err;
+}
+
+
+msg_error_t SmsPluginStorage::getnthPushEvent(int index, int *appcode)
+{
+       msg_error_t err = MSG_SUCCESS;
+       if((unsigned int)index > pushAppInfoList.size() - 1)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       std::list<PUSH_APPLICATION_INFO_S>::iterator it = pushAppInfoList.begin();
+       int count = 0;
+       for (; it != pushAppInfoList.end(); it++)
+       {
+               if(index == count){
+                       *appcode = it->appcode;
+                       break;
+               }
+               count++;
+       }
+
+       return err;
+}
+
+
+msg_error_t SmsPluginStorage::releasePushEvent()
+{
+       msg_error_t err = MSG_SUCCESS;
+       std::list<PUSH_APPLICATION_INFO_S>::iterator it = pushAppInfoList.begin();
+
+       for (; it != pushAppInfoList.end(); it++)
+               it = pushAppInfoList.erase(it);
+
+       return err;
+}
diff --git a/plugin/sms_cdma_plugin/SmsCdmaPluginTransport.cpp b/plugin/sms_cdma_plugin/SmsCdmaPluginTransport.cpp
new file mode 100755 (executable)
index 0000000..6aa284b
--- /dev/null
@@ -0,0 +1,563 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+
+#include <errno.h>
+
+#include "MsgGconfWrapper.h"
+#include "MsgException.h"
+
+#include "MsgUtilStorage.h"
+
+#ifndef MSG_NOTIFICATION_NOT_SUPPORTED
+#include "MsgNotificationWrapper.h"
+#endif
+
+#include "SmsCdmaPluginTransport.h"
+#include "SmsCdmaPluginCodec.h"
+#include "SmsCdmaPluginEventHandler.h"
+#include "SmsCdmaPluginCallback.h"
+
+extern "C" {
+#include "TapiUtility.h"
+#include "TelSms.h"
+#include "TelNetwork.h"
+#include "ITapiNetText.h"
+}
+
+extern struct tapi_handle *pTapiHandle;
+extern bool isMemAvailable;
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+
+SmsPluginTransport* SmsPluginTransport::pInstance = NULL;
+
+
+SmsPluginTransport::SmsPluginTransport()
+{
+       msgRef          = 0x00;
+       msgRef8bit      = 0x00;
+       msgRef16bit     = 0x0000;
+
+       msgSeqNum   = 0x00;
+       msgSubmitId = MsgSettingGetInt(MSG_MESSAGE_ID_COUNTER);
+}
+
+
+SmsPluginTransport::~SmsPluginTransport()
+{
+
+}
+
+
+SmsPluginTransport* SmsPluginTransport::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginTransport();
+
+       return pInstance;
+}
+
+
+unsigned char SmsPluginTransport::getMsgRef()
+{
+       return msgRef++;
+}
+
+
+unsigned char SmsPluginTransport::getSeqNum()
+{
+       msgSeqNum = ((msgSeqNum + 1) % SMS_SEQ_NUM_MAX);
+
+       return msgSeqNum;
+}
+
+
+unsigned char SmsPluginTransport::getSubmitMsgId()
+{
+       msgSubmitId = ((msgSubmitId + 1) % SMS_MAX_MESSAGE_ID);
+
+       MsgSettingSetInt(MSG_MESSAGE_ID_COUNTER, msgSubmitId);
+
+       return msgSubmitId;
+}
+
+
+void SmsPluginTransport::convertMsgInfoToTelesvcMsg(const MSG_MESSAGE_INFO_S *pMsgInfo, sms_trans_msg_s *pTransMsg)
+{
+       switch (pTransMsg->type) {
+               case SMS_TRANS_P2P_MSG:
+               {
+                       MSG_DEBUG("Convert  MSG_MESSAGE_INFO_S data to SMS_TRANS_MSG_S data.");
+                       sms_trans_p2p_msg_s *pPtpMsg = (sms_trans_p2p_msg_s *)&(pTransMsg->data.p2p_msg);
+
+                       convertMsgInfoToPtp(pMsgInfo, pPtpMsg);
+               }
+                       break;
+               default:
+                       MSG_DEBUG("Error Unsupported Transport Type");
+                       break;
+       }
+}
+
+
+void SmsPluginTransport::convertMsgInfoToPtp(const MSG_MESSAGE_INFO_S *pMsgInfo, sms_trans_p2p_msg_s *pPtpMsg)
+{
+
+       /* 1. Set Teleservice ID */
+       pPtpMsg->telesvc_id = SMS_TRANS_TELESVC_CMT_95;
+
+       /* 2. Set Service category */
+       pPtpMsg->svc_ctg = SMS_TRANS_SVC_CTG_UNDEFINED;
+
+       /* 3. Convert Address values */
+       pPtpMsg->address.digit_mode = SMS_DIGIT_4BIT_DTMF;
+       pPtpMsg->address.number_mode = SMS_NUMBER_MODE_NONE_DATANETWORK;
+       pPtpMsg->address.number_type = SMS_NUMBER_TYPE_UNKNOWN;
+       pPtpMsg->address.number_plan = SMS_NPI_UNKNOWN;
+       pPtpMsg->address.addr_len = strlen(pMsgInfo->addressList[0].addressVal);
+       strncpy(pPtpMsg->address.szData, pMsgInfo->addressList[0].addressVal, pPtpMsg->address.addr_len);
+
+       if (pMsgInfo->addressList[0].addressVal[0] == '+') {
+               pPtpMsg->address.digit_mode = SMS_DIGIT_8BIT;
+               pPtpMsg->address.number_type = SMS_NUMBER_TYPE_INTERNATIONAL;
+       }
+       else {
+               pPtpMsg->address.number_type = SMS_NUMBER_TYPE_NATIONAL;
+       }
+
+       /* 4. Convert Sub-address values */
+       // TODO
+
+       /* 5. Set Reply sequence number. */
+       pPtpMsg->reply_seq = getSeqNum();
+
+       /* convert msgInfo to Teleservice Message */
+       switch (pPtpMsg->telesvc_msg.type) {
+               case SMS_TYPE_SUBMIT:
+                       convertMsgInfoToSubmit(pMsgInfo, &(pPtpMsg->telesvc_msg.data.submit));
+                       break;
+               default:
+                       break;
+       }
+
+}
+
+
+void SmsPluginTransport::convertMsgInfoToSubmit(const MSG_MESSAGE_INFO_S *pMsgInfo, sms_telesvc_submit_s *pSubmit)
+{
+       if (pSubmit == NULL)
+               return;
+
+       /* 1. Set msg ID. */
+       pSubmit->msg_id.msg_id = getSubmitMsgId();
+       pSubmit->msg_id.header_ind = false;
+
+       /* 2. Set User Data */
+       unsigned char decodeData[SMS_MAX_USER_DATA_LEN + 1];
+       memset(decodeData, 0x00, sizeof(decodeData));
+
+       MsgTextConvert *textCvt = MsgTextConvert::instance();
+
+       msg_encode_type_t encodeType = MSG_ENCODE_GSM7BIT;
+
+
+       if (pMsgInfo->bTextSms == true) {
+               if (pMsgInfo->encodeType == MSG_ENCODE_GSM7BIT)
+               {
+                       pSubmit->user_data.encode_type = SMS_ENCODE_GSM7BIT;
+               }
+               else if (pMsgInfo->encodeType == MSG_ENCODE_8BIT)
+               {
+                       pSubmit->user_data.encode_type = SMS_ENCODE_OCTET;
+               }
+               else if (pMsgInfo->encodeType == MSG_ENCODE_UCS2)
+               {
+                       pSubmit->user_data.encode_type = SMS_ENCODE_UNICODE;
+               }
+               else if (pMsgInfo->encodeType == MSG_ENCODE_AUTO)
+               {
+                       textCvt->convertUTF8ToAuto(decodeData, SMS_MAX_USER_DATA_LEN + 1, (unsigned char*)pMsgInfo->msgText, (int)pMsgInfo->dataSize, &encodeType);
+                       if (encodeType == MSG_ENCODE_ASCII7BIT) {
+                               pSubmit->user_data.encode_type = SMS_ENCODE_7BIT_ASCII;
+                       }
+                       else if (encodeType == MSG_ENCODE_8BIT) {
+                               pSubmit->user_data.encode_type = SMS_ENCODE_OCTET;
+                       }
+                       else if (encodeType == MSG_ENCODE_UCS2) {
+                               pSubmit->user_data.encode_type = SMS_ENCODE_UNICODE;
+                       }
+               }
+       }
+
+       memset(pSubmit->user_data.user_data, 0x00, sizeof(pSubmit->user_data.user_data));
+       snprintf((char *)pSubmit->user_data.user_data, sizeof(pSubmit->user_data.user_data), "%s", pMsgInfo->msgText);
+       pSubmit->user_data.data_len = pMsgInfo->dataSize;
+
+       MSG_DEBUG("encode type : [%d]", pSubmit->user_data.encode_type);
+
+       /* 3. Set Valid period */
+#if 0
+       pSubmit->val_period.format = SMS_TIME_ABSOLUTE;
+       pSubmit->val_period.time.abs_time.year = 0;
+       pSubmit->val_period.time.abs_time.month = 0;
+       pSubmit->val_period.time.abs_time.day = 0;
+       pSubmit->val_period.time.abs_time.hours = 0;
+       pSubmit->val_period.time.abs_time.minutes = 0;
+       pSubmit->val_period.time.abs_time.seconds = 0;
+#else
+       pSubmit->val_period.format = SMS_TIME_RELATIVE;
+       pSubmit->val_period.time.rel_time.rel_time = SMS_REL_TIME_INDEFINITE;
+#endif
+
+       /* 4. Set Defer valid period */
+       // TODO
+
+       /* 5. Set Priority */
+       switch (pMsgInfo->priority) {
+               case MSG_MESSAGE_PRIORITY_HIGH:
+                       pSubmit->priority = SMS_PRIORITY_URGENT;
+                       break;
+               default:
+                       pSubmit->priority = SMS_PRIORITY_NORMAL;
+                       break;
+       }
+
+       /* 6. Set Privacy */
+       pSubmit->privacy = SMS_PRIVACY_NOT_RESTRICTED;
+
+       /* 7. Set Reply option */
+       MsgSettingGetBool(SMS_SEND_DELIVERY_REPORT, (bool *)&(pSubmit->reply_opt.deliver_ack_req));
+
+       /* 8. Set Alert priority */
+       pSubmit->alert_priority = SMS_ALERT_MOBILE_DEFAULT;
+
+       /* 9. Set Language */
+       pSubmit->language = SMS_LAN_UNKNOWN;
+
+       /* 10. Set Callback number */
+       // TODO :: Set callback number to MSISDN
+
+       /* 11. Set Multi encode data */
+       // TODO
+
+       /* 12. Set Deposit id */
+       // TODO
+
+       /* 13. Set Service category program data */
+       // TODO
+
+}
+
+
+
+void SmsPluginTransport::submitRequest(sms_request_info_s *pReqInfo)
+{
+       int tapiRet = TAPI_API_SUCCESS;
+
+       if (pReqInfo == NULL) {
+               THROW(MsgException::SMS_PLG_ERROR, "pReqInfo is NULL");
+       }
+
+       // Get address informations.
+       MsgDbHandler *dbHandle = getDbHandle();
+       //contacts-service is not used for gear
+#ifndef MSG_CONTACTS_SERVICE_NOT_SUPPORTED
+       MsgStoGetAddressByMsgId(dbHandle, pReqInfo->msgInfo.msgId, 0, &pReqInfo->msgInfo.nAddressCnt, &pReqInfo->msgInfo.addressList);
+#else
+       //contactNameOrder is never used
+       MsgStoGetAddressByMsgId(dbHandle, pReqInfo->msgInfo.msgId, &pReqInfo->msgInfo.nAddressCnt, &pReqInfo->msgInfo.addressList);
+#endif //MSG_CONTACTS_SERVICE_NOT_SUPPORTED
+
+       MSG_DEBUG("pReqInfo->msgInfo.nAddressCnt [%d]", pReqInfo->msgInfo.nAddressCnt);
+
+       // Get MSISDN
+       char *msisdn = NULL;
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       int simIndex = 1;
+
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_MSISDN, simIndex);
+
+       msisdn = MsgSettingGetString(keyName);
+
+       // Tapi Data Structure
+       TelSmsDatapackageInfo_t tapi_data_pkg;
+       memset(&tapi_data_pkg, 0x00, sizeof(TelSmsDatapackageInfo_t));
+
+       bool bMoreMsgToSend = false;
+
+       tapi_data_pkg.format = (TelSmsNetType_t)TAPI_NETTEXT_NETTYPE_3GPP2;
+
+       /* convert msg_info to trans_msg */
+       sms_trans_msg_s  trans_msg;
+       memset(&trans_msg, 0x00, sizeof(sms_trans_msg_s));
+
+       trans_msg.type = (sms_trans_msg_type_t)SMS_TRANS_P2P_MSG;
+       trans_msg.data.p2p_msg.telesvc_msg.type = (sms_message_type_t)SMS_TYPE_SUBMIT;
+
+       convertMsgInfoToTelesvcMsg(&pReqInfo->msgInfo, &trans_msg);
+
+       /* encode msg data */
+       unsigned char tel_sms_data[TAPI_NETTEXT_SMDATA_SIZE_MAX+1] = {0,};
+
+       tapi_data_pkg.MsgLength = SmsPluginMsgCodec::instance()->encodeMsg(&trans_msg, tel_sms_data);
+
+       memcpy((void *)tapi_data_pkg.szData, (void *)tel_sms_data, sizeof(tapi_data_pkg.szData));
+
+       MSG_DEBUG("Submit Request TPDU.");
+       char pduDbg[TAPI_NETTEXT_SMDATA_SIZE_MAX*2];
+       memset(pduDbg, 0x00, sizeof(pduDbg));
+
+       for (int i = 0; i < tapi_data_pkg.MsgLength; i++) {
+               snprintf(pduDbg+(i*2), sizeof(pduDbg)- (i*2), "%02x", tapi_data_pkg.szData[i]);
+       }
+       MSG_DEBUG("Encode PDU= [%s]", pduDbg);
+
+       /* send request */
+       sms_network_status_t retStatus;
+       sms_sent_info_s sent_info;
+       memset(&sent_info, 0x00, sizeof(sms_sent_info_s));
+       memcpy(&sent_info.reqInfo, pReqInfo, sizeof(sent_info.reqInfo));
+
+       sent_info.bLast = true;
+
+       SmsPluginEventHandler::instance()->SetSentInfo(&sent_info);
+
+       int svc_type;
+       tel_get_property_int(pTapiHandle, TAPI_PROP_NETWORK_SERVICE_TYPE, &svc_type);
+
+       if(svc_type < TAPI_NETWORK_SERVICE_TYPE_2G){
+               MSG_DEBUG("Network service is not available : [%d]", svc_type);
+               SmsPluginEventHandler::instance()->handleSentStatus(MSG_NETWORK_SEND_PENDING);
+               goto _RETURN_FUNC;
+       }
+
+       curStatus = SMS_NETWORK_SENDING;
+
+       // Send SMS
+       tapiRet = tel_send_sms(pTapiHandle, &tapi_data_pkg, bMoreMsgToSend, TapiEventSentStatus, NULL);
+
+       if (tapiRet == TAPI_API_SUCCESS)
+       {
+               MSG_DEBUG("########  tel_send_sms Success !!! return : [%d] #######", tapiRet);
+       }
+       else
+       {
+               SmsPluginEventHandler::instance()->handleSentStatus(MSG_NETWORK_SEND_FAIL);
+               THROW(MsgException::SMS_PLG_ERROR, "########  tel_send_sms Fail !!! return : [%d] #######", tapiRet);
+       }
+
+       // Tizen Validation System
+       MSG_SMS_VLD_INFO("%d, SMS Send Start, %s->%s, %s",  pReqInfo->msgInfo.msgId, \
+                                                                                                                               (msisdn == NULL)?"ME":msisdn, \
+                                                                                                                               pReqInfo->msgInfo.addressList[0].addressVal, \
+                                                                                                                               (tapiRet == TAPI_API_SUCCESS)?"Success":"Fail");
+
+       MSG_SMS_VLD_TXT("%d, [%s]", pReqInfo->msgInfo.msgId, pReqInfo->msgInfo.msgText);
+
+       retStatus = getNetStatus();
+
+       MSG_SMS_VLD_INFO("%d, SMS Send End, %s->%s, %s",  pReqInfo->msgInfo.msgId, \
+                                                                                                                       (msisdn == NULL)?"ME":msisdn, \
+                                                                                                                       pReqInfo->msgInfo.addressList[0].addressVal, \
+                                                                                                                       (retStatus == SMS_NETWORK_SEND_SUCCESS)?"Success":"Fail");
+
+       if (retStatus == SMS_NETWORK_SEND_SUCCESS)
+       {
+               MSG_DEBUG("########  Msg Sent was Successful !!! #######");
+       }
+       else
+       {
+               if (retStatus == SMS_NETWORK_SEND_FAIL_TIMEOUT)
+                       SmsPluginEventHandler::instance()->handleSentStatus(MSG_NETWORK_SEND_FAIL);
+
+               if (retStatus == SMS_NETWORK_SEND_FAIL_FDN_RESTRICED) {
+                       MsgInsertTicker("Unable to send the message while Fixed dialling mode is enabled", SMS_FDN_RESTRICTED, true, 0);
+               } else if(retStatus == SMS_NETWORK_SEND_PENDING) {
+                       MsgInsertTicker("Unable to send message. It will be sent when service available.", SMS_MESSAGE_SENDING_PENDING, true, 0);
+               }else {
+                       MsgInsertTicker("Sending SMS is failed", SMS_MESSAGE_SENDING_FAIL, true, pReqInfo->msgInfo.msgId);
+               }
+       }
+
+_RETURN_FUNC :
+       if (msisdn) {
+               free(msisdn);
+               msisdn = NULL;
+       }
+
+       MSG_END();
+
+       return;
+}
+
+void SmsPluginTransport::sendDeliverReport(msg_error_t err, sms_trans_p2p_msg_s *p_p2p_msg)
+{
+       MSG_BEGIN();
+
+       int tapiRet = TAPI_API_SUCCESS;
+       TelSmsResponse_t response;
+
+       sms_trans_msg_s  trans_msg;
+       memset(&trans_msg, 0x00, sizeof(sms_trans_msg_s));
+
+       trans_msg.type = (sms_trans_msg_type_t)SMS_TRANS_ACK_MSG;
+
+       if (p_p2p_msg)
+               memcpy(&(trans_msg.data.ack_msg.address), &(p_p2p_msg->address), sizeof(sms_trans_addr_s));
+
+       sms_trans_cause_code_s  cause_code;
+       memset(&cause_code, 0x00, sizeof(sms_trans_cause_code_s));
+
+       if (p_p2p_msg->reply_seq > 0)
+               cause_code.reply_seq = p_p2p_msg->reply_seq;
+
+
+       if (err == MSG_SUCCESS)
+       {
+               cause_code.error_class = SMS_TRANS_ERR_CLASS_NONE;
+
+               response = TAPI_NETTEXT_SENDSMS_SUCCESS;
+
+               if(isMemAvailable == false)
+               {
+                       tapiRet = tel_set_sms_memory_status(pTapiHandle, TAPI_NETTEXT_PDA_MEMORY_STATUS_AVAILABLE, TapiEventMemoryStatus, NULL);
+
+                       if (tapiRet == TAPI_API_SUCCESS)
+                       {
+                               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
+                       }
+                       else
+                       {
+                               MSG_DEBUG("########  tel_set_sms_memory_status() Failed !!! return : [%d] #######", tapiRet);
+                       }
+               }
+
+       } else if (err == MSG_ERR_MESSAGE_COUNT_FULL) {
+
+               cause_code.error_class = SMS_TRANS_ERR_CLASS_TEMPORARY;
+
+               response = TAPI_NETTEXT_ME_FULL;
+//             MsgInsertTicker("Not enough memory. Delete some items.", SMS_MESSAGE_MEMORY_FULL, true, 0);
+
+               tapiRet = tel_set_sms_memory_status(pTapiHandle, TAPI_NETTEXT_PDA_MEMORY_STATUS_FULL, TapiEventMemoryStatus, NULL);
+
+               if (tapiRet == TAPI_API_SUCCESS)
+               {
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
+               }
+               else
+               {
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Failed !!! return : [%d] #######", tapiRet);
+               }
+       } else if (err == MSG_ERR_UNKNOWN) {
+               cause_code.error_class = SMS_TRANS_ERR_CLASS_TEMPORARY;
+               cause_code.cause_code = SMS_CAUSE_CODE_SERVICE_TERMINATION_DENIED;
+
+               response = TAPI_NETTEXT_SENDSMS_SUCCESS;
+
+       } else if (err == MSG_ERR_INVALID_MSG_TYPE) {
+               cause_code.error_class = SMS_TRANS_ERR_CLASS_PERMANENT;
+               cause_code.cause_code = SMS_CAUSE_CODE_INVAILD_TELESERVICE_ID;
+
+               response = TAPI_NETTEXT_INVALID_MSG;
+       }
+       else
+       {
+               cause_code.error_class = SMS_TRANS_ERR_CLASS_TEMPORARY;
+               response = TAPI_NETTEXT_SIM_FULL;
+
+       }
+
+       memcpy(&(trans_msg.data.ack_msg.cause_code), &(cause_code), sizeof(sms_trans_cause_code_s));
+
+       MSG_DEBUG("err : [%d], response : [%02x]", err, response);
+
+       int bufLen = 0;
+
+       unsigned char buf[512];
+       memset(buf, 0x00, sizeof(buf));
+       bufLen = SmsPluginMsgCodec::encodeMsg(&trans_msg, buf);
+
+
+       MSG_DEBUG("######## DeliverReport tpdu #########");
+       for(int i=0; i < bufLen; i++)
+       {
+               printf("[%02x] ", buf[i]);
+       }
+       MSG_DEBUG("#################################");
+
+       // Make Telephony Structure
+       TelSmsDatapackageInfo_t pkgInfo;
+
+       pkgInfo.format = TAPI_NETTEXT_NETTYPE_3GPP2;
+
+       // Set TPDU data
+       memset((void*)pkgInfo.szData, 0x00, sizeof(pkgInfo.szData));
+       memcpy((void*)pkgInfo.szData, buf, bufLen);
+
+       pkgInfo.szData[bufLen] = 0;
+       pkgInfo.MsgLength = bufLen;
+
+
+       // Send Deliver Report
+       tapiRet = tel_send_sms_deliver_report(pTapiHandle, &pkgInfo, response, TapiEventDeliveryReportCNF, NULL);
+
+       if (tapiRet == TAPI_API_SUCCESS)
+       {
+               MSG_DEBUG("########  tel_send_sms_deliver_report() Success !!! #######");
+       }
+       else
+       {
+               MSG_DEBUG("########  tel_send_sms_deliver_report() Fail !!! return : [%d] #######", tapiRet);
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginTransport::setNetStatus(sms_network_status_t sentStatus)
+{
+       mx.lock();
+       curStatus = sentStatus;
+       cv.signal();
+       mx.unlock();
+}
+
+
+sms_network_status_t SmsPluginTransport::getNetStatus()
+{
+       mx.lock();
+
+       int ret = 0;
+
+       if (curStatus == SMS_NETWORK_SENDING)
+               ret = cv.timedwait(mx.pMutex(), 125);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT)
+       {
+               MSG_DEBUG("WARNING: SENT STATUS TIME-OUT");
+               curStatus = SMS_NETWORK_SEND_FAIL_TIMEOUT;
+       }
+
+       return curStatus;
+}
diff --git a/plugin/sms_cdma_plugin/SmsCdmaPluginUAManager.cpp b/plugin/sms_cdma_plugin/SmsCdmaPluginUAManager.cpp
new file mode 100755 (executable)
index 0000000..986e6f6
--- /dev/null
@@ -0,0 +1,106 @@
+
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+
+#include "MsgException.h"
+#include "MsgCppTypes.h"
+#include "SmsCdmaPluginUAManager.h"
+#include "SmsCdmaPluginTransport.h"
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginUAManager - Member Functions
+==================================================================================================*/
+SmsPluginUAManager* SmsPluginUAManager::pInstance = NULL;
+
+
+SmsPluginUAManager::SmsPluginUAManager() : mx(), cv()
+{
+       start();
+}
+
+
+SmsPluginUAManager::~SmsPluginUAManager()
+{
+
+}
+
+
+SmsPluginUAManager* SmsPluginUAManager::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginUAManager();
+
+       return pInstance;
+}
+
+
+void SmsPluginUAManager::run()
+{
+       while (1)
+       {
+               lock();
+               while (smsTranQ.empty()) {
+                       wait();
+               }
+               sms_request_info_s request;
+               smsTranQ.front(&request);
+               unlock();
+
+               request.msgInfo.addressList = NULL;
+               unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&request.msgInfo.addressList, unique_ptr_deleter);
+
+               try
+               {
+                       SmsPluginTransport::instance()->submitRequest(&request);
+               }
+               catch (MsgException& e)
+               {
+                       MSG_FATAL("%s", e.what());
+
+                       lock();
+                       smsTranQ.pop_front();
+                       unlock();
+                       continue;
+               }
+               catch (exception& e)
+               {
+                       MSG_FATAL("%s", e.what());
+                       lock();
+                       smsTranQ.pop_front();
+                       unlock();
+                       continue;
+               }
+
+               lock();
+               smsTranQ.pop_front();
+               unlock();
+       }
+}
+
+
+void SmsPluginUAManager::addReqEntity(sms_request_info_s *request)
+{
+       sms_request_info_s reqTmp = {0,};
+
+       memcpy(&reqTmp, request, sizeof(sms_request_info_s));
+
+       lock();
+       smsTranQ.push_back(reqTmp);
+       cv.signal();
+       unlock();
+}
+
diff --git a/plugin/sms_cdma_plugin/SmsCdmaPluginWapPushHandler.cpp b/plugin/sms_cdma_plugin/SmsCdmaPluginWapPushHandler.cpp
new file mode 100755 (executable)
index 0000000..20e7d2b
--- /dev/null
@@ -0,0 +1,3461 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include "MsgDebug.h"
+#include "MsgCppTypes.h"
+#include "MsgGconfWrapper.h"
+#include "MsgException.h"
+#include "MsgUtilFile.h"
+#include "SmsCdmaPluginStorage.h"
+#include "SmsCdmaPluginTransport.h"
+#include "SmsCdmaPluginEventHandler.h"
+#include "SmsCdmaPluginWapPushHandler.h"
+
+#include <glib.h>
+#include <gio/gio.h>
+
+#if MSG_DRM_SUPPORT
+#include <drm_client.h>
+#endif
+
+static unsigned short wapPushPortList [] = {0x0b84, 0x0b85, 0x23F0, 0x23F1, 0x23F2, 0x23F3, 0xC34F};
+
+char gWapCodeBufferLeft[WSP_CODE_BUFFER_LEFT_LEN_MAX];
+char gWapCodeBufferRight[WSP_CODE_BUFFER_RIGHT_LEN_MAX];
+
+const unsigned long wspUintvarDecodeTable[] = { 0x00000001, 0x00000080, 0x00004000, 0x00200000, 0x10000000};
+
+const unsigned char wspHeaderFieldCount  = 0x43;
+const unsigned char wspContentsTypeCount = 0x34;
+const unsigned long wspLanguageCount    = 0x11a;
+const unsigned char wspSecurityTypeCount = 0x04;
+
+
+static const SMS_WSP_CONTENTS_TYPE_S wspExtendedContentsType[] =
+{
+       { (char*)"text/vnd/wap/connectivity-xml", 0x35 },
+       { (char*)"application/vnd.wap.connectivity-wbxml", 0x36 },
+       { (char*)"application/pkcs7-mime",  0x37 },
+       { (char*)"application/vnd.wap.hashed-certificate", 0x38 },
+       { (char*)"application/vnd.wap.signed-certificate", 0x39  },
+       { (char*)"application/vnd.wap.cert-response", 0x3A },
+       { (char*)"application/xhtml+xml", 0x3B },
+       { (char*)"application/wml+xml", 0x3C  },
+       { (char*)"text/css", 0x3D },
+
+       { (char*)"application/vnd.wap.mms-message", 0x3E },
+
+       { (char*)"application/vnd.wap.rollover-certificate", 0x3F  },
+       { (char*)"application/vnd.wap.locc+wbxml", 0x40 },
+       { (char*)"application/vnd.wap.loc+xml", 0x41 },
+       { (char*)"application/vnd.syncml.dm+wbxml", 0x42 },
+       { (char*)"application/vnd.syncml.dm+xml", 0x43 },
+       { (char*)"application/vnd.syncml.notification", 0x44 },
+       { (char*)"application/vnd.wap.xhtml+xml", 0x45 },
+       { (char*)"application/vnd.wv.csp.cir", 0x46 },
+
+       { (char*)"application/vnd.oma.dd+xml", 0x47},
+       { (char*)"application/vnd.oma.drm.message", 0x48 },
+       { (char*)"application/vnd.oma.drm.content", 0x49 },
+       { (char*)"application/vnd.oma.drm.rights+xml", 0x4A },
+       { (char*)"application/vnd.oma.drm.rights+wbxml", 0x4B },
+       { (char*)"application/vnd.syncml.ds.notification", 0x4E},
+       { (char*)"application/mikey", 0x52},
+       { (char*)"", 0xff }
+};
+
+
+const char* wspHeaderFieldName[] =
+{
+       (char*)"Accept",  //0x00
+       (char*)"Accept-Charset",
+       (char*)"Accept-Encoding",
+       (char*)"Accept-Language",
+       (char*)"Accept-Ranges",
+       (char*)"Age", //0x05
+       (char*)"Allow",
+       (char*)"Authorization",
+       (char*)"Cache-Control",
+       (char*)"Connection",
+       (char*)"Content-Base", //0x0a
+       (char*)"Content-Encoding",
+       (char*)"Content-Language",
+       (char*)"Content-Length",
+       (char*)"Content-Location",
+       (char*)"Content-MD5",
+       (char*)"Content-Range", //0x10
+       (char*)"Content-Type",
+       (char*)"Date",
+       (char*)"ETag",
+       (char*)"Expires",
+       (char*)"From", //0x15
+       (char*)"Host",
+       (char*)"If-Modified-Since",
+       (char*)"If-Match",
+       (char*)"If-None-Match",
+       (char*)"If-Range", //0x1a
+       (char*)"If-Unmodified-Since",
+       (char*)"Location",
+       (char*)"Last-Modified",
+       (char*)"Max-Forwards",
+       (char*)"Pragma",
+       (char*)"Proxy-Authenticate", //0x20
+       (char*)"Proxy-Authorization",
+       (char*)"Public",
+       (char*)"Range",
+       (char*)"Referer",
+       (char*)"Retry-After", //0x25
+       (char*)"Server",
+       (char*)"Transfer-Encodig",
+       (char*)"Upgrade",
+       (char*)"User-Agent",
+       (char*)"Vary", //0x2a
+       (char*)"Via",
+       (char*)"Warning",
+       (char*)"Www-Authenticate",
+       (char*)"Content-Disposition",
+       (char*)"X-Wap-Application-Id",
+       (char*)"X-Wap-Content-URI", //0x30
+       (char*)"X-Wap-Iinitiator-URI",
+       (char*)"Accept-Application", // Back
+       (char*)"Bearer-Indication",
+       (char*)"Push-Flag",
+       (char*)"Profile", //0x35
+       (char*)"Profile-Diff",
+       (char*)"Profile-Warning", // end of WAP 1.2
+       (char*)"Expect",
+       (char*)"Te",
+       (char*)"Trailer", //0x3a
+       (char*)"Accept-Charset", //Back
+       (char*)"Accept-Encoding", // Back
+       (char*)"Cache-Control", // back
+       (char*)"Content-Range",
+       (char*)"X-Wap-Tod",
+       (char*)"Content-ID", //x40
+       (char*)"Set-Cookie",
+       (char*)"Cookie",
+       (char*)"Encoding-Version"
+};
+
+
+const SMS_WSP_CHARSET_S wspCharset[] =
+{
+       { (char*)"big5", 0x07ea },
+       { (char*)"iso-10646-ucs-2", 0x03e8 },
+       { (char*)"iso-8859-1", 0x04 },
+       { (char*)"iso-8859-2", 0x05 },
+       { (char*)"iso-8859-3", 0x06 },
+       { (char*)"iso-8859-4", 0x07 },
+       { (char*)"iso-8859-5", 0x08 },
+       { (char*)"iso-8859-6", 0x09 },
+       { (char*)"iso-8859-7", 0x0a },
+       { (char*)"iso-8859-8", 0x0b },
+       { (char*)"iso-8859-9", 0x0c },
+       { (char*)"shift-JIS", 0x11 },
+       { (char*)"us-ascii", 0x03 },
+       { (char*)"utf-8", 0x6a },
+       { (char*)"none", 0x26 },
+       { (char*)"", 0xffff }
+};
+
+
+
+const char* wspEncodeMethod[] =
+{
+       (char*)"Gzip",
+       (char*)"Compress",
+       (char*)"Deflate"
+};
+
+
+const SMS_WSP_CONTENTS_TYPE_S wspContentsType[] =
+{
+       { (char*)"*/*", 0x00 },
+       { (char*)"text/*", 0x01 },
+       { (char*)"text/html", 0x02 },
+       { (char*)"text/plain", 0x03 },
+       { (char*)"text/x-hdml", 0x04 },
+       { (char*)"text/x-ttml", 0x05 },
+       { (char*)"text/x-vCalendar", 0x06 },
+       { (char*)"text/x-vCard", 0x07 },
+       { (char*)"text/vnd.wap.wml", 0x08 },
+       { (char*)"text/vnd.wap.wmlscript", 0x09 },
+       { (char*)"text/vnd.wap.wta-event", 0x0a },
+       { (char*)"multipart/*", 0x0b },
+       { (char*)"multipart/mixed", 0x0c },
+       { (char*)"multipart/form-data", 0x0d },
+       { (char*)"multipart/byteranges", 0x0e },
+       { (char*)"multipart/alternative", 0x0f },
+       { (char*)"application/*", 0x10 },
+       { (char*)"application/java-vm", 0x11 },
+       { (char*)"application/x-www-form-urlencoded", 0x12 },
+       { (char*)"application/x-hdmlc", 0x13 },
+       { (char*)"application/vnd.wap.wmlc", 0x14 },
+       { (char*)"application/vnd.wap.wmlscriptc", 0x15 },
+       { (char*)"application/vnd.wap.wta-eventc", 0x16 },
+       { (char*)"application/vnd.wap.uaprof", 0x17 },
+       { (char*)"application/vnd.wap.wtls-ca-certificate", 0x18 },
+       { (char*)"application/vnd.wap.wtls-user-certificate", 0x19 },
+       { (char*)"application/x-x509-ca-cert", 0x1a },
+       { (char*)"application/x-x509-user-cert", 0x1b },
+       { (char*)"image/*", 0x1c },
+       { (char*)"image/gif", 0x1d },
+       { (char*)"image/jpeg", 0x1e },
+       { (char*)"image/tiff", 0x1f },
+       { (char*)"image/png", 0x20 },
+       { (char*)"image/vnd.wap.wbmp", 0x21 },
+       { (char*)"application/vnd.wap.multipart.*", 0x22 },
+       { (char*)"application/vnd.wap.multipart.mixed", 0x23 },
+       { (char*)"application/vnd.wap.multipart.form-data", 0x24 },
+       { (char*)"application/vnd.wap.multipart.byteranges", 0x25 },
+       { (char*)"application/vnd.wap.multipart.alternative", 0x26 },
+       { (char*)"application/xml", 0x27 },
+       { (char*)"text/xml",0x28 },
+       { (char*)"application/vnd.wap.wbxml", 0x29 },
+       { (char*)"application/x-x968-cross-cert", 0x2a },
+       { (char*)"application/x-x968-ca-cert", 0x2b },
+       { (char*)"application/x-x968-user-cert", 0x2c },
+       { (char*)"text/vnd.wap.si", 0x2d },
+       { (char*)"application/vnd.wap.sic", 0x2e },
+       { (char*)"text/vnd.wap.sl", 0x2f },
+       { (char*)"application/vnd.wap.slc", 0x30 },
+       { (char*)"text/vnd.wap.co", 0x31 },
+       { (char*)"application/vnd.wap.coc", 0x32 },
+       { (char*)"application/vnd.wap.multipart.related", 0x33 },
+       { (char*)"application/vnd.wap.sia", 0x34 },
+
+       { (char*)"text/vnd/wap/connectivity-xml", 0x35 },
+       { (char*)"application/vnd.connectivity-wbxml", 0x36 },
+       { (char*)"application/pkcs7-mime",  0x37 },
+       { (char*)"application/vnd.wap.hashed-certificate", 0x38 },
+       { (char*)"application/vnd.wap.signed-certificate", 0x39  },
+       { (char*)"application/vnd.wap.cert-response", 0x3A },
+       { (char*)"application/xhtml+xml", 0x3B },
+       { (char*)"application/wml+xml", 0x3C  },
+       { (char*)"text/css", 0x3D },
+
+       { (char*)"application/vnd.wap.mms-message", 0x3E },
+
+       { (char*)"application/vnd.wap.rollover-certificate", 0x3F  },
+       { (char*)"application/vnd.wap.locc+wbxml", 0x40 },
+       { (char*)"application/vnd.wap.loc+xml", 0x41 },
+       { (char*)"application/vnd.syncml.dm+wbxml", 0x42 },
+       { (char*)"application/vnd.syncml.dm+xml", 0x43 },
+       { (char*)"application/vnd.syncml.notification", 0x44 },
+       { (char*)"application/vnd.wap.xhtml+xml", 0x45 },
+       { (char*)"application/vnd.wv.csp.cir", 0x46 }
+};
+
+static const SMS_WAP_UNREGISTER_CONTENTS_TYPE_S wspUnregisterContentsType[]=
+{
+       { (char*)"application/vnd.wap.emn+wbxml", 0x30A},
+       { (char*)"application/vnd.omaloc-supl-init", 0x312},
+       { (char*)"application/vnd.oma.drm.roap-trigger+wbxml", 0x316}
+};
+
+const unsigned long wspUnregisteredContentsTypeCount = sizeof(wspUnregisterContentsType)/sizeof(SMS_WAP_UNREGISTER_CONTENTS_TYPE_S);
+
+const SMS_WSP_LANGUAGE_S wspLanguage[] =
+{
+       { (char*)"English", 0x19 },
+       { (char*)"en", 0x19 },
+       { (char*)"Korean", 0x3d },
+       { (char*)"*", 0x00 },
+       { (char*)"Afar", 0x01 },
+       { (char*)"aa", 0x01 },
+       { (char*)"Abkhazian", 0x02 },
+       { (char*)"ab", 0x02 },
+       { (char*)"Afrikaans", 0x03 },
+       { (char*)"af", 0x03 },
+       { (char*)"Amharic", 0x04 },
+       { (char*)"am", 0x04 },
+       { (char*)"Arabic", 0x05 },
+       { (char*)"ar", 0x05 },
+       { (char*)"Assamese", 0x06 },
+       { (char*)"as", 0x06 },
+       { (char*)"Aymara", 0x07 },
+       { (char*)"ay", 0x07 },
+       { (char*)"Azerbaijani", 0x08 },
+       { (char*)"az", 0x08 },
+       { (char*)"Bashkir", 0x09 },
+       { (char*)"ba", 0x09 },
+       { (char*)"Byelorussian", 0x0a },
+       { (char*)"be", 0x0a },
+       { (char*)"Bulgarian", 0x0b },
+       { (char*)"bg", 0x0b },
+       { (char*)"Bihari", 0x0c },
+       { (char*)"bh", 0x0c },
+       { (char*)"Bislama", 0x0d },
+       { (char*)"bi", 0x0f },
+       { (char*)"Bengali", 0x0e },
+       { (char*)"Bangla", 0x0e },
+       { (char*)"bn", 0x0e },
+       { (char*)"Tibetan", 0x0f },
+       { (char*)"bo", 0x0f },
+       { (char*)"Breton", 0x10 },
+       { (char*)"br", 0x10 },
+       { (char*)"Catalan", 0x11 },
+       { (char*)"ca", 0x11 },
+       { (char*)"Corsican", 0x12 },
+       { (char*)"co", 0x12 },
+       { (char*)"Czech", 0x13 },
+       { (char*)"cs", 0x13 },
+       { (char*)"Welsh", 0x14 },
+       { (char*)"cy", 0x14 },
+       { (char*)"Denish", 0x15 },
+       { (char*)"da", 0x15 },
+       { (char*)"German", 0x16 },
+       { (char*)"de", 0x16 },
+       { (char*)"Bhutani", 0x17 },
+       { (char*)"dz", 0x17 },
+       { (char*)"Greek", 0x18 },
+       { (char*)"el", 0x18 },
+       { (char*)"Esperanto", 0x81 },
+       { (char*)"eo", 0x1a },
+       { (char*)"Spanish", 0x1b },
+       { (char*)"es", 0x1b },
+       { (char*)"Estonian", 0x1c },
+       { (char*)"et", 0x1c },
+       { (char*)"Basque", 0x1d },
+       { (char*)"eu", 0x1d },
+       { (char*)"Persian", 0x1e },
+       { (char*)"fa", 0x1e },
+       { (char*)"Finnish", 0x1f },
+       { (char*)"fi", 0x1f },
+       { (char*)"Fiji", 0x20 },
+       { (char*)"fj", 0x20 },
+       { (char*)"Faeroese", 0x82 },
+       { (char*)"fo", 0x82 },
+       { (char*)"French", 0x22 },
+       { (char*)"fr", 0x22 },
+       { (char*)"Frisian", 0x83 },
+       { (char*)"fy", 0x83 },
+       { (char*)"Irish", 0x24 },
+       { (char*)"ga", 0x24 },
+       { (char*)"Scots Gaelic", 0x25 },
+       { (char*)"gd", 0x25 },
+       { (char*)"Galician", 0x26 },
+       { (char*)"gl", 0x26 },
+       { (char*)"Guarani", 0x27 },
+       { (char*)"gn", 0x27 },
+       { (char*)"Gujarati", 0x28 },
+       { (char*)"gu", 0x28 },
+       { (char*)"Hausa", 0x29 },
+       { (char*)"ha", 0x29 },
+       { (char*)"Hebrew", 0x2a },
+       { (char*)"he", 0x2a },
+       { (char*)"Hindi", 0x2b },
+       { (char*)"hi", 0x2b },
+       { (char*)"Croatian", 0x2c },
+       { (char*)"hr", 0x2c },
+       { (char*)"Hungarian", 0x2d },
+       { (char*)"hu", 0x2d },
+       { (char*)"Armenian", 0x2e },
+       { (char*)"hy", 0x2e },
+       { (char*)"Interlingua", 0x84 },
+       { (char*)"ia", 0x84 },
+       { (char*)"Indonesian", 0x30 },
+       { (char*)"id", 0x30 },
+       { (char*)"Interlingue", 0x86 },
+       { (char*)"ie", 0x86 },
+       { (char*)"Maori", 0x47 },
+       { (char*)"mi", 0x47 },
+       { (char*)"Macedonian", 0x48 },
+       { (char*)"mk", 0x48 },
+       { (char*)"Malayalam", 0x49 },
+       { (char*)"ml", 0x49 },
+       { (char*)"Mongolian", 0x4a },
+       { (char*)"mn", 0x4a },
+       { (char*)"Moldavian", 0x4b },
+       { (char*)"mo", 0x4d },
+       { (char*)"Marathi", 0x4c },
+       { (char*)"mr", 0x4c },
+       { (char*)"Malay", 0x4d },
+       { (char*)"ms", 0x4d },
+       { (char*)"Maltese", 0x4e },
+       { (char*)"mt", 0x4e },
+       { (char*)"Burmese", 0x4f },
+       { (char*)"my", 0x4f },
+       { (char*)"Nauru", 0x50 },
+       { (char*)"na", 0x50 },
+       { (char*)"Nepali", 0x51 },
+       { (char*)"ne", 0x51 },
+       { (char*)"Dutch", 0x52 },
+       { (char*)"nl", 0x52 },
+       { (char*)"Norwegian", 0x53 },
+       { (char*)"no", 0x53 },
+       { (char*)"Occitan", 0x54 },
+       { (char*)"oc", 0x54 },
+       { (char*)"(Afan) Oromo", 0x55 },
+       { (char*)"(Afan)Oromo", 0x55 },
+       { (char*)"om", 0x55 },
+       { (char*)"Oriya", 0x56 },
+       { (char*)"or", 0x56 },
+       { (char*)"Punjabi", 0x57 },
+       { (char*)"pa", 0x57 },
+       { (char*)"Polish", 0x58 },
+       { (char*)"po", 0x58 },
+       { (char*)"Pashto", 0x59 },
+       { (char*)"Pushto", 0x59 },
+       { (char*)"ps", 0x59 },
+       { (char*)"Portugurse", 0x5a },
+       { (char*)"pt", 0x5a },
+       { (char*)"Quechua", 0x5b },
+       { (char*)"qu", 0x5b },
+       { (char*)"Rhaeto-Romance", 0x8c },
+       { (char*)"rm", 0x8c },
+       { (char*)"Kirundi", 0x5d },
+       { (char*)"rn", 0x5d },
+       { (char*)"Romanian", 0x5e },
+       { (char*)"ro", 0x5e },
+       { (char*)"Russian", 0x5f },
+       { (char*)"ru", 0x5f },
+       { (char*)"Kinyarwanda", 0x60 },
+       { (char*)"rw", 0x60 },
+       { (char*)"Sanskrit", 0x61 },
+       { (char*)"sa", 0x61 },
+       { (char*)"Sindhi", 0x62 },
+       { (char*)"sd", 0x62 },
+       { (char*)"Sangho", 0x63 },
+       { (char*)"sg", 0x63 },
+       { (char*)"Serbo-Croatian", 0x64 },
+       { (char*)"sh", 0x64 },
+       { (char*)"Sinhalese", 0x65 },
+       { (char*)"si", 0x65 },
+       { (char*)"Slovak", 0x66 },
+       { (char*)"sk", 0x66 },
+       { (char*)"Slovenian", 0x67 },
+       { (char*)"sl", 0x67 },
+       { (char*)"Samoan", 0x68 },
+       { (char*)"sm", 0x68 },
+       { (char*)"Shona", 0x69 },
+       { (char*)"sn", 0x69 },
+       { (char*)"Somali", 0x6a },
+       { (char*)"so", 0x6a },
+       { (char*)"Albanian", 0x6b },
+       { (char*)"sq", 0x6b },
+       { (char*)"Serbian", 0x6c },
+       { (char*)"sr", 0x6c },
+       { (char*)"Siswati", 0x6d },
+       { (char*)"ss", 0x6d },
+       { (char*)"Sesotho", 0x6e },
+       { (char*)"st", 0x6e },
+       { (char*)"Sundanese", 0x6f },
+       { (char*)"su", 0x6f },
+       { (char*)"Swedish", 0x70 },
+       { (char*)"sv", 0x70 },
+       { (char*)"Swahili", 0x71 },
+       { (char*)"sw", 0x71 },
+       { (char*)"Tamil", 0x72 },
+       { (char*)"ta", 0x72 },
+       { (char*)"Telugu", 0x73 },
+       { (char*)"te", 0x73 },
+       { (char*)"Tajik", 0x74 },
+       { (char*)"tg", 0x74 },
+       { (char*)"Thai", 0x75 },
+       { (char*)"th", 0x75 },
+       { (char*)"Tigrinya", 0x76 },
+       { (char*)"ti", 0x76 },
+       { (char*)"Turkmen", 0x77 },
+       { (char*)"tk", 0x77 },
+       { (char*)"Inupiak", 0x87 },
+       { (char*)"ik", 0x87 },
+       { (char*)"Icelandic", 0x33 },
+       { (char*)"is", 0x33 },
+       { (char*)"Italian", 0x34 },
+       { (char*)"it", 0x34 },
+       { (char*)"Inuktitut", 0x89 },
+       { (char*)"iu", 0x89 },
+       { (char*)"Japanese", 0x36 },
+       { (char*)"ja", 0x36 },
+       { (char*)"Javanese", 0x37 },
+       { (char*)"jw", 0x37 },
+       { (char*)"Georgian", 0x38 },
+       { (char*)"ka", 0x38 },
+       { (char*)"Kazakh", 0x39 },
+       { (char*)"kk", 0x39 },
+       { (char*)"Gerrnlandic", 0x8a },
+       { (char*)"kl", 0x8a },
+       { (char*)"Cambodian", 0x3b },
+       { (char*)"km", 0x3b },
+       { (char*)"Kannada", 0x3c },
+       { (char*)"kn", 0x3c },
+       { (char*)"Kashmiri", 0x3e },
+       { (char*)"ks", 0x3e },
+       { (char*)"Kurdish", 0x3f },
+       { (char*)"ku", 0x3f },
+       { (char*)"Kirghiz", 0x40 },
+       { (char*)"ky", 0x40 },
+       { (char*)"Latin", 0x8b },
+       { (char*)"la", 0x8b },
+       { (char*)"Lingala", 0x42 },
+       { (char*)"ln", 0x42 },
+       { (char*)"Laothian", 0x43 },
+       { (char*)"lo", 0x43 },
+       { (char*)"Lithuanian", 0x44 },
+       { (char*)"lt", 0x44 },
+       { (char*)"Lavian", 0x45 },
+       { (char*)"Lettish", 0x45 },
+       { (char*)"lv", 0x45 },
+       { (char*)"Malagasy", 0x46 },
+       { (char*)"mg", 0x46 },
+       { (char*)"Tagalog", 0x78 },
+       { (char*)"tl", 0x78 },
+       { (char*)"Setswana", 0x79 },
+       { (char*)"tn", 0x79 },
+       { (char*)"Tonga", 0x7a },
+       { (char*)"to", 0x7a },
+       { (char*)"Turkish", 0x7b },
+       { (char*)"tr", 0x7b },
+       { (char*)"Tsonga", 0x7c },
+       { (char*)"ts", 0x7c },
+       { (char*)"Tatar", 0x7d },
+       { (char*)"tt", 0x7d },
+       { (char*)"Twi", 0x7e },
+       { (char*)"tw", 0x7e },
+       { (char*)"Uighur", 0x7f },
+       { (char*)"ug", 0x7f },
+       { (char*)"Ukrainian", 0x1a },
+       { (char*)"uk", 0x1a },
+       { (char*)"Urdu", 0x21 },
+       { (char*)"ur", 0x21 },
+       { (char*)"Uzbek", 0x23 },
+       { (char*)"uz", 0x23 },
+       { (char*)"Vietnamese", 0x2f },
+       { (char*)"vi", 0x2f },
+       { (char*)"Volapuk", 0x85 },
+       { (char*)"vo", 0x85 },
+       { (char*)"Wolof", 0x31 },
+       { (char*)"wo" , 0x31 },
+       { (char*)"Xhosa", 0x32 },
+       { (char*)"xh", 0x32 },
+       { (char*)"Yiddish", 0x88 },
+       { (char*)"yi", 0x88 },
+       { (char*)"Yoruba", 0x35 },
+       { (char*)"yo", 0x35 },
+       { (char*)"Zhuang", 0x3a },
+       { (char*)"z", 0x3a },
+       { (char*)"Chinese", 0x41 },
+       { (char*)"ch", 0x41 },
+       { (char*)"Zulu", 0x5c },
+       { (char*)"zu", 0x5c },
+       { (char*)"Ko", 0x3d }
+};
+
+
+const SMS_WSP_HEADER_PARAMETER_S wspHeaderApplId[] =
+{
+       { (char*)"x-wap-application:*",  0x00 },
+       { (char*)"x-wap-application:push.sia",  0x01},
+       { (char*)"x-wap-application:wml.ua",  0x02 },
+       { (char*)"x-wap-application:wta.ua", 0x03 },
+       { (char*)"x-wap-application:mms.ua", 0x04 },
+       { (char*)"x-wap-application:push.syncml", 0x05 },
+       { (char*)"x-wap-application:loc.ua",  0x06 },
+       { (char*)"x-wap-application:syncml.dm", 0x07 },
+       { (char*)"x-wap-application:drm.ua", 0x08 },
+       { (char*)"x-wap-application:emn.ua", 0x09 },
+       { (char*)"x-oma-application:ulp.ua ", 0x90 },
+       { (char*)"x-oma-docomo:open.ctl", 0x9055 },
+       { (char*)"x-oma-docomo:xmd.mail.ua", 0x905C },
+       { (char*)"x-oma-docomo:xmd.storage.ua", 0x905F },
+       { (char*)"x-oma-docomo:xmd.lcsapp.ua", 0x9060 },
+       { (char*)"x-oma-docomo:xmd.info.ua", 0x9061 },
+       { (char*)"x-oma-docomo:xmd.agent.ua", 0x9062 },
+       { (char*)"x-oma-docomo:xmd.sab.ua", 0x9063 },
+       { (char*)"x-oma-docomo:xmd.am.ua", 0x9064 },
+       { (char*)"x-oma-docomo:xmd.emdm.ua", 0x906B },
+       { (char*)"x-oma-docomo:xmd.lac.ua", 0x906C },
+       { (char*)"x-oma-docomo:xmd.osv.ua", 0x906D },
+       { (char*)"x-oma-docomo:xmd.dcs.ua", 0x906E },
+       { (char*)"x-oma-docomo:xmd.wipe.ua", 0x906F },
+       { (char*)"x-oma-docomo:xmd.vdapp.ua ", 0x9070 },
+};
+
+
+const char* wspCacheControl[] =
+{
+       (char*)"No-cache",
+       (char*)"No-store",
+       (char*)"Max-age",
+       (char*)"Max-stale",
+       (char*)"Min-fresh",
+       (char*)"Only-if-cached",
+       (char*)"Public",
+       (char*)"Private",
+       (char*)"No-transform",
+       (char*)"Must-revalidate",
+       (char*)"Proxy-revalidate"
+};
+
+const SMS_WSP_METHOD_TYPE_S wspMethodType[] =
+{
+       { (char*)"GET", 0x40 },
+       { (char*)"OPTIONS", 0x41 },
+       { (char*)"HEAD", 0x42 },
+       { (char*)"DELETE", 0x43 },
+       { (char*)"TRACE", 0x44 },
+       { (char*)"POST", 0x60 },
+       { (char*)"PUT", 0x61 }
+};
+
+
+const SMS_WSP_SECURITY_TYPE_S wspSecurityType[] =
+{
+       {(char*)"NETWPIN",0x00},
+       {(char*)"USERPIN",0x01},
+       {(char*)"USERNETWPIN",0x02},
+       {(char*)"USERPINMAC",0x03}
+};
+
+
+
+const char* wspWeek[] =
+{
+       (char*)"Sun",
+       (char*)"Mon",
+       (char*)"Tue",
+       (char*)"Wed",
+       (char*)"Thu",
+       (char*)"Fri",
+       (char*)"Sat"
+};
+
+
+const char* wspWeekDay[] =
+{
+       (char*)"Sunday",
+       (char*)"Monday",
+       (char*)"Tuesday",
+       (char*)"Wednesday",
+       (char*)"Thursday",
+       (char*)"Friday",
+       (char*)"Saturday"
+};
+
+const char* wspMonth[] =
+{
+       (char*)"Jan",
+       (char*)"Feb",
+       (char*)"Mar",
+       (char*)"Apr",
+       (char*)"May",
+       (char*)"Jun",
+       (char*)"Jul",
+       (char*)"Aug",
+       (char*)"Sep",
+       (char*)"Oct",
+       (char*)"Nov",
+       (char*)"Dec"
+};
+
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginWapPushHandler - Member Functions
+==================================================================================================*/
+SmsPluginWapPushHandler* SmsPluginWapPushHandler::pInstance = NULL;
+
+
+SmsPluginWapPushHandler::SmsPluginWapPushHandler()
+{
+       memset(&tmpAddress, 0x00, sizeof(tmpAddress));
+}
+
+
+SmsPluginWapPushHandler::~SmsPluginWapPushHandler()
+{
+
+}
+
+
+SmsPluginWapPushHandler* SmsPluginWapPushHandler::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginWapPushHandler();
+
+       return pInstance;
+}
+
+bool SmsPluginWapPushHandler::IsWapPushMsg(unsigned short dstport)
+{
+       MSG_BEGIN();
+
+       int PortCount = sizeof(wapPushPortList)/sizeof(wapPushPortList[0]);
+
+       MSG_DEBUG("Port Count [%d]", PortCount);
+
+       for (int i = 0; i < PortCount; i++) {
+               if (dstport == wapPushPortList[i]) {
+                       MSG_DEBUG("Wap Push Msg : [%04x]", wapPushPortList[i]);
+                       return true;
+               }
+       }
+
+       MSG_END();
+
+       return false;
+}
+
+#if 0
+sms_wap_app_code_t SmsPluginWapPushHandler::getAppCode(const char *pPushHeader)
+{
+       int appCount = sizeof(pushDefaultApplication)/sizeof(pushDefaultApplication[0]) - 1;
+
+       unsigned char *header = NULL;
+       SMS_WAP_APP_CODE_T      appCode = SMS_WAP_APPLICATION_DEFAULT;
+
+       MSG_DEBUG("Application Count [%d]", appCount);
+
+       for (int i = 0; i < appCount; i++) {
+
+               header = (unsigned char*)strcasestr(pPushHeader, pushDefaultApplication[i].pContentType);
+
+               if (header != NULL) {
+                       appCode = pushDefaultApplication[i].appCode;
+                       break;
+               }
+       }
+
+       if (appCode == SMS_WAP_APPLICATION_DEFAULT) {
+               MSG_DEBUG("Application Type is not supported");
+       } else {
+               MSG_DEBUG("Find Application [%d]", appCode);
+       }
+
+       return appCode;
+}
+#endif
+
+
+void SmsPluginWapPushHandler::copyDeliverData(sms_trans_addr_s *pAddr)
+{
+       memcpy(&tmpAddress, pAddr, sizeof(tmpAddress));
+
+       MSG_SEC_DEBUG("Address [%s]", tmpAddress.szData);
+
+/*
+       tmpTimeStamp.format = pDeliver->timeStamp.format;
+
+       if (tmpTimeStamp.format == SMS_TIME_ABSOLUTE) {
+               tmpTimeStamp.time.absolute.year = pDeliver->timeStamp.time.absolute.year;
+               tmpTimeStamp.time.absolute.month = pDeliver->timeStamp.time.absolute.month;
+               tmpTimeStamp.time.absolute.day = pDeliver->timeStamp.time.absolute.day;
+               tmpTimeStamp.time.absolute.hour = pDeliver->timeStamp.time.absolute.hour;
+               tmpTimeStamp.time.absolute.minute = pDeliver->timeStamp.time.absolute.minute;
+               tmpTimeStamp.time.absolute.second = pDeliver->timeStamp.time.absolute.second;
+               tmpTimeStamp.time.absolute.timeZone = pDeliver->timeStamp.time.absolute.timeZone;
+       }
+*/
+}
+
+
+void SmsPluginWapPushHandler::handleWapPushMsg(const char *pUserData, int DataSize)
+{
+       MSG_BEGIN();
+
+#ifdef MSG_FW_FOR_DEBUG
+       MSG_DEBUG("DataSize [%d]", DataSize);
+
+       MSG_DEBUG("[pUserData]");
+       for (int i = 0; i < DataSize; i++)
+       {
+               printf("[%02x]", pUserData[i]);
+       }
+       printf("\n\n");
+#endif
+
+       unsigned char* pPDUTypeData = (unsigned char*)pUserData;
+       unsigned long PDUTypeDataLen = DataSize;
+
+       char* pPushHeader = NULL;
+       unique_ptr<char*, void(*)(char**)> pushHeaderBuf(&pPushHeader, unique_ptr_deleter);
+       unsigned long pushHeaderLen = 0;
+
+       char* pPushBody = NULL;
+       unique_ptr<char*, void(*)(char**)> PushBodyBuf(&pPushBody, unique_ptr_deleter);
+       unsigned long pushBodyLen = 0;
+
+       unsigned long iPDU = 1;
+
+       char* pWspHeader = NULL;
+       unique_ptr<char*, void(*)(char**)> WspHeaderBuf(&pWspHeader, unique_ptr_deleter);
+       unsigned long   wspHeaderLen = 0;
+
+       char* pWspBody = NULL;
+       unique_ptr<char*, void(*)(char**)> WspBodyBuf(&pWspBody, unique_ptr_deleter);
+       unsigned long wspBodyLen = 0;
+
+       /** pass PDU type */
+       iPDU++;
+
+       pushHeaderLen = wspRetriveUintvarDecode( pPDUTypeData, &iPDU );
+
+       MSG_DEBUG("PDUTypeDataLen [%d]", PDUTypeDataLen);
+       MSG_DEBUG("pushHeaderLen [%d]", pushHeaderLen);
+       MSG_DEBUG("iPDU [%d]", iPDU);
+
+       wspHeaderLen = pushHeaderLen + iPDU;
+
+       MSG_DEBUG("wspBodyLen [%d]", wspBodyLen);
+
+       if (wspHeaderLen > 0) {
+
+               pWspHeader = new char[wspHeaderLen];
+
+               if (pWspHeader == NULL) {
+                       MSG_DEBUG("pWspHeader Memory Allocation Failed");
+                       return;
+               } else {
+                       memcpy(pWspHeader, pPDUTypeData, wspHeaderLen);
+               }
+       }
+
+#ifdef MSG_FW_FOR_DEBUG
+       MSG_DEBUG("wspHeaderLen [%d]", wspHeaderLen);
+
+       MSG_DEBUG("[pWspHeader]");
+       for (int i = 0; i < wspHeaderLen; i++)
+       {
+               printf("[%02x]", pWspHeader[i]);
+       }
+       printf("\n\n");
+#endif
+
+       /** return if it is below case error */
+       if (PDUTypeDataLen < wspHeaderLen) {
+               MSG_DEBUG("PDUTypeDataLen < wspHeaderLen !!!");
+               return;
+       }
+
+       /** Finding wspBody Information */
+       wspBodyLen = PDUTypeDataLen - wspHeaderLen;
+
+       if (wspBodyLen > 0) {
+
+               pWspBody = new char[wspBodyLen];
+
+               if (pWspBody == NULL) {
+                       MSG_DEBUG("pWspBody Memory Allocation Failed");
+                       return;
+               } else {
+                       memcpy(pWspBody, pPDUTypeData + wspHeaderLen, wspBodyLen);
+               }
+       } else {
+               pWspBody = NULL;
+       }
+
+       wspDecodeHeader(pPDUTypeData + iPDU, pushHeaderLen, PDUTypeDataLen - (iPDU + pushHeaderLen), TRUE, &pPushHeader);
+
+       iPDU = iPDU + pushHeaderLen;
+
+       pushBodyLen = PDUTypeDataLen - iPDU ;
+
+       if (pushBodyLen > 0) {
+               pPushBody = new char[pushBodyLen];
+
+               if (pPushBody == NULL)  {
+                       MSG_DEBUG("pPushBody Memory Allocation Failed");
+                       return;
+               } else {
+                       memcpy(pPushBody, pPDUTypeData+ iPDU, pushBodyLen);
+               }
+       } else {
+               pPushBody = NULL;
+               return;
+       }
+
+       handleWapPushCallback((char *)pPushHeader, (char *)pPushBody, (int)pushBodyLen, (char *)pWspHeader, (int)wspHeaderLen, (char *)pWspBody, (int)wspBodyLen);
+
+       MSG_END();
+}
+
+#if 0
+void SmsPluginWapPushHandler::handleWapPushCallback(char* pPushHeader, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen, char* pWspBody, int WspBodyLen)
+{
+       MSG_BEGIN();
+
+       if (pPushBody == NULL) {
+               MSG_DEBUG("pPushBody is NULL");
+               return;
+       }
+
+       SMS_WAP_APP_CODE_T      appCode = getAppCode(pPushHeader);
+
+       /**  check Push message receive setting */
+       bool bPushRecv = false;
+
+       MsgSettingGetBool(PUSH_RECV_OPTION, &bPushRecv);
+
+       if ((bPushRecv == false) && (appCode != SMS_WAP_APPLICATION_MMS_UA)) {
+               MSG_DEBUG("Push Message Receive option is OFF. Drop Push Message.");
+               return;
+       }
+
+       switch (appCode) {
+       case SMS_WAP_APPLICATION_MMS_UA:
+               MSG_DEBUG("Received MMS Notification");
+               handleMMSNotification(pPushBody, PushBodyLen);
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_SI:
+               MSG_DEBUG("Received WAP Push (Service Indication Textual form)");
+               handleSIMessage(pPushBody, PushBodyLen, true);
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_SIC:
+               MSG_DEBUG("Received WAP Push (Service Indication Tokenised form)");
+               handleSIMessage(pPushBody, PushBodyLen, false);
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_SL:
+               MSG_DEBUG("Received WAP Push (Service Loading Textual form)");
+               handleSLMessage(pPushBody, PushBodyLen, true);
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_SLC:
+               MSG_DEBUG("Received WAP Push (Service Loading Tokenised form)");
+               handleSLMessage(pPushBody, PushBodyLen, false);
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_CO:
+               MSG_DEBUG("Received WAP Push (Cache Operation Textual form)");
+               handleCOMessage(pPushBody, PushBodyLen, true);
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_COC:
+               MSG_DEBUG("Received WAP Push (Cache Operation Tokenised form)");
+               handleCOMessage(pPushBody, PushBodyLen, false);
+               break;
+
+       case SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP:
+               MSG_DEBUG("Received DM BOOTSTRAP");
+               SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DM_WBXML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+               break;
+
+       case SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP_XML:
+               MSG_DEBUG("Received DM BOOTSTRAP");
+               SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DM_XML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_PROVISIONING_XML:
+               MSG_DEBUG("Received Provisioning");
+               SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(CP_XML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_PROVISIONING_WBXML:
+               MSG_DEBUG("Received Provisioning");
+               SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(CP_WBXML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_BROWSER_SETTINGS:
+       case SMS_WAP_APPLICATION_PUSH_BROWSER_BOOKMARKS:
+               MSG_DEBUG("Received Provisioning");
+               SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(OTHERS, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+               break;
+
+       case SMS_WAP_APPLICATION_SYNCML_DM_NOTIFICATION:
+               MSG_DEBUG("Received DM Notification");
+               SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DM_NOTIFICATION, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+               break;
+
+       case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION:
+               MSG_DEBUG("Received DS Notification");
+               SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DS_NOTIFICATION, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+               break;
+
+       case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION_WBXML:
+               MSG_DEBUG("Received DS Notification");
+               SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DS_WBXML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+               break;
+
+       case SMS_WAP_APPLICATION_DRM_UA_RIGHTS_XML:
+       case SMS_WAP_APPLICATION_DRM_UA_RIGHTS_WBXML:
+               MSG_DEBUG("Received DRM UA");
+
+               if (pPushBody != NULL)
+                       handleDrmVer1(pPushBody, PushBodyLen);
+
+               break;
+
+       case SMS_WAP_APPLICATION_DRM_V2_RO_XML:
+       case SMS_WAP_APPLICATION_DRM_V2_ROAP_PDU_XML:
+       case SMS_WAP_APPLICATION_DRM_V2_ROAP_TRIGGER_XML:
+       case SMS_WAP_APPLICATION_DRM_V2_ROAP_TRIGGER_WBXML:
+               MSG_DEBUG("Received DRM V2");
+               // TODO: DRM V2
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_EMAIL:
+       case SMS_WAP_APPLICATION_PUSH_EMAIL_XML:
+       case SMS_WAP_APPLICATION_PUSH_EMAIL_WBXML:
+               MSG_DEBUG("Received Email");
+               // TODO: Email
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_IMPS_CIR:
+               MSG_DEBUG("Received IMPS CIR");
+               // TODO: IMPS CIR
+               break;
+
+       case SMS_WAP_APPLICATION_LBS :
+               MSG_DEBUG("Received LBS related message");
+               SmsPluginEventHandler::instance()->handleLBSMsgIncoming(pPushHeader, pPushBody, PushBodyLen);
+               // TODO: LBS
+               break;
+
+       case SMS_WAP_APPLICATION_PUSH_SIA :
+               MSG_DEBUG("Received SIA");
+               // TODO: SIA
+               break;
+
+       default:
+               MSG_DEBUG("Unknown Application [%d]", appCode);
+               break;
+       }
+
+       MSG_END();
+}
+#else
+
+static void launchProcessByAppcode(int appcode)
+{
+       MSG_BEGIN();
+       GError *error = NULL;
+       GDBusConnection *connection_agent = NULL;
+       GDBusProxy *dbus_proxy_agent = NULL;
+       GDBusConnection *connection_service = NULL;
+       GDBusProxy *dbus_proxy_service = NULL;
+       GVariant *result_agent = NULL;
+       GVariant *result_service = NULL;
+
+       switch(appcode){
+               case SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP:
+               case SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP_XML:
+               case SMS_WAP_APPLICATION_PUSH_PROVISIONING_XML:
+               case SMS_WAP_APPLICATION_PUSH_PROVISIONING_WBXML:
+               case SMS_WAP_APPLICATION_PUSH_BROWSER_SETTINGS:
+               case SMS_WAP_APPLICATION_PUSH_BROWSER_BOOKMARKS:
+               case SMS_WAP_APPLICATION_SYNCML_DM_NOTIFICATION:
+                       {
+                               connection_agent = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to system bus failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               dbus_proxy_agent = g_dbus_proxy_new_sync(connection_agent, G_DBUS_PROXY_FLAGS_NONE,
+                                                                                       NULL, "org.tizen.omadmagent", "/org/tizen/omadmagent",
+                                                                                       "org.tizen.omadmagent", NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to agent proxy failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               result_agent = g_dbus_proxy_call_sync(dbus_proxy_agent, "Hello_Agent", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("invoking agent proxy call failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               connection_service = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to system bus failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               dbus_proxy_service =g_dbus_proxy_new_sync(connection_service, G_DBUS_PROXY_FLAGS_NONE, NULL,
+                                                                                       "org.tizen.omadmservice", "/org/tizen/omadmservice",
+                                                                                       "org.tizen.omadmservice", NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to service proxy failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               result_service = g_dbus_proxy_call_sync(dbus_proxy_service, "wakeup", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("invoking service proxy call failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               Mutex mx;
+                               CndVar cv;
+                               mx.lock();
+                               cv.timedwait(mx.pMutex(), 2);
+                               mx.unlock();
+
+                               MSG_END();
+                       }
+                       break;
+               case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION:
+               case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION_WBXML:
+                       {
+                               connection_agent = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to system bus failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               dbus_proxy_agent = g_dbus_proxy_new_sync(connection_agent, G_DBUS_PROXY_FLAGS_NONE, NULL,
+                                                                                       "org.tizen.omadsagent", "/org/tizen/omadsagent",
+                                                                                       "org.tizen.omadsagent", NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to agent proxy failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               result_agent = g_dbus_proxy_call_sync(dbus_proxy_agent, "Hello_Agent", NULL,
+                                                                               G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("invoking service error: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+                       }
+                       break;
+               default:
+                       break;
+       }
+
+_DBUS_ERROR:
+       if (error) {
+               g_error_free(error);
+               error = NULL;
+       }
+
+       if (connection_agent) {
+               g_object_unref(connection_agent);
+               connection_agent = NULL;
+       }
+
+       if (dbus_proxy_agent) {
+               g_object_unref(dbus_proxy_agent);
+               dbus_proxy_agent = NULL;
+       }
+
+       if (result_agent) {
+               g_object_unref(result_service);
+               result_service = NULL;
+       }
+
+       if (connection_service) {
+               g_object_unref(connection_service);
+               connection_service = NULL;
+       }
+
+       if (dbus_proxy_service) {
+               g_object_unref(dbus_proxy_service);
+               dbus_proxy_service = NULL;
+       }
+
+       if (result_service) {
+               g_object_unref(result_service);
+               result_service = NULL;
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginWapPushHandler::handleWapPushCallback(char* pPushHeader, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen, char* pWspBody, int WspBodyLen)
+{
+       MSG_BEGIN();
+
+       if (pPushBody == NULL) {
+               MSG_DEBUG("pPushBody is NULL");
+               return;
+       }
+
+       msg_error_t err = MSG_SUCCESS;
+       int pushEvt_cnt = 0;
+       char app_id[MAX_WAPPUSH_ID_LEN] = {0,};
+       char content_type[MAX_WAPPUSH_CONTENT_TYPE_LEN] = {0,};
+       SmsPluginStorage *storageHandler = SmsPluginStorage::instance();
+
+       err = storageHandler->getRegisteredPushEvent(pPushHeader, &pushEvt_cnt, app_id, sizeof(app_id), content_type, sizeof(content_type));
+       MSG_DEBUG("pushEvt_cnt: %d", pushEvt_cnt);
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to get registered push event");
+               return;
+       }
+
+       for(int i = 0; i < pushEvt_cnt; ++i)    {
+
+               /**  check Push message receive setting */
+               bool bPushRecv = false;
+               int appcode = 0;
+               MsgSettingGetBool(PUSH_RECV_OPTION, &bPushRecv);
+
+               storageHandler->getnthPushEvent(i, &appcode);
+               MSG_DEBUG("pushEvt_cnt: %d, appcode: %d", pushEvt_cnt, appcode);
+               if ((bPushRecv == false) && (appcode != SMS_WAP_APPLICATION_MMS_UA)) {
+                       MSG_DEBUG("Push Message Receive option is OFF. Drop Push Message.");
+                       return;
+               }
+
+#ifdef FEATURE_MMS_DISABLE
+               if (appcode == SMS_WAP_APPLICATION_MMS_UA){
+                       MSG_DEBUG("Drop MMS Notification for DOCOMO");
+                       return;
+               }
+
+#endif
+               launchProcessByAppcode(appcode);
+
+               switch (appcode) {
+               case SMS_WAP_APPLICATION_MMS_UA:
+                       MSG_DEBUG("Received MMS Notification");
+                       handleMMSNotification(pPushBody, PushBodyLen);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_SI:
+                       MSG_DEBUG("Received WAP Push (Service Indication Textual form)");
+//                     handleSIMessage(pPushBody, PushBodyLen, true);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_SIC:
+                       MSG_DEBUG("Received WAP Push (Service Indication Tokenised form)");
+//                     handleSIMessage(pPushBody, PushBodyLen, false);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_SL:
+                       MSG_DEBUG("Received WAP Push (Service Loading Textual form)");
+//                     handleSLMessage(pPushBody, PushBodyLen, true);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_SLC:
+                       MSG_DEBUG("Received WAP Push (Service Loading Tokenised form)");
+//                     handleSLMessage(pPushBody, PushBodyLen, false);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_CO:
+                       MSG_DEBUG("Received WAP Push (Cache Operation Textual form)");
+//                     handleCOMessage(pPushBody, PushBodyLen, true);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_COC:
+                       MSG_DEBUG("Received WAP Push (Cache Operation Tokenised form)");
+//                     handleCOMessage(pPushBody, PushBodyLen, false);
+                       break;
+
+               case SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP:
+                       MSG_DEBUG("Received DM BOOTSTRAP");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DM_WBXML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+                       break;
+
+               case SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP_XML:
+                       MSG_DEBUG("Received DM BOOTSTRAP");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DM_XML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_PROVISIONING_XML:
+                       MSG_DEBUG("Received Provisioning");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(CP_XML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_PROVISIONING_WBXML:
+                       MSG_DEBUG("Received Provisioning");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(CP_WBXML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_BROWSER_SETTINGS:
+               case SMS_WAP_APPLICATION_PUSH_BROWSER_BOOKMARKS:
+                       MSG_DEBUG("Received Provisioning");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(OTHERS, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+                       break;
+
+               case SMS_WAP_APPLICATION_SYNCML_DM_NOTIFICATION:
+                       MSG_DEBUG("Received DM Notification");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DM_NOTIFICATION, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+                       break;
+
+               case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION:
+                       MSG_DEBUG("Received DS Notification");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DS_NOTIFICATION, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+                       break;
+
+               case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION_WBXML:
+                       MSG_DEBUG("Received DS Notification");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DS_WBXML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen);
+                       break;
+
+               case SMS_WAP_APPLICATION_DRM_UA_RIGHTS_XML:
+               case SMS_WAP_APPLICATION_DRM_UA_RIGHTS_WBXML:
+                       MSG_DEBUG("Received DRM UA");
+
+                       if (pPushBody != NULL)
+                               handleDrmVer1(pPushBody, PushBodyLen);
+
+                       break;
+
+               case SMS_WAP_APPLICATION_DRM_V2_RO_XML:
+               case SMS_WAP_APPLICATION_DRM_V2_ROAP_PDU_XML:
+               case SMS_WAP_APPLICATION_DRM_V2_ROAP_TRIGGER_XML:
+               case SMS_WAP_APPLICATION_DRM_V2_ROAP_TRIGGER_WBXML:
+                       MSG_DEBUG("Received DRM V2");
+                       // TODO: DRM V2
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_EMAIL:
+               case SMS_WAP_APPLICATION_PUSH_EMAIL_XML:
+               case SMS_WAP_APPLICATION_PUSH_EMAIL_WBXML:
+                       MSG_DEBUG("Received Email");
+                       // TODO: Email
+                       break;
+
+
+               case SMS_WAP_APPLICATION_PUSH_IMPS_CIR:
+                       MSG_DEBUG("Received IMPS CIR");
+                       // TODO: IMPS CIR
+                       break;
+
+               case SMS_WAP_APPLICATION_LBS :
+                       MSG_DEBUG("Received LBS related message");
+                       SmsPluginEventHandler::instance()->handleLBSMsgIncoming(pPushHeader, pPushBody, PushBodyLen);
+                       // TODO: LBS
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_SIA :
+                       MSG_DEBUG("Received SIA");
+                       // TODO: SIA
+                       break;
+
+               default:
+                       SmsPluginEventHandler::instance()->handlePushMsgIncoming(pPushHeader, pPushBody, PushBodyLen, app_id, content_type);
+                       break;
+               }
+       }
+       storageHandler->releasePushEvent();
+
+       MSG_END();
+}
+#endif
+
+void SmsPluginWapPushHandler::handleMMSNotification(const char *pPushBody, int PushBodyLen)
+{
+       MSG_BEGIN();
+
+#ifdef MSG_FW_FOR_DEBUG
+       printf("\n\n[handleMMSNotification] Push Body.\n");
+
+       for (int i = 0; i < PushBodyLen; i++)
+       {
+               printf(" [%02x]", pPushBody[i]);
+       }
+       printf("\n\n");
+#endif
+
+       /** Make MSG_MESSAGE_INFO_S */
+       MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       createMsgInfo(&msgInfo);
+
+       /** Convert Type values */
+       msgInfo.msgType.mainType = MSG_MMS_TYPE;
+       msgInfo.msgType.subType = MSG_NOTIFICATIONIND_MMS;
+       msgInfo.msgType.classType = MSG_CLASS_NONE;
+       msgInfo.storageId = MSG_STORAGE_PHONE;
+       msgInfo.dataSize = PushBodyLen;
+
+       if (msgInfo.dataSize > MAX_MSG_TEXT_LEN) {
+               msgInfo.bTextSms = false;
+
+               /** Save Message Data into File */
+               char fileName[MSG_FILENAME_LEN_MAX+1];
+               memset(fileName, 0x00, sizeof(fileName));
+
+               if (MsgCreateFileName(fileName) == false) {
+                       THROW(MsgException::FILE_ERROR, "MsgCreateFileName error");
+               }
+
+               if (MsgWriteIpcFile(fileName, pPushBody, msgInfo.dataSize) == false) {
+                       THROW(MsgException::FILE_ERROR, "MsgWriteIpcFile error");
+               }
+
+               strncpy(msgInfo.msgData, fileName, MAX_MSG_DATA_LEN);
+       } else {
+               msgInfo.bTextSms = true;
+
+               memcpy(msgInfo.msgText, pPushBody, msgInfo.dataSize);
+               msgInfo.msgText[msgInfo.dataSize] = '\0';
+       }
+
+       msg_error_t err = MSG_SUCCESS;
+
+       /** Add MMS Noti Msg into DB */
+       err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
+
+       if (err == MSG_SUCCESS) {
+               /**  Callback */
+               err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+               }
+       } else {
+               MSG_DEBUG("checkMessage() Error !! [%d]", err);
+       }
+
+       MSG_END();
+}
+
+void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen, bool isText)
+{
+       MSG_BEGIN();
+
+       MSG_PUSH_MESSAGE_S pushMsg = {};
+
+       xmlDocPtr       xmlDoc = NULL;
+       xmlNodePtr      topNode = NULL;
+       xmlNodePtr      indNode = NULL;
+
+       xmlChar*                tmpXmlChar = NULL;
+
+       if (pPushBody == NULL) {
+               MSG_DEBUG("pPushBody is NULL");
+               return;
+       }
+
+       getXmlDoc(pPushBody, PushBodyLen, &xmlDoc, isText);
+
+       if (xmlDoc == NULL) {
+               MSG_DEBUG("xmlDoc is NULL");
+               return;
+       }
+
+       topNode = xmlDocGetRootElement(xmlDoc);
+
+       if (topNode == NULL) {
+               MSG_DEBUG("topNode is NULL");
+               xmlFreeDoc(xmlDoc);
+               return;
+       }
+
+       indNode = topNode->xmlChildrenNode;
+
+       while (indNode != NULL) {
+               if (!xmlStrcmp(indNode->name, (const xmlChar*) "indication")) {
+                       MSG_SEC_DEBUG("indNode->name = %s\n", indNode->name);
+                       break;
+               }
+
+               indNode = indNode->next;
+       }
+
+       if (indNode == NULL) {
+               MSG_DEBUG("indNode is NULL.");
+               return;
+       }
+
+       /**  temporary set to max. */
+       pushMsg.expires = 0xFFFFFFFF;
+
+       /** setting received time */
+       time_t  t               =       time(NULL);
+       time_t  utfTime =       time(&t);
+
+       pushMsg.received = (unsigned long)utfTime;
+
+       tmpXmlChar = xmlGetProp(indNode, (xmlChar*)SMS_PUSH_XML_HREF_TAG);
+
+       if (tmpXmlChar == NULL) {
+               MSG_DEBUG("href is NULL.");
+               return;
+       }
+
+       if (tmpXmlChar != NULL)
+               strncpy(pushMsg.href, (char*)tmpXmlChar, MAX_WAPPUSH_HREF_LEN-1);
+
+       tmpXmlChar = xmlGetProp(indNode, (xmlChar*)SMS_PUSH_XML_SI_ID_TAG);
+
+       if (tmpXmlChar != NULL)
+               strncpy(pushMsg.id, (char*)tmpXmlChar, MAX_WAPPUSH_ID_LEN-1);
+
+       tmpXmlChar = xmlGetProp(indNode, (xmlChar*)SMS_PUSH_XML_CREATED_TAG);
+
+       if (tmpXmlChar != NULL)
+               pushMsg.created = convertXmlCharToSec((char*)tmpXmlChar);
+
+       if (pushMsg.created == 0)
+               pushMsg.created = pushMsg.received;
+
+       tmpXmlChar = xmlGetProp(indNode, (xmlChar*)SMS_PUSH_XML_EXPIRES_TAG);
+
+       if (tmpXmlChar != NULL)
+               pushMsg.expires = convertXmlCharToSec((char*)tmpXmlChar);
+
+       tmpXmlChar = xmlGetProp(indNode, (xmlChar*)SMS_PUSH_XML_ACTION_TAG);
+
+       pushMsg.action = convertSIActionStrToEnum((char*)tmpXmlChar);
+
+       tmpXmlChar = xmlNodeListGetString(xmlDoc, indNode->xmlChildrenNode, 1);
+
+       if (tmpXmlChar == NULL) {
+               MSG_DEBUG("contents is NULL.");
+               return;
+       }
+
+       strncpy(pushMsg.contents, (char*)tmpXmlChar, MAX_WAPPUSH_CONTENTS_LEN-1);
+
+       /** Write push Msg to file */
+       char fileName[MSG_FILENAME_LEN_MAX+1];
+       memset(fileName, 0x00, sizeof(fileName));
+
+       if (MsgCreateFileName(fileName) == false) {
+               xmlFree(xmlDoc);
+               xmlFree(tmpXmlChar);
+               THROW(MsgException::FILE_ERROR, "MsgCreateFileName error");
+       }
+
+       if (MsgWriteIpcFile(fileName, (char*)(&pushMsg), sizeof(pushMsg)) == false) {
+               xmlFree(xmlDoc);
+               xmlFree(tmpXmlChar);
+               THROW(MsgException::FILE_ERROR, "MsgWriteIpcFile error");
+       }
+
+       /**  Pack Message Info Structure */
+       MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       createMsgInfo(&msgInfo);
+
+       strncpy(msgInfo.msgData, fileName, MAX_MSG_DATA_LEN);
+
+       /**  Convert Type values */
+       msgInfo.msgType.mainType = MSG_SMS_TYPE;
+       msgInfo.msgType.subType = MSG_WAP_SI_SMS;
+
+       msgInfo.dataSize = sizeof(pushMsg);
+
+       xmlFree(xmlDoc);
+       xmlFree(tmpXmlChar);
+
+       msg_error_t err = MSG_SUCCESS;
+
+       /** Add WAP Push Msg into DB */
+       err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
+
+       if (err == MSG_SUCCESS) {
+               /** Callback */
+               err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+
+               if (err != MSG_SUCCESS){
+                       MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+               }
+       } else {
+               MSG_DEBUG("checkMessage() Error !! [%d]", err);
+       }
+
+       MSG_END();
+
+       return;
+}
+
+
+void SmsPluginWapPushHandler::handleSLMessage(char* pPushBody, int PushBodyLen, bool isText)
+{
+       MSG_BEGIN();
+
+       MSG_PUSH_MESSAGE_S pushMsg = {};
+
+       xmlDocPtr       xmlDoc = NULL;
+       xmlNodePtr      topNode = NULL;
+       xmlNodePtr      indNode = NULL;
+
+       xmlChar*                tmpXmlChar = NULL;
+
+       msg_error_t err = MSG_SUCCESS;
+
+       if (pPushBody == NULL) {
+               MSG_DEBUG("pPushBody is NULL \n" );
+               return;
+       }
+
+       getXmlDoc(pPushBody, PushBodyLen, &xmlDoc, isText);
+
+       if (xmlDoc == NULL) {
+               MSG_DEBUG("xmlDoc is NULL \n" );
+               return;
+       }
+
+       topNode = xmlDocGetRootElement(xmlDoc);
+
+       if (topNode == NULL) {
+               MSG_DEBUG("Empty Document." );
+               xmlFreeDoc(xmlDoc);
+               return;
+       } else {
+               MSG_SEC_DEBUG("Not an empty Document and topNode->name = %s \n",topNode->name );
+       }
+
+       indNode = topNode;
+
+       while (indNode != NULL) {
+               if (!xmlStrcmp(indNode->name, (const xmlChar*) "sl")) {
+                       MSG_SEC_DEBUG("indNode->name = %s\n",indNode->name);
+                       break;
+               }
+
+               indNode = indNode->next;
+       }
+
+       /**  setting received time setting */
+       time_t  t               =       time(NULL);
+       time_t  utfTime =       time(&t);
+
+       pushMsg.received = (unsigned long)utfTime;
+
+       tmpXmlChar = xmlGetProp(indNode, (xmlChar*)SMS_PUSH_XML_HREF_TAG);
+
+       if (tmpXmlChar == NULL) {
+               MSG_DEBUG("href is NULL.");
+               return;
+       }
+
+       strncpy(pushMsg.href, (char*)tmpXmlChar, MAX_WAPPUSH_HREF_LEN-1);
+
+       tmpXmlChar = xmlGetProp(indNode, (xmlChar*)SMS_PUSH_XML_ACTION_TAG);
+       pushMsg.action = convertSLActionStrToEnum((char*)tmpXmlChar);
+
+       /** Setting other parameters in default values */
+       pushMsg.created = pushMsg.received;
+       /** temporary set to MAX value. */
+       pushMsg.expires = 0xFFFFFFFF;
+
+       MSG_DEBUG("check pushMsg data");
+       MSG_DEBUG("pushMsg.action : [%d]", pushMsg.action);
+       MSG_DEBUG("pushMsg.received : [%d]", pushMsg.received);
+       MSG_DEBUG("pushMsg.created : [%d]", pushMsg.created);
+       MSG_DEBUG("pushMsg.expires : [%d]", pushMsg.expires);
+       MSG_SEC_DEBUG("pushMsg.id : [%s]", pushMsg.id);
+       MSG_DEBUG("pushMsg.href : [%s]", pushMsg.href);
+       MSG_DEBUG("pushMsg.contents : [%s]", pushMsg.contents);
+
+       /** Write push Msg to file */
+       char fileName[MSG_FILENAME_LEN_MAX+1];
+       memset(fileName, 0x00, sizeof(fileName));
+
+       if (MsgCreateFileName(fileName) == false)
+               THROW(MsgException::FILE_ERROR, "MsgCreateFileName error");
+
+       if (MsgWriteIpcFile(fileName, (char*)(&pushMsg), sizeof(pushMsg)) == false)
+               THROW(MsgException::FILE_ERROR, "MsgWriteIpcFile error");
+
+       /** Pack Message Info Structure */
+       MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       createMsgInfo(&msgInfo);
+
+       strncpy(msgInfo.msgData, fileName, MAX_MSG_DATA_LEN);
+
+       /** Convert Type values */
+       msgInfo.msgType.mainType = MSG_SMS_TYPE;
+       msgInfo.msgType.subType = MSG_WAP_SL_SMS;
+
+       /**  Update Msg Text */
+       strncpy(msgInfo.msgText, pushMsg.href, MAX_MSG_TEXT_LEN);
+
+       msgInfo.dataSize = sizeof(pushMsg);
+
+       MSG_DEBUG("dataSize : %d", msgInfo.dataSize);
+
+       /** Add WAP Push Msg into DB */
+       err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
+
+       if (err == MSG_SUCCESS) {
+               /** Callback to MSG FW */
+               err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+
+               if (err != MSG_SUCCESS)
+                       MSG_DEBUG("callbackMsgIncoming is failed, err=[%d]", err);
+       } else {
+               MSG_DEBUG("checkMessage() Error !! [%d]", err);
+       }
+
+       xmlFree(xmlDoc);
+       xmlFree(tmpXmlChar);
+
+       MSG_END();
+
+       return;
+}
+
+void SmsPluginWapPushHandler::handleCOMessage(char* pPushBody, int PushBodyLen, bool isText)
+{
+       MSG_PUSH_CACHEOP_S cacheOp;
+
+       xmlDocPtr       xmlDoc = NULL;
+       xmlNodePtr      topNode = NULL;
+       xmlNodePtr      indNode = NULL;
+
+       memset(&cacheOp, 0x00, sizeof(cacheOp));
+
+       MSG_DEBUG("Enter handleCOMessage");
+
+       if (pPushBody == NULL) {
+               MSG_DEBUG("pPushBody is NULL \n" );
+               return;
+       }
+
+       getXmlDoc(pPushBody, PushBodyLen, &xmlDoc, isText);
+
+       if (xmlDoc == NULL) {
+               MSG_DEBUG("xmlDoc is NULL \n" );
+               return;
+       }
+
+       topNode = xmlDocGetRootElement(xmlDoc);
+       if (topNode == NULL) {
+               MSG_DEBUG("Warning:Empty Document\n" );
+               xmlFreeDoc(xmlDoc);
+               return;
+       }
+
+       indNode = topNode->xmlChildrenNode;
+
+
+       while(indNode != NULL) {
+
+               xmlChar* tmpUrl = NULL;
+               if (!xmlStrcmp(indNode->name, (const xmlChar*) SMS_PUSH_XML_INVAL_OBJ)) {
+                       MSG_SEC_DEBUG("indNode->name = %s\n", indNode->name);
+
+                       tmpUrl = xmlGetProp(indNode, (xmlChar*) SMS_PUSH_XML_CO_URI);
+
+                       if (tmpUrl != NULL) {
+                               strncpy(cacheOp.invalObjectUrl[cacheOp.invalObjectCnt++], (char*)tmpUrl, MAX_PUSH_CACHEOP_MAX_URL_LEN-1);
+
+                               MSG_DEBUG("%dth invalObjectUrl is <%s>\n", cacheOp.invalObjectCnt, cacheOp.invalObjectUrl[cacheOp.invalObjectCnt-1]);
+                       } else {
+                               MSG_DEBUG("NO href value from the xmlDoc\n");
+                       }
+               } else if (!xmlStrcmp(indNode->name, (const xmlChar*) SMS_PUSH_XML_INVAL_SVC)) {
+                       MSG_SEC_DEBUG("indNode->name = %s\n",indNode->name);
+                       tmpUrl = xmlGetProp(indNode, (xmlChar*)SMS_PUSH_XML_CO_URI);
+
+                       if (tmpUrl != NULL) {
+                               strncpy(cacheOp.invalServiceUrl[cacheOp.invalServiceCnt++], (char*)tmpUrl, MAX_PUSH_CACHEOP_MAX_URL_LEN-1);
+                               MSG_DEBUG("%dth invalServiceUrl is <%s>\n", cacheOp.invalServiceCnt, cacheOp.invalServiceUrl[cacheOp.invalServiceCnt-1]);
+                       } else {
+                               MSG_DEBUG("NO href value from the xmlDoc\n");
+                       }
+               }
+
+               if (tmpUrl != NULL)
+                       xmlFree(tmpUrl);
+
+               indNode = indNode->next;
+       }
+
+       /**  Write push Msg to file */
+       char fileName[MSG_FILENAME_LEN_MAX+1];
+       memset(fileName, 0x00, sizeof(fileName));
+
+       if (MsgCreateFileName(fileName) == false) {
+               xmlFree(xmlDoc);
+               THROW(MsgException::FILE_ERROR, "MsgCreateFileName error");
+       }
+
+       if (MsgWriteIpcFile(fileName, (char*)(&cacheOp), sizeof(cacheOp)) == false) {
+               xmlFree(xmlDoc);
+               THROW(MsgException::FILE_ERROR, "MsgWriteIpcFile error");
+       }
+
+       /**  Pack Message Info Structure */
+       MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       createMsgInfo(&msgInfo);
+
+       strncpy(msgInfo.msgData, fileName, MAX_MSG_DATA_LEN);
+
+       /**  Convert Type values */
+       msgInfo.msgType.mainType = MSG_SMS_TYPE;
+       msgInfo.msgType.subType = MSG_WAP_CO_SMS;
+
+       msgInfo.dataSize = sizeof(cacheOp);
+
+       msg_error_t err = MSG_SUCCESS;
+
+       /** Add WAP Push Msg into DB */
+       err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
+
+       if (err == MSG_SUCCESS) {
+               /** Callback */
+               err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+               }
+       } else {
+               MSG_DEBUG("checkMessage() Error !! [%d]", err);
+       }
+
+       xmlFree(xmlDoc);
+
+       return;
+}
+
+
+void SmsPluginWapPushHandler::handleDrmVer1(char* pPushBody, int PushBodyLen)
+{
+#if MSG_DRM_SUPPORT
+       int drmRt = DRM_RETURN_SUCCESS;
+       char* cid = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&cid, unique_ptr_deleter);
+
+       MSG_DEBUG("Received DRM RIGHTS OBJECT Type WAP Push Message.");
+       drm_request_type_e request_type = DRM_REQUEST_TYPE_REGISTER_LICENSE;
+       drm_register_lic_info_s lic_req_info;
+       drm_register_lic_resp_s lic_resp_info;
+
+       bzero(&lic_req_info, sizeof(drm_register_lic_info_s));
+       bzero(&lic_resp_info, sizeof(drm_register_lic_resp_s));
+       bzero(lic_req_info.lic_data, sizeof(lic_req_info.lic_data));
+
+       memcpy(lic_req_info.lic_data, pPushBody, PushBodyLen);
+
+       lic_req_info.lic_version = DRM_OMA_DRMV1_RIGHTS;
+       lic_req_info.roap_init_src = DRM_ROAP_INIT_FROM_WAPPUSH;
+       lic_req_info.operation_callback.callback = NULL;
+
+       drmRt = drm_process_request(request_type, &lic_req_info, &lic_resp_info);
+       if (drmRt == DRM_RETURN_SUCCESS) {
+               MSG_DEBUG("DRM successfully registed to drm-service.");
+       } else {
+               MSG_DEBUG("Fail to regist DRM to drm-service.");
+       }
+#endif
+       return;
+}
+
+
+void SmsPluginWapPushHandler::createMsgInfo(MSG_MESSAGE_INFO_S* pMsgInfo)
+{
+       /** Convert class Type values */
+       pMsgInfo->msgType.classType = MSG_CLASS_NONE;
+
+       /**  set folder id (temporary) */
+       pMsgInfo->folderId = MSG_INBOX_ID;
+
+       pMsgInfo->networkStatus = MSG_NETWORK_RECEIVED;
+       pMsgInfo->bRead = false;
+       pMsgInfo->bProtected = false;
+       pMsgInfo->priority = MSG_MESSAGE_PRIORITY_NORMAL;
+       pMsgInfo->direction = MSG_DIRECTION_TYPE_MT;
+
+       time_t rawtime = time(NULL);
+
+/*** Comment below lines to save local UTC time..... (it could be used later.)
+
+       if (tmpTimeStamp.format == SMS_TIME_ABSOLUTE) {
+
+               MSG_DEBUG("year : %d", tmpTimeStamp.time.absolute.year);
+               MSG_DEBUG("month : %d", tmpTimeStamp.time.absolute.month);
+               MSG_DEBUG("day : %d", tmpTimeStamp.time.absolute.day);
+               MSG_DEBUG("hour : %d", tmpTimeStamp.time.absolute.hour);
+               MSG_DEBUG("minute : %d", tmpTimeStamp.time.absolute.minute);
+               MSG_DEBUG("second : %d", tmpTimeStamp.time.absolute.second);
+               MSG_DEBUG("timezone : %d", tmpTimeStamp.time.absolute.timeZone);
+
+               char displayTime[32];
+               struct tm * timeTM;
+
+               struct tm timeinfo;
+               memset(&timeinfo, 0x00, sizeof(tm));
+
+               timeinfo.tm_year = (tmpTimeStamp.time.absolute.year + 100);
+               timeinfo.tm_mon = (tmpTimeStamp.time.absolute.month - 1);
+               timeinfo.tm_mday = tmpTimeStamp.time.absolute.day;
+               timeinfo.tm_hour = tmpTimeStamp.time.absolute.hour;
+               timeinfo.tm_min = tmpTimeStamp.time.absolute.minute;
+               timeinfo.tm_sec = tmpTimeStamp.time.absolute.second;
+               timeinfo.tm_isdst = 0;
+
+               rawtime = mktime(&timeinfo);
+
+               MSG_DEBUG("tzname[0] [%s]", tzname[0]);
+               MSG_DEBUG("tzname[1] [%s]", tzname[1]);
+               MSG_DEBUG("timezone [%d]", timezone);
+               MSG_DEBUG("daylight [%d]", daylight);
+
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", &timeinfo);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= (tmpTimeStamp.time.absolute.timeZone * (3600/4));
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= timezone;
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+       }
+
+***/
+
+       pMsgInfo->displayTime = rawtime;
+
+       /**  Convert Address values */
+       pMsgInfo->nAddressCnt = 1;
+
+       pMsgInfo->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+       memset(pMsgInfo->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+       pMsgInfo->addressList[0].addressType = MSG_ADDRESS_TYPE_PLMN;
+       strncpy(pMsgInfo->addressList[0].addressVal, tmpAddress.szData, MAX_ADDRESS_VAL_LEN);
+
+       pMsgInfo->msgPort.valid = false;
+       pMsgInfo->msgPort.dstPort = 0;
+       pMsgInfo->msgPort.srcPort = 0;
+
+}
+
+void SmsPluginWapPushHandler::getXmlDoc(const char* pPushBody, const int PushBodyLen, xmlDocPtr *pXmlDoc, const bool isText)
+{
+       if (pPushBody == NULL) {
+               MSG_DEBUG("pPushBody is NULL");
+               return;
+       }
+
+
+       if (isText) {
+               *pXmlDoc = xmlParseMemory(pPushBody, AcStrlen(pPushBody));
+       } else {
+               WB_UTINY*       xmldata = NULL;
+               WBXMLConvWBXML2XML *conv = NULL;
+               WBXMLError ret = WBXML_OK;
+
+               ret = wbxml_conv_wbxml2xml_create(&conv);
+               if (ret != WBXML_OK)
+                       return;
+
+               ret = wbxml_conv_wbxml2xml_run(conv, (WB_UTINY*)pPushBody, (WB_ULONG)PushBodyLen, &xmldata, NULL);
+
+               wbxml_conv_wbxml2xml_destroy(conv);
+
+               if (ret != WBXML_OK ||xmldata == NULL) {
+                       MSG_DEBUG("xmldata is NULL. Error code is [%d].\n", ret);
+                       return;
+               }
+
+               MSG_DEBUG("xmldata : \n%s\n", xmldata);
+
+               *pXmlDoc = xmlParseMemory((char*)xmldata, AcStrlen((char*)xmldata));
+       }
+
+}
+
+unsigned long SmsPluginWapPushHandler::convertXmlCharToSec(char* pDate)
+{
+       struct tm       timeStruct;
+       time_t          nTimeInSec = 0;
+       char                    tmpBuf[10];
+       int                     i = 0, index = 0;
+
+       memset(tmpBuf, 0x00, sizeof(tmpBuf));
+       memset(&timeStruct, 0x00, sizeof(struct tm));
+
+       /** check pDate */
+       if (AcStrlen(pDate)<20)
+               return 0;
+
+       MSG_DEBUG("pDate [%s]", pDate);
+
+       /** Year */
+       for (i = 0; i < 4; i++) {
+               tmpBuf[i] = pDate[index++];
+       }
+       tmpBuf[i] = '\0';
+       index++;
+       timeStruct.tm_year = (atoi( tmpBuf)-1900);
+
+       /**  Month */
+       for (i = 0; i < 2; i++) {
+               tmpBuf[i] = pDate[index++];
+       }
+       tmpBuf[i] = '\0';
+       index++;
+       timeStruct.tm_mon = (atoi( tmpBuf) - 1);
+
+       /** Date */
+       for (i = 0; i < 2; i++) {
+               tmpBuf[i] = pDate[index++];
+       }
+       tmpBuf[i] = '\0';
+       index++;
+       timeStruct.tm_mday = atoi( tmpBuf);
+
+       /** Hours */
+       for (i = 0; i < 2; i++) {
+               tmpBuf[i] = pDate[index++];
+       }
+       tmpBuf[i] = '\0';
+       index++;
+       timeStruct.tm_hour = atoi( tmpBuf);
+
+       /** Minites */
+       for (i = 0; i < 2; i++) {
+               tmpBuf[i] = pDate[index++];
+       }
+       tmpBuf[i] = '\0';
+       index++;
+       timeStruct.tm_min = atoi( tmpBuf);
+
+       /** Seconds */
+       for (i = 0; i < 2; i++) {
+               tmpBuf[i] = pDate[index++];
+       }
+       tmpBuf[i] = '\0';
+       index++;
+       timeStruct.tm_sec = atoi( tmpBuf);
+
+       nTimeInSec = mktime(&timeStruct);
+
+       return nTimeInSec;
+}
+
+msg_push_action_t SmsPluginWapPushHandler::convertSIActionStrToEnum(char* pAction)
+{
+       int comp = 0;
+
+       if (pAction == NULL) {
+               MSG_DEBUG("pAction is NULL. Setting to default action type.");
+               return MSG_PUSH_SI_ACTION_SIGNAL_MEDIUM;
+       }
+
+       /** compare  with signal-none. */
+       comp = g_strcmp0( "signal-none", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SI_ACTION_SIGNAL_NONE;
+
+       /** compare  with signal-low. */
+       comp = g_strcmp0( "signal-low", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SI_ACTION_SIGNAL_LOW;
+
+       /**  compare  with signal-medium. */
+       comp = g_strcmp0( "signal-medium", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SI_ACTION_SIGNAL_MEDIUM;
+
+       /**  compare  with signal-high. */
+       comp = g_strcmp0( "signal-high", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SI_ACTION_SIGNAL_HIGH;
+
+       /**  compare  with delete. */
+       comp = g_strcmp0( "delete", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SI_ACTION_DELETE;
+
+       /**  signal-medium is default action value. */
+       return MSG_PUSH_SI_ACTION_SIGNAL_MEDIUM;
+
+}
+
+msg_push_action_t SmsPluginWapPushHandler::convertSLActionStrToEnum(char* pAction)
+{
+       int comp = 0;
+
+       if (pAction == NULL) {
+               MSG_DEBUG( "MSG_DEBUG is NULL. Setting to default action type.\n" );
+               return MSG_PUSH_SL_ACTION_EXECUTE_LOW;
+       }
+
+       /**  compare pSrcStr with execute-low. */
+       comp = g_strcmp0( "execute-low", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SL_ACTION_EXECUTE_LOW;
+
+       /**  compare pSrcStr with execute-high. */
+       comp = g_strcmp0( "execute-high", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SL_ACTION_EXECUTE_HIGH;
+
+       /** compare pSrcStr with cache. */
+       comp = g_strcmp0( "cache", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SL_ACTION_CACHE;
+
+       /** default SL action value is execute-low. */
+       return MSG_PUSH_SL_ACTION_EXECUTE_LOW;
+
+}
+
+
+unsigned long SmsPluginWapPushHandler::wspRetriveUintvarDecode( unsigned char* sourceData, unsigned long* currentPointer )
+{
+       unsigned long i = 0;
+       unsigned long decodedValue;
+
+       while (sourceData[*currentPointer +i] >= 0x80) i++;
+
+       decodedValue = wspDecodeUintvar( i+1, sourceData + *currentPointer );
+       *currentPointer = *currentPointer + i + 1;
+       MSG_DEBUG("wspRetriveUintvarDecode: decodedValue=%d .\n",decodedValue );
+       return decodedValue;
+}
+
+
+unsigned long SmsPluginWapPushHandler::wspDecodeUintvar(unsigned long length, unsigned char* userVar )
+{
+       unsigned long i;
+       unsigned long decodedUintvar = 0;
+
+
+       for (i = 0 ; i < length; i++) {
+               decodedUintvar = decodedUintvar +  ( wspUintvarDecodeTable[i] * (userVar[length-(i+1)] & 0x7f ));
+       }
+
+       return decodedUintvar;
+}
+
+
+void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, unsigned long encodedHeaderLen, unsigned long contentsLength, bool fContentType, char** pHeader)
+{
+       unsigned long iField;
+       bool   continueField = FALSE;
+       unsigned long currentLength;
+
+       char* encodedHeader = NULL;
+       unique_ptr<char*, void(*)(char**)> encodedHeaderbuf(&encodedHeader, unique_ptr_deleter);
+
+       char* outTemper = NULL;
+
+       char* temper = NULL;
+       unique_ptr<char*, void(*)(char**)> temperbuf(&temper, unique_ptr_deleter);
+
+       unsigned char track;
+       unsigned long iEncodedHeader = 0;
+       unsigned char fieldCode = 0xff;
+
+       /* outTemper is Decoded Headers.
+           temper is Single Decoded Header.
+       */
+       if (NULL == ( outTemper = new char[ WSP_STANDARD_STR_LEN_MAX * 5 ])) {
+               MSG_DEBUG("outTemper Memory allocation is failed.\n" );
+               return;
+       }
+       memset(outTemper, 0, (WSP_STANDARD_STR_LEN_MAX * 5));
+       currentLength = WSP_STANDARD_STR_LEN_MAX;
+
+       MSG_DEBUG("wspDecodeHeader: Message header decoding started.\n" );
+
+       int loop;
+       char szBuf[64];
+
+       szBuf[0] = 0x00;
+       MSG_DEBUG("wspDecodeHeader: RAW data \n" );
+       for (loop = 0 ; loop<(int)encodedHeaderLen; loop++) {
+               char szTempBuf[5];
+               szTempBuf[0] = 0x00;
+               sprintf( szTempBuf, "%2X ", sEncodedHeader[loop] );
+
+               if (AcStrlen( szBuf ) + 7 < 64) {
+                       strncat( szBuf, szTempBuf, sizeof(szBuf)-AcStrlen(szBuf)-1 );
+               } else {
+                       strncat( szBuf, "\n", sizeof(szBuf)-AcStrlen(szBuf)-1 );
+                       MSG_DEBUG("[%s]", szBuf);
+                       szBuf[0] = 0x00;
+                       strncat( szBuf, szTempBuf, sizeof(szBuf)-AcStrlen(szBuf)-1 );
+               }
+       }
+       strncat( szBuf, "\n", sizeof(szBuf)-AcStrlen(szBuf)-1 );
+       MSG_DEBUG("[%s]", szBuf);
+       MSG_DEBUG("fContentType=%d  \n",fContentType );
+       /* operation for content-type */
+       /* makes psuedo- content-type fieldcode */
+       /* content - type is processed with header. But it's come without field code. So existence of fContentType can decide adding content type header field code whether ContentType + general header is or not. */
+
+       if (fContentType) {
+               encodedHeader = new char[ encodedHeaderLen + 1 ];
+               if (encodedHeader == NULL)      {
+                       MSG_DEBUG("encodedHeader Memory allocation is failed.\n" );
+                       return;
+               }
+               encodedHeader[0] = 0x91;
+               memcpy( encodedHeader + 1, sEncodedHeader, (size_t)encodedHeaderLen );
+       } else {
+               encodedHeader = new char[ encodedHeaderLen ];
+               if (encodedHeader == NULL)      {
+                       MSG_DEBUG("encodedHeader Memory allocation is failed.\n" );
+                       return;
+               }
+
+               memcpy( encodedHeader, sEncodedHeader, (size_t)encodedHeaderLen );
+       }
+
+       /* Is it reacehd end of header? */
+       while (iEncodedHeader < encodedHeaderLen) {
+               /* Get memory for single header */
+               if (temper == NULL) {
+                       temper = new char[ WSP_STANDARD_STR_LEN_MAX * 5 ];
+
+                       if (temper == NULL) {
+                               MSG_DEBUG("temper Memory allocation is failed.\n" );
+                               return;
+                       }
+                       memset(temper, 0x00, (WSP_STANDARD_STR_LEN_MAX * 5));
+               } else {
+                       memset(temper, 0x00, (WSP_STANDARD_STR_LEN_MAX * 5));
+               }
+
+
+               /* this section presents header code page shifting procedure
+                  This part can be implemented by future request.
+               if (track == 0x 7f )
+               */
+               track = encodedHeader[iEncodedHeader];
+
+               if (track == 0x00) {
+                       MSG_DEBUG("WspLDecodeHeader: fieldcode  is 0 \n" );
+                       strncpy((char*) temper, (char*)"", (WSP_STANDARD_STR_LEN_MAX * 5)-1);
+                       fieldCode = 0xff;
+                       iEncodedHeader++;
+               } else if (( track > 0 ) && ( track < 0x20 )) {
+                       iEncodedHeader++;
+               } else if (( track < 0x7f ) && ( track > 0x1f )) { /* In this case, first byte is normal string. So it's considered to unknown header. */
+                       unsigned char* fieldName = (unsigned char*)gWapCodeBufferLeft;
+                       unsigned char* fieldValue = (unsigned char*)gWapCodeBufferRight;
+
+                       strncpy( (char*)fieldName, (char*)(encodedHeader + iEncodedHeader ),WSP_CODE_BUFFER_LEFT_LEN_MAX-1);
+                       fieldName[WSP_CODE_BUFFER_LEFT_LEN_MAX-1] = '\0';
+                       iEncodedHeader = iEncodedHeader + AcStrlen( (char*)fieldName ) + 1;
+                       strncpy( (char*)fieldValue, (char*)(encodedHeader + iEncodedHeader ), WSP_CODE_BUFFER_RIGHT_LEN_MAX-1);
+                       fieldValue[WSP_CODE_BUFFER_RIGHT_LEN_MAX-1] = '\0';
+                       iEncodedHeader = iEncodedHeader + AcStrlen( (char*)fieldValue ) + 1;
+
+                       strncat((char*)temper, (char*)fieldName, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                       strncat((char*)temper, ": ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                       strncat((char*)temper, (char*)fieldValue, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                       /* this means 'don't process anymore.' */
+                       fieldCode = 0xff;
+
+               } else if (track > 0x7f) {
+                       /* In case of first byte is field code, else case is error. */
+
+                       /*if (( track & 0x7f ) <= wspHeaderFieldCount ) */
+                       {
+
+                               unsigned long  fieldValueLen = encodedHeader[iEncodedHeader + 1];
+                               unsigned char fieldValue[1275];
+                               fieldCode = track & 0x7f;
+                               /*
+                               if (( fieldValueLen == 0 ) || ( fieldValueLen == 0x80 ))
+                               {
+                                       dprint( DNET_WAP,DNET_DBG_HIGH, "%X %X %X %X %X %X\n" , fieldCode, encodedHeader[iEncodedHeader + 1], encodedHeader[iEncodedHeader + 2],encodedHeader[iEncodedHeader + 3],encodedHeader[iEncodedHeader + 4], encodedHeader[iEncodedHeader + 5] );
+                               }
+                               */
+                               memset(fieldValue, 0, 1275);
+                               {
+                                       /* add field name */
+                                       /* This continueField flag show whether previous field code and current field code are same or not. If it's same, there are some sequential display effect by omitting field name addition process. The reason why it should be do that can be found in encoding example of spec. */
+                                       if (!continueField) {
+                                               strncat( (char*)temper, (char*)wspHeaderFieldName[fieldCode], (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                               strncat( (char*)temper, ": ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                               continueField = FALSE;
+                                       }
+
+                                       /* field value is string */
+                                       /* In this case, it just copy field value. */
+                                       if (( fieldValueLen > LENGTH_QUOTE ) && ( fieldValueLen < 0x80 )) {
+
+                                               /* string field value should be NULL terminated */
+                                               strncat( (char*)temper, (char*)(encodedHeader + iEncodedHeader + 1 ), (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1);
+                                               strncat( (char*)temper, (char*)fieldValue, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+
+                                               iEncodedHeader = iEncodedHeader + AcStrlen( (char*)encodedHeader + iEncodedHeader + 1 ) + 2;
+                                               fieldCode = 0xff;
+                                       }
+                                       /* first field value is length */
+                                       /* If first byte of field value is length value, allocate field value by the length.
+                                       In field value, data is
+                                       1D 03 8F 24 24  - Then 8F 24 24 is field value.
+                                       1D 1F 33.... - Then  allocate 33H for FieldValue.
+                                       1D 8F - Then 8F
+                                       1D 'Hi man!' Like 00, if string is come, then process without calculating field value.
+                                       1D 8F 24 24 - In this case, original data is wrong.
+                                       If  accept-charset: ISO-10646-ucs-2;Q=0.7 is
+                                       01 03 03 E8 47
+                                       01 - field code
+                                       03 - field value length
+                                       03 E8 47 - field value
+                                       it's decoded by above value.
+                                       */
+                                       if (fieldValueLen < 0x20) {
+
+                                               if (fieldValueLen  == LENGTH_QUOTE) {
+
+                                                       /* field length is encoded in UINTVAR */
+                                                       unsigned long  uintvarLen = 0;
+                                                       fieldValueLen = wspRetriveUintvarDecode((unsigned char*) encodedHeader + iEncodedHeader + 2, &uintvarLen );
+                                                       memcpy( fieldValue, encodedHeader + iEncodedHeader + 2 + uintvarLen, (size_t)fieldValueLen );
+                                                       iEncodedHeader = iEncodedHeader + fieldValueLen + uintvarLen + 2;
+
+                                               } else {
+
+                                                       if (fieldValueLen == 1) {
+                                                               /* field value is one byte integer over 0x80 */
+                                                               /** make it two byte integer */
+                                                               fieldValue[0] = 0x00;
+                                                               memcpy( fieldValue + 1, encodedHeader + iEncodedHeader + 2, (size_t)fieldValueLen);
+                                                               fieldValueLen = 2;
+                                                               iEncodedHeader = iEncodedHeader + 1 + 2;
+                                                       } else {
+                                                               memcpy( fieldValue, encodedHeader + iEncodedHeader + 2, (size_t)fieldValueLen );
+                                                               fieldValue[fieldValueLen] = 0;
+                                                               iEncodedHeader = iEncodedHeader + fieldValueLen + 2;
+                                                               if (( fieldValueLen == 0 ) || ( fieldValueLen == 0x80 )) {
+                                                                       MSG_DEBUG("%X \n",  encodedHeader[iEncodedHeader] );
+                                                               }
+                                                       }
+                                               }
+                                       }
+                                       /* field value is single encoded */
+                                       if (fieldValueLen > 0x7f) {
+                                               fieldValue[0] = encodedHeader[iEncodedHeader + 1];
+                                               fieldValueLen = 1;
+                                               iEncodedHeader = iEncodedHeader + 2;
+                                       }
+                                       /* processing normal pre-defined field decoding */
+
+                                       MSG_DEBUG("WspLDecodeHeader: FieldCode %X\n", fieldCode );
+                                       MSG_DEBUG("WspLDecodeHeader: fieldSize %d\n", fieldValueLen );
+
+                                       if (( fieldCode  > wspHeaderFieldCount ) && ( fieldCode != 0xff )) {
+                                               MSG_DEBUG("WspLDecodeHeader: unknown fieldcode %X \n", track );
+                                               strncpy((char*) temper, (char*)"", (WSP_STANDARD_STR_LEN_MAX * 5)-1);
+                                               fieldCode = 0xff;
+                                       }
+
+
+                                       switch ( fieldCode )
+                                       {
+                                               /* accept charset */
+                                               /* It's normal way of field process. */
+                                               case 0x01 :
+                                                       {
+                                                               unsigned long  i = 0;
+                                                               unsigned long  code;
+
+                                                               /* Case of length of charset greater than 1 are two thigins.
+                                                               1. code length of charset is greater than 1.
+                                                               2. It include parameter.
+                                                               3. Or both of two
+                                                               */
+                                                               if (1 != fieldValueLen) {
+                                                                       code = wspHeaderDecodeInteger( fieldValue );
+                                                                       /* Calculate iField. */
+                                                                       if (fieldValue[0] < 0x80 )
+                                                                               iField = fieldValue[0];
+                                                                       else
+                                                                               iField = 1;
+
+                                                                       while ( wspCharset[i].charsetCode != code )
+                                                                               i++;
+                                                                       strncat( (char*)temper, (char*)wspCharset[i].charsetName, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                                       /* If parameter exist */
+                                                                       if (iField < fieldValueLen) {
+                                                                               char* param = NULL;
+                                                                               unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
+                                                                               wspHeaderDecodeQValue( fieldValueLen - iField, fieldValue + iField, &param);
+                                                                               strncat( (char*)temper, (char*)param, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                                       }
+                                                               } else {
+                                                                       code = fieldValue[0] & 0x7f;
+
+                                                                       while (( wspCharset[i].charsetCode != code ) && ( wspCharset[i].charsetCode != 0xffff  )) i++;
+                                                                       strncat( (char*)temper, (char*)wspCharset[i].charsetName, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                               }
+
+                                                       }
+                                                       break;
+
+                                               /* type encoding */
+                                               /* Like below routine, Same decoding routine process together. */
+                                               /* Accept-encoding */
+                                               case 0x02 :
+                                               /* content-encoding */
+                                               case 0x0b :
+                                                       {
+                                                               int integerValue;
+
+                                                               integerValue = wspHeaderDecodeIntegerByLength(fieldValue, fieldValueLen );
+                                                               if (integerValue > 2) {
+                                                                       MSG_DEBUG("WspLDecodeHeader: integerValue is over limit(2).\n");
+                                                                       break;
+                                                               }
+                                                               strncat( (char*)temper, (char*)wspEncodeMethod[integerValue], (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1);
+                                                       }
+                                                       break;
+                                               /* contents type decoder */
+                                               /* accept */
+                                               case 0x00 :
+                                               /* content-type */
+                                               case 0x11 :
+                                                       {
+                                                               unsigned long  contentsTypeCode;
+                                                               unsigned long  i = 0;
+                                                               /* encoded content type length body */
+                                                               unsigned long  tempLen;
+                                                               MSG_DEBUG("fieldValueLen: %d", fieldValueLen);
+
+                                                               /* Like HTTP result state 304, it's for processing without Content type. This part doesn't defined. */
+                                                               if (0 == fieldValueLen) {
+                                                                       strncat( (char*)temper, (char*)"None" , (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1);
+                                                                       break;
+                                                               }
+                                                               /* 01 AE --> 00 AE --> AE*/
+                                                               if (fieldValueLen == 2  &&  fieldValue[0] == 0) {
+                                                                       memcpy( fieldValue, encodedHeader + iEncodedHeader -1, (size_t)fieldValueLen-1 );
+                                                                       MSG_DEBUG("WspLDecodeHeader:For mmO2 problem\r\n" );
+                                                               }
+
+                                                               if ((fieldValue[0] < 0x20 ) || (fieldValue[0] >= 0x80 )) {
+                                                                       if (fieldValue[0] >= 0x80) {
+                                                                               tempLen = 1;
+                                                                       } else if (fieldValueLen == 2 && fieldValue[0] == 0x03 && fieldValue[1] == 0x0A) { /** 06 05 02 03 0A AF 89 */
+                                                                               fieldValue[3] = fieldValue[2];
+                                                                               fieldValue[2] = fieldValue[1];
+                                                                               fieldValue[1] = fieldValue[0];
+                                                                               fieldValue[0] = 0x02;
+                                                                               tempLen = 2;
+                                                                               fieldValueLen = 3;
+                                                                               MSG_DEBUG("WspLDecodeHeader:For CPE problem\r\n" );
+                                                                       } else {
+                                                                               tempLen = fieldValue[0]; /** 06 06 03 02 03 16 AF 88 */
+                                                                       }
+
+                                                                       if (tempLen == 1) {
+
+                                                                               char* szExtendedContent;
+
+                                                                               contentsTypeCode = fieldValue[0] & 0x7f;
+                                                                               while (( wspContentsType[i].contentsTypeCode != contentsTypeCode ) && ( i < wspContentsTypeCount )) i++;
+
+                                                                               /* If specified content type doesn't exist */
+                                                                               if (i < wspContentsTypeCount)
+                                                                                       strncat( (char*)temper, (char*)wspContentsType[i].contentsTypeName, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+
+                                                                               szExtendedContent =  wspExtendedDecodeType( (char)contentsTypeCode );
+
+                                                                               if (szExtendedContent != NULL) {
+                                                                                       MSG_DEBUG("WspLDecodeHeader: Tele2 server problem \n " );
+                                                                                       strncat( (char*)temper, (char*)szExtendedContent, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                                               }
+                                                                       } else {
+                                                                               contentsTypeCode = wspHeaderDecodeInteger(fieldValue);
+
+                                                                               while ((i < wspUnregisteredContentsTypeCount) && (wspUnregisterContentsType[i].contentsTypeCode != contentsTypeCode)) i++;
+
+                                                                               /** If there is a Content-Type assigned, */
+                                                                               if (i < wspUnregisteredContentsTypeCount)
+                                                                                       strncat ((char*)temper, (char*)wspUnregisterContentsType[i].contentsTypeName, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1);
+
+                                                                               tempLen +=1;
+                                                                       }
+                                                               } else {
+                                                                       tempLen = AcStrlen( (char*)fieldValue ) + 1;
+
+                                                                       strncat ((char*)temper, (char*)fieldValue, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1);
+                                                                       MSG_DEBUG("WspLDecodeHeader: Attention, Decoding Check of Content-Type\n ", tempLen);
+                                                               }
+
+                                                               /* If there is a parameter */
+                                                               if (tempLen < fieldValueLen) {
+                                                                       char* param = NULL;
+                                                                       unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
+                                                                       wspHeaderDecodeParameter( fieldValue + tempLen, fieldValueLen - tempLen, &param);
+                                                                       if (param != NULL) {
+                                                                               strncat( (char*)temper, "; ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1);
+                                                                               strncat( (char*)temper, (char*)param, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                                       }
+                                                               }
+                                                       }
+                                                       break;
+
+                                               /* language */
+                                               /* content-language */
+                                               case 0x0c :
+                                               /* accept-language */
+                                               case 0x03 :
+                                                       {
+                                                               unsigned long i = 0;
+                                                               unsigned long code;
+                                                               unsigned long tempLen;
+                                                               if ((fieldValue[0] < 0x20 ) || (fieldValue[0] > 0x80 )) {
+                                                                       if (fieldValue[0] > 0x80 )
+                                                                               tempLen = 1;
+                                                                       else
+                                                                               tempLen = fieldValue[0];
+                                                               } else {
+                                                                       tempLen = AcStrlen( (char*)fieldValue ) + 1;
+                                                               }
+
+                                                               if (tempLen == 1) {
+
+                                                                       code = wspHeaderDecodeInteger( fieldValue );
+                                                                       while ( wspLanguage[i].languageCode != code) {
+                                                                               i++;
+                                                                               if (i == wspLanguageCount)
+                                                                                       break;
+                                                                       }
+
+                                                                       if (i < wspLanguageCount) {
+                                                                               strncat( (char*)temper, (char*)wspLanguage[i].languageName, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                                       }
+                                                               } else {
+                                                                       strncat( (char*)temper, (char*)fieldValue, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1);
+                                                               }
+
+                                                               if (tempLen < fieldValueLen) {
+                                                                       char* param = NULL;
+                                                                       unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
+                                                                       wspHeaderDecodeQValue(  fieldValueLen - tempLen, fieldValue + tempLen, &param );
+                                                                       strncat( (char*)temper, (char*)param, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                               }
+                                                       }
+                                                       break;
+
+                                               /* integer */
+                                               /* Max-forwards */
+                                               case 0x1e :
+                                               /* content-length */
+                                               case 0x0d :
+                                               /* age */
+                                               case 0x05 :
+                                               /* Bearer-indication */
+                                               case 0x33 :
+                                               /* Push-Flag */
+                                               case 0x34 :
+                                                       {
+
+                                                               unsigned char temp[16];
+                                                               /*
+                                                               if (( fieldValueLen == 2 ) && ( fieldValue[0] > 0x7f ))
+                                                                       AcSprintf( (char*)temp, "%u", (unsigned int)fieldValue[1]);
+                                                               else
+                                                               */
+                                                               sprintf( (char*)temp, "%u", (unsigned int)wspHeaderDecodeIntegerByLength( fieldValue, fieldValueLen ));
+                                                               strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       }
+                                                       break;
+                                               /* X-Wap-Application-Id */
+                                               case 0x2f :
+                                                       {
+                                                               unsigned char temp[64];
+                                                               int         integerValue;
+
+                                                               if (fieldValueLen == 2 &&  fieldValue[0] == 0) {
+                                                                       memcpy( fieldValue, encodedHeader + iEncodedHeader -1, (size_t)fieldValueLen-1 );
+                                                                       MSG_DEBUG("WspLDecodeHeader:For mmO2 problem\r\n" );
+                                                                       fieldValueLen = 1;
+                                                               }
+
+                                                               integerValue = wspHeaderDecodeIntegerByLength(fieldValue, fieldValueLen);
+
+                                                               int count = sizeof(wspHeaderApplId)/sizeof(SMS_WSP_HEADER_PARAMETER_S);
+                                                               for(int i = 0; i < count ; ++i)
+                                                               {
+                                                                       if ((unsigned int)integerValue == wspHeaderApplId[i].parameterCode)
+                                                                       {
+                                                                               snprintf((char*)temp, 64, "%s", wspHeaderApplId[i].parameterToken);
+                                                                               strncat((char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1);
+                                                                               break;
+                                                                       }
+                                                               }
+                                                       }
+                                                       break;
+                                               /* Accept-Application */
+                                               case 0x32 :
+                                                       if (0x80 == fieldValue[0]) {
+                                                               strncat( (char*)temper, "*", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1 );
+                                                       } else {
+
+                                                               unsigned char temp[16];
+                                                               /*
+                                if (( fieldValueLen == 2 ) && ( fieldValue[0] == 1 ))
+                                       AcSprintf( (char*)temp, "%u", (unsigned int)fieldValue[0]);
+                                else
+                                                               */
+                                                               sprintf( (char*)temp, "%u", (unsigned int)wspHeaderDecodeIntegerByLength( fieldValue, fieldValueLen ));
+                                                               strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1);
+                                                       }
+                                                       break;
+
+
+                                               /* date */
+                                               /* last-modified */
+                                               case 0x1d :
+                                               /* if-unmodified-since */
+                                               case 0x1b :
+                                               /* if-range */
+                                               case 0x1a :
+                                               /* if-modified-since */
+                                               case 0x17 :
+                                               /* expires */
+                                               case 0x14 :
+                                               /* date */
+                                               case 0x12 :
+                                                       {
+                                                               char* decodedString = NULL;
+                                                               unique_ptr<char*, void(*)(char**)> decodedStringbuf(&decodedString, unique_ptr_deleter);
+                                                               wspHeaderDecodeDateValue( fieldValueLen, fieldValue, &decodedString);
+                                                               strncat( (char*)temper, (char*)decodedString, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1 );
+                                                       }
+                                                       break;
+
+                                               /* connection */
+                                               case 0x09 :
+                                                       if (fieldValue[0] == 0x80 )
+                                                               strncat( (char*)temper, "Close", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1 );
+                                                       break;
+                                               /* accept-ranges */
+                                               case 0x04 :
+                                                       if (fieldValue[0] == 0x80 )
+                                                               strncat( (char*)temper, "None", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1 );
+                                                       if (fieldValue[0] == 0x81 )
+                                                               strncat( (char*)temper, "Bytes", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1 );
+                                                       break;
+                                               /* content-md5 */
+                                               case 0x0f :
+                                                       {
+                                                               unsigned char temp[1275];
+                                                               memcpy( temp, fieldValue, (size_t)fieldValueLen );
+                                                               temp[fieldValueLen] = 0;
+                                                               wspHeaderCopyDecodedString( temp, &currentLength, &temper );
+                                                       }
+                                                       break;
+                                               /* Credential */
+                                               /* authorization */
+                                               case 0x07 :
+                                               /* proxy - authorization */
+                                               case 0x21 :
+                                                       if (fieldValue[0] == 0x80) {
+                                                               char* addString = NULL;
+                                                               unique_ptr<char*, void(*)(char**)> addStringbuf(&addString, unique_ptr_deleter);
+                                                               wspHeaderDecodeAuth(fieldValueLen, fieldValue, &addString );
+                                                               strncat( (char*)temper, addString, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       } else {
+                                                               iField = AcStrlen( (char*)fieldValue) + 1;
+
+                                                               strncat( (char*)temper, (char*)fieldValue, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                               if (iField < fieldValueLen) {
+                                                                       char* param = NULL;
+                                                                       unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
+                                                                       wspHeaderDecodeParameter( fieldValue + 1, fieldValueLen - 1, &param );
+                                                                       if (param != NULL) {
+                                                                               strncat( (char*)temper, ", ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                                               strncat( (char*)temper, (char*)param, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                                       }
+                                                               }
+                                                       }
+                                                       break;
+
+
+                                               /* Challenge */
+                                               /* www - auth */
+                                               case 0x2d :
+                                               /* Proxy-authenticate */
+                                               case 0x20 :
+                                                       if (0 == fieldValueLen )
+                                                               break;
+                                                       if (fieldValue[0] == 0x80) {
+                                                               char* addString = NULL;
+                                                               unique_ptr<char*, void(*)(char**)> addStringbuf(&addString, unique_ptr_deleter);
+                                                               wspHeaderDecodeChallenge(fieldValueLen, fieldValue, &addString );
+                                                               strncat( (char*)temper, addString, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       } else {
+                                                               unsigned char  authScheme[WSP_STANDARD_STR_LEN_MAX + 1];
+                                                               unsigned char  realmValue[WSP_STANDARD_STR_LEN_MAX];
+                                                               unsigned char  addedString[WSP_STANDARD_STR_LEN_MAX];
+
+                                                               strncpy( (char*)authScheme, (char*)fieldValue, WSP_STANDARD_STR_LEN_MAX -1);
+                                                               iField = AcStrlen( (char*)authScheme ) + 1;
+                                                               strncpy( (char*)realmValue, (char*)(fieldValue + iField ), WSP_STANDARD_STR_LEN_MAX-1);
+                                                               iField = iField + AcStrlen( (char*)realmValue ) + 1;
+                                                               snprintf( (char*)addedString, sizeof(addedString), "%s %s", authScheme, realmValue );
+                                                               wspHeaderCopyDecodedString( addedString, &currentLength, &temper );
+
+                                                               if (iField < fieldValueLen) {
+                                                                       char* param = NULL;
+                                                                       unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
+                                                                       wspHeaderDecodeParameter( fieldValue + iField, fieldValueLen - iField, &param );
+                                                                       if (param != NULL) {
+                                                                               strncat( (char*)temper, ", ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                                               wspHeaderCopyDecodedString( (unsigned char*)param, &currentLength, &temper );
+                                                                       }
+                                                               }
+                                                       }
+                                                       break;
+
+                                               /* content -range */
+                                               case 0x10 :
+                                                       {
+                                                               unsigned long  first, len, last;
+
+                                                               unsigned char  temp[16];
+                                                               iField = 0;
+
+                                                               strncat( (char*)temper," bytes ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+
+                                                               first = wspRetriveUintvarDecode( fieldValue, &iField );
+                                                               len = wspRetriveUintvarDecode( fieldValue, &iField );
+                                                               /* Originally range of HTTP include entity length. But WSP omit it. Finally to calculate this, it should be get content length from export. If this field is included without content length, then it can get wrong result. This content length can be get by calculating PDU length.
+                                                               */
+                                                               last = first + contentsLength - 1;
+
+                                                               sprintf( (char*)temp, "%u-%u/%u", (unsigned int)first, (unsigned int)last, (unsigned int)len );
+                                                               strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       }
+                                                       break;
+
+                                               /* cache-control */
+                                               case 0x08 :
+                                                       {
+                                                               char* cacheString = NULL;
+                                                               unique_ptr<char*, void(*)(char**)> cacheStringbuf(&cacheString, unique_ptr_deleter);
+
+                                                               wspHeaderDecodeCacheControl( fieldValue, fieldValueLen, &cacheString );
+                                                               strncat( (char*)temper, (char*)cacheString, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       }
+                                                       break;
+
+                                               /* pragma */
+                                               case 0x1f :
+                                                       if (fieldValue[0] == 0x80) {
+                                                               strncat( (char*)temper, (char*)wspCacheControl[0], (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       } else {
+                                                               if (1 < fieldValueLen) {
+                                                                       char* param = NULL;
+                                                                       unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
+                                                                       wspHeaderDecodeParameter( fieldValue, fieldValueLen, &param );
+
+                                                                       if (param != NULL) {
+                                                                               strncat( (char*)temper, "; ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                                               strncat( (char*)temper, (char*)param, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                                       }
+                                                               }
+                                                       }
+
+                                                       break;
+                                               /* public */
+                                               case 0x22 :
+                                               /* allow */
+                                               case 0x06 :
+                                                       {
+                                                               unsigned long  i = 0;
+                                                               while ( wspHeaderDecodeIntegerByLength( fieldValue, fieldValueLen ) != wspMethodType[i].methodCode ) i++;
+                                                               strncat( (char*)temper, (char*)wspMethodType[i].methodName, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       }
+                                                       break;
+                                               /* range */
+                                               case 0x23 :
+                                                       strncat( (char*)temper, "bytes=", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       if (fieldValue[0] == 0x80) {
+                                                               unsigned char temp[16];
+                                                               unsigned long  first, last;
+                                                               iField = 0;
+
+                                                               first = wspRetriveUintvarDecode( fieldValue, &iField );
+                                                               last = wspRetriveUintvarDecode( fieldValue, &iField );
+
+                                                               sprintf( (char*)temp, "%u-%u", (unsigned int)first, (unsigned int)last );
+                                                               strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       }
+                                                       if (fieldValue[0] == 0x81) {
+                                                               unsigned char temp[16];
+                                                               unsigned long  suffix;
+
+                                                               suffix = wspRetriveUintvarDecode( fieldValue, &iField );
+
+                                                               sprintf( (char*)temp, "-%u", (unsigned int)suffix );
+
+                                                       }
+                                                       break;
+                                               /* retry-after */
+                                               case 0x25 :
+                                                       if (fieldValue[0] == 0x80) {
+                                                               char* temp = NULL;
+                                                               unique_ptr<char*, void(*)(char**)> tempbuf(&temp, unique_ptr_deleter);
+
+                                                               wspHeaderDecodeDateValue( fieldValueLen - 1, fieldValue + 1, &temp );
+                                                               strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       }
+
+                                                       if (fieldValue[0] == 0x81) {
+                                                               unsigned char temp[16];
+
+                                                               sprintf( (char*)temp, "%u", (unsigned int)wspHeaderDecodeIntegerByLength( fieldValue,fieldValueLen ));
+                                                               strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       }
+                                                       break;
+                                               /* transfer-encoding */
+                                               case 0x27 :
+                                                       /* No other cases allowed */
+                                                       if (fieldValue[0] == 0x80 )
+                                                               strncat( (char*)temper, "chunked", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+
+                                                       break;
+                                               /* vary */
+                                               case 0x2a :
+                                                       {
+                                                               int integerValue = wspHeaderDecodeIntegerByLength(fieldValue,fieldValueLen );
+                                                               if (integerValue > wspHeaderFieldCount) {
+                                                                       MSG_DEBUG("WspLDecodeHeader: integerValue is over limit(0x%x).\n",wspHeaderFieldCount);
+                                                                       break;
+                                                               }
+                                                               strncat( (char*)temper, (char*)wspHeaderFieldName[integerValue], (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       }
+                                                       break;
+                                               /* warning */
+                                               case 0x2c :
+                                                       {
+                                                               unsigned char temp[WSP_STANDARD_STR_LEN_MAX];
+
+                                                               if (fieldValue[0] < 0x20 )
+                                                                       iField = fieldValue[0];
+                                                               else
+                                                                       iField = 1;
+
+                                                               snprintf( (char*)temp, sizeof(temp), "%u", (unsigned int)wspHeaderDecodeIntegerByLength( fieldValue, iField ));
+                                                               strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                               if (iField < fieldValueLen) {
+                                                                       unsigned char agent[WSP_STANDARD_STR_LEN_MAX];
+                                                                       unsigned char text[WSP_STANDARD_STR_LEN_MAX];
+                                                                       strncpy( (char*)agent, (char*)(fieldValue + iField ),WSP_STANDARD_STR_LEN_MAX-1);
+                                                                       iField = iField + AcStrlen((char*)agent ) + 1;
+                                                                       strncpy((char*)text, (char*)(fieldValue + iField ),WSP_STANDARD_STR_LEN_MAX-1);
+                                                                       snprintf( (char*)temp, sizeof(temp), " %s %s", agent, text );
+                                                                       wspHeaderCopyDecodedString( temp, &currentLength, &temper );
+                                                               }
+                                                       }
+                                                       break;
+                                               /* content-disposition */
+                                               case 0x2e :
+                                                       if (fieldValue[0] == 0x80 )
+                                                               strncat( (char*)temper, "form-data", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+
+                                                       if (fieldValue[0] == 0x81 )
+                                                               strncat( (char*)temper, "attachment", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+
+                                                       if (1 < fieldValueLen) {
+                                                               char* param = NULL;
+                                                               unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
+                                                               wspHeaderDecodeParameter( fieldValue + 1, fieldValueLen - 1, &param );
+
+                                                               if (param != NULL) {
+                                                                       strncat( (char*)temper, "; ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                                       strncat( (char*)temper, (char*)param, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                               }
+                                                       }
+                                                       break;
+                                               /* Profile-diff */
+                                               case 0x36 :
+                                                       temper[AcStrlen((char*)temper) + fieldValueLen] = '\0';
+                                                       memcpy( temper, fieldValue, (size_t)fieldValueLen );
+                                                       break;
+                                               /* Profile-Warning */
+                                               case 0x37 :
+                                                       {
+                                                               unsigned char temp[WSP_STANDARD_STR_LEN_MAX];
+
+                                                               snprintf( (char*)temp, sizeof(temp), "%lX", wspHeaderDecodeInteger(fieldValue ));
+                                                               temp[2] = temp[1];
+                                                               temp[1] = (unsigned char)0x30;
+                                                               temp[3] = '\0';
+                                                               if (fieldValueLen > 1) {
+                                                                       /* copy warn-target - URI */
+                                                                       strncat( (char*)temp, (char*)(fieldValue + 1), WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)temp)-1 );
+                                                                       if (fieldValueLen > ( AcStrlen( (char*)(fieldValue + 1)) + 1 )) {
+                                                                               /* copy warn-date */
+                                                                               char* decodedString = NULL;
+                                                                               unique_ptr<char*, void(*)(char**)> decodedStringbuf(&decodedString, unique_ptr_deleter);
+                                                                               wspHeaderDecodeDateValue( fieldValueLen - ( AcStrlen( (char*)(fieldValue + 1)) + 2 ), fieldValue + AcStrlen( (char*)(fieldValue + 1)) + 1, &decodedString );
+                                                                               strncat( (char*)temp, (char*)decodedString, WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)temp)-1 );
+                                                                       }
+                                                               }
+                                                               strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                                                       }
+                                                       break;
+
+                                               default :
+                                                       break;
+                                       }
+
+                               }
+                       }
+               }
+               /* It deosn't finished decoding yet. */
+               if (( iEncodedHeader < encodedHeaderLen ) && ( fieldCode != 0xff )) {
+                       /* In here, iEncodedHeader already point next field code to be decoded. */
+                       /* If this code is same, then set continueField else add CRLF. */
+                       if (fieldCode == (encodedHeader[iEncodedHeader] & 0x7f )) {
+                               strncat( (char*)temper, ", ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                               continueField = TRUE;
+                       } else {
+                               strncat( (char*)temper, "\r\n", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+                               continueField = FALSE;
+                       }
+               } else {
+                       strncat( (char*)temper, "\r\n", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
+               }
+
+               /* add single header to total headers */
+               strncat( (char*)outTemper, (char*)temper, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)outTemper)-1 );
+               MSG_DEBUG("WspLDecodeHeader: Single Header : %s\r\n", temper );
+
+       }
+
+
+       MSG_DEBUG("WspLDecodeHeader: Header decoding ended.\n" );
+
+       *pHeader = outTemper;
+
+       return;
+
+}
+
+
+unsigned long SmsPluginWapPushHandler::wspHeaderDecodeInteger( unsigned char* data )
+{
+       /* we only can handle max 32bit integer */
+       unsigned long i;
+
+       union {
+               unsigned long integer;
+               unsigned char seg[4];
+       } returner;
+
+       returner.integer = 0;
+
+       if (data[0] < 0x80) {
+               unsigned long IntLen = 0;
+
+               IntLen = (data[0]>0x04) ? 0x04:data[0];
+
+               MSG_DEBUG("WspLHeaderDecodeInteger: input %d , length %d\n", data[0], IntLen);
+
+               for (i=0; i<IntLen; i++)
+                       returner.seg[IntLen-( i+1)] = data[i+1];
+
+               return returner.integer;
+       }
+
+       return data[0] & 0x7f;
+}
+
+
+void SmsPluginWapPushHandler::wspHeaderDecodeQValue( unsigned long length, unsigned char* data, char** pDecodedString)
+{
+       unsigned short qBase = 0;
+       float  qValue;
+
+       *pDecodedString = new char[WSP_STANDARD_STR_LEN_MAX];
+       if (*pDecodedString == NULL) {
+               MSG_DEBUG("WspLHeaderDecodeQValue:MemAlloc failed\n");
+               return;
+       }
+
+       memcpy( &qBase, data, (size_t)length );
+       qValue = (float)qBase;
+       if (qValue > 100) {
+               qValue = qValue - 100;
+               qValue = qValue / 1000;
+               sprintf( (char*)*pDecodedString, "; q=%.3f", qValue );
+       } else {
+               /* qValue variable is divided by 100. And it's multiplied by 100.
+                  It's to resolve problem of changed 0.01 of qValue. */
+               unsigned long qValueTemp;
+               qValue = qValue - 1;
+               qValue = qValue / 100;
+               qValueTemp = (unsigned long)(qValue * 100);
+               if (0 == (qValueTemp % 10 ))
+                       sprintf( (char*)*pDecodedString, "; q=%.1f", qValue );
+               else
+                       sprintf( (char*)*pDecodedString, "; q=%.2f", qValue );
+       }
+       return;
+}
+
+
+unsigned long SmsPluginWapPushHandler::wspHeaderDecodeIntegerByLength(unsigned char* data, unsigned long length )
+{
+       unsigned long i;
+
+       union {
+               unsigned long integer;
+               unsigned short  seg[4];
+       } returner;
+
+       returner.integer = 0;
+
+       if (length == 1 )
+               return data[0] & 0x7f;
+
+       returner.integer = 0;
+
+       for (i = 0 ; i < length; i++) {
+               returner.integer  =  returner.integer + ( data[i]  *  (0x1  << ( ( length - ( i + 1)) * 8 )));
+               MSG_DEBUG("WspLHeaderDecodeIntegerByLength: %d \n", returner.integer );
+       }
+
+       return returner.integer;
+}
+
+
+char* SmsPluginWapPushHandler::wspExtendedDecodeType(char contentType  )
+{
+       int i = 0;
+
+       while ( wspExtendedContentsType[i].contentsTypeCode != contentType) {
+               if (wspExtendedContentsType[i].contentsTypeCode == 0xff)
+                       return NULL;
+               i++;
+       }
+
+       return (char*)wspExtendedContentsType[i].contentsTypeName;
+}
+
+
+void SmsPluginWapPushHandler::wspHeaderDecodeParameter( unsigned char* data, unsigned long length, char** pParam)
+{
+       char* param = *pParam;
+
+       unsigned long SecurityTypeCode;
+       unsigned long  i = 0;
+
+       if (data[0] < 0x80) {
+               /* unknown parameter type */
+               param = new char[WSP_STANDARD_STR_LEN_MAX];
+
+               if (param == NULL) {
+                       MSG_DEBUG("WspLHeaderDecodeParameter:MemAlloc failed\n" );
+                       return;
+               }
+
+               strncpy( (char*)param, (char*)data, WSP_STANDARD_STR_LEN_MAX - 1);
+
+               if (NO_VALUE == data[AcStrlen( (char*)param ) + 1]) {
+                       *pParam = param;
+                       return;
+               }
+
+               strncat( (char*)param, "=", WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)param)-1 );
+               strncat( (char*)param, (char*)(data + AcStrlen( (char*)param )), WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)param)-1);
+
+               *pParam = param;
+
+               return;
+       }
+
+       switch ( data[0] & 0x7f )
+       {
+               case 0x00 :
+                       wspHeaderDecodeQValue(  length - 1, data + 1, &param);
+                       break;
+               case 0x01 :
+                       wspHeaderDecodeCharset( length - 1 , data + 1, &param);
+                       break;
+               case 0x02 :
+                       wspHeaderDecodeVersion( length - 1, data + 1, &param);
+                       break;
+                       /* integer */
+               case 0x03 :
+                       //param = (unsigned char *)malloc( (size_t)WSP_STANDARD_STR_LEN_MAX );
+                       param = new char[WSP_STANDARD_STR_LEN_MAX];
+                       if (param == NULL) {
+                               MSG_DEBUG("WspLHeaderDecodeParameter: 0x03 MemAlloc failed\n");
+                               return;
+                       } else {
+                               sprintf( (char*)param, "Type=%i", (int)wspHeaderDecodeInteger( data + 1 ));
+                       }
+                       break;
+               case 0x08 :
+                       param = new char[WSP_STANDARD_STR_LEN_MAX];
+
+                       if (param == NULL) {
+                               MSG_DEBUG("WspLHeaderDecodeParameter:0x08 MemAlloc failed\n");
+                               return;
+                       } else {
+                               sprintf( (char*)param, "Padding=%i", (int)wspHeaderDecodeInteger( data + 1 ));
+                       }
+                       break;
+               case 0x05 :
+                       param = new char[WSP_STANDARD_STR_LEN_MAX];
+
+                       if (param == NULL) {
+                               MSG_DEBUG("WspLHeaderDecodeParameter:0x05 MemAlloc failed\n");
+                               return;
+                       } else {
+                               strncpy( (char*)param, "Name=", WSP_STANDARD_STR_LEN_MAX-1);
+                               memcpy( param + 5, data + 1, length - 1 );
+                               param[5 + length - 1] = '\0';
+                       }
+                       break;
+               case 0x06 :
+                       param = new char[WSP_STANDARD_STR_LEN_MAX];
+
+                       if (param == NULL) {
+                               MSG_DEBUG("WspLHeaderDecodeParameter:0x06 MemAlloc failed\n");
+                               return;
+                       } else {
+                               strncpy( (char*)param, "Filename=", WSP_STANDARD_STR_LEN_MAX-1);
+                               memcpy( param + 9, (char*)(data + 1), (size_t)(length - 1) );
+                               param[9 + length - 1] = '\0';
+                       }
+                       break;
+               case 0x07 :
+                       param = NULL;
+                       /* TBI */
+                       break;
+                       /*OMA Provisioning*/
+               case 0x11 :
+                       param = new char[WSP_STANDARD_STR_LEN_MAX];
+
+                       if (param == NULL) {
+                               MSG_DEBUG("WspLHeaderDecodeParameter:0x11 MemAlloc failed\n");
+                               return;
+                       } else {
+                               strncpy((char*)param, "SEC=", WSP_STANDARD_STR_LEN_MAX-1);
+                               SecurityTypeCode = data[1] & 0x7f;
+                               while (( i < wspSecurityTypeCount ) && ( wspSecurityType[i].SecurityTypeCode != SecurityTypeCode )) i++;
+
+                               if (i < wspSecurityTypeCount) {
+                                       strncat( (char*)param, (char*)wspSecurityType[i].SecurityTypeName, WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)param)-1);
+                               }
+
+                               if (0x12 == (data[2] & 0x7f)) {
+                                       strncat( (char*)param, "; MAC=", WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)param)-1 );
+                                       memcpy(param+AcStrlen( (char*)param),(char*)(data+3),(size_t)length-3 );
+                               }
+                       }
+                       break;
+
+               default :
+                       param = NULL;
+                       break;
+       }
+
+       *pParam = param;
+       return;
+}
+
+
+void SmsPluginWapPushHandler::wspHeaderDecodeCharset( unsigned long length, unsigned char* data, char**pDecodedString)
+{
+
+       *pDecodedString = new char[WSP_STANDARD_STR_LEN_MAX];
+
+       if (*pDecodedString == NULL) {
+               MSG_DEBUG("WspLHeaderDecodeCharset:MemAlloc failed\n");
+               return;
+       }
+
+       strncpy( (char*)*pDecodedString, "charset=", WSP_STANDARD_STR_LEN_MAX-1);
+
+       if (data[0] > 0x80) {
+               unsigned long code = wspHeaderDecodeInteger(data );
+               unsigned long i = 0;
+               while (wspCharset[i].charsetCode !=  code) {
+                       if (wspCharset[i].charsetCode == 0xffff) {
+                               return;
+                       }
+                       i++;
+               }
+               strncat( (char*)*pDecodedString, (char*)wspCharset[i].charsetName, WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)*pDecodedString)-1 );
+       } else {
+               unsigned long  lastLen = AcStrlen((char*)*pDecodedString);
+               memcpy( (char*)(*pDecodedString + lastLen), data, (size_t)length );
+               *pDecodedString[length + lastLen] = '\0';
+       }
+
+       return;
+}
+
+
+
+void SmsPluginWapPushHandler::wspHeaderDecodeVersion( unsigned long length, unsigned char* data, char** pDecodedString )
+{
+       *pDecodedString = new char[WSP_STANDARD_STR_LEN_MAX];
+
+       if (*pDecodedString == NULL) {
+               MSG_DEBUG("WspLHeaderDecodeVersion:MemAlloc failed\n");
+               return;
+       }
+
+       if (length > 1) {
+               /* untyped version */
+               memcpy( *pDecodedString, data, (size_t)length );
+       } else {
+               /* typed version */
+               unsigned char majorVer  = ((data[0] & 0x7f ) >> 4 );
+               unsigned char minorVer = data[0] & 0x0f;
+               sprintf( (char*)*pDecodedString, "level=%u.%u", majorVer, minorVer );
+       }
+
+       return;
+}
+
+
+void SmsPluginWapPushHandler::wspHeaderDecodeDateValue( unsigned long length, unsigned char* data, char** pDecodedString )
+{
+       time_t  lTime;
+       struct  tm* pTMData;
+
+       MSG_DEBUG("WspLHeaderDecodeDateValue:   \n" );
+
+       *pDecodedString = new char[WSP_STANDARD_STR_LEN_MAX];
+
+       if (*pDecodedString == NULL) {
+               MSG_DEBUG( "WspLHeaderDecodeDateValue:MemAlloc failed\n");
+               return;
+       }
+
+       lTime = wspHeaderDecodeIntegerByLength(data, length);
+
+       pTMData = (struct tm*)gmtime((const time_t* )&lTime);
+
+       if (pTMData == NULL) {
+               MSG_DEBUG( "WspLHeaderDecodeDateValue: Date decode fail \n" );
+               strncpy( (char*)*pDecodedString, "Decoding Failed", WSP_STANDARD_STR_LEN_MAX-1);
+               return;
+       }
+
+       /* check date value validity */
+       {
+               if (( pTMData->tm_wday > 6 ) || (pTMData->tm_mon > 11 ) || (pTMData->tm_mday >  31 ))
+               {
+                       MSG_DEBUG( "WspLHeaderDecodeDateValue: Date decode fail %d, %d, %d \n", pTMData->tm_wday, pTMData->tm_mon, pTMData->tm_mday );
+                       strncpy( (char*)*pDecodedString, "Decoding Failed", WSP_STANDARD_STR_LEN_MAX-1);
+                       return;
+               }
+       }
+
+#ifdef MSG_FW_FOR_DEBUG
+       /** Date type selection */
+       switch ( wspMachineStatus.dateType )
+       {
+                       /* UNIX asciitime function */
+               case UNIX_DATE_TYPE :
+                       snprintf( (char*)decodedString, sizeof(decodedString), "%s %s %-2u %u:%u:%u %u GMT", wspWeek[pTMData->tm_wday], wspMonth[pTMData->tm_mon],
+                                          pTMData->tm_mday, pTMData->tm_hour, pTMData->tm_min, pTMData->tm_sec, pTMData->tm_year + 1900 );
+                       break;
+               case RFC1123_DATE_TYPE :
+                       snprintf( (char*)decodedString, sizeof(decodedString), "%s, %u %s %u %u:%u:%u GMT", wspWeek[pTMData->tm_wday], pTMData->tm_mday,
+                                          wspMonth[pTMData->tm_mon], pTMData->tm_year + 1900, pTMData->tm_hour, pTMData->tm_min, pTMData->tm_sec );
+                       break;
+               case RFC850_DATE_TYPE :
+                       /* Have some Y2K Problems */
+                       /* In RFC 850, date is represented like 11-May-99. So Y2K problem always can be occured. So remainer (year divided by 100) is used.                     */
+                       snprintf( (char*)decodedString, sizeof(decodedString), "%s, %2u-%s-%2u %u:%u:%u GMT", wspWeekDay[pTMData->tm_wday], pTMData->tm_mday,
+                                          wspMonth[pTMData->tm_mon], pTMData->tm_year % CENTURY, pTMData->tm_hour, pTMData->tm_min, pTMData->tm_sec );
+
+                       break;
+       }
+#endif
+       /**UNIX_DATE_TYPE : */
+       snprintf( (char*)*pDecodedString, (sizeof(char)*WSP_STANDARD_STR_LEN_MAX), "%s %s %-2u %u:%u:%u %u GMT", wspWeek[pTMData->tm_wday], wspMonth[pTMData->tm_mon],
+                                                                                       pTMData->tm_mday, pTMData->tm_hour, pTMData->tm_min, pTMData->tm_sec, pTMData->tm_year + 1900 );
+
+       return;
+
+}
+
+void SmsPluginWapPushHandler::wspHeaderCopyDecodedString( unsigned char* szDecodedString, unsigned long* currentLen, char** pTemper )
+{
+       unsigned long elementLen = AcStrlen( (char*)szDecodedString );
+       char* temper2 = NULL;
+
+       /**  // CR+LF */
+       *currentLen = *currentLen + elementLen + 2;
+
+       if ( *currentLen > AcStrlen( (char*)* pTemper ) + 2) {
+               temper2 = new char[(*currentLen + 1 )];
+
+               if (temper2 == NULL) {
+                       MSG_DEBUG( "WspLHeaderCopyDecodedString:MemAlloc failed\n");
+                       return;
+               }
+               strncpy( (char*)temper2, (char*)* pTemper, *currentLen);
+               delete[] *pTemper;
+               strncpy( (char*)temper2, (char*)szDecodedString, *currentLen);
+       }
+
+       *pTemper = temper2;
+
+       return;
+}
+
+
+void SmsPluginWapPushHandler::wspHeaderDecodeAuth(unsigned long fieldValueLen, unsigned char* fieldValue, char** pDecodedString )
+{
+       unsigned char  userId[WSP_STANDARD_STR_LEN_MAX];
+       unsigned char  passWd[WSP_STANDARD_STR_LEN_MAX];
+       unsigned long iField = 0;
+       char authStr[256];
+
+       *pDecodedString = new char[WSP_STANDARD_STR_LEN_MAX * 2];
+
+       if (*pDecodedString == NULL) {
+               MSG_DEBUG("WspLHeaderDecodeAuth:MemAlloc failed\n" );
+               return;
+       }
+
+       /* skip 'basic' code */
+       iField++;
+       memset(authStr, 0x00, sizeof(authStr));
+       snprintf(authStr, sizeof(authStr), "%%%ds", sizeof(userId));
+       sscanf((char*)(fieldValue + iField), authStr, userId );
+       iField = iField + AcStrlen( (char*)userId ) + 1;
+       memset(authStr, 0x00, sizeof(authStr));
+       snprintf(authStr, sizeof(authStr), "%%%ds", sizeof(passWd));
+       sscanf( (char*)(fieldValue + iField), authStr, passWd );
+       iField = iField + AcStrlen( (char*)userId ) + 1;
+       snprintf( (char*)*pDecodedString, (sizeof(char)*WSP_STANDARD_STR_LEN_MAX*2), "basic %s/%s", userId, passWd );
+
+       return;
+}
+
+
+void SmsPluginWapPushHandler::wspHeaderDecodeChallenge(unsigned long fieldValueLen, unsigned char* fieldValue, char** pDecodedString )
+{
+       unsigned char userId[WSP_STANDARD_STR_LEN_MAX];
+       unsigned long iField = 0;
+       char authStr[256];
+
+       *pDecodedString = new char[WSP_STANDARD_STR_LEN_MAX];
+
+       if (*pDecodedString == NULL) {
+               MSG_DEBUG( "WspLHeaderDecodeChallenge:MemAlloc failed\n");
+               return;
+       }
+
+       /* skip 'basic' code */
+       iField++;
+       memset(authStr, 0x00, sizeof(authStr));
+       snprintf(authStr, sizeof(authStr), "%%%ds", sizeof(userId));
+       sscanf( (char*)(fieldValue + iField), authStr, userId );
+       iField = iField + AcStrlen( (char*)userId ) + 1;
+
+       snprintf( (char*)*pDecodedString, (sizeof(char)*WSP_STANDARD_STR_LEN_MAX), "basic realm=\"%s\"", userId );
+
+       return;
+}
+
+
+void SmsPluginWapPushHandler::wspHeaderDecodeCacheControl(unsigned char* fieldValue, unsigned long fieldValueLen, char** pCacheString)
+{
+       unsigned char  paramString[WSP_STANDARD_STR_LEN_MAX];
+       unsigned char  cacheCode;
+
+       *pCacheString = new char[WSP_STANDARD_STR_LEN_MAX];
+       if (*pCacheString == NULL) {
+               MSG_DEBUG( "WspLHeaderDecodeCacheControl:MemAlloc failed\n");
+               return;
+       }
+
+       if (1 == fieldValueLen) {
+               /* only one directive */
+               if (fieldValue[0] > 0x8b) {
+                       return; /* It's error detection. can be omitted. */
+               }
+               strncpy( (char*)*pCacheString, (char*)wspCacheControl[fieldValue[0] & 0x7f], WSP_STANDARD_STR_LEN_MAX-1);
+               return;
+       }
+
+       if (fieldValue[0] > 0x7f) {
+               /* directive that has parameter */
+               cacheCode = fieldValue[0] & 0x7f;
+               switch ( cacheCode )
+               {
+                               /* field name */
+                               /* no-cache */
+                       case 0x00 :
+                               /* private */
+                       case 0x07 :
+                               if (fieldValue[1] > 0x7f) {
+                                       /* well known field name */
+                                       strncpy( (char*)paramString, (char*)wspHeaderFieldName[fieldValue[1] & 0x7f],WSP_STANDARD_STR_LEN_MAX-1 );
+                                       paramString[WSP_STANDARD_STR_LEN_MAX-1] = '\0';
+                               } else {
+                                       /* unknown field name */
+                                       strncpy( (char*)paramString, (char*)fieldValue + 1 , WSP_STANDARD_STR_LEN_MAX-1);
+                               }
+                               break;
+                               /* secound */
+                               /* max-age */
+                       case 0x02 :
+                               /* max- stale */
+                       case 0x03 :
+                               /* min-fresh */
+                       case 0x04 :
+                               snprintf( (char*)paramString, sizeof(paramString), "%u", (unsigned int)wspHeaderDecodeInteger( fieldValue + 1));
+                               break;
+
+                       default :
+                               break;
+
+               }
+               snprintf((char*)*pCacheString, (sizeof(char)*WSP_STANDARD_STR_LEN_MAX), "%s=%s", (char*)wspCacheControl[cacheCode], (char*)paramString );
+       } else {
+               /* cache extentions */
+               /* In case of come directive of doesn't specified string style */
+
+               unsigned long stringLen;
+               char szString[32];
+               strncpy( (char*)*pCacheString, (char*)fieldValue, WSP_STANDARD_STR_LEN_MAX-1);
+               stringLen = AcStrlen((char*)*pCacheString );
+
+               if (stringLen + 1 < fieldValueLen) {
+
+                       if (fieldValue[stringLen+ 1] > 0x7f) {
+                               int untyped = (int)wspHeaderDecodeIntegerByLength( fieldValue + stringLen + 1, fieldValueLen - (stringLen + 1 ));
+
+                               snprintf( szString, sizeof(szString), "%d", untyped );
+                               strncat( (char*)*pCacheString, (char*)"=", WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)*pCacheString)-1 );
+                               strncat( (char*)*pCacheString, (char*)szString, WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)*pCacheString)-1 );
+                       } else {
+                               if (fieldValue[fieldValueLen] == 0) {
+                                       strncat( (char*)*pCacheString, (char*)"=", WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)*pCacheString)-1 );
+                                       strncat( (char*)*pCacheString, (char*)fieldValue + stringLen + 1 , WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)*pCacheString)-1);
+                               }
+                       }
+               }
+       }
+
+       return;
+}
diff --git a/plugin/sms_cdma_plugin/include/SmsCdmaPluginCallback.h b/plugin/sms_cdma_plugin/include/SmsCdmaPluginCallback.h
new file mode 100755 (executable)
index 0000000..70aa3e4
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SMS_CDMA_PLUGIN_CALLBACK_H
+#define SMS_CDMA_PLUGIN_CALLBACK_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <map>
+#include <vector>
+
+extern "C"
+{
+       #include <tapi_common.h>
+       #include <TelSms.h>
+       #include <TelSim.h>
+       #include <TapiUtility.h>
+       #include <ITapiNetText.h>
+       #include <ITapiNetwork.h>
+}
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+void TapiEventDeviceReady(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
+
+void TapiEventMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
+
+void TapiEventNetworkStatusChange(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
+
+void TapiEventMemoryStatus(TapiHandle *handle, int result, void *data, void *user_data);
+
+void TapiEventSentStatus(TapiHandle *handle, int result, void *data, void *user_data);
+
+void TapiEventDeliveryReportCNF(TapiHandle *handle, int result, void *data, void *user_data);
+
+void TapiEventSetConfigData(TapiHandle *handle, int result, void *data, void *user_data);
+
+void TapiEventGetCBConfig(TapiHandle *handle, int result, void *data, void *user_data);
+
+void TapiEventSimRefreshed(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
+
+void TapiEventGetMsisdnInfo(TapiHandle *handle, int result, void *data, void *user_data);
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginCallback
+{
+public:
+       static SmsPluginCallback* instance();
+
+       void registerEvent();
+       void deRegisterEvent();
+
+private:
+       SmsPluginCallback();
+       ~SmsPluginCallback();
+
+       static SmsPluginCallback* pInstance;
+};
+
+#endif //SMS_CDMA_PLUGIN_CALLBACK_H
+
diff --git a/plugin/sms_cdma_plugin/include/SmsCdmaPluginCodec.h b/plugin/sms_cdma_plugin/include/SmsCdmaPluginCodec.h
new file mode 100755 (executable)
index 0000000..cdfd814
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SMS_CDMA_PLUGIN_CODEC_H
+#define SMS_CDMA_PLUGIN_CODEC_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "SmsCdmaPluginTypes.h"
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginMsgCodec
+{
+public:
+
+       static SmsPluginMsgCodec* instance();
+
+       static bool checkInvalidPDU(const unsigned char *p_pkg_str, const int p_pkg_len);
+
+       static int encodeMsg(const sms_trans_msg_s *pMsg, unsigned char *p_pkg_str);
+       static int decodeMsg(const unsigned char *p_pkg_str, int p_pkg_len, sms_trans_msg_s *p_msg);
+
+private:
+       SmsPluginMsgCodec();
+       ~SmsPluginMsgCodec();
+
+       static SmsPluginMsgCodec* pInstance;
+
+       static int encodeP2PMsg(const sms_trans_p2p_msg_s *p_msg, unsigned char *p_pkg_str);
+       static int encodeAckMsg(const sms_trans_ack_msg_s *p_msg, unsigned char *p_pkg_str);
+       static int encodeCBMsg(const sms_trans_broadcast_msg_s *p_msg, unsigned char *p_pkg_str);
+
+       static int encodeTelesvcMsg(const sms_telesvc_msg_s *p_msg, unsigned char *p_pkg_str);
+
+       static int encodeTelesvcCancelMsg(const sms_telesvc_cancel_s *p_msg, unsigned char *p_pkg_str);
+       static int encodeTelesvcSubmitMsg(const sms_telesvc_submit_s *p_msg, unsigned char *p_pkg_str);
+       static int encodeTelesvcUserAckMsg(const sms_telesvc_user_ack_s *p_msg, unsigned char *p_pkg_str);
+       static int encodeTelesvcReadAckMsg(const sms_telesvc_read_ack_s *p_msg, unsigned char *p_pkg_str);
+       static int encodeTelesvcDeliverReportMsg(const sms_telesvc_report_s *p_msg, unsigned char *p_pkg_str);
+
+       static int decodeP2PMsg(const unsigned char *p_pkg_str, int p_pkg_len, sms_trans_p2p_msg_s *p_p2p);
+       static int decodeCBMsg(const unsigned char *p_pkg_str, int p_pkg_len, sms_trans_broadcast_msg_s *p_cb);
+       static int decodeAckMsg(const unsigned char *p_pkg_str, int p_pkg_len, sms_trans_ack_msg_s *p_ack);
+
+       static void decodeP2PTelesvcMsg(const unsigned char *p_pkg_str, int p_pkg_len, sms_telesvc_msg_s *p_telesvc);
+       static void decodeP2PDeliveryAckMsg(const unsigned char *p_pkg_str, int p_pkg_len, sms_telesvc_deliver_ack_s *p_del_ack);
+       static void decodeP2PSubmitReportMsg(const unsigned char *p_pkg_str, int p_pkg_len, sms_telesvc_report_s *p_sub_report);
+       static void decodeP2PUserAckMsg(const unsigned char *p_pkg_str, int p_pkg_len, sms_telesvc_user_ack_s *p_user_ack);
+       static void decodeP2PReadAckMsg(const unsigned char *p_pkg_str, int p_pkg_len, sms_telesvc_read_ack_s *p_read_ack);
+       static void decodeP2PDeliverMsg(const unsigned char *p_pkg_str, int p_pkg_len, sms_telesvc_deliver_s *p_del);
+       static void decodeP2PSubmitMsg(const unsigned char *p_pkg_str, int p_pkg_len, sms_telesvc_submit_s *p_sub);
+       static void decodeCBBearerData(const unsigned char *p_pkg_str, int p_pkg_len, sms_telesvc_msg_s *p_telesvc, bool isCMAS);
+
+       static int encodeUserData(const unsigned char* src, unsigned char *dest, int src_size);
+       static void decodeUserData(unsigned char *p_pkg_str, int p_pkg_len, sms_telesvc_userdata_s *p_user);
+       static void decodeCMASData(unsigned char *p_pkg_str, int p_pkg_len, sms_telesvc_cmasdata_s *p_cmas);
+
+       static int decodeTeleId(const unsigned char *p_pkg_str, int p_pkg_len, sms_trans_telesvc_id_t *tele_id);
+       static int decodeSvcCtg(const unsigned char *p_pkg_str, int p_pkg_len, sms_trans_svc_ctg_t *svc_ctg);
+       static int decodeAddress(const unsigned char *p_pkg_str, int p_pkg_len, sms_trans_addr_s *addr);
+       static int decodeSubAddress(const unsigned char *p_pkg_str, int p_pkg_len, sms_trans_sub_addr_s *sub_addr);
+
+       static int decodeMsgId(const unsigned char *p_pkg_str, int pkg_len, sms_trans_msg_id_s *p_msg_id);
+       static void decodeCallBackNum(const unsigned char *p_pkg_str, int pkg_len, sms_telesvc_addr_s *p_callback);
+       static int decodeAbsTime(const unsigned char *p_pkg_str, sms_time_abs_s *p_time_abs);
+       static sms_message_type_t findMsgType(const unsigned char *p_pkg_str, int pkg_len);
+};
+
+#endif //SMS_CDMA_PLUGIN_CODEC_H
diff --git a/plugin/sms_cdma_plugin/include/SmsCdmaPluginEventHandler.h b/plugin/sms_cdma_plugin/include/SmsCdmaPluginEventHandler.h
new file mode 100755 (executable)
index 0000000..2abf4c9
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SMS_CDMA_PLUGIN_EVENT_HANDLER_H
+#define SMS_CDMA_PLUGIN_EVENT_HANDLER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <string>
+#include <map>
+#include <vector>
+#include <list>
+
+using namespace std;
+
+#include "MsgMutex.h"
+#include "MsgTextConvert.h"
+#include "MsgPluginInterface.h"
+#include "SmsCdmaPluginTypes.h"
+
+
+/*==================================================================================================
+                                     VARIABLES AND DEFINES
+==================================================================================================*/
+struct wap_data_s
+{
+       int     length;
+       char data[SMS_MAX_USER_DATA_LEN+1];
+};
+
+typedef map<unsigned char, wap_data_s> wapDataMap;
+
+typedef struct _sms_wap_msg_s
+{
+       unsigned short  msgId;
+       unsigned char           totalSeg;
+       unsigned char           segNum;
+} sms_wap_msg_s;
+
+typedef struct _sms_wap_info_s
+{
+       unsigned short  msgId;
+       unsigned char           totalSeg;
+       unsigned char           segNum;
+
+       unsigned int            totalSize;
+       wapDataMap                      data;
+} sms_wap_info_s;
+
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginEventHandler
+{
+public:
+       static SmsPluginEventHandler* instance();
+
+       void registerListener(MSG_PLUGIN_LISTENER_S *pListener);
+       void handleSentStatus(msg_network_status_t NetStatus);
+       void handleMsgIncoming(sms_trans_p2p_msg_s *p_p2p_msg);
+       void handleCbMsgIncoming(sms_trans_broadcast_msg_s *p_cb_msg);
+       void handleWapMsgIncoming(sms_trans_p2p_msg_s *p_p2p_msg);
+
+       void handleResendMessage(void);
+
+       msg_error_t callbackMsgIncoming(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t callbackStorageChange(msg_storage_change_type_t storageChangeType, MSG_MESSAGE_INFO_S *pMsgInfo);
+
+       void convertTpduToMsginfo(sms_trans_p2p_msg_s *p_p2p_msg, MSG_MESSAGE_INFO_S *p_msg_info);
+       void convertTpduToMsginfo(sms_trans_broadcast_msg_s *p_cb_msg, MSG_MESSAGE_INFO_S *p_msg_info);
+
+       void SetSentInfo(sms_sent_info_s *pSentInfo);
+
+       void setDeviceStatus();
+       bool getDeviceStatus();
+       void setNeedInitConfig(bool bNeeded);
+       bool getNeedInitConfig();
+
+       void handleSyncMLMsgIncoming(msg_syncml_message_type_t msgType, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen);
+       void handleLBSMsgIncoming(char* pPushHeader, char* pPushBody, int pushBodyLen);
+       void handlePushMsgIncoming(char* pPushHeader, char* pPushBody, int pushBodyLen, char *app_id, char *content_type);
+
+private:
+       SmsPluginEventHandler();
+       virtual ~SmsPluginEventHandler();
+
+       static SmsPluginEventHandler* pInstance;
+
+       MSG_PLUGIN_LISTENER_S listener;
+
+       sms_sent_info_s sentInfo;
+
+       bool devStatus;
+       bool bNeedInitConfig;
+
+       Mutex mx;
+       CndVar cv;
+       vector<sms_wap_info_s> wapList;
+
+       void convertDeliverMsgToMsgInfo(sms_telesvc_deliver_s *p_deliver, MSG_MESSAGE_INFO_S *p_msg_info);
+       void convertCMASMsgToMsgInfo(sms_telesvc_deliver_s *p_deliver, MSG_MESSAGE_INFO_S *p_msg_info);
+       void convertAckMsgToMsgInfo(sms_telesvc_deliver_ack_s *p_deliver, MSG_MESSAGE_INFO_S *p_msg_info);
+       void convertReportMsgToMsgInfo(sms_telesvc_report_s *p_deliver, MSG_MESSAGE_INFO_S *p_msg_info);
+
+       msg_encode_type_t getEncodeType(sms_encoding_type_t encode_type);
+
+       unsigned short checkWapMsg(sms_wap_msg_s *pMsg, sms_telesvc_userdata_s *pUserdata);
+       int MakeWapUserData(unsigned short msgId, char **ppTotalData);
+
+       bool checkCbOpt(sms_trans_svc_ctg_t svc_ctg);
+       std::list<MSG_CB_DUPLICATE_S> duplicateCb;
+
+};
+
+#endif //SMS_CDMA_PLUGIN_EVENT_HANDLER_H
+
diff --git a/plugin/sms_cdma_plugin/include/SmsCdmaPluginMain.h b/plugin/sms_cdma_plugin/include/SmsCdmaPluginMain.h
new file mode 100755 (executable)
index 0000000..2ff6bd8
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SMS_CDMA_PLUGIN_MAIN_H
+#define SMS_CDMA_PLUGIN_MAIN_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "SmsCdmaPluginTypes.h"
+#include "MsgPluginInterface.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+msg_error_t SmsPlgInitialize();
+
+msg_error_t SmsPlgFinalize();
+
+msg_error_t SmsPlgRegisterListener(MSG_PLUGIN_LISTENER_S *pListener);
+
+msg_error_t SmsPlgSubmitRequest(MSG_REQUEST_INFO_S *pReqInfo);
+
+msg_error_t SmsPlgSaveSimMessage(const MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList);
+
+msg_error_t SmsPlgDeleteSimMessage(msg_sim_id_t SimMsgId);
+
+msg_error_t SmsPlgGetSimMessage(msg_sim_id_t SimMsgId);
+
+msg_error_t SmsPlgSetReadStatus(msg_sim_id_t SimMsgId);
+
+msg_error_t SmsPlgSetMemoryStatus(msg_error_t Error);
+
+msg_error_t SmsPlgSetConfigData(const MSG_SETTING_S *pSetting);
+
+msg_error_t SmsPlgGetConfigData(MSG_SETTING_S *pSetting);
+
+msg_error_t SmsPlgAddMessage(MSG_MESSAGE_INFO_S *pMsgInfo,  MSG_SENDINGOPT_INFO_S* pSendOptInfo, char* pFileData);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //SMS_CDMA_PLUGIN_MAIN_H
+
diff --git a/plugin/sms_cdma_plugin/include/SmsCdmaPluginParamCodec.h b/plugin/sms_cdma_plugin/include/SmsCdmaPluginParamCodec.h
new file mode 100755 (executable)
index 0000000..bf4fd61
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SMS_CDMA_PLUGIN_PARAMCODEC_H
+#define SMS_CDMA_PLUGIN_PARAMCODEC_H
+
+
+/*==================================================================================================
+                                                                               INCLUDE FILES
+==================================================================================================*/
+#include "SmsCdmaPluginTypes.h"
+
+
+/*==================================================================================================
+                                                                               CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginParamCodec
+{
+public:
+
+       static SmsPluginParamCodec* instance();
+
+       static int convertDigitToBcd(char *pDigit, int DigitLen, unsigned char *pBcd);
+       static int convertBcdToDigit(const unsigned char *pBcd, int BcdLen, char *pDigit);
+       static int convertDigitToDTMF(const char *pDigit, int DigitLen, int startBit, unsigned char *pDtmf);
+       static int convertDTMFToDigit(const unsigned char *pDtmf, int DtmfLen, int startBit, char *pDigit);
+
+private:
+       SmsPluginParamCodec();
+       virtual ~SmsPluginParamCodec();
+
+       static SmsPluginParamCodec* pInstance;
+
+       static bool isDtmfNumber(const char *pDigit, int DigitLen);
+};
+
+#endif /*SMS_CDMA_PLUGIN_PARAMCODEC_H*/
diff --git a/plugin/sms_cdma_plugin/include/SmsCdmaPluginSetting.h b/plugin/sms_cdma_plugin/include/SmsCdmaPluginSetting.h
new file mode 100755 (executable)
index 0000000..c31fb9d
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SMS_CDMA_PLUGIN_SETTING_H
+#define SMS_CDMA_PLUGIN_SETTING_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgMutex.h"
+#include "MsgSettingTypes.h"
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginSetting
+{
+public:
+       static SmsPluginSetting* instance();
+
+       void setSimChangeStatus();
+
+       void setConfigData(const MSG_SETTING_S *pSetting);
+       void getConfigData(MSG_SETTING_S *pSetting);
+       void getMeImei(char *pImei);
+
+       void setCbConfigEvent(const MSG_CBMSG_OPT_S *pCbOpt, bool bSuccess);
+
+       void setResultImei(bool bResult, char *pImei);
+       void setResultFromEvent(bool bResult);
+       void setResultFromSim(bool bResult);
+
+       void setMwiInfo(MSG_SUB_TYPE_T type, int count);
+       void SimRefreshCb();
+
+       bool getUpdateVoicemailByMdn();
+
+private:
+       SmsPluginSetting();
+       ~SmsPluginSetting();
+
+       void updateSimStatus();
+
+       void initConfigData();
+       static void* init_config_data(void *data);
+       static void* initSimInfo(void *data);
+
+       msg_error_t addCbOpt(MSG_CBMSG_OPT_S *pCbOpt);
+       void getCbOpt(MSG_SETTING_S *pSetting);
+
+       void setVoiceMailInfo(const MSG_VOICEMAIL_OPT_S *pVoiceOpt);
+       bool setCbConfig(const MSG_CBMSG_OPT_S *pCbOpt);
+       bool getCbConfig(MSG_CBMSG_OPT_S *pCbOpt);
+
+       bool getMsisdnInfo(void);
+
+       bool getResultImei(char *pImei);
+
+       bool getCbConfigEvent(MSG_CBMSG_OPT_S *pCbOpt);
+
+       bool getResultFromSim();
+
+       static SmsPluginSetting* pInstance;
+
+       MSG_SMSC_DATA_S         smscData;
+       MSG_CBMSG_OPT_S         cbOpt;
+
+       bool            bTapiResult;
+       bool            bUpdateVoicemailByMdn;
+
+       char    meImei[MAX_ME_IMEI_LEN + 1];
+
+       Mutex mx;
+       CndVar cv;
+};
+
+#endif //SMS_CDMA_PLUGIN_SETTING_H
+
diff --git a/plugin/sms_cdma_plugin/include/SmsCdmaPluginStorage.h b/plugin/sms_cdma_plugin/include/SmsCdmaPluginStorage.h
new file mode 100755 (executable)
index 0000000..85910bd
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SMS_CDMA_PLUGIN_STORAGE_H
+#define SMS_CDMA_PLUGIN_STORAGE_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgMutex.h"
+
+#include "MsgStorageTypes.h"
+#include "SmsCdmaPluginTypes.h"
+#include "MsgInternalTypes.h"
+#include "MsgSqliteWrapper.h"
+#include <list>
+
+extern "C"
+{
+       #include <tapi_common.h>
+       #include <TelSms.h>
+       #include <TapiUtility.h>
+       #include <ITapiNetText.h>
+}
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginStorage
+{
+public:
+       static SmsPluginStorage* instance();
+
+       msg_error_t insertMsgRef(MSG_MESSAGE_INFO_S *pMsg, unsigned char msgRef, int index);
+       msg_error_t updateMsgDeliverStatus(MSG_MESSAGE_INFO_S *pMsgInfo, unsigned char msgRef);
+
+       msg_error_t updateSentMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_network_status_t Status);
+
+       msg_error_t checkMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t addSmsMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t deleteSmsMessage(msg_message_id_t msgId);
+       msg_error_t addSmsSendOption(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo);
+
+       msg_error_t checkStorageStatus(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t getRegisteredPushEvent(char* pPushHeader, int *count, char *app_id, int app_id_len, char *content_type, int content_type_len);
+       msg_error_t getnthPushEvent(int index, int *appcode);
+       msg_error_t releasePushEvent();
+
+private:
+       SmsPluginStorage();
+       ~SmsPluginStorage();
+
+       static SmsPluginStorage* pInstance;
+
+       MSG_MESSAGE_INFO_S msgInfo;
+       MSG_ADDRESS_INFO_S addrInfo;
+
+       std::list<PUSH_APPLICATION_INFO_S> pushAppInfoList;
+};
+
+#endif //SMS_CDMA_PLUGIN_STORAGE_H
+
diff --git a/plugin/sms_cdma_plugin/include/SmsCdmaPluginTransport.h b/plugin/sms_cdma_plugin/include/SmsCdmaPluginTransport.h
new file mode 100755 (executable)
index 0000000..38169ea
--- /dev/null
@@ -0,0 +1,76 @@
+
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SMS_CDMA_PLUGIN_TRANSPORT_H
+#define SMS_CDMA_PLUGIN_TRANSPORT_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgInternalTypes.h"
+#include "MsgMutex.h"
+#include "SmsCdmaPluginTypes.h"
+
+extern "C"
+{
+       #include <TelSat.h>
+}
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginTransport
+{
+public:
+       static SmsPluginTransport* instance();
+
+       void submitRequest(sms_request_info_s *pReqInfo);
+       void sendDeliverReport(msg_error_t err, sms_trans_p2p_msg_s *p_p2p_msg);
+
+       void setNetStatus(sms_network_status_t sentStatus);
+
+private:
+       SmsPluginTransport();
+       ~SmsPluginTransport();
+
+       static SmsPluginTransport* pInstance;
+
+       unsigned char getMsgRef();
+       unsigned char getSeqNum();
+       unsigned char getSubmitMsgId();
+
+       sms_network_status_t getNetStatus();
+
+       void convertMsgInfoToTelesvcMsg(const MSG_MESSAGE_INFO_S *pMsgInfo, sms_trans_msg_s *pMsg);
+       void convertMsgInfoToPtp(const MSG_MESSAGE_INFO_S *pMsgInfo, sms_trans_p2p_msg_s *pPtpMsg);
+       void convertMsgInfoToSubmit(const MSG_MESSAGE_INFO_S *pMsgInfo, sms_telesvc_submit_s *pSubmit);
+
+       unsigned char           msgRef;
+       unsigned char           msgSeqNum;
+       unsigned char           msgSubmitId;
+
+       unsigned char           msgRef8bit;
+       unsigned short          msgRef16bit;
+
+       sms_network_status_t    curStatus;
+
+       Mutex mx;
+       CndVar cv;
+};
+
+#endif //SMS_PLUGIN_TRANSPORT_H
diff --git a/plugin/sms_cdma_plugin/include/SmsCdmaPluginTypes.h b/plugin/sms_cdma_plugin/include/SmsCdmaPluginTypes.h
new file mode 100755 (executable)
index 0000000..e15039d
--- /dev/null
@@ -0,0 +1,1011 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include "MsgDebug.h"
+#include "MsgTypes.h"
+#include "MsgInternalTypes.h"
+
+#ifndef SMS_CDMA_PLUGIN_TYPES_H
+#define SMS_CDMA_PLUGIN_TYPES_H
+
+#define SMS_MAX_MESSAGE_ID                     65536
+#define SMS_SEQ_NUM_MAX                                64
+#define SMS_MAX_USER_DATA_LEN          160
+#define SMS_MAX_SUBMIT_MESSAGE_ID      256
+
+#define SMS_TRANS_ADDRESS_MAX_LEN      256
+
+#define SMS_MAX_NUMBER_OF_ACK          8
+
+#define SMS_PUSH_XML_HREF_TAG          "href"
+#define SMS_PUSH_XML_SI_ID_TAG         "si-id"
+#define SMS_PUSH_XML_CREATED_TAG       "created"
+#define SMS_PUSH_XML_EXPIRES_TAG       "si-expires"
+#define SMS_PUSH_XML_ACTION_TAG                "action"
+
+#define SMS_PUSH_XML_INVAL_OBJ         "invalidate-object"
+#define SMS_PUSH_XML_INVAL_SVC         "invalidate-service"
+#define SMS_PUSH_XML_CO_URI                    "uri"
+
+
+typedef unsigned char sms_wap_app_code_t;      /* _sms_wap_app_code_e */
+
+typedef struct _SMS_WSP_CONTENTS_TYPE_S
+{
+       char*         contentsTypeName;
+       unsigned char contentsTypeCode;
+} SMS_WSP_CONTENTS_TYPE_S;
+
+
+typedef struct _SMS_WSP_CHARSET_S
+{
+       char*  charsetName;
+       unsigned short charsetCode;
+} SMS_WSP_CHARSET_S;
+
+
+typedef struct _SMS_WAP_UNREGISTER_CONTENTS_TYPE_S
+{
+       char*         contentsTypeName;
+       unsigned short contentsTypeCode;
+} SMS_WAP_UNREGISTER_CONTENTS_TYPE_S;
+
+
+typedef struct _SMS_WSP_LANGUAGE_S
+{
+       char*         languageName;
+       unsigned char languageCode;
+} SMS_WSP_LANGUAGE_S;
+
+
+typedef struct _SMS_WSP_HEADER_PARAMETER_S
+{
+       char*         parameterToken;
+       unsigned int parameterCode;
+} SMS_WSP_HEADER_PARAMETER_S;
+
+
+typedef struct _SMS_WSP_METHOD_TYPE_S
+{
+       char*         methodName;
+       unsigned char methodCode;
+} SMS_WSP_METHOD_TYPE_S;
+
+
+typedef struct _SMS_WSP_SECURITY_TYPE_S
+{
+       char*         SecurityTypeName;
+       unsigned char SecurityTypeCode;
+}SMS_WSP_SECURITY_TYPE_S;
+
+typedef struct
+{
+       msg_request_id_t                        reqId;          /**< Indicates the request ID, which is unique. When applications submit a request to the framework, this value will be set by the framework. */
+       MSG_MESSAGE_INFO_S                      msgInfo;        /**< Indicates the message structure to be sent by applications. */
+       MSG_SENDINGOPT_INFO_S           sendOptInfo;
+} sms_request_info_s;
+
+
+typedef struct _sms_sent_info_s
+{
+       sms_request_info_s              reqInfo;                /**< Indicates the corresponding request structure. */
+       bool                                            bLast;
+} sms_sent_info_s;
+
+
+enum _sms_network_status_e {
+       SMS_NETWORK_SEND_SUCCESS = 0x00,
+       SMS_NETWORK_SENDING,
+       SMS_NETWORK_SEND_FAIL,
+       SMS_NETWORK_SEND_FAIL_TIMEOUT,
+       SMS_NETWORK_SEND_FAIL_MANDATORY_INFO_MISSING,
+       SMS_NETWORK_SEND_FAIL_TEMPORARY,
+       SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_WITH_MOD,
+       SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_NOT_ALLOWED,
+       SMS_NETWORK_SEND_FAIL_FDN_RESTRICED,
+       SMS_NETWORK_SEND_PENDING,
+       SMS_NETWORK_SEND_FAIL_UNKNOWN_SUBSCRIBER,
+       SMS_NETWORK_SEND_FAIL_MS_DISABLED,
+       SMS_NETWORK_SEND_FAIL_NETWORK_NOT_READY,
+};
+
+enum _sms_wap_app_code_e
+{
+       SMS_WAP_APPLICATION_DEFAULT = 0x00,
+
+       SMS_WAP_APPLICATION_PUSH_SI,
+       SMS_WAP_APPLICATION_PUSH_SIC,
+
+       SMS_WAP_APPLICATION_PUSH_SL,
+       SMS_WAP_APPLICATION_PUSH_SLC,
+
+       SMS_WAP_APPLICATION_PUSH_CO,
+       SMS_WAP_APPLICATION_PUSH_COC,
+
+       SMS_WAP_APPLICATION_MMS_UA,
+
+       SMS_WAP_APPLICATION_PUSH_SIA,
+
+       SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP,
+       SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP_XML,
+       SMS_WAP_APPLICATION_SYNCML_DM_NOTIFICATION,
+       SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION,
+       SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION_WBXML,
+
+       SMS_WAP_APPLICATION_LOC_UA_WBXML,
+       SMS_WAP_APPLICATION_LOC_UA_XML,
+
+       SMS_WAP_APPLICATION_DRM_UA_XML,
+       SMS_WAP_APPLICATION_DRM_UA_MESSAGE,
+       SMS_WAP_APPLICATION_DRM_UA_CONETENT,
+       SMS_WAP_APPLICATION_DRM_UA_RIGHTS_XML,
+       SMS_WAP_APPLICATION_DRM_UA_RIGHTS_WBXML,
+       SMS_WAP_APPLICATION_DRM_V2_RO_XML,
+       SMS_WAP_APPLICATION_DRM_V2_ROAP_PDU_XML,
+       SMS_WAP_APPLICATION_DRM_V2_ROAP_TRIGGER_XML,
+       SMS_WAP_APPLICATION_DRM_V2_ROAP_TRIGGER_WBXML,
+
+       SMS_WAP_APPLICATION_PUSH_PROVISIONING,
+       SMS_WAP_APPLICATION_PUSH_PROVISIONING_XML,
+       SMS_WAP_APPLICATION_PUSH_PROVISIONING_WBXML,
+
+       SMS_WAP_APPLICATION_PUSH_BROWSER_SETTINGS,
+       SMS_WAP_APPLICATION_PUSH_BROWSER_BOOKMARKS,
+       SMS_WAP_APPLICATION_PUSH_SYNCSET_WBXML,
+       SMS_WAP_APPLICATION_PUSH_SYNCSET_XML,
+
+       SMS_WAP_APPLICATION_PUSH_EMAIL_XML,
+       SMS_WAP_APPLICATION_PUSH_EMAIL_WBXML,
+
+       SMS_WAP_APPLICATION_PUSH_IMPS_CIR,
+
+       SMS_WAP_APPLICATION_PUSH_WAP_WMLC,
+
+       SMS_WAP_APPLICATION_WML_UA,
+       SMS_WAP_APPLICATION_WTA_UA,
+
+       SMS_WAP_APPLICATION_PUSH_SYNCML,
+       SMS_WAP_APPLICATION_LOC_UA,
+       SMS_WAP_APPLICATION_SYNCML_DM,
+       SMS_WAP_APPLICATION_PUSH_EMAIL,
+
+       SMS_OMA_APPLICATION_ULP_UA,
+       SMS_OMA_APPLICATION_DLOTA_UA,
+
+       SMS_WAP_APPLICATION_LBS,
+};
+
+
+typedef unsigned char  sms_network_status_t;   /* _sms_network_status_e */
+
+/********************************************************************************/
+/*                                                             TELESERVICE LAYER                                                               */
+/********************************************************************************/
+
+
+typedef bool                           sms_digit_mode_t;                       /* _sms_digit_mode_e */
+
+typedef bool                           sms_number_mode_t;                      /* _sms_number_mode_e */
+
+typedef unsigned char          sms_number_type_t;                      /* _sms_number_type_e */
+
+typedef unsigned char          sms_number_plan_t;                      /* _sms_number_plan_e */
+
+
+typedef enum _sms_message_type_e
+{
+       SMS_TYPE_RESERVED               = 0x00,         // reserved
+       SMS_TYPE_DELIVER,                                       // mobile-terminated only
+       SMS_TYPE_SUBMIT,                                        // mobile-originated only
+       SMS_TYPE_CANCEL,                                        // mobile-originated only
+       SMS_TYPE_DELIVERY_ACK,                          // mobile-terminated only
+       SMS_TYPE_USER_ACK,                                      // either direction
+       SMS_TYPE_READ_ACK,                                      // either direction
+       SMS_TYPE_DELIVER_REPORT,                        // mobile-originated only
+       SMS_TYPE_SUBMIT_REPORT  = 0x08,         // mobile-terminated only
+       SMS_TYPE_MAX_VALUE
+}sms_message_type_t;
+
+
+typedef enum _sms_alert_option_e
+{
+       SMS_ALERT_NO_ALERT                              = 0,
+       SMS_ALERT_DEFAULT_ALERT,
+       SMS_ALERT_VIBRATE_ONCE,
+       SMS_ALERT_VIBRATE_REPEAT,
+       SMS_ALERT_VISUAL_ONCE,
+       SMS_ALERT_VISUAL_REPEAT,
+       SMS_ALERT_LOW_PRIORITY_ONCE,
+       SMS_ALERT_LOW_PRIORITY_REPEAT,
+       SMS_ALERT_MEDIUM_PRIORITY_ONCE,
+       SMS_ALERT_MEDIUM_PRIORITY_REPEAT,
+       SMS_ALERT_HIGH_PRIORITY_ONCE,
+       SMS_ALERT_HIGH_PRIORITY_REPEAT,
+       SMS_ALERT_RESERVED
+}sms_alert_option_t;
+
+
+typedef enum _sms_language_type_e {
+       SMS_LAN_UNKNOWN,
+       SMS_LAN_ENGLISH,
+       SMS_LAN_FRENCH,
+       SMS_LAN_SPANISH,
+       SMS_LAN_JAPANESE,
+       SMS_LAN_KOREAN,
+       SMS_LAN_CHINESE,
+       SMS_LAN_HEBREW,
+}sms_language_type_t;
+
+
+typedef enum _sms_priority_indicator_e
+{
+       SMS_PRIORITY_NORMAL                             = 0x00,
+       SMS_PRIORITY_INTERACTIVE,
+       SMS_PRIORITY_URGENT,
+       SMS_PRIORITY_EMERGENCY
+}sms_priority_indicator_t;
+
+
+typedef enum _sms_privacy_indicator_e
+{
+       SMS_PRIVACY_NOT_RESTRICTED              = 0x00,
+       SMS_PRIVACY_RESTRICTED,
+       SMS_PRIVACY_CONFIDENTIAL,
+       SMS_PRIVACY_SECRET
+}sms_privacy_indicator_t;
+
+
+typedef enum _sms_alert_priority_e
+{
+       SMS_ALERT_MOBILE_DEFAULT                = 0x00,
+       SMS_ALERT_LOW_PRIORITY,
+       SMS_ALERT_MEDIUM_PRIORITY,
+       SMS_ALERT_HIGH_PRIORITY
+}sms_alert_priority_t;
+
+
+typedef enum _sms_display_mode_e
+{
+       SMS_DISPLAY_IMMEDIATE                   = 0x00,
+       SMS_DISPLAY_DEFAULT_SETTING,
+       SMS_DISPLAY_USER_INVOKE,
+       SMS_DISPLAY_RESERVED
+}sms_display_mode_t;
+
+
+typedef enum _sms_encoding_type_e
+{
+       SMS_ENCODE_OCTET        = 0x0,
+       SMS_ENCODE_EPM  = 0x1,  /*IS-91 Extended Protocol Message*/
+       SMS_ENCODE_7BIT_ASCII   = 0x2,
+       SMS_ENCODE_IA5  = 0x3,
+       SMS_ENCODE_UNICODE      = 0x4,
+       SMS_ENCODE_SHIFT_JIS    = 0x5,
+       SMS_ENCODE_KOREAN       = 0x6,
+       SMS_ENCODE_LATIN_HEBREW = 0x7,
+       SMS_ENCODE_LATIN        = 0x8,
+       SMS_ENCODE_GSM7BIT      = 0x9,
+       SMS_ENCODE_GSMDCS = 0xa,
+       SMS_ENCODE_EUCKR = 0x10,
+       SMS_ENCODE_RESERVED
+}sms_encoding_type_t;
+
+
+typedef enum _sms_relative_time_e
+{
+       SMS_REL_TIME_5_MINS                     = 0,
+       SMS_REL_TIME_12_HOURS           = 143,
+       SMS_REL_TIME_1_DAY                      = 167,
+       SMS_REL_TIME_2_DAYS                     = 168,
+       SMS_REL_TIME_3_DAYS                     = 169,
+       SMS_REL_TIME_1_WEEK                     = 173,
+       SMS_REL_TIME_INDEFINITE         = 245,
+       SMS_REL_TIME_IMMEDIATE          = 246,
+       SMS_REL_TIME_ACTIVE                     = 247,
+       SMS_REL_TIME_REGISTRATION       = 248,
+       SMS_REL_TIME_RESERVED
+}sms_relative_time_t;
+
+
+typedef enum _sms_status_code_e
+{
+       /* ERROR_CLASS = '00' (no error) */
+       SMS_STATUS_ACCEPTED                             = 0x00,
+       SMS_STATUS_DEPOSITED                    = 0x01,
+       SMS_STATUS_DELIVERED                    = 0x02,
+       SMS_STATUS_CANCELLED                    = 0x03,
+
+       /* ERROR_CLASS = '10' (temporary condition) */
+       SMS_STATUS_TEMP_NETWORK_CONGESTION      = 0x84,
+       SMS_STATUS_TEMP_NETWORK_ERROR           = 0x85,
+       SMS_STATUS_TEMP_UNKNOWN_ERROR           = 0x9F,
+
+       /* ERROR_CLASS = '11' (permanent condition) */
+       SMS_STATUS_PERMANENT_NETWORK_CONGESTION = 0xC4,
+       SMS_STATUS_PERMANENT_NETWORK_ERROR              = 0xC5,
+       SMS_STATUS_PERMANENT_CANCEL_FAILED              = 0xC6,
+       SMS_STATUS_PERMANENT_BLOCKED_DESTINATION        = 0xC7,
+       SMS_STATUS_PERMANENT_TEXT_TOO_LONG              = 0xC8,
+       SMS_STATUS_PERMANENT_DUPLICATE_MESSAGE  = 0xC9,
+       SMS_STATUS_PERMANENT_INVALID_DESTINATION        = 0xCA,
+       SMS_STATUS_PERMANENT_MESSAGE_EXPIRED    = 0xCD,
+       SMS_STATUS_PERMANENT_UNKNOWN_ERROR              = 0xDF,
+
+}sms_status_code_t;
+
+
+typedef enum _sms_cmae_category_e {
+       SMS_CMAE_CTG_GEO                                = 0x00,
+       SMS_CMAE_CTG_MET                                = 0x01,
+       SMS_CMAE_CTG_SAFETY                     = 0x02,
+       SMS_CMAE_CTG_SECURITY           = 0x03,
+       SMS_CMAE_CTG_RESCUE                     = 0x04,
+       SMS_CMAE_CTG_FIRE                               = 0x05,
+       SMS_CMAE_CTG_HEALTH                     = 0x06,
+       SMS_CMAE_CTG_ENV                                = 0x07,
+       SMS_CMAE_CTG_TRANSPORT          = 0x08,
+       SMS_CMAE_CTG_INFRA                      = 0x09,
+       SMS_CMAE_CTG_CBRNE                      = 0x0a,
+       SMS_CMAE_CTG_OTHER                      = 0x0b,
+       SMS_CMAE_CTG_RESERVED,
+}sms_cmae_category_t;
+
+
+typedef enum _sms_cmae_response_type_e {
+       SMS_CMAE_RESP_TYPE_SHELTER                              = 0x00,
+       SMS_CMAE_RESP_TYPE_EVACUATE                             = 0x01,
+       SMS_CMAE_RESP_TYPE_PREPARE                              = 0x02,
+       SMS_CMAE_RESP_TYPE_EXECUTE                              = 0x03,
+       SMS_CMAE_RESP_TYPE_MONITOR                              = 0x04,
+       SMS_CMAE_RESP_TYPE_AVOID                                        = 0x05,
+       SMS_CMAE_RESP_TYPE_ASSESS                               = 0x06,
+       SMS_CMAE_RESP_TYPE_NONE                                 = 0x07,
+       SMS_CMAE_RESP_TYPE_RESERVED,
+}sms_cmae_response_type_t;
+
+
+typedef enum _sms_cmae_severity_e {
+       SMS_CMAE_SEVERITY_EXTREME                       = 0x0,
+       SMS_CMAE_SEVERITY_SEVERE                                = 0x1,
+       SMS_CMAE_SEVERITY_RESERVED,
+}sms_cmae_severity_t;
+
+
+typedef enum _sms_cmae_urgency_e {
+       SMS_CMAE_URGENCY_IMMEDIATE                      = 0x0,
+       SMS_CMAE_URGENCY_EXPECTED                       = 0x1,
+       SMS_CMAE_URGENCY_RESERVED,
+}sms_cmae_urgency_t;
+
+
+typedef enum _sms_cmae_certainty_e {
+       SMS_CMAE_CERTAINTY_OBSERVED                     = 0x0,
+       SMS_CMAE_CERTAINTY_LIKELY                       = 0x1,
+       SMS_CMAE_CERTAINTY_RESERVED,
+}sms_cmae_certainty_t;
+
+
+typedef enum _sms_cmae_alert_handle_e {
+       SMS_CMAE_ALERT_PRESIDENTIAL                             = 0x00,
+       SMS_CMAE_ALERT_EXTREME                                  = 0x01,
+       SMS_CMAE_ALERT_SEVERE                                   = 0x02,
+       SMS_CMAE_ALERT_AMBER                                            = 0x03,
+       SMS_CMAE_ALERT_RESERVED,
+}sms_cmae_alert_handle_t;
+
+
+enum _sms_bearer_sub_param_e
+{
+       SMS_BEARER_MESSAGE_IDENTIFIER                           = 0x00,
+       SMS_BEARER_USER_DATA                                            = 0x01,
+       SMS_BEARER_USER_RESPONSE_CODE                           = 0x02,
+       SMS_BEARER_MSG_CENTER_TIME_STAMP                        = 0x03,
+       SMS_BEARER_VALIDITY_PERIOD_ABSOLUTE                     = 0x04,
+       SMS_BEARER_VALIDITY_PERIOD_RELATIVE                     = 0x05,
+       SMS_BEARER_DEFERRED_DELIVERY_TIME_ABSOLUTE      = 0x06,
+       SMS_BEARER_DEFERRED_DELIVERY_TIME_RELATIVE      = 0x07,
+       SMS_BEARER_PRIORITY_INDICATOR                           = 0x08,
+       SMS_BEARER_PRIVACY_INDICATOR                            = 0x09,
+       SMS_BEARER_REPLY_OPTION                                         = 0x0A,
+       SMS_BEARER_NUMBER_OF_MESSAGES                           = 0x0B,
+       SMS_BEARER_ALERT_ON_MSG_DELIVERY                        = 0x0C,
+       SMS_BEARER_LANGUAGE_INDICATOR                           = 0x0D,
+       SMS_BEARER_CALLBACK_NUMBER                                      = 0x0E,
+       SMS_BEARER_MSG_DISPLAY_MODE                                     = 0x0F,
+       SMS_BEARER_MULTI_ENCODING_USER_DATA                     = 0x10,
+       SMS_BEARER_MSG_DEPOSIT_INDEX                            = 0x11,
+       SMS_BEARER_SVC_CATEGORY_PROGRAM_DATA            = 0x12,
+       SMS_BEARER_SVC_CATEGORY_PROGRAM_RESULT          = 0x13,
+       SMS_BEARER_MESSAGE_STATUS                                       = 0x14,
+       SMS_BEARER_TP_FAILURE_CAUSE                                     = 0x15,
+       SMS_BEARER_ENHANCED_VMN                                         = 0x16,
+       SMS_BEARER_ENHANCED_VMN_ACK                                     = 0x17,
+       SMS_BEARER_MAX_VALUE
+};
+
+
+enum _sms_svc_ctg_result_e
+{
+       SMS_SVC_RESULT_SUCCESS                                  = 0x00,
+       SMS_SVC_RESULT_MEMORY_LIMIT_EXCEEDED,
+       SMS_SVC_RESULT_LIMIT_EXCEEDED,
+       SMS_SVC_RESULT_ALREADY_PROGRAMMED,
+       SMS_SVC_RESULT_NOT_PREVIOUSLY_PROGRAMMED,
+       SMS_SVC_RESULT_INVALID_MAX_MESSAGES,
+       SMS_SVC_RESULT_INVALID_ALERT_OPTION,
+       SMS_SVC_RESULT_INVALID_SVC_CTG_NAME,
+       SMS_SVC_RESULT_INSPECIFIED_PROGRAMMING_FAILURE,
+       SMS_SVC_RESULT_RESERVED
+};
+
+enum _SMS_TIME_FORMAT_E {
+       SMS_TIME_EMPTY = 0,
+       SMS_TIME_RELATIVE       ,
+       SMS_TIME_ABSOLUTE
+};
+
+
+enum _sms_tp_failure_cause_e {
+       /*      0x00 ~ 0x7f reserved                    */
+       SMS_TP_CAUSE_RESERVED,
+
+       /*      0x80 ~ 0x8f TP-PID errors       */
+       SMS_TP_CAUSE_TELEMATIC_INTERWORKING_NOT_SUPPORTED       = 0x80,
+       SMS_TP_CAUSE_SHORT_MSG_TYPE_0_NOT_SUPPORTED                     = 0x81,
+       SMS_TP_CAUSE_CANNOT_REPLACE_SHORT_MSG                                   = 0x82,
+       SMS_TP_CAUSE_UNSPECIFIED_TP_PID_ERROR                                   = 0x8f,
+
+       /* 0x90 ~ 0x9f TP-DCS errors    */
+       SMS_TP_CAUSE_DCS_NOT_SPPORTED                                           = 0x90,
+       SMS_TP_CAUSE_MSG_CLASS_NOT_SUPPORTED                            = 0x91,
+       SMS_TP_CAUSE_UNSPECIFIED_TP_DCS_ERROR                           = 0x9f,
+
+       /* 0xa0 ~ 0xaf TP-Command Errors        */
+       SMS_TP_CAUSE_CMD_CANNOT_BE_ACTIONED                             = 0xa0,
+       SMS_TP_CAUSE_CMD_UNSUPPORTED                                            = 0xa1,
+       SMS_TP_CAUSE_UNSPECIFIED_TP_CMD_ERROR                           = 0xaf,
+
+       SMS_TP_CAUSE_TPDU_NOT_SUPPORTED                                         = 0xb0,
+
+       SMS_TP_CAUSE_SC_BUSY                                                                    = 0xc0,
+       SMS_TP_CAUSE_NO_SC_SUBCRIPTION                                          = 0xc1,
+       SMS_TP_CAUSE_SC_SYSTEM_FAILURE                                          = 0xc2,
+       SMS_TP_CAUSE_INVALID_SME_ADDRESS                                        = 0xc3,
+       SMS_TP_CAUSE_DESTINATION_SME_BARRED                             = 0xc4,
+       SMS_TP_CAUSE_SM_REJECTED_DUPLICATE_SM                           = 0xc5,
+       SMS_TP_CAUSE_TP_VPF_NOT_SUPPORTED                                       = 0xc6,
+       SMS_TP_CAUSE_TP_VP_NOT_SUPPORTED                                        = 0xc7,
+
+       SMS_TP_CAUSE_SIM_SMS_STORAGE_FULL                                       = 0xd0,
+       SMS_TP_CAUSE_NO_SMS_STORAGE_CAPABILITY_IN_SIM           = 0xd1,
+       SMS_TP_CAUSE_ERROR_IN_MS                                                                = 0xd2,
+       SMS_TP_CAUSE_MEMORY_CAPACITY_EXCEEDED                           = 0xd3,
+       SMS_TP_CAUSE_SIM_APPLICATION_TOOLKIT_BUSY                       = 0xd4,
+       SMS_TP_CAUSE_SIM_DATA_DOWNLOAD_ERROR                            = 0xd5,
+
+       /* 0xe0 ~ 0xfe Values specific to an application        */
+       SMS_TP_CAUSE_SPECIFIC_TO_APPLICATION_MIN                        = 0xe0,
+       SMS_TP_CAUSE_SPECIFIC_TO_APPLICATION_MAX                        = 0xfe,
+
+       SMS_TP_CAUSE_UNSPECIFIED_ERROR_CAUSE                            = 0xff
+};
+
+
+typedef struct _sms_trans_msg_id_s
+{
+       unsigned short          msg_id;
+       bool                            header_ind;
+}sms_trans_msg_id_s;
+
+
+typedef struct _sms_telesvc_addr_s
+{
+       sms_digit_mode_t        digit_mode;
+       sms_number_type_t       number_type;
+       sms_number_plan_t       number_plan;
+       unsigned int            addr_len;
+       char                            szData[SMS_TRANS_ADDRESS_MAX_LEN + 1];
+}sms_telesvc_addr_s;
+
+
+typedef struct _sms_reply_option_s
+{
+       bool    user_ack_req;
+       bool    deliver_ack_req;
+       bool    read_ack_req;
+       bool    report_req;
+}sms_reply_option_s;
+
+
+typedef struct _sms_time_relative_s
+{
+       sms_relative_time_t             rel_time;
+}sms_time_rel_s;
+
+typedef struct _sms_time_stamp_s
+{
+       unsigned char           year;           // range 00-99 (96~99 : 19xx, 00~95 : 20xx)
+       unsigned char           month;          // range 1-12
+       unsigned char           day;
+       unsigned char           hours;          // range 0-23
+       unsigned char           minutes;        // range 0-59
+       unsigned char           seconds;        // range 0-59
+}sms_time_abs_s;
+
+
+typedef struct _sms_val_period_s
+{
+       unsigned char           format;
+       union {
+               sms_time_rel_s  rel_time;
+               sms_time_abs_s  abs_time;
+       }time;
+}sms_val_period_s;
+
+
+typedef struct _sms_encoding_specific_s
+{
+       sms_encoding_type_t             encode_type;
+       unsigned int                    data_len;
+       char                                    user_data[SMS_MAX_USER_DATA_LEN +1];
+}sms_encoding_specific_s;
+
+
+typedef struct _sms_ctg_specific_s
+{
+       unsigned char           operation_code;
+       unsigned short          category;
+       sms_language_type_t     language;
+       unsigned char           max_msg;
+       sms_alert_option_t      alert_option;
+       unsigned int            data_len;
+       char                            user_data[SMS_MAX_USER_DATA_LEN +1];
+}sms_ctg_specific_s;
+
+
+typedef struct _sms_svc_ctg_program_data_s
+{
+       sms_encoding_type_t             encode_type;
+       unsigned int                    num_data;
+       sms_ctg_specific_s              *specific_data;
+}sms_svc_ctg_program_data_s;
+
+
+typedef struct _sms_telesvc_userdata_s
+{
+       sms_encoding_type_t             encode_type;
+       unsigned char                   msg_type;
+       unsigned int                    data_len;
+       unsigned char                   user_data[SMS_MAX_USER_DATA_LEN +1];
+}sms_telesvc_userdata_s;
+
+
+typedef struct _sms_telesvc_cmasdata_s
+{
+       unsigned int                            data_len;
+       sms_encoding_type_t             encode_type;
+       unsigned char                           alert_text[SMS_MAX_USER_DATA_LEN +1];
+       sms_cmae_category_t             category;
+       sms_cmae_response_type_t                response_type;
+       sms_cmae_severity_t                     severity;
+       sms_cmae_urgency_t                      urgency;
+       sms_cmae_certainty_t                    certainty;
+       unsigned short          id;
+       sms_cmae_alert_handle_t                 alert_handle;           /* 00:Presidential 01:Extreme 02:Severe 03:AMBER 04:Test */
+       sms_time_abs_s                  expires;
+       sms_language_type_t             language;
+       bool                                    is_wrong_recode_type;
+}sms_telesvc_cmasdata_s;
+
+
+typedef struct _sms_enhanced_vmn_s
+{
+       sms_priority_indicator_t                priority;
+       bool                                                    password_req;
+       bool                                                    setup_req;
+       bool                                                    pw_change_req;
+       unsigned char                                   min_pw_len;
+       unsigned char                                   max_pw_len;
+       unsigned char                                   vm_num_unheard_msg;
+       bool                                                    vm_mailbox_alm_full;
+       bool                                                    vm_mailbox_full;
+       bool                                                    reply_allowed;
+       bool                                                    fax_included;
+       unsigned short                          vm_len;
+       unsigned char                                   vm_ret_day;
+       unsigned short                          vm_msg_id;
+       unsigned short                          vm_mailbox_id;
+
+       sms_digit_mode_t                                an_digit_mode;
+       sms_number_type_t                               an_number_type;
+       sms_number_plan_t                               an_number_plan;
+       unsigned char                                   an_num_field;
+       unsigned char                                   an_char[SMS_MAX_USER_DATA_LEN+1];
+
+       sms_digit_mode_t                                cli_digit_mode;
+       sms_number_type_t                               cli_number_type;
+       sms_number_plan_t                               cli_number_plan;
+       unsigned char                                   cli_num_field;
+       unsigned char                                   cli_char[SMS_MAX_USER_DATA_LEN+1];
+}sms_enhanced_vmn_s;
+
+
+typedef struct _sms_enhanced_vmn_ack_s
+{
+       unsigned short                          vm_mailbox_id;
+       unsigned char                                   vm_num_unheard_msg;
+       unsigned char                                   num_delete_ack;
+       unsigned char                                   num_play_ack;
+
+       unsigned short                          da_vm_msg_id[SMS_MAX_NUMBER_OF_ACK+1];
+       unsigned short                          pa_vm_msg_id[SMS_MAX_NUMBER_OF_ACK+1];
+}sms_enhanced_vmn_ack_s;
+
+
+typedef struct _sms_telesvc_deliver_s
+{
+       sms_trans_msg_id_s                      msg_id;
+       sms_telesvc_userdata_s          user_data;
+       sms_telesvc_cmasdata_s          cmas_data;
+       sms_time_abs_s                          time_stamp;
+       sms_val_period_s                        val_period;
+       sms_val_period_s                        defer_val_period;
+       sms_priority_indicator_t                priority;
+       sms_privacy_indicator_t         privacy;
+       sms_reply_option_s                      reply_opt;
+       unsigned int                            num_msg;
+       sms_alert_priority_t            alert_priority;
+       sms_language_type_t                     language;
+       sms_telesvc_addr_s                      callback_number;
+       sms_display_mode_t                      display_mode;
+       sms_encoding_specific_s         multi_encode_data;
+       unsigned short                          deposit_id;
+       //sms_svc_ctg_program_data_s    svc_ctg;
+       sms_enhanced_vmn_s                      enhanced_vmn;
+       sms_enhanced_vmn_ack_s          enhanced_vmn_ack;
+}sms_telesvc_deliver_s;
+
+
+typedef struct _sms_telesvc_submit_s
+{
+       sms_trans_msg_id_s                      msg_id;
+       sms_telesvc_userdata_s          user_data;
+       sms_val_period_s                        val_period;
+       sms_val_period_s                        defer_val_period;
+       sms_priority_indicator_t        priority;
+       sms_privacy_indicator_t         privacy;
+       sms_reply_option_s                      reply_opt;
+       sms_alert_priority_t            alert_priority;
+       sms_language_type_t                     language;
+       sms_telesvc_addr_s                      callback_number;
+       sms_encoding_specific_s         multi_encode_data;
+       unsigned char                           deposit_id;
+       //sms_svc_ctg_program_data_s    svc_ctg;
+}sms_telesvc_submit_s;
+
+
+typedef struct _sms_telesvc_cancel_s
+{
+       sms_trans_msg_id_s              msg_id;
+}sms_telesvc_cancel_s;
+
+
+typedef struct _sms_telesvc_user_ack_s
+{
+       sms_trans_msg_id_s                      msg_id;
+       sms_telesvc_userdata_s          user_data;
+       unsigned char                           resp_code;
+       sms_time_abs_s                          time_stamp;
+       sms_encoding_specific_s         multi_encode_data;
+       unsigned char                           deposit_id;
+}sms_telesvc_user_ack_s;
+
+
+typedef struct _sms_telesvc_deliver_ack_s
+{
+       sms_trans_msg_id_s                      msg_id;
+       sms_telesvc_userdata_s          user_data;
+       sms_time_abs_s                          time_stamp;
+       sms_encoding_specific_s         multi_encode_data;
+       sms_status_code_t                       msg_status;
+}sms_telesvc_deliver_ack_s;
+
+
+typedef struct _sms_telesvc_read_ack_s
+{
+       sms_trans_msg_id_s                      msg_id;
+       sms_telesvc_userdata_s          user_data;
+       sms_time_abs_s                          time_stamp;
+       sms_encoding_specific_s         multi_encode_data;
+       unsigned char                           deposit_id;
+}sms_telesvc_read_ack_s;
+
+typedef struct _sms_telesvc_deliver_report_s
+{
+       sms_trans_msg_id_s              msg_id;
+       unsigned char                   tp_fail_cause;
+       sms_telesvc_userdata_s  user_data;
+       sms_language_type_t             language;
+       unsigned char                   multi_encode_data;
+}sms_telesvc_report_s;
+
+
+typedef struct _sms_telesvc_msg_s
+{
+       sms_message_type_t              type;
+
+       union {
+               sms_telesvc_deliver_s                   deliver;
+               sms_telesvc_submit_s                    submit;
+               sms_telesvc_cancel_s                    cancel;
+               sms_telesvc_user_ack_s                  user_ack;
+               sms_telesvc_deliver_ack_s               delivery_ack;
+               sms_telesvc_read_ack_s                  read_ack;
+               sms_telesvc_report_s                    report;
+       }data;
+}sms_telesvc_msg_s;
+
+
+
+/********************************************************************************/
+/*                                                             TRANSPORT LAYER                                                                 */
+/********************************************************************************/
+
+typedef unsigned short                 sms_trans_param_id_t;           /* _sms_trans_param_id_e */
+
+typedef unsigned short                 sms_trans_telesvc_id_t;         /* _sms_trans_telesvc_id_e */
+
+typedef unsigned short                 sms_trans_svc_ctg_t;                    /* _sms_trans_svc_ctg_e */
+
+typedef unsigned char          sms_trans_reply_seq_t;
+
+
+typedef enum _sms_trans_msg_type_e
+{
+       SMS_TRANS_P2P_MSG                       = 0x00,
+       SMS_TRANS_BROADCAST_MSG         = 0x01,
+       SMS_TRANS_ACK_MSG                       = 0x02,
+       SMS_TRANS_TYPE_RESERVED
+}sms_trans_msg_type_t;
+
+
+enum _sms_trans_param_id_e
+{
+       SMS_TRANS_PARAM_TELESVC_IDENTIFIER              = 0x00,
+       SMS_TRANS_PARAM_SERVICE_CATEGORY                = 0x01,
+       SMS_TRANS_PARAM_ORG_ADDRESS                             = 0x02,
+       SMS_TRANS_PARAM_ORG_SUB_ADDRESS                 = 0x02,
+       SMS_TRANS_PARAM_DEST_ADDRESS                    = 0x04,
+       SMS_TRANS_PARAM_DEST_SUB_ADDRESS                = 0x05,
+       SMS_TRANS_PARAM_BEARER_REPLY_OPTION             = 0x06,
+       SMS_TRANS_PARAM_CAUSE_CODES                             = 0x07,
+       SMS_TRANS_PARAM_BEARER_DATA                             = 0x08,
+       SMS_TRANS_PARAM_RESERVED
+};
+
+
+enum _sms_trans_telesvc_id_e
+{
+       SMS_TRANS_TELESVC_CMT_91                = 0x1000,       /* IS-91 Extended Protocol Enhanced Services */
+       SMS_TRANS_TELESVC_CPT_95                = 0x1001,       /* Wireless Paging Teleservice */
+       SMS_TRANS_TELESVC_CMT_95                = 0x1002,       /* Wireless Messaging Teleservice */
+       SMS_TRANS_TELESVC_VMN_95                = 0x1003,       /* Voice Mail Notification */
+       SMS_TRANS_TELESVC_WAP                   = 0x1004,       /* Wireless Application Protocol */
+       SMS_TRANS_TELESVC_WEMT                  = 0x1005,       /* Wireless Enhanced Messaging Teleservice */
+       SMS_TRANS_TELESVC_SCPT                  = 0x1006,       /* Service Category Programming Teleservice */
+       SMS_TRANS_TELESVC_CATPT                 = 0x1007,       /* Card Application Toolkit Protocol Teleservice */
+       SMS_TRANS_TELESVC_RESERVED              = 0xffff
+};
+
+
+enum _sms_trans_svc_ctg_e
+{
+       SMS_TRANS_SVC_CTG_UNKNOWN                               = 0x0000,
+       SMS_TRANS_SVC_CTG_EMERGENCY                             = 0x0001,
+       SMS_TRANS_SVC_CTG_ADMINISTRATIVE                = 0x0002,
+       SMS_TRANS_SVC_CTG_MAINTENANCE                   = 0x0003,
+       SMS_TRANS_SVC_CTG_GNEWS_LOCAL                   = 0x0004,
+       SMS_TRANS_SVC_CTG_GNEWS_REGIONAL                = 0x0005,
+       SMS_TRANS_SVC_CTG_GNEWS_NATIONAL                = 0x0006,
+       SMS_TRANS_SVC_CTG_GNEWS_INTERNATIONAL   = 0x0007,
+       SMS_TRANS_SVC_CTG_BFNEWS_LOCAL                  = 0x0008,
+       SMS_TRANS_SVC_CTG_BFNEWS_REGIONAL               = 0x0009,
+       SMS_TRANS_SVC_CTG_BFNEWS_NATIONAL               = 0x000a,
+       SMS_TRANS_SVC_CTG_BFNEWS_INTERNATIONAL  = 0x000b,
+       SMS_TRANS_SVC_CTG_SNEWS_LOCAL                   = 0x000c,
+       SMS_TRANS_SVC_CTG_SNEWS_REGIONAL                = 0x000d,
+       SMS_TRANS_SVC_CTG_SNEWS_NATIONAL                = 0x000e,
+       SMS_TRANS_SVC_CTG_SNEWS_INTERNATIONAL   = 0x000f,
+       SMS_TRANS_SVC_CTG_ENEWS_LOCAL                   = 0x0010,
+       SMS_TRANS_SVC_CTG_ENEWS_REGIONAL                = 0x0011,
+       SMS_TRANS_SVC_CTG_ENEWS_NATIONAL                = 0x0012,
+       SMS_TRANS_SVC_CTG_ENEWS_INTERNATIONAL   = 0x0013,
+       SMS_TRANS_SVC_CTG_LOCAL_WEATHER                 = 0x0014,
+       SMS_TRANS_SVC_CTG_TRAFFIC_REPORTS               = 0x0015,
+       SMS_TRANS_SVC_CTG_FLIGHT_SCHEDULES              = 0x0016,
+       SMS_TRANS_SVC_CTG_RESTAURANTS                   = 0x0017,
+       SMS_TRANS_SVC_CTG_LODGINGS                              = 0x0018,
+       SMS_TRANS_SVC_CTG_RETAIL_DIRECTORY              = 0x0019,
+       SMS_TRANS_SVC_CTG_ADVERTISEMENTS                = 0x001a,
+       SMS_TRANS_SVC_CTG_STOCK_QUOTES                  = 0x001b,
+       SMS_TRANS_SVC_CTG_EMPLOYMENT                    = 0x001c,
+       SMS_TRANS_SVC_CTG_MEDICAL                               = 0x001d,
+       SMS_TRANS_SVC_CTG_TECHNOLOGY_NEWS               = 0x001e,
+       SMS_TRANS_SVC_CTG_MULTI_CTG                             = 0x001f,
+       SMS_TRANS_SVC_CTG_CATPT                                 = 0x0020,
+       SMS_TRANS_SVC_CTG_KDDI_CORP_MIN1                = 0x0021,
+       SMS_TRANS_SVC_CTG_KDDI_CORP_MAX1                = 0x003f,
+       SMS_TRANS_SVC_CTG_CMAS_PRESIDENTIAL     = 0x1000,
+       SMS_TRANS_SVC_CTG_CMAS_EXTREME                  = 0x1001,
+       SMS_TRANS_SVC_CTG_CMAS_SEVERE                   = 0x1002,
+       SMS_TRANS_SVC_CTG_CMAS_AMBER                    = 0x1003,
+       SMS_TRANS_SVC_CTG_CMAS_TEST                             = 0x1004,
+       SMS_TRANS_SVC_CTG_KDDI_CORP_MIN2                = 0x8001,
+       SMS_TRANS_SVC_CTG_KDDI_CORP_MAX2                = 0x803f,
+       SMS_TRANS_SVC_CTG_KDDI_CORP_MIN3                = 0xc001,
+       SMS_TRANS_SVC_CTG_KDDI_CORP_MAX3                = 0xc03f,
+       SMS_TRANS_SVC_CTG_RESERVED,
+       SMS_TRANS_SVC_CTG_UNDEFINED                             = 0x8001,
+};
+
+
+typedef enum _sms_trans_err_class_e
+{
+       SMS_TRANS_ERR_CLASS_NONE                                = 0x00,
+       SMS_TRANS_ERR_CLASS_TEMPORARY                   = 0x02,
+       SMS_TRANS_ERR_CLASS_PERMANENT                   = 0x03
+}sms_trans_err_class_t;
+
+
+typedef enum _sms_trans_cause_code_e
+{
+       SMS_CAUSE_CODE_INVAILD_TELESERVICE_ID   = 0x04,
+       SMS_CAUSE_CODE_SERVICE_TERMINATION_DENIED               = 0x62,
+       SMS_TODO_FILL_THIS_ENUMS
+}sms_trans_cause_code_t;
+
+
+typedef enum _sms_trans_sub_addr_type_e
+{
+       SMS_TRANS_SUB_ADDR_NSAP                                 = 0x00,
+       SMS_TRANS_SUB_ADDR_USER                                 = 0x01,
+       SMS_TRANS_SUB_ADDR_RESERVED
+}sms_trans_sub_addr_type_t;
+
+
+
+enum _sms_trans_dnet_addr_type_e
+{
+       SMS_TRANS_DNET_UNKNOWN                                  = 0x00,
+       SMS_TRANS_DNET_INTERNET_PROTOCOL                = 0x01,
+       SMS_TRANS_DNET_INTERNET_MAIL_ADDR               = 0x02,
+       SMS_TRANS_DNET_RESERVED
+};
+
+
+enum _sms_digit_mode_e {
+       SMS_DIGIT_4BIT_DTMF     = 0,
+       SMS_DIGIT_8BIT  = 1
+};
+
+
+enum _sms_number_mode_e {
+       SMS_NUMBER_MODE_NONE_DATANETWORK        = 0,
+       SMS_NUMBER_MODE_DATANETWORK     = 1,    /*using data network address format*/
+};
+
+
+enum _sms_dnet_number_type_e {
+       SMS_ADDRESS_TYPE_UNKNOWN        = 0x00,
+       SMS_ADDRESS_TYPE_INTERNET_PROTOCOL      = 0x01,
+       SMS_ADDRESS_TYPE_EMAIL_ADDRESS  = 0x02,
+};
+
+
+enum _sms_number_type_e {
+       SMS_NUMBER_TYPE_UNKNOWN = 0x00,
+       SMS_NUMBER_TYPE_INTERNATIONAL   = 0x01,
+       SMS_NUMBER_TYPE_NATIONAL        = 0x02,
+       SMS_NUMBER_TYPE_NETWORK_SPECIFIC        = 0x03,
+       SMS_NUMBER_TYPE_SUBSCRIBER      = 0x04,
+       SMS_NUMBER_TYPE_RESERVED_5      = 0x05,
+       SMS_NUMBER_TYPE_ABBREVIATED     = 0x06,
+       SMS_NUMBER_TYPE_RESERVED_7      = 0x07,
+/*
+ * TODO : check this type is valid or not
+ *     SMS_NUMBER_TYPE_IP      = 0x11,
+ *     SMS_NUMBER_TYPE_EMAILADDR       = 0x12,
+ */
+};
+
+
+enum _sms_number_plan_e {
+       SMS_NPI_UNKNOWN = 0,
+       SMS_NPI_ISDN    = 1,
+       SMS_NPI_DATA    = 3,
+       SMS_NPI_TELEX   = 4,
+       SMS_NPI_PRIVATE = 9,
+       SMS_NPI_RESERVED        = 15,
+};
+
+
+typedef struct _sms_trans_addr_s
+{
+       sms_digit_mode_t        digit_mode;
+       sms_number_mode_t       number_mode;
+       sms_number_type_t       number_type;
+       sms_number_plan_t       number_plan;
+       unsigned int            addr_len;
+       char                            szData[SMS_TRANS_ADDRESS_MAX_LEN + 1];
+}sms_trans_addr_s;
+
+
+typedef struct _sms_trans_sub_addr_s
+{
+       sms_trans_sub_addr_type_t       type;
+       bool                                            odd;
+       unsigned int                            addr_len;
+       char                                            szData[SMS_TRANS_ADDRESS_MAX_LEN + 1];
+}sms_trans_sub_addr_s;
+
+
+typedef struct _sms_trans_cause_code_s
+{
+       sms_trans_reply_seq_t                   reply_seq;
+       sms_trans_err_class_t                   error_class;
+       sms_trans_cause_code_t                  cause_code;
+}sms_trans_cause_code_s;
+
+
+typedef struct _sms_trans_p2p_msg_s
+{
+       sms_trans_telesvc_id_t                  telesvc_id;
+       sms_trans_svc_ctg_t                             svc_ctg;
+       sms_trans_addr_s                                address;
+       sms_trans_sub_addr_s                    sub_address;
+       sms_trans_reply_seq_t                   reply_seq;
+       sms_telesvc_msg_s                               telesvc_msg;
+}sms_trans_p2p_msg_s;
+
+
+typedef struct _sms_trans_broadcast_msg_s
+{
+       sms_trans_svc_ctg_t                             svc_ctg;
+       sms_telesvc_msg_s                               telesvc_msg;
+}sms_trans_broadcast_msg_s;
+
+
+typedef struct _sms_trans_ack_msg_s
+{
+       sms_trans_addr_s                                address;
+       sms_trans_sub_addr_s                    sub_address;
+       sms_trans_cause_code_s                  cause_code;
+}sms_trans_ack_msg_s;
+
+
+typedef struct _sms_trans_msg_s
+{
+       sms_trans_msg_type_t            type;
+       union {
+               sms_trans_p2p_msg_s                     p2p_msg;
+               sms_trans_broadcast_msg_s       cb_msg;
+               sms_trans_ack_msg_s                     ack_msg;
+       }data;
+}sms_trans_msg_s;
+
+
+#endif //SMS_CDMA_PLUGIN_TYPES_H
+
diff --git a/plugin/sms_cdma_plugin/include/SmsCdmaPluginUAManager.h b/plugin/sms_cdma_plugin/include/SmsCdmaPluginUAManager.h
new file mode 100755 (executable)
index 0000000..e4de518
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SMS_CDMA_PLUGIN_UA_MANAGER_H
+#define SMS_CDMA_PLUGIN_UA_MANAGER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgMutex.h"
+#include "MsgQueue.h"
+#include "MsgThread.h"
+#include "SmsCdmaPluginTypes.h"
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginUAManager : public MsgThread
+{
+public:
+       static SmsPluginUAManager* instance();
+
+       //virtual void start();
+
+       void addReqEntity(sms_request_info_s *request);
+
+private:
+       SmsPluginUAManager();
+       ~SmsPluginUAManager();
+       void lock()     { mx.lock(); };
+       void unlock()   { mx.unlock(); };
+       void wait()     { cv.wait(mx.pMutex()); };
+       void signal()   { cv.signal(); };
+
+       virtual void run();
+
+       static SmsPluginUAManager* pInstance;
+
+       bool bRunning;
+
+       MsgSimpleQ <sms_request_info_s> smsTranQ;
+
+       Mutex mx;
+       CndVar cv;
+};
+
+#endif //SMS_CDMA_PLUGIN_UA_MANAGER_H
+
diff --git a/plugin/sms_cdma_plugin/include/SmsCdmaPluginWapPushHandler.h b/plugin/sms_cdma_plugin/include/SmsCdmaPluginWapPushHandler.h
new file mode 100755 (executable)
index 0000000..dea5882
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+* Copyright 2012-2013  Samsung Electronics Co., Ltd
+*
+* Licensed under the Flora License, Version 1.1 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*    http://floralicense.org/license/
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#ifndef SMS_CDMA_PLUGIN_WAPPUSH_HANDLER_H
+#define SMS_CDMA_PLUGIN_WAPPUSH_HANDLER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <wbxml/wbxml.h>
+#include <libxml/parser.h>
+
+
+#include "SmsCdmaPluginTypes.h"
+
+
+/*==================================================================================================
+                                         DEFINES
+==================================================================================================*/
+#define WSP_STANDARD_STR_LEN_MAX        255
+#define LENGTH_QUOTE  0x1F
+#define        NO_VALUE                                                0x00
+
+#define WSP_CODE_BUFFER_LEFT_LEN_MAX   1024
+#define WSP_CODE_BUFFER_RIGHT_LEN_MAX  2048
+
+#define  AcStrlen(x) ((x==NULL)?0:strlen(x))
+#define MIN(a,b)  (((a)  <  (b)) ? (a)  :  (b))
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginWapPushHandler
+{
+public:
+       static SmsPluginWapPushHandler* instance();
+
+       //void registerPushCallback();
+       bool IsWapPushMsg(unsigned short dstport);
+
+       void copyDeliverData(sms_trans_addr_s *pAddr);
+       void handleWapPushMsg(const char *pUserData, int DataSize);
+       void handleWapPushCallback(char* pPushHeader, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen, char* pWspBody, int WspBodyLen);
+
+private:
+       SmsPluginWapPushHandler();
+       virtual ~SmsPluginWapPushHandler();
+
+       static SmsPluginWapPushHandler* pInstance;
+
+       sms_wap_app_code_t getAppCode(const char *pPushHeader);
+
+       void handleMMSNotification(const char *pPushBody, int PushBodyLen);
+       void handleSIMessage(char* pPushBody, int PushBodyLen, bool isText);
+       void handleSLMessage(char* pPushBody, int PushBodyLen, bool isText);
+       void handleCOMessage(char* pPushBody, int PushBodyLen, bool isText);
+       void handleDrmVer1(char* pPushBody, int PushBodyLen);
+       void getXmlDoc(const char* pPushBody, const int PushBodyLen, xmlDocPtr *pXmlDoc, const bool isText);
+       void createMsgInfo(MSG_MESSAGE_INFO_S* pMsgInfo);
+       unsigned long convertXmlCharToSec(char* pDate);
+       msg_push_action_t convertSIActionStrToEnum(char* pAction);
+       msg_push_action_t convertSLActionStrToEnum(char* pAction);
+
+       unsigned long wspRetriveUintvarDecode( unsigned char* sourceData, unsigned long* currentPointer );
+       unsigned long wspDecodeUintvar(unsigned long length, unsigned char* userVar );
+       void wspDecodeHeader( unsigned char* sEncodedHeader, unsigned long encodedHeaderLen, unsigned long contentsLength, bool fContentType, char** pHeader);
+       unsigned long wspHeaderDecodeInteger( unsigned char* data );
+       void wspHeaderDecodeQValue( unsigned long length, unsigned char* data, char** pDecodedString);
+       unsigned long wspHeaderDecodeIntegerByLength(unsigned char* data, unsigned long length );
+       char* wspExtendedDecodeType(char contentType  );
+       void wspHeaderDecodeParameter( unsigned char* data, unsigned long length, char** pParam);
+       void wspHeaderDecodeCharset( unsigned long length, unsigned char* data, char**pDecodedString);
+       void wspHeaderDecodeVersion( unsigned long length, unsigned char* data, char** pDecodedString );
+       void wspHeaderDecodeDateValue( unsigned long length, unsigned char* data, char** pDecodedString );
+       void wspHeaderCopyDecodedString( unsigned char* szDecodedString, unsigned long* currentLen, char** pTemper );
+       void wspHeaderDecodeAuth(unsigned long fieldValueLen, unsigned char* fieldValue, char** pDecodedString );
+       void wspHeaderDecodeChallenge(unsigned long fieldValueLen, unsigned char* fieldValue, char** pDecodedString );
+       void wspHeaderDecodeCacheControl(unsigned char* fieldValue, unsigned long fieldValueLen, char** pCacheString);
+
+
+       sms_trans_addr_s        tmpAddress;
+//     SMS_TIMESTAMP_S tmpTimeStamp;
+};
+
+#endif //SmsPluginWapPushHandler
+
index 468b4e8..cb86b86 100755 (executable)
@@ -8,14 +8,13 @@ IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
 ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
 MESSAGE("Build type: ${CMAKE_BUILD_TYPE}")
 
-SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
+SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
 
 ##########################################################
 # Define SMS Plugin
 ##########################################################
 
 SET(SMS-PLUGIN-SRCS
-       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginTextConvert.cpp
        ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginUDCodec.cpp
        ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginParamCodec.cpp
        ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginTpduCodec.cpp
@@ -31,17 +30,19 @@ SET(SMS-PLUGIN-SRCS
        ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginUAManager.cpp
        ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginCallback.cpp
        ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginMain.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginDSHandler.cpp
 )
 
 INCLUDE_DIRECTORIES(
     ${CMAKE_SOURCE_DIR}/include/mapi
        ${CMAKE_SOURCE_DIR}/include/common
        ${CMAKE_SOURCE_DIR}/include/utils
+       ${CMAKE_SOURCE_DIR}/include/externals
        ${CMAKE_CURRENT_SOURCE_DIR}/include
 )
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(sms_plugin_pkgs REQUIRED glib-2.0 tapi libxml-2.0 libwbxml2 drm-client dlog vconf)
+pkg_check_modules(sms_plugin_pkgs REQUIRED glib-2.0 tapi libxml-2.0 libwbxml2 dlog vconf gio-2.0 db-util capi-telephony)
 
 FOREACH(flag ${sms_plugin_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
@@ -54,7 +55,7 @@ ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
 SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
 
 ADD_LIBRARY(${SMS-PLUGIN-LIB} SHARED ${SMS-PLUGIN-SRCS})
-TARGET_LINK_LIBRARIES(${SMS-PLUGIN-LIB} ${sms_plugin_pkgs_LDFLAGS} ${UTILS-LIB})
+TARGET_LINK_LIBRARIES(${SMS-PLUGIN-LIB} ${sms_plugin_pkgs_LDFLAGS} ${UTILS-LIB} ${EXTERNALS-LIB})
 
 INSTALL(TARGETS ${SMS-PLUGIN-LIB} LIBRARY DESTINATION lib)
 
index 337a4e7..5fc318b 100755 (executable)
@@ -1,23 +1,24 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <glib.h>
 #include <pthread.h>
 
 #include "MsgDebug.h"
+#include "MsgCppTypes.h"
 #include "MsgException.h"
 #include "SmsPluginEventHandler.h"
 #include "SmsPluginCbMsgHandler.h"
 #include "SmsPluginSatHandler.h"
 #include "SmsPluginParamCodec.h"
 #include "SmsPluginTpduCodec.h"
+#include "SmsPluginTransport.h"
 #include "SmsPluginSimMsg.h"
 #include "SmsPluginSetting.h"
 #include "MsgGconfWrapper.h"
 #include "SmsPluginCallback.h"
+#include "SmsPluginDSHandler.h"
+
+extern bool isMemAvailable;
 
-extern struct tapi_handle *pTapiHandle;
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
-void TapiEventDeviceReady(TapiHandle *handle, int result, void *data, void *user_data)
+void TapiEventDeviceReady(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
 {
-       MSG_DEBUG("TapiEventDeviceReady is called. : result = [%d]", result);
+       MSG_DEBUG("TapiEventDeviceReady is called. : noti_id = [%d]", noti_id);
 
        try
        {
                // Call Event Handler
-               SmsPluginEventHandler::instance()->setDeviceStatus();
+               SmsPluginEventHandler::instance()->setDeviceStatus(handle);
        }
        catch (MsgException& e)
        {
@@ -53,26 +57,100 @@ void TapiEventDeviceReady(TapiHandle *handle, int result, void *data, void *user
 
 }
 
+SMS_NETWORK_STATUS_T convertTapiRespToSmsPlugin(int result)
+{
+       SMS_NETWORK_STATUS_T sentStatus;
+
+       /* Convert TAPI status -> SMS network status */
+       switch ((TelSmsResponse_t)result) {
+               case TAPI_NETTEXT_SENDSMS_SUCCESS :
+                       sentStatus = SMS_NETWORK_SEND_SUCCESS;
+                       break;
+
+               case TAPI_NETTEXT_INVALID_MANDATORY_INFO :
+                       sentStatus = SMS_NETWORK_SEND_FAIL_MANDATORY_INFO_MISSING;
+                       break;
+
+               case TAPI_NETTEXT_DESTINAITION_OUTOFSERVICE :
+               case TAPI_NETTEXT_TEMPORARY_FAILURE :
+               case TAPI_NETTEXT_CONGESTION :
+               case TAPI_NETTEXT_RESOURCES_UNAVAILABLE :
+               case TAPI_NETTEXT_MESSAGE_NOT_COMPAT_PROTOCOL :
+               case TAPI_NETTEXT_NETWORK_OUTOFORDER:
+                       sentStatus = SMS_NETWORK_SEND_FAIL_TEMPORARY;
+                       break;
+
+               case TAPI_NETTEXT_MESSAGE_TRANSFER_REJECTED :
+                       sentStatus = SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_NOT_ALLOWED;
+                       break;
+
+               case TAPI_NETTEXT_DEST_ADDRESS_FDN_RESTRICTED :
+               case TAPI_NETTEXT_SCADDRESS_FDN_RESTRICTED :
+                       sentStatus = SMS_NETWORK_SEND_FAIL_FDN_RESTRICED;
+                       break;
+               case TAPI_NETTEXT_ROUTING_NOT_AVAILABLE :
+                       sentStatus = SMS_NETWORK_SEND_FAIL_NO_ROUTING;
+                       break;
+               default :
+                       sentStatus = SMS_NETWORK_SEND_FAIL;
+                       break;
+       }
+       return sentStatus;
+}
 
 void TapiEventSentStatus(TapiHandle *handle, int result, void *data, void *user_data)
 {
-       MSG_DEBUG("TapiEventSentStatus is called. : result = [%d]", result);
+       MSG_DEBUG("TapiEventSentStatus is called. : result = [0x%x]", result);
+
+       SMS_NETWORK_STATUS_T sentStatus;
+
+       TelSatMoSmCtrlIndData_t *moCtrlStatus = (TelSatMoSmCtrlIndData_t *)user_data;
 
+       sentStatus = convertTapiRespToSmsPlugin(result);
+
+       if (moCtrlStatus && sentStatus == SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_NOT_ALLOWED) {
+               if (moCtrlStatus->moSmsCtrlResult == TAPI_SAT_CALL_CTRL_R_ALLOWED_WITH_MOD)
+                       sentStatus = SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_WITH_MOD;
+       }
+
+       if (result != TAPI_NETTEXT_SENDSMS_SUCCESS)
+               MSG_INFO("sentStatus:[%d], tapi_result:[0x%x]", sentStatus, result);
+
+       MSG_DEBUG("SMS Network Status = [%d]", sentStatus);
+
+       /* only temporary errors should be returned without calling handleSentStatus() in order to resend sms  */
+       if (sentStatus == SMS_NETWORK_SEND_FAIL_TEMPORARY ||
+                       sentStatus == SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_WITH_MOD) {
+               SmsPluginTransport::instance()->setNetStatus(sentStatus);
+               return;
+       }
+
+       if (sentStatus == SMS_NETWORK_SEND_FAIL) {
+               int svc_type;
+               tel_get_property_int(handle, TAPI_PROP_NETWORK_SERVICE_TYPE, &svc_type);
+               if (svc_type < TAPI_NETWORK_SERVICE_TYPE_2G) {
+                       sentStatus = SMS_NETWORK_SEND_PENDING;
+               }
+       }
+
+       /* Convert SMS status -> Messaging network status */
        msg_network_status_t netStatus;
 
-       // Convert TAPI status -> Messaging status
-       if ((TelSmsResponse_t)result == TAPI_NETTEXT_SENDSMS_SUCCESS)
+       if (sentStatus == SMS_NETWORK_SEND_SUCCESS) {
                netStatus = MSG_NETWORK_SEND_SUCCESS;
-       else
+       } else if (sentStatus == SMS_NETWORK_SENDING) {
+               netStatus = MSG_NETWORK_SENDING;
+       } else if (sentStatus == SMS_NETWORK_SEND_PENDING) {
+               netStatus = MSG_NETWORK_SEND_PENDING;
+       } else {
                netStatus = MSG_NETWORK_SEND_FAIL;
+       }
 
        try
        {
-               // Call Event Handler
                SmsPluginEventHandler::instance()->handleSentStatus(netStatus);
 
-               // Call SAT Handler
-               SmsPluginSatHandler::instance()->ctrlSms(netStatus);
+               SmsPluginTransport::instance()->setNetStatus(sentStatus);
        }
        catch (MsgException& e)
        {
@@ -82,19 +160,52 @@ void TapiEventSentStatus(TapiHandle *handle, int result, void *data, void *user_
 
 }
 
+void TapiEventSatSmsSentStatus(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSatSmsSentStatus is called. : result = [%d]", result);
+
+       SMS_NETWORK_STATUS_T sentStatus;
+
+       sentStatus = convertTapiRespToSmsPlugin(result);
+
+       MSG_DEBUG("SMS Network Status = [%d]", sentStatus);
+
+       if (sentStatus == SMS_NETWORK_SEND_FAIL && result != TAPI_NETTEXT_DEVICE_FAILURE)
+       {
+               int svc_type;
+               tel_get_property_int(handle, TAPI_PROP_NETWORK_SERVICE_TYPE, &svc_type);
+               if (svc_type < TAPI_NETWORK_SERVICE_TYPE_2G){
+                       sentStatus = SMS_NETWORK_SEND_PENDING;
+               }
+       }
+
+       try
+       {
+               SmsPluginSatHandler::instance()->ctrlSms(handle, sentStatus);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+}
 
 void TapiEventMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
 {
-       MSG_DEBUG("TapiEventMsgIncoming is called. noti_id [%s]", noti_id);
+       MSG_SEC_DEBUG("TapiEventMsgIncoming is called. noti_id [%s]", noti_id);
 
        if (data == NULL) {
                MSG_DEBUG("Error. evt->pData is NULL.");
                return;
        }
-
+#if 0
+       SmsPluginCbMsgHandler::instance()->handleCbMsg(handle, NULL);
+       return;
+#endif
        TelSmsDatapackageInfo_t* pDataPackage = (TelSmsDatapackageInfo_t*)data;
 
        SMS_TPDU_S tpdu;
+       memset(&tpdu, 0x00, sizeof(SMS_TPDU_S));
 
        // Decode Incoming Message
        SmsPluginTpduCodec::decodeTpdu(pDataPackage->szData, pDataPackage->MsgLength, &tpdu);
@@ -112,7 +223,8 @@ void TapiEventMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, v
                MSG_DEBUG("tpdu.data.deliver.dcs.msgClass : %d", tpdu.data.deliver.dcs.msgClass);
                MSG_DEBUG("tpdu.data.deliver.dcs.codingScheme : %d", tpdu.data.deliver.dcs.codingScheme);
                MSG_DEBUG("tpdu.data.deliver.dcs.codingGroup : %d", tpdu.data.deliver.dcs.codingGroup);
-               MSG_DEBUG("tpdu.data.deliver.originAddress.address : %s", tpdu.data.deliver.originAddress.address);
+               MSG_DEBUG("tpdu.data.deliver.dcs.bIndActive : %d", tpdu.data.deliver.dcs.bIndActive);
+               MSG_SEC_DEBUG("tpdu.data.deliver.originAddress.address : %s", tpdu.data.deliver.originAddress.address);
                MSG_DEBUG("tpdu.data.deliver.timeStamp.time : %d/%d/%d %d:%d:%d ", tpdu.data.deliver.timeStamp.time.absolute.year, tpdu.data.deliver.timeStamp.time.absolute.month, tpdu.data.deliver.timeStamp.time.absolute.day,
                        tpdu.data.deliver.timeStamp.time.absolute.hour, tpdu.data.deliver.timeStamp.time.absolute.minute, tpdu.data.deliver.timeStamp.time.absolute.second);
                MSG_DEBUG("tpdu.data.deliver.userData.headerCnt : %d", tpdu.data.deliver.userData.headerCnt);
@@ -133,7 +245,7 @@ void TapiEventMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, v
                MSG_DEBUG("tpdu.data.statusRep.dcs.msgClass : %d", tpdu.data.statusRep.dcs.msgClass);
                MSG_DEBUG("tpdu.data.statusRep.dcs.codingScheme : %d", tpdu.data.statusRep.dcs.codingScheme);
                MSG_DEBUG("tpdu.data.statusRep.dcs.codingGroup : %d", tpdu.data.statusRep.dcs.codingGroup);
-               MSG_DEBUG("tpdu.data.statusRep.recipAddress.address : %s", tpdu.data.statusRep.recipAddress.address);
+               MSG_SEC_DEBUG("tpdu.data.statusRep.recipAddress.address : %s", tpdu.data.statusRep.recipAddress.address);
                MSG_DEBUG("tpdu.data.statusRep.timeStamp.time : %d/%d/%d %d:%d:%d ", tpdu.data.statusRep.timeStamp.time.absolute.year, tpdu.data.statusRep.timeStamp.time.absolute.month, tpdu.data.statusRep.timeStamp.time.absolute.day,
                        tpdu.data.statusRep.timeStamp.time.absolute.hour, tpdu.data.statusRep.timeStamp.time.absolute.minute, tpdu.data.statusRep.timeStamp.time.absolute.second);
                MSG_DEBUG("tpdu.data.statusRep.dischargeTime.time : %d/%d/%d %d:%d:%d ", tpdu.data.statusRep.dischargeTime.time.absolute.year, tpdu.data.statusRep.dischargeTime.time.absolute.month, tpdu.data.statusRep.dischargeTime.time.absolute.day,
@@ -148,19 +260,24 @@ void TapiEventMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, v
        {
                if (tpdu.tpduType == SMS_TPDU_DELIVER)
                {
+                       if (tpdu.data.deliver.dcs.msgClass == SMS_MSG_CLASS_2) {
+                               // For GCF test, 34.2.5.3
+                               SmsPluginSimMsg::instance()->setSmsData((const char*)pDataPackage->Sca, (const char *)pDataPackage->szData, pDataPackage->MsgLength);
+                       }
+
                        if (SmsPluginConcatHandler::instance()->IsConcatMsg(&(tpdu.data.deliver.userData)) == true ||
                                SmsPluginWapPushHandler::instance()->IsWapPushMsg(&(tpdu.data.deliver.userData)) == true)
                        {
-                               SmsPluginConcatHandler::instance()->handleConcatMsg(&tpdu); // Call Concat Msg Handler
+                               SmsPluginConcatHandler::instance()->handleConcatMsg(handle, &tpdu); // Call Concat Msg Handler
                        }
                        else
                        {
-                               SmsPluginEventHandler::instance()->handleMsgIncoming(&tpdu); // Call Event Handler
+                               SmsPluginEventHandler::instance()->handleMsgIncoming(handle, &tpdu); // Call Event Handler
                        }
                }
                else if (tpdu.tpduType == SMS_TPDU_STATUS_REP)
                {
-                       SmsPluginEventHandler::instance()->handleMsgIncoming(&tpdu); // Call Event Handler
+                       SmsPluginEventHandler::instance()->handleMsgIncoming(handle, &tpdu); // Call Event Handler
                }
        }
        catch (MsgException& e)
@@ -174,7 +291,7 @@ void TapiEventMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, v
 
 void TapiEventCbMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
 {
-       MSG_DEBUG("TapiEventCbMsgIncoming is called. noti_id [%s]", noti_id);
+       MSG_SEC_DEBUG("TapiEventCbMsgIncoming is called. noti_id [%s]", noti_id);
 
        if (data == NULL) {
                MSG_DEBUG("Error. evt->pData is NULL.");
@@ -185,7 +302,7 @@ void TapiEventCbMsgIncoming(TapiHandle *handle, const char *noti_id, void *data,
 
        try
        {
-               SmsPluginCbMsgHandler::instance()->handleCbMsg(pCbMsg);
+               SmsPluginCbMsgHandler::instance()->handleCbMsg(handle, pCbMsg);
        }
        catch (MsgException& e)
        {
@@ -196,6 +313,29 @@ void TapiEventCbMsgIncoming(TapiHandle *handle, const char *noti_id, void *data,
 }
 
 
+void TapiEventEtwsMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
+{
+       MSG_SEC_DEBUG("TapiEventEtwsMsgIncoming is called. noti_id [%s]", noti_id);
+
+       if (data == NULL) {
+               MSG_DEBUG("Error. evt->pData is NULL.");
+               return;
+       }
+
+       TelSmsEtwsMsg_t *pEtwsMsg = (TelSmsEtwsMsg_t*)data;
+
+       try
+       {
+               SmsPluginCbMsgHandler::instance()->handleEtwsMsg(handle, pEtwsMsg);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+}
+
+
 void TapiEventDeliveryReportCNF(TapiHandle *handle, int result, void *data, void *user_data)
 {
        MSG_DEBUG("TapiEventDeliveryReportCNF is called. : result = [%d]", result);
@@ -213,11 +353,11 @@ void TapiEventGetSimMsgCnt(TapiHandle *handle, int result, void *data, void *use
                MSG_DEBUG("Error. data is NULL.");
                MSG_SIM_COUNT_S simCnt;
                memset(&simCnt, 0x00, sizeof(MSG_SIM_COUNT_S));
-               SmsPluginSimMsg::instance()->setSimMsgCntEvent(&simCnt);
+               SmsPluginSimMsg::instance()->setSimMsgCntEvent(handle, &simCnt);
                return;
        }
 
-       SmsPluginSimMsg::instance()->setSimMsgCntEvent((MSG_SIM_COUNT_S *)data);
+       SmsPluginSimMsg::instance()->setSimMsgCntEvent(handle, (MSG_SIM_COUNT_S *)data);
 
 }
 
@@ -230,12 +370,16 @@ void TapiEventGetSimMsg(TapiHandle *handle, int result, void *data, void *user_d
        {
                MSG_DEBUG("Error!! pEvent->Status [%d]", result);
 
-               SmsPluginSimMsg::instance()->setSimMsgEvent(NULL, false);
+               SmsPluginSimMsg::instance()->setSimMsgEvent(handle, NULL, false);
 
                return;
        }
 
+
        TelSmsData_t* pSmsTpdu = (TelSmsData_t*)data;
+       //SmsPluginSimMsg::instance()->deleteSimMessage((msg_sim_id_t)pSmsTpdu->SimIndex);
+
+       int *simIdList = (int *)user_data;
 
        // Reading TelSmsData_t
        MSG_DEBUG ("sim index %d", pSmsTpdu->SimIndex);
@@ -246,7 +390,7 @@ void TapiEventGetSimMsg(TapiHandle *handle, int result, void *data, void *user_d
        {
                MSG_DEBUG ("WARNING: tpdu_len > MAX_SMS_TPDU_SIZE [%d] bytes. setting to 0.", pSmsTpdu->SmsData.MsgLength);
 
-               SmsPluginSimMsg::instance()->setSimMsgEvent(NULL, false);
+               SmsPluginSimMsg::instance()->setSimMsgEvent(handle, NULL, false);
 
                return;
        }
@@ -268,21 +412,37 @@ void TapiEventGetSimMsg(TapiHandle *handle, int result, void *data, void *user_d
 
        if (tpdu.tpduType == SMS_TPDU_DELIVER)
        {
-               MSG_DEBUG("headerCnt [%d]", tpdu.data.deliver.userData.headerCnt);
+               if (tpdu.data.deliver.dcs.codingScheme == SMS_CHARSET_8BIT && tpdu.data.deliver.pid == 0x11) {
+                       MSG_DEBUG("Unsupported message!!");
+                       SmsPluginSimMsg::instance()->setSimMsgEvent(handle, NULL, false);
+                       return;
+               }
 
+               MSG_DEBUG("headerCnt [%d]", tpdu.data.deliver.userData.headerCnt);
                for (int i = 0; i < tpdu.data.deliver.userData.headerCnt; i++)
                {
                        // Handler Concatenated Message
                        if (tpdu.data.deliver.userData.header[i].udhType == SMS_UDH_CONCAT_8BIT ||
-                               tpdu.data.deliver.userData.header[i].udhType == SMS_UDH_CONCAT_16BIT)
-                       {
-                               SmsPluginSimMsg::instance()->setSimMsgEvent(NULL, false);
+                               tpdu.data.deliver.userData.header[i].udhType == SMS_UDH_CONCAT_16BIT) {
+                               SmsPluginConcatHandler::instance()->handleSimConcatMsg(handle, &tpdu, pSmsTpdu->SimIndex, bRead, simIdList);
+                               //SmsPluginSimMsg::instance()->setSimMsgEvent(NULL, false);
+                               return;
+                       }
+
+                       if (tpdu.data.deliver.userData.header[i].udhType == SMS_UDH_SPECIAL_SMS) {
+                               MSG_DEBUG("Unsupported Special SMS!!");
+                               SmsPluginSimMsg::instance()->setSimMsgEvent(handle, NULL, false);
                                return;
                        }
                }
        }
        else if (tpdu.tpduType == SMS_TPDU_SUBMIT)
        {
+               if (tpdu.data.submit.dcs.codingScheme == SMS_CHARSET_8BIT && tpdu.data.submit.pid == 0x11) {
+                       MSG_DEBUG("Unsupported message!!");
+                       SmsPluginSimMsg::instance()->setSimMsgEvent(handle, NULL, false);
+                       return;
+               }
                MSG_DEBUG("headerCnt [%d]", tpdu.data.submit.userData.headerCnt);
 
                for (int i = 0; i < tpdu.data.submit.userData.headerCnt; i++)
@@ -291,7 +451,7 @@ void TapiEventGetSimMsg(TapiHandle *handle, int result, void *data, void *user_d
                        if (tpdu.data.submit.userData.header[i].udhType == SMS_UDH_CONCAT_8BIT ||
                                tpdu.data.submit.userData.header[i].udhType == SMS_UDH_CONCAT_16BIT)
                        {
-                               SmsPluginSimMsg::instance()->setSimMsgEvent(NULL, false);
+                               SmsPluginConcatHandler::instance()->handleSimConcatMsg(handle, &tpdu, pSmsTpdu->SimIndex, bRead, simIdList);
                                return;
                        }
                }
@@ -301,23 +461,64 @@ void TapiEventGetSimMsg(TapiHandle *handle, int result, void *data, void *user_d
        MSG_MESSAGE_INFO_S msgInfo;
        memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
 
+       // set storage id
+       msgInfo.storageId = MSG_STORAGE_SIM;
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
        SmsPluginEventHandler::instance()->convertTpduToMsginfo(&tpdu, &msgInfo);
 
-       // set Sim Message ID
-       msgInfo.msgId = pSmsTpdu->SimIndex;
+       msgInfo.sim_idx = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+       if (tpdu.tpduType == SMS_TPDU_DELIVER && tpdu.data.deliver.dcs.bMWI == true) {
+               if (tpdu.data.deliver.pid == 0x20 && tpdu.data.deliver.originAddress.ton == SMS_TON_ALPHANUMERIC) {
+                       char keyName[MAX_VCONFKEY_NAME_LEN];
+                       char *voiceNumber = NULL;
+                       char *voiceAlphaId = NULL;
+
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_NUMBER, msgInfo.sim_idx);
+                       voiceNumber = MsgSettingGetString(keyName);
+
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_ALPHA_ID, msgInfo.sim_idx);
+                       voiceAlphaId = MsgSettingGetString(keyName);
+
+                       memset(msgInfo.addressList[0].addressVal, 0x00, sizeof(msgInfo.addressList[0].addressVal));
+                       memset(msgInfo.addressList[0].displayName, 0x00, sizeof(msgInfo.addressList[0].displayName));
+
+                       if (voiceNumber) {
+                               snprintf(msgInfo.addressList[0].addressVal, sizeof(msgInfo.addressList[0].addressVal), "%s", voiceNumber);
+                               free(voiceNumber);
+                               voiceNumber = NULL;
+                       }
+
+                       if (voiceAlphaId) {
+                               snprintf(msgInfo.addressList[0].displayName, sizeof(msgInfo.addressList[0].displayName), "%s", voiceAlphaId);
+                               free(voiceAlphaId);
+                               voiceAlphaId = NULL;
+                       }
+
+                       memset(msgInfo.msgText, 0x00, sizeof(msgInfo.msgText));
+                       snprintf(msgInfo.msgText, sizeof(msgInfo.msgText), "Voice message");
+               }
+       }
+       else if (tpdu.tpduType == SMS_TPDU_SUBMIT) {
+               msgInfo.displayTime =  time(NULL);
+       }
 
        // set read status
        msgInfo.bRead = bRead;
 
-       // set storage id
-       msgInfo.storageId = MSG_STORAGE_SIM;
-
+       simIdList[0] = pSmsTpdu->SimIndex + 1;
        /// Print MSG_MESSAGE_INFO_S
        MSG_DEBUG("############# Convert  tpdu values to Message Info values ####################");
        MSG_DEBUG("msgInfo.msgId : %d", msgInfo.msgId);
        MSG_DEBUG("msgInfo.nAddressCnt : %d", msgInfo.nAddressCnt);
        MSG_DEBUG("msgInfo.addressList[0].addressType : %d", msgInfo.addressList[0].addressType);
-       MSG_DEBUG("msgInfo.addressList[0].addressVal : %s", msgInfo.addressList[0].addressVal);
+       MSG_SEC_DEBUG("msgInfo.addressList[0].addressVal : %s", msgInfo.addressList[0].addressVal);
+       MSG_SEC_DEBUG("msgInfo.addressList[0].displayName : %s", msgInfo.addressList[0].displayName);
        MSG_DEBUG("msgInfo.priority : %d", msgInfo.priority);
        MSG_DEBUG("msgInfo.bProtected : %d", msgInfo.bProtected);
        MSG_DEBUG("msgInfo.bRead : %d", msgInfo.bRead);
@@ -326,15 +527,17 @@ void TapiEventGetSimMsg(TapiHandle *handle, int result, void *data, void *user_d
        MSG_DEBUG("msgInfo.msgType.mainType : %d", msgInfo.msgType.mainType);
        MSG_DEBUG("msgInfo.msgType.subType : %d", msgInfo.msgType.subType);
        MSG_DEBUG("msgInfo.msgType.classType : %d", msgInfo.msgType.classType);
-       MSG_DEBUG("msgInfo.displayTime : %s", ctime(&msgInfo.displayTime));
+       MSG_DEBUG("msgInfo.displayTime : %d", msgInfo.displayTime);
        MSG_DEBUG("msgInfo.dataSize : %d", msgInfo.dataSize);
        if (msgInfo.bTextSms == true)
-               MSG_DEBUG("msgInfo.msgText : %s", msgInfo.msgText);
+               MSG_SEC_DEBUG("msgInfo.msgText : %s", msgInfo.msgText);
        else
-       MSG_DEBUG("msgInfo.msgData : %s", msgInfo.msgData);
+               MSG_SEC_DEBUG("msgInfo.msgData : %s", msgInfo.msgData);
+       MSG_DEBUG("msgInfo.sim_idx : %d", msgInfo.sim_idx);
        MSG_DEBUG("###############################################################");
 
-       SmsPluginSimMsg::instance()->setSimMsgEvent(&msgInfo, true); // Call Event Handler
+       SmsPluginSimMsg::instance()->setSimMsgEvent(handle, &msgInfo, true); // Call Event Handler
+
 
 }
 
@@ -343,19 +546,51 @@ void TapiEventSaveSimMsg(TapiHandle *handle, int result, void *data, void *user_
 {
        MSG_DEBUG("TapiEventSaveSimMsg is called. result [%d]", result);
 
-       if (result != TAPI_API_SUCCESS || data == NULL)
-       {
-               MSG_DEBUG("Error. data is NULL.");
-               SmsPluginSimMsg::instance()->setSimEvent((msg_sim_id_t)0, false);
-               return;
+       int simId = -1;
+
+       if (data != NULL)
+               simId = *((int*)data);
+       else
+               MSG_DEBUG("Data(SIM Msg ID) is NULL");
+
+       SmsPluginSimMsg::instance()->setSaveSimMsgEvent(handle, simId, result);
+}
+
+
+void TapiEventSaveClass2Msg(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSaveClass2Msg is called. result [%d]", result);
+
+       int simId = -1;
+
+       if (data != NULL) {
+               simId = *((int*)data);
+               MSG_DEBUG("SIM Msg ID : %d", simId);
+       } else {
+               MSG_DEBUG("Data(SIM Msg ID) is NULL");
        }
 
-       int simId = *((int*)data);
+       MSG_MESSAGE_INFO_S *pMsgInfo = (MSG_MESSAGE_INFO_S *)user_data;
 
-       MSG_DEBUG("sim ID : [%d], status : [%d]", simId, (TelSmsCause_t)result);
+       SmsPluginSimMsg::instance()->setSaveClass2MsgEvent(handle, simId, result, pMsgInfo);
 
-       SmsPluginSimMsg::instance()->setSimEvent((msg_sim_id_t)simId, true);
+       if(result == TAPI_NETTEXT_SENDSMS_SUCCESS)
+       {
+               SmsPluginSimMsg::instance()->setSimEvent((msg_sim_id_t)simId, true);
+       }
+       else
+       {
+               SmsPluginSimMsg::instance()->setSimEvent((msg_sim_id_t)0, false);
+       }
 
+       if (pMsgInfo) {
+               if (pMsgInfo->addressList) {
+                       delete[] pMsgInfo->addressList;
+                       pMsgInfo->addressList = NULL;
+               }
+               free(pMsgInfo);
+               pMsgInfo = NULL;
+       }
 }
 
 
@@ -363,18 +598,16 @@ void TapiEventDeleteSimMsg(TapiHandle *handle, int result, void *data, void *use
 {
        MSG_DEBUG("TapiEventDeleteSimMsg is called. result [%d]", result);
 
-       MSG_DEBUG("status : [%d]", (TelSmsCause_t)result);
-
        if (result != TAPI_API_SUCCESS || data == NULL)
        {
                MSG_DEBUG("Error. data is NULL.");
-               SmsPluginSimMsg::instance()->setSimEvent((msg_sim_id_t)0, false);
+               SmsPluginSimMsg::instance()->setDelSimEvent(-1, false);
                return;
        }
 
        int sim_id = *((int*)data);
 
-       SmsPluginSimMsg::instance()->setSimEvent((msg_sim_id_t)sim_id, true);
+       SmsPluginSimMsg::instance()->setDelSimEvent(sim_id, true);
 
 }
 
@@ -460,7 +693,7 @@ void TapiEventGetParam(TapiHandle *handle, int result, void *data, void *user_da
        if (result != TAPI_API_SUCCESS || data == NULL)
        {
                MSG_DEBUG("Error. data is NULL.");
-               SmsPluginSetting::instance()->setParamEvent(NULL, -1, false);
+               SmsPluginSetting::instance()->setParamEvent(handle, NULL, -1, false);
                return;
        }
 
@@ -478,7 +711,7 @@ void TapiEventGetParam(TapiHandle *handle, int result, void *data, void *user_da
        {
                MSG_DEBUG("Wrong Alpha ID Length[%d]", alphaIdLen);
 
-               SmsPluginSetting::instance()->setParamEvent(NULL, -1, false);
+               SmsPluginSetting::instance()->setParamEvent(handle, NULL, -1, false);
 
                return;
        }
@@ -490,13 +723,13 @@ void TapiEventGetParam(TapiHandle *handle, int result, void *data, void *user_da
        if(addrLen > SMSC_ADDR_MAX)
        {
                MSG_DEBUG("addrLen is too long: %d", addrLen);
-               SmsPluginSetting::instance()->setParamEvent(NULL, -1, false);
+               SmsPluginSetting::instance()->setParamEvent(handle, NULL, -1, false);
                return;
        }
        else if(addrLen < 2)
        {
                MSG_DEBUG("addrLen is too short: %d", addrLen);
-               SmsPluginSetting::instance()->setParamEvent(NULL, -1, false);
+               SmsPluginSetting::instance()->setParamEvent(handle, NULL, -1, false);
                return;
        }
 
@@ -522,19 +755,25 @@ void TapiEventGetParam(TapiHandle *handle, int result, void *data, void *user_da
                memset(smscData.smscAddr.address, 0x00, SMSC_ADDR_MAX+1);
                paramCodec.decodeSMSC(smsParam->TpSvcCntrAddr.szDiallingNum, addrLen, smscData.smscAddr.ton, smscData.smscAddr.address);
 
-               MSG_DEBUG("SMSC Address : [%s]", smscData.smscAddr.address);
+               MSG_SEC_DEBUG("SMSC Address : [%s]", smscData.smscAddr.address);
 
                memset(smscData.name, 0x00, SMSC_NAME_MAX+1);
                memcpy(smscData.name, smsParam->szAlphaId, alphaIdLen);
                smscData.name[alphaIdLen] = '\0';
 
-               MSG_DEBUG("SMSC Name : [%s]", smscData.name);
+               MSG_SEC_DEBUG("SMSC Name : [%s]", smscData.name);
        }
        else
        {
                MSG_DEBUG("SMSC Address is not present");
 
-               SmsPluginSetting::instance()->setParamEvent(NULL, -1, false);
+//             smscData.smscAddr.ton = MSG_TON_UNKNOWN;
+//             smscData.smscAddr.npi = MSG_NPI_UNKNOWN;
+//
+//             memset(smscData.smscAddr.address, 0x00, SMSC_ADDR_MAX+1);
+//             memset(smscData.name, 0x00, SMSC_NAME_MAX+1);
+
+               SmsPluginSetting::instance()->setParamEvent(handle, NULL, -1, false);
 
                return;
        }
@@ -580,6 +819,20 @@ void TapiEventGetParam(TapiHandle *handle, int result, void *data, void *user_da
                MSG_DEBUG("MSG_PID_TEXT is inserted to PID");
        }
 
+#if 0
+       /*Get the DCS value*/
+       if (0x00 == (0x08 & smsParam->ParamIndicator))
+       {
+               smscList.smscData[index].dcs = smsParam->TpDataCodingScheme;
+               MSG_DEBUG("dcs : %d", smscList.smscData[index].dcs);
+       }
+       else
+       {
+               smscList.smscData[index].dcs = MSG_ENCODE_GSM7BIT;
+               MSG_DEBUG("DCS is not present");
+       }
+#endif
+
        /*Get the ValidityPeriod value*/
        if (0x00 == (0x10 & smsParam->ParamIndicator))
        {
@@ -588,26 +841,42 @@ void TapiEventGetParam(TapiHandle *handle, int result, void *data, void *user_da
        }
        else
        {
+
                smscData.valPeriod = 0;
+
                MSG_DEBUG("Validity Period is not present");
        }
 
-       SmsPluginSetting::instance()->setParamEvent(&smscData, (int)smsParam->RecordIndex, true);
+       SmsPluginSetting::instance()->setParamEvent(handle, &smscData, (int)smsParam->RecordIndex, true);
 
 }
 
 
+void TapiEventSetSmscInfo(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSetSmscInfo is called. result=[%d]", result);
+
+       if (result != TAPI_API_SUCCESS) {
+               SmsPluginSetting::instance()->setResultFromSim(false);
+       } else {
+               SmsPluginSetting::instance()->setResultFromSim(true);
+       }
+}
+
+
 void TapiEventGetCBConfig(TapiHandle *handle, int result, void *data, void *user_data)
 {
        MSG_DEBUG("TapiEventGetCBConfig is called.");
 
        MSG_CBMSG_OPT_S cbOpt = {0};
 
-       if (result != TAPI_API_SUCCESS || data == NULL)
+       int simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+       if (result != TAPI_API_SUCCESS || data == NULL || simIndex == 0)
        {
                MSG_DEBUG("Error. data is NULL.");
 
-               SmsPluginSetting::instance()->setCbConfigEvent(NULL, false);
+               SmsPluginSetting::instance()->setCbConfigEvent(handle, NULL, false);
 
                return;
        }
@@ -618,7 +887,9 @@ void TapiEventGetCBConfig(TapiHandle *handle, int result, void *data, void *user
 
        cbOpt.maxSimCnt = pCBConfig->MsgIdMaxCount;
 
-       MSG_DEBUG("Receive [%d], Max SIM Count [%d]", cbOpt.bReceive, cbOpt.maxSimCnt);
+       cbOpt.simIndex = simIndex;
+
+       MSG_DEBUG("Sim Index [%d], Receive [%d], Max SIM Count [%d]", simIndex, cbOpt.bReceive, cbOpt.maxSimCnt);
 
        cbOpt.channelData.channelCnt = pCBConfig->MsgIdRangeCount;
 
@@ -628,10 +899,6 @@ void TapiEventGetCBConfig(TapiHandle *handle, int result, void *data, void *user
                cbOpt.channelData.channelCnt = CB_CHANNEL_MAX;
        }
 
-       if (MsgSettingSetInt(CB_CHANNEL_COUNT, cbOpt.channelData.channelCnt) != MSG_SUCCESS) {
-               MSG_DEBUG("Error to set config data [%s]", CB_CHANNEL_COUNT);
-       }
-
        MSG_DEBUG("Channel Count [%d]", cbOpt.channelData.channelCnt);
 
        for (int i = 0; i < cbOpt.channelData.channelCnt; i++)
@@ -644,10 +911,210 @@ void TapiEventGetCBConfig(TapiHandle *handle, int result, void *data, void *user
                MSG_DEBUG("Channel FROM [%d], Channel TO [%d] ", cbOpt.channelData.channelInfo[i].from, cbOpt.channelData.channelInfo[i].to);
        }
 
-       SmsPluginSetting::instance()->setCbConfigEvent(&cbOpt, true);
+       SmsPluginSetting::instance()->setCbConfigEvent(handle, &cbOpt, true);
+}
+
+void TapiEventSetMailboxInfo(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSetMailboxInfo is called. result = [%d]", result);
+
+       bool bRet = true;
+       bool *bShowError = (bool*)user_data;
+
+       if (result != TAPI_SIM_ACCESS_SUCCESS && *bShowError == true)
+               bRet = false;
+
+       SmsPluginSetting::instance()->setResultFromSim(bRet);
+}
+
+void TapiEventGetMailboxInfo(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetMailboxInfo is called. result=[%d]", result);
+
+       if (result == TAPI_API_SIM_SERVICE_IS_DISABLED) {
+               MSG_INFO("result is TAPI_API_SIM_SERVICE_IS_DISABLED");
+               char keyName[MAX_VCONFKEY_NAME_LEN];
+               int sim_idx = SmsPluginDSHandler::instance()->getSimIndex(handle);
+               char *voiceNum = NULL;
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_NUMBER, sim_idx);
+               voiceNum = MsgSettingGetString(keyName);
+
+               if (voiceNum && strlen(voiceNum)) {
+                       MSG_DEBUG("Voice mailbox number exist in vconf");
+                       SmsPluginSetting::instance()->setMailboxInfoEvent(handle, NULL, true, false);
+                       free(voiceNum);
+                       voiceNum = NULL;
+                       return;
+               } else {
+                       SmsPluginSetting::instance()->setMailboxInfoEvent(handle, NULL, false, false);
+                       if (voiceNum) {
+                               free(voiceNum);
+                               voiceNum = NULL;
+                       }
+                       return;
+               }
+       } else if (result != TAPI_SIM_ACCESS_SUCCESS || data == NULL) {
+               MSG_ERR("Error. data is NULL.");
+               /*If result is not TAPI_SIM_ACCESS_SUCCESS, set bMbdnEnable to false*/
+               SmsPluginSetting::instance()->setMailboxInfoEvent(handle, NULL, false, false);
+               return;
+       }
+
+       TelSimMailboxList_t *list = (TelSimMailboxList_t *)data;
+       SMS_SIM_MAILBOX_LIST_S mbList = {0,};
+
+       if (list->count <= 0) {
+               MSG_INFO("Mailbox list is empty");
+               SmsPluginSetting::instance()->setMailboxInfoEvent(handle, NULL, false, true);
+               return;
+       }
+
+       mbList.count = list->count;
+
+       for (int i = 0; i < mbList.count; i++) {
+               mbList.list[i].b_cphs = list->list[i].b_cphs;
+               mbList.list[i].alpha_id_max_len = list->list[i].alpha_id_max_len;
+               mbList.list[i].mb_type = list->list[i].mb_type;
+               mbList.list[i].profile_num = list->list[i].profile_num;
+               mbList.list[i].rec_index = list->list[i].rec_index;
+               mbList.list[i].ton = list->list[i].ton;
+               mbList.list[i].npi = list->list[i].npi;
+               snprintf(mbList.list[i].alpha_id, sizeof(mbList.list[i].alpha_id), "%s", list->list[i].alpha_id);
+               snprintf(mbList.list[i].num, sizeof(mbList.list[i].num), "%s", list->list[i].num);
+               mbList.list[i].cc_id = list->list[i].cc_id;
+               mbList.list[i].ext1_id = list->list[i].ext1_id;
+               mbList.list[i].num_len = strlen(mbList.list[i].num);
+       }
+
+       SmsPluginSetting::instance()->setMailboxInfoEvent(handle, &mbList, true, true);
+}
+
+void TapiEventSetMwiInfo(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSetMwiInfo is called. result = [%d]", result);
+}
+
+void TapiEventGetMwiInfo(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetMwiInfo is called.");
+
+       if (result != TAPI_SIM_ACCESS_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+               SmsPluginSetting::instance()->setMwiInfoEvent(handle, NULL, false);
+
+               return;
+       }
+
+       TelSimMessageWaitingResp_t *MwiInfo = (TelSimMessageWaitingResp_t *)data;
+       SMS_SIM_MWI_INFO_S simMwiInfo = {0,};
+
+       memcpy(&simMwiInfo, MwiInfo, sizeof(SMS_SIM_MWI_INFO_S));
+
+       SmsPluginSetting::instance()->setMwiInfoEvent(handle, &simMwiInfo, true);
+}
+
+void TapiEventGetMsisdnInfo(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetMsisdnInfo is called.");
+
+       bool bRet = false;
+
+       if (result != TAPI_SIM_ACCESS_SUCCESS || data == NULL) {
+               MSG_DEBUG("Error. data is NULL.");
+               SmsPluginSetting::instance()->setResultFromSim(bRet);
+               return;
+       }
+
+       TelSimMsisdnList_t *list = (TelSimMsisdnList_t *)data;
+
+       for (int i = 0; i < list->count; i++) {
+               if (list->list[i].num[0] != '\0') {
+                       char keyName[MAX_VCONFKEY_NAME_LEN];
+                       int simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_MSISDN, simIndex);
+
+                       if (MsgSettingSetString(keyName, list->list[i].num) == MSG_SUCCESS) {
+                               MSG_SEC_DEBUG("Get MSISDN from SIM : [%s]", list->list[i].num);
+                               bRet = true;
+                       } else {
+                               MSG_DEBUG("Getting MSISDN is failed!");
+                       }
+                       break;
+               }
+       }
 
+       SmsPluginSetting::instance()->setResultFromSim(bRet);
 }
 
+void TapiEventGetSimServiceTable(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetSimServiceTable is called.");
+
+    TelSimAccessResult_t access_rt = (TelSimAccessResult_t)result;
+    TelSimServiceTable_t *svct = (TelSimServiceTable_t *)data;
+
+       bool bRet = true;
+
+       if (access_rt != TAPI_SIM_ACCESS_SUCCESS || svct == NULL)
+       {
+               MSG_ERR("Error. data is NULL and access_rt [%d] failed", access_rt);
+               SmsPluginSetting::instance()->setResultFromSim(false);
+               return;
+       }
+
+       msg_error_t err = MSG_SUCCESS;
+
+       char sstKey[128];
+       char moCtrlKey[128];
+
+       int simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+       memset(sstKey, 0x00, sizeof(sstKey));
+       snprintf(sstKey, sizeof(sstKey), "%s/%d", MSG_SIM_SERVICE_TABLE, simIndex);
+
+       memset(moCtrlKey, 0x00, sizeof(moCtrlKey));
+       snprintf(moCtrlKey, sizeof(moCtrlKey), "%s/%d", MSG_SIM_MO_CONTROL, simIndex);
+
+       if (svct->sim_type == TAPI_SIM_CARD_TYPE_GSM) {
+               if (svct->table.sst.service[TAPI_SIM_SST_SMS] == 1) {
+                       err = MsgSettingSetBool(sstKey, true);
+               } else {
+                       err = MsgSettingSetBool(sstKey, false);
+               }
+               MSG_DEBUG("Setting result = [%d]", err);
+
+               if (svct->table.sst.service[TAPI_SIM_SST_MO_SMS_CTRL_BY_SIM] == 1){
+                       err = MsgSettingSetBool(moCtrlKey, true);
+               } else {
+                       err = MsgSettingSetBool(moCtrlKey, false);
+               }
+               MSG_DEBUG("Setting result = [%d]", err);
+
+       } else if (svct->sim_type == TAPI_SIM_CARD_TYPE_USIM) {
+               if (svct->table.sst.service[TAPI_SIM_UST_SMS] == 1) {
+                       err = MsgSettingSetBool(sstKey, true);
+               } else {
+                       err = MsgSettingSetBool(sstKey, false);
+               }
+               MSG_DEBUG("Setting result = [%d]", err);
+
+               if (svct->table.sst.service[TAPI_SIM_UST_MO_SMS_CTRL] == 1){
+                       err = MsgSettingSetBool(moCtrlKey, true);
+               } else {
+                       err = MsgSettingSetBool(moCtrlKey, false);
+               }
+               MSG_DEBUG("Setting result = [%d]", err);
+
+       } else {
+               MSG_DEBUG("Unknown SIM type value");
+       }
+
+       SmsPluginSetting::instance()->setResultFromSim(bRet);
+}
 
 void TapiEventSatSmsRefresh(TapiHandle *handle, int result, void *data, void *user_data)
 {
@@ -661,7 +1128,7 @@ void TapiEventSatSmsRefresh(TapiHandle *handle, int result, void *data, void *us
 
        try
        {
-               SmsPluginSatHandler::instance()->refreshSms(data);
+               SmsPluginSatHandler::instance()->refreshSms(handle, data);
        }
        catch (MsgException& e)
        {
@@ -684,7 +1151,7 @@ void TapiEventSatSendSms(TapiHandle *handle, const char *noti_id, void *data, vo
 
        try
        {
-               SmsPluginSatHandler::instance()->sendSms(data);
+               SmsPluginSatHandler::instance()->sendSms(handle, data);
        }
        catch (MsgException& e)
        {
@@ -695,11 +1162,11 @@ void TapiEventSatSendSms(TapiHandle *handle, const char *noti_id, void *data, vo
 }
 
 
-void TapiEventSatMoSmsCtrl(TapiHandle *handle, int result, void *data, void *user_data)
+void TapiEventSatMoSmsCtrl(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
 {
        MSG_DEBUG("TapiEventSatMoSmsCtrl is called.");
 
-       if (result != TAPI_API_SUCCESS || data == NULL)
+       if (data == NULL)
        {
                MSG_DEBUG("Error. data is NULL.");
                return;
@@ -707,7 +1174,7 @@ void TapiEventSatMoSmsCtrl(TapiHandle *handle, int result, void *data, void *use
 
        try
        {
-               SmsPluginSatHandler::instance()->ctrlSms(data);
+               SmsPluginSatHandler::instance()->ctrlSms(handle, data);
        }
        catch (MsgException& e)
        {
@@ -717,6 +1184,93 @@ void TapiEventSatMoSmsCtrl(TapiHandle *handle, int result, void *data, void *use
 
 }
 
+void TapiEventMemoryStatus(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("Tapi result is [%d]", result);
+       if(result == TAPI_API_SUCCESS)
+       {
+               isMemAvailable = true;
+       }
+}
+
+void TapiEventSetMsgStatus(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSetMsgStatus is called. result [%d]", result);
+
+       if (result != TAPI_API_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+               SmsPluginSimMsg::instance()->setSimEvent((msg_sim_id_t)0, false);
+               return;
+       }
+
+       msg_sim_id_t sim_id = *((msg_sim_id_t *)user_data);
+
+       SmsPluginSimMsg::instance()->setSimEvent(sim_id, true);
+}
+
+
+void TapiEventGetMeImei(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_SEC_DEBUG("TapiEventGetMeImei is called. result [%d]", result);
+
+       if (result != TAPI_API_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+               SmsPluginSetting::instance()->setResultImei(false, NULL);
+               return;
+       }
+
+       char *tmpImei = (char *)data;
+
+       SmsPluginSetting::instance()->setResultImei(true, tmpImei);
+}
+
+
+void TapiEventSimStatusChange(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSimStatusChange is called.");
+
+       if (data == NULL) {
+               MSG_DEBUG("Error. data is NULL.");
+               return;
+       }
+
+        int status = *(int *)data;
+
+        MSG_DEBUG("SIM Status [%d]", status);
+
+        if (status == TAPI_SIM_STATUS_SIM_INIT_COMPLETED) {
+                MSG_INFO("SIM Initialize by sim status change callback");
+                SmsPluginSetting::instance()->setSimChangeStatus(handle, false);
+        }
+}
+
+void TapiEventNetworkStatusChange(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventNetworkStatusChange is called.");
+
+       if (data == NULL) {
+               MSG_DEBUG("Error. data is NULL.");
+               return;
+       }
+
+       TelNetworkServiceType_t *type = (TelNetworkServiceType_t *)data;
+
+       MSG_INFO("network status type [%d], simIndex [%d]", *type, (int)user_data);
+
+       if (*type > TAPI_NETWORK_SERVICE_TYPE_SEARCH) {
+               SmsPluginEventHandler::instance()->handleResendMessage(); // Call Event Handler
+       }
+}
+
+void TapiEventSimRefreshed(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSimRefreshed is called.");
+
+       SmsPluginSetting::instance()->SimRefreshCb(handle);
+}
+
 /*==================================================================================================
                                      IMPLEMENTATION OF SmsPluginCallback - Member Functions
 ==================================================================================================*/
@@ -732,8 +1286,7 @@ SmsPluginCallback::SmsPluginCallback()
 
 SmsPluginCallback::~SmsPluginCallback()
 {
-       if (pInstance != NULL)
-       {
+       if (pInstance != NULL) {
                delete pInstance;
                pInstance = NULL;
        }
@@ -751,13 +1304,37 @@ SmsPluginCallback* SmsPluginCallback::instance()
 
 void SmsPluginCallback::registerEvent()
 {
-       unsigned int tempId = 0;
-
-       tel_register_noti_event(pTapiHandle, TAPI_NOTI_SMS_INCOM_MSG, TapiEventMsgIncoming, NULL);
-       tel_register_noti_event(pTapiHandle, TAPI_NOTI_SMS_CB_INCOM_MSG, TapiEventCbMsgIncoming, NULL);
-//     tel_register_noti_event(pTapiHandle, TAPI_NOTI_SAT_REFRESH, TapiEventSatSmsRefresh, NULL);
-       tel_register_noti_event(pTapiHandle, TAPI_NOTI_SAT_SEND_SMS, TapiEventSatSendSms, NULL);
-//     tel_register_noti_event(pTapiHandle, TAPI_NOTI_SAT_MO_SMS_CTRL, TapiEventSatMoSmsCtrl, NULL);
+       struct tapi_handle *pTapiHandle;
+
+       int count = SmsPluginDSHandler::instance()->getTelHandleCount();
+
+       for (int i = 1; i <= count; ++i) {
+               pTapiHandle = SmsPluginDSHandler::instance()->getTelHandle(i);
+               int simIndex = SmsPluginDSHandler::instance()->getSimIndex(pTapiHandle);
+
+               if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SMS_DEVICE_READY, TapiEventDeviceReady, NULL) != TAPI_API_SUCCESS)
+                       MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SMS_DEVICE_READY);
+               if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SMS_INCOM_MSG, TapiEventMsgIncoming, NULL) != TAPI_API_SUCCESS)
+                       MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SMS_INCOM_MSG);
+               if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SMS_CB_INCOM_MSG, TapiEventCbMsgIncoming, NULL) != TAPI_API_SUCCESS)
+                       MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SMS_CB_INCOM_MSG);
+               if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SMS_ETWS_INCOM_MSG, TapiEventEtwsMsgIncoming, NULL) != TAPI_API_SUCCESS)
+                       MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SMS_ETWS_INCOM_MSG);
+               if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SAT_SEND_SMS, TapiEventSatSendSms, NULL) != TAPI_API_SUCCESS)
+                       MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SAT_SEND_SMS);
+               if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SAT_MO_SM_CONTROL_RESULT, TapiEventSatMoSmsCtrl, NULL) != TAPI_API_SUCCESS)
+                       MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SAT_MO_SM_CONTROL_RESULT);
+               if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SIM_STATUS, TapiEventSimStatusChange, NULL) != TAPI_API_SUCCESS)
+                       MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SIM_STATUS);
+               if (tel_register_noti_event(pTapiHandle, TAPI_PROP_NETWORK_SERVICE_TYPE, TapiEventNetworkStatusChange, (void*)simIndex) != TAPI_API_SUCCESS)
+                       MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_PROP_NETWORK_SERVICE_TYPE);
+               if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SIM_REFRESHED, TapiEventSimRefreshed, NULL) != TAPI_API_SUCCESS)
+                       MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SIM_REFRESHED);
+//             if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SAT_REFRESH, TapiEventSatSmsRefresh, NULL) != TAPI_API_SUCCESS)
+//                     MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SAT_REFRESH);
+//             if (tel_register_noti_event(pTapiHandle, TAPI_NOTI_SAT_MO_SMS_CTRL, TapiEventSatMoSmsCtrl, NULL) != TAPI_API_SUCCESS)
+//                     MSG_DEBUG("tel_register_noti_event is failed : [%s]", TAPI_NOTI_SAT_MO_SMS_CTRL);
+       }
 }
 
 
index 82d22f5..6701f15 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <time.h>
 #include "MsgException.h"
 #include "MsgGconfWrapper.h"
 #include "MsgUtilFile.h"
-#include "SmsPluginTextConvert.h"
+#include "MsgUtilStorage.h"
 #include "SmsPluginUDCodec.h"
 #include "SmsPluginStorage.h"
 #include "SmsPluginEventHandler.h"
 #include "SmsPluginCbMsgHandler.h"
-
+#include "SmsPluginDSHandler.h"
 
 /*==================================================================================================
                                      IMPLEMENTATION OF SmsPluginCbMsgHandler - Member Functions
@@ -55,12 +55,33 @@ SmsPluginCbMsgHandler* SmsPluginCbMsgHandler::instance()
 }
 
 
-void SmsPluginCbMsgHandler::handleCbMsg(TelSmsCbMsg_t *pCbMsg)
+void SmsPluginCbMsgHandler::handleCbMsg(TapiHandle *handle, TelSmsCbMsg_t *pCbMsg)
 {
        MSG_BEGIN();
 
-       SMS_CB_NETWORK_TYPE_T type = pCbMsg->CbMsgType;
+#if 0
+       char temp[1000]= {0x01, 0xa4, 0x1f, 0x51, 0x10, 0x11, 0x02, 0xea, 0x30, 0x30, 0xa8, 0x30, 0xea, 0x30, 0xa2, 0x30, 0xe1, 0x30, 0xfc, 0x30, 0xeb, 0x91, 0x4d, 0x4f, 0xe1, 0x30, 0xc6, 0x30, 0xb9, 0x30, 0xc8, 0x00, 0x0d, 0x00, 0x0a, 0x30, 0x53, 0x30, 0x8c, 0x30, 0x6f, 0x8a, 0x66, 0x9a, 0x13, 0x75, 0x28, 0x30, 0x6e, 0x30, 0xe1, 0x30, 0xc3, 0x30, 0xbb, 0x30, 0xfc, 0x30, 0xb8, 0x30, 0x67, 0x30, 0x59, 0x30, 0x02, 0x00, 0x0d, 0x00, 0x0a, 0xff, 0x08, 0x00, 0x32, 0x00, 0x30, 0x00, 0x31, 0x00, 0x33, 0x00, 0x2f, 0x00, 0x31, 0x00, 0x31, 0x00, 0x2f, 0x00, 0x32, 0x52, 0xea, 0x30, 0x00, 0x37, 0x00, 0x20, 0x00, 0x31, 0x00, 0x35, 0x00, 0x3a, 0x00, 0x34, 0x00, 0x34, 0xff, 0x09, 0x00, 0x0d, 0x00, 0x0a, 0xff, 0x08, 0x30, 0xa8, 0x30, 0xea, 0x30, 0xa2, 0x5e, 0x02, 0xff, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22};
+       TelSmsEtwsMsg_t *pCbMsg = (TelSmsEtwsMsg_t *)calloc(1, sizeof(TelSmsEtwsMsg_t));
+       pCbMsg->Length = 173;
+       pCbMsg->EtwsMsgType = (TelSmsEtwsMsgType_t)2;
+       memcpy(pCbMsg->szMsgData, temp, pCbMsg->Length);
 
+       SMS_CB_NETWORK_TYPE_T type = pCbMsg->EtwsMsgType;
+       SMS_CBMSG_PAGE_S CbMsgPage = {0};
+
+       switch (type)
+       {
+               case SMS_CB_NETWORK_TYPE_2G_GSM :
+                       Decode2gCbMsg((TelSmsCbMsg_t *)pCbMsg, &CbMsgPage);
+               break;
+
+               case SMS_CB_NETWORK_TYPE_3G_UMTS :
+                       Decode3gCbMsg((TelSmsCbMsg_t *)pCbMsg, &CbMsgPage);
+               break;
+
+       }
+#else
+       SMS_CB_NETWORK_TYPE_T type = pCbMsg->CbMsgType;
        SMS_CBMSG_PAGE_S CbMsgPage = {0};
 
        switch (type)
@@ -72,12 +93,15 @@ void SmsPluginCbMsgHandler::handleCbMsg(TelSmsCbMsg_t *pCbMsg)
                case SMS_CB_NETWORK_TYPE_3G_UMTS :
                        Decode3gCbMsg(pCbMsg, &CbMsgPage);
                break;
-       }
 
+       }
+#endif
        // Check CB Msg Options
        bool bJavaMsg = false;
 
-       if (!checkCbOpt(CbMsgPage, &bJavaMsg))
+       int simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+       if (!checkCbOpt(&CbMsgPage, &bJavaMsg, simIndex))
        {
                MSG_DEBUG("The CB Msg is not supported by option.");
                return;
@@ -89,32 +113,53 @@ void SmsPluginCbMsgHandler::handleCbMsg(TelSmsCbMsg_t *pCbMsg)
                CbMsgPage.cbMsgType = SMS_CBMSG_TYPE_JAVACBS;
        }
 
+
        // Check CB Pages
-       unsigned char pageCnt = checkCbPage(CbMsgPage);
+       unsigned char pageCnt = checkCbPage(&CbMsgPage);
 
        if (pageCnt == CbMsgPage.pageHeader.totalPages)
        {
                MSG_DEBUG("RECEIVED LAST MSG : %d", pageCnt);
 
-               SMS_CBMSG_S cbMsg = {};
-               MSG_MESSAGE_INFO_S msgInfo = {};
+               SMS_CBMSG_S *cbMsg = NULL;
+               unique_ptr<SMS_CBMSG_S*, void(*)(SMS_CBMSG_S**)> buf(&cbMsg, unique_ptr_deleter);
+               cbMsg = (SMS_CBMSG_S *)new char[sizeof(SMS_CBMSG_S)];
+               memset(cbMsg, 0x00, sizeof(SMS_CBMSG_S));
+
+               MSG_MESSAGE_INFO_S msgInfo;
+
+               /** initialize msgInfo */
+               memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+               msgInfo.addressList = NULL;
+               unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
 
                // Make CB Msg Structure
-               MakeCbMsg(CbMsgPage, &cbMsg);
+               MakeCbMsg(&CbMsgPage, cbMsg);
 
                // Convert to MSG_MESSAGE_INFO_S
-               convertCbMsgToMsginfo(cbMsg, &msgInfo);
+               convertCbMsgToMsginfo(cbMsg, &msgInfo, simIndex);
 
                // Add CB Msg into DB
                msg_error_t err = MSG_SUCCESS;
 
-               err = SmsPluginStorage::instance()->addMessage(&msgInfo);
+               err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
 
                if (err == MSG_SUCCESS)
                {
-                       // Callback
-                       err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
-
+                       MSG_CB_MSG_S cbOutMsg = {0, };
+
+                       cbOutMsg.type = MSG_CB_SMS;
+                       cbOutMsg.receivedTime = cbMsg->recvTime;
+                       cbOutMsg.serialNum = encodeCbSerialNum (CbMsgPage.pageHeader.serialNum);
+                       cbOutMsg.messageId = cbMsg->msgId;
+                       cbOutMsg.dcs = CbMsgPage.pageHeader.dcs.rawData;
+                       memset (cbOutMsg.cbText, 0x00, sizeof(cbOutMsg.cbText));
+
+                       cbOutMsg.cbTextLen= convertTextToUtf8((unsigned char*)cbOutMsg.cbText, sizeof(cbOutMsg.cbText), cbMsg);
+                       memset(cbOutMsg.language_type, 0x00, sizeof(cbOutMsg.language_type));
+                       memcpy(cbOutMsg.language_type, CbMsgPage.pageHeader.dcs.iso639Lang, 3);
+                       err = SmsPluginEventHandler::instance()->callbackCBMsgIncoming(&cbOutMsg, &msgInfo);
                        if (err != MSG_SUCCESS)
                        {
                                MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
@@ -122,27 +167,78 @@ void SmsPluginCbMsgHandler::handleCbMsg(TelSmsCbMsg_t *pCbMsg)
                }
                else
                {
-                       MSG_DEBUG("addMessage() Error !! [%d]", err);
+                       MSG_DEBUG("checkMessage() Error !! [%d]", err);
                }
 
+#if 0
+               // insert message-id to internal CB message table
+               SmsPluginStorage *storageHandler = SmsPluginStorage::instance();
+               err = storageHandler->insertReceivedCBMessage(CbMsgPage);
+               if (err != MSG_SUCCESS)
+               {
+                       MSG_DEBUG("insertReceivedCBMessage() Error !! [%d]", err);
+               }
+#endif
                // Remove From List
-               removeFromPageList(CbMsgPage);
+               removeFromPageList(&CbMsgPage);
        }
        MSG_END();
 }
 
 
-void SmsPluginCbMsgHandler::Decode2gCbMsg(TelSmsCbMsg_t *pCbMsg, SMS_CBMSG_PAGE_S *pCbPage)
+void SmsPluginCbMsgHandler::handleEtwsMsg(TapiHandle *handle, TelSmsEtwsMsg_t *pEtwsMsg)
 {
-       if (pCbMsg->Length > MAX_CBMSG_PAGE_SIZE)
-               THROW(MsgException::SMS_PLG_ERROR, "CB Msg Size is over MAX [%d]", pCbMsg->Length);
+       MSG_BEGIN();
+       msg_error_t err = MSG_SUCCESS;
+       TelSmsEtwsMsgType_t type = pEtwsMsg->EtwsMsgType;
+       //MSG_MESSAGE_INFO_S msgInfo = {};
+       SMS_ETWS_PRIMARY_S              etwsPn = {0, };
+       MSG_CB_MSG_S                    cbOutMsg = {0, };
+
+       if(type != TAPI_NETTEXT_ETWS_PRIMARY)
+       {
+               MSG_DEBUG("The Etws secondary Message");
+               handleCbMsg(handle, (TelSmsCbMsg_t *)pEtwsMsg);
+               return;
+       }
+       DecodeEtwsMsg(pEtwsMsg, &etwsPn);
+       //convertEtwsMsgToMsginfo(&CbMsgPage, &msgInfo, simIndex);
+
+       cbOutMsg.type = MSG_ETWS_SMS;
+       cbOutMsg.receivedTime = etwsPn.recvTime;
+       cbOutMsg.serialNum = encodeCbSerialNum (etwsPn.serialNum);
+       cbOutMsg.messageId = etwsPn.msgId;
+       cbOutMsg.etwsWarningType = etwsPn.warningType;
+       memcpy (cbOutMsg.etwsWarningSecurityInfo, etwsPn.warningSecurityInfo, sizeof(cbOutMsg.etwsWarningSecurityInfo));
+
+       err = SmsPluginEventHandler::instance()->callbackCBMsgIncoming(&cbOutMsg, NULL);
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+       }
 
+       MSG_END();
+}
+
+
+void SmsPluginCbMsgHandler::Decode2gCbMsg(TelSmsCbMsg_t *pCbMsg, SMS_CBMSG_PAGE_S *pCbPage)
+{
        unsigned char cbData[pCbMsg->Length+1];
 
        memset(cbData, 0x00, sizeof(cbData));
        memcpy(cbData, pCbMsg->szMsgData, pCbMsg->Length);
        cbData[pCbMsg->Length] = '\0';
 
+       // print cb data
+       MSG_INFO("Received CB length:%d", pCbMsg->Length);
+       char cbDataTmp[(pCbMsg->Length*2)+1];
+       memset(cbDataTmp, 0x00, sizeof(cbDataTmp));
+
+       for (int i = 0; i < pCbMsg->Length; i++) {
+               snprintf(cbDataTmp+(i*2), sizeof(cbDataTmp)-(i*2), "%02X", cbData[i]);
+       }
+       MSG_INFO("[%s]", cbDataTmp);
+
        pCbPage->cbMsgType = SMS_CBMSG_TYPE_CBS;
 
        // Serial Number
@@ -153,14 +249,14 @@ void SmsPluginCbMsgHandler::Decode2gCbMsg(TelSmsCbMsg_t *pCbMsg, SMS_CBMSG_PAGE_
 
        pCbPage->pageHeader.serialNum.updateNum = cbData[1] & 0x0F;
 
-MSG_DEBUG("geoScope : [%d], msgCode : [%d], updateNum : [%d]", pCbPage->pageHeader.serialNum.geoScope, pCbPage->pageHeader.serialNum.msgCode, pCbPage->pageHeader.serialNum.updateNum);
+       MSG_DEBUG("geoScope : [%d], msgCode : [%d], updateNum : [%d]", pCbPage->pageHeader.serialNum.geoScope, pCbPage->pageHeader.serialNum.msgCode, pCbPage->pageHeader.serialNum.updateNum);
 
        pCbPage->pageHeader.msgId = (cbData[2] << 8) | cbData[3];
 
-MSG_DEBUG("MSG ID : [%d]", pCbPage->pageHeader.msgId);
+       MSG_DEBUG("MSG ID : [%d]", pCbPage->pageHeader.msgId);
 
        // DCS
-       decodeCbMsgDCS(cbData[4], (unsigned char*)cbData[6], &(pCbPage->pageHeader.dcs));
+       decodeCbMsgDCS(cbData[4], (unsigned char*)cbData + 6, &(pCbPage->pageHeader.dcs));
 
        // Page Parameter
        pCbPage->pageHeader.totalPages = cbData[5] & 0x0F;
@@ -169,19 +265,21 @@ MSG_DEBUG("MSG ID : [%d]", pCbPage->pageHeader.msgId);
        if (pCbPage->pageHeader.totalPages > MAX_CBMSG_PAGE_NUM)
                THROW(MsgException::SMS_PLG_ERROR, "CB Page Count is over MAX[%d]", pCbPage->pageHeader.totalPages);
 
-MSG_DEBUG("Total Page : [%d], Page : [%d]", pCbPage->pageHeader.totalPages, pCbPage->pageHeader.page);
+       MSG_DEBUG("Total Page : [%d], Page : [%d]", pCbPage->pageHeader.totalPages, pCbPage->pageHeader.page);
 
        // Convert Language Type
        convertLangType(pCbPage->pageHeader.dcs.langType, &(pCbPage->pageHeader.langType));
 
-MSG_DEBUG("In Language Type : [%d], Out Language Type : [%d]", pCbPage->pageHeader.dcs.langType, pCbPage->pageHeader.langType);
-
+       MSG_DEBUG("In Language Type : [%d], Out Language Type : [%d]", pCbPage->pageHeader.dcs.langType, pCbPage->pageHeader.langType);
+       MSG_DEBUG("iso639Lang : [%s]", pCbPage->pageHeader.dcs.iso639Lang);
        // Get Receive Time
        pCbPage->pageHeader.recvTime = getRecvTime();
 
        // Decode CB Data
        int dataLen = pCbMsg->Length - 6;
 
+       MSG_DEBUG("codingScheme:[%d]", pCbPage->pageHeader.dcs.codingScheme);
+
        switch (pCbPage->pageHeader.dcs.codingScheme)
        {
                case SMS_CHARSET_7BIT :
@@ -191,53 +289,124 @@ MSG_DEBUG("In Language Type : [%d], Out Language Type : [%d]", pCbPage->pageHead
                        dataLen = (dataLen*8) / 7;
 
                        SmsPluginUDCodec udCodec;
-                       int unpackLen = udCodec.unpack7bitChar(&cbData[6], dataLen, 0, pCbPage->pageData);
+                       char pageData[MAX_CBMSG_PAGE_SIZE+1];
+                       int unpackLen = udCodec.unpack7bitChar(&cbData[6], dataLen, 0, pageData);
+
+                       if(pCbPage->pageHeader.dcs.iso639Lang[0])
+                       {
+                               unpackLen = unpackLen - 3;
+                               if (unpackLen > 0)
+                                       memcpy(pCbPage->pageData, &pageData[3], unpackLen);
+                               else
+                                       unpackLen = 0;
+                       } else {
+                               memcpy(pCbPage->pageData, &pageData, unpackLen);
+                       }
 
-MSG_DEBUG("dataLen : [%d]", dataLen);
-MSG_DEBUG("unpackLen : [%d]", unpackLen);
+                       MSG_DEBUG("unpackLen : [%d]", unpackLen);
 
                        pCbPage->pageLength = unpackLen;
                        pCbPage->pageData[unpackLen] = '\0';
-
-//                     pCbPage->pageLength = strlen(pCbPage->pageData);
-//                     pCbPage->pageData[pCbPage->pageLength] = '\0';
                }
                break;
 
                case SMS_CHARSET_8BIT :
                case SMS_CHARSET_UCS2 :
                {
-                       MSG_DEBUG("UCS2");
-
-                       memcpy(pCbPage->pageData, &cbData[6], dataLen);
-
-                       pCbPage->pageLength = strlen(pCbPage->pageData);
+                       MSG_DEBUG("UCS2 or 8BIT");
 
-                       pCbPage->pageData[pCbPage->pageLength] = '\0';
+                       if(pCbPage->pageHeader.dcs.iso639Lang[0])
+                       {
+                               memcpy(pCbPage->pageData, &cbData[8], dataLen - 2);
+                               pCbPage->pageLength = dataLen - 2;
+                       } else {
+                               memcpy(pCbPage->pageData, &cbData[6], dataLen);
+                               pCbPage->pageLength = dataLen;
+                       }
                }
                break;
        }
 
-MSG_DEBUG("Page Length : [%d], Page Data : [%s]", pCbPage->pageLength, pCbPage->pageData);
+       MSG_DEBUG("Page Length : [%d], Page Data : [%s]", pCbPage->pageLength, pCbPage->pageData);
 }
 
 
-void SmsPluginCbMsgHandler::Decode3gCbMsg(TelSmsCbMsg_t *pCbMsg, SMS_CBMSG_PAGE_S *pCbPage)
+void SmsPluginCbMsgHandler::DecodeEtwsMsg(TelSmsEtwsMsg_t *pEtwsMsg, SMS_ETWS_PRIMARY_S *pEtwsPn)
 {
-       if (pCbMsg->Length > (MAX_CBMSG_PAGE_SIZE*MAX_CBMSG_PAGE_NUM))
-               THROW(MsgException::SMS_PLG_ERROR, "CB Msg Size is over MAX [%d]", pCbMsg->Length);
+       if ( !pEtwsMsg || !pEtwsPn )
+               return;
 
-       char cbData[(MAX_CBMSG_PAGE_SIZE*MAX_CBMSG_PAGE_NUM)+1];
+       if (pEtwsMsg->Length > MAX_ETWS_SIZE)
+               THROW(MsgException::SMS_PLG_ERROR, "ETWS Msg Size is over MAX [%d]", pEtwsMsg->Length);
+
+       unsigned char EtwsData[pEtwsMsg->Length+1];
+
+       memset(EtwsData, 0x00, sizeof(EtwsData));
+       memcpy(EtwsData, pEtwsMsg->szMsgData, pEtwsMsg->Length);
+       EtwsData[pEtwsMsg->Length] = '\0';
+
+       // print received msg data
+       MSG_INFO("Received Etws length:%d", pEtwsMsg->Length);
+       char EtwsDataTmp[(pEtwsMsg->Length*2)+1];
+       memset(EtwsDataTmp, 0x00, sizeof(EtwsDataTmp));
+
+       for (int i = 0; i < pEtwsMsg->Length; i++) {
+               snprintf(EtwsDataTmp+(i*2), sizeof(EtwsDataTmp)-(i*2), "%02X", EtwsData[i]);
+       }
+       MSG_INFO("[%s]", EtwsDataTmp);
+
+       // received time
+       pEtwsPn->recvTime = getRecvTime();
+
+       // Serial Number
+       pEtwsPn->serialNum.geoScope = (EtwsData[0] & 0xC0) >> 6;
+       pEtwsPn->serialNum.msgCode = (EtwsData[0] & 0x3F) << 4;
+       pEtwsPn->serialNum.msgCode |= (EtwsData[1] & 0xF0) >> 4;
+       pEtwsPn->serialNum.updateNum = EtwsData[1] & 0x0F;
+
+       MSG_DEBUG("geoScope : [%d], msgCode : [%d], updateNum : [%d]", pEtwsPn->serialNum.geoScope, pEtwsPn->serialNum.msgCode, pEtwsPn->serialNum.updateNum);
+
+       // Message Identifier
+       pEtwsPn->msgId = (EtwsData[2] << 8) | EtwsData[3];
+       MSG_DEBUG("MSG ID : [%d]", pEtwsPn->msgId);
+
+       // warning type
+       pEtwsPn->warningType = (EtwsData[4] << 8) | EtwsData[5];
+       MSG_DEBUG("warningType : [0x%04x]", pEtwsPn->msgId);
+
+       // warning security information
+       memcpy(pEtwsPn->warningSecurityInfo, &EtwsData[6], sizeof(pEtwsPn->warningSecurityInfo));       // 50bytes
+       for (unsigned int i = 0; i < sizeof(pEtwsPn->warningSecurityInfo); i++)
+       {
+               MSG_DEBUG("warning secu info [%02x]", pEtwsPn->warningSecurityInfo[i] );
+       }
+}
+
+void SmsPluginCbMsgHandler::Decode3gCbMsg(TelSmsCbMsg_t *pCbMsg, SMS_CBMSG_PAGE_S *pCbPage)
+{
+       unsigned char *cbData = NULL;
+       unique_ptr<unsigned char*, void(*)(unsigned char**)> buf(&cbData, unique_ptr_deleter);
+       cbData = (unsigned char *)new char[(MAX_CBMSG_PAGE_SIZE*MAX_CBMSG_PAGE_NUM)+1];
+       memset(cbData, 0x00, sizeof((MAX_CBMSG_PAGE_SIZE*MAX_CBMSG_PAGE_NUM)+1));
 
-       memset(cbData, 0x00, sizeof(cbData));
        memcpy(cbData, pCbMsg->szMsgData, pCbMsg->Length);
        cbData[pCbMsg->Length] = '\0';
 
+       // print cb data
+       MSG_INFO("Received CB length:%d", pCbMsg->Length);
+       char cbDataTmp[(pCbMsg->Length*2)+1];
+       memset(cbDataTmp, 0x00, sizeof(cbDataTmp));
+
+       for (int i = 0; i < pCbMsg->Length; i++) {
+               snprintf(cbDataTmp+(i*2), sizeof(cbDataTmp)-(i*2), "%02X", cbData[i]);
+       }
+       MSG_INFO("[%s]", cbDataTmp);
+
        pCbPage->cbMsgType = (SMS_CBMSG_TYPE_T)cbData[0];
 
        pCbPage->pageHeader.msgId = (cbData[1] << 8) | cbData[2];
 
-MSG_DEBUG("MSG ID : [%d]", pCbPage->pageHeader.msgId);
+       MSG_DEBUG("MSG ID : [%d]", pCbPage->pageHeader.msgId);
 
        // Serial Number
        pCbPage->pageHeader.serialNum.geoScope = (cbData[3] & 0xC0) >> 6;
@@ -247,25 +416,166 @@ MSG_DEBUG("MSG ID : [%d]", pCbPage->pageHeader.msgId);
 
        pCbPage->pageHeader.serialNum.updateNum = cbData[4] & 0x0F;
 
-MSG_DEBUG("geoScope : [%d], msgCode : [%d], updateNum : [%d]", pCbPage->pageHeader.serialNum.geoScope, pCbPage->pageHeader.serialNum.msgCode, pCbPage->pageHeader.serialNum.updateNum);
+       MSG_DEBUG("geoScope : [%d], msgCode : [%d], updateNum : [%d]", pCbPage->pageHeader.serialNum.geoScope, pCbPage->pageHeader.serialNum.msgCode, pCbPage->pageHeader.serialNum.updateNum);
 
        // DCS
-       decodeCbMsgDCS(cbData[5], (unsigned char*)cbData[6], &(pCbPage->pageHeader.dcs));
+       decodeCbMsgDCS(cbData[5], (unsigned char*)cbData + 6, &(pCbPage->pageHeader.dcs));
 
        // Convert Language Type
        convertLangType(pCbPage->pageHeader.dcs.langType, &(pCbPage->pageHeader.langType));
 
-MSG_DEBUG("In Language Type : [%d], Out Language Type : [%d]", pCbPage->pageHeader.dcs.langType, pCbPage->pageHeader.langType);
+       MSG_DEBUG("In Language Type : [%d], Out Language Type : [%d]", pCbPage->pageHeader.dcs.langType, pCbPage->pageHeader.langType);
 
        // Get Receive Time
        pCbPage->pageHeader.recvTime = getRecvTime();
+       pCbPage->pageHeader.totalPages = cbData[6];
+
+       // Decode CB Data
+       int dataLen = 0;
+       int offset = 0;
+
+       switch (pCbPage->pageHeader.dcs.codingScheme)
+       {
+               case SMS_CHARSET_7BIT :
+               {
+                       for(int i = 0; i < pCbPage->pageHeader.totalPages; ++i)
+                       {
+                               char cbMessage[MAX_CBMSG_PAGE_SIZE]= {0,};
+                               dataLen = cbData[7+(i+1)*82 + i];
+                               memcpy(cbMessage, &cbData[7+(i*82)+ i], dataLen);
+
+                               dataLen = (dataLen*8) / 7;
+
+                               if (dataLen > MAX_CBMSG_PAGE_SIZE)
+                                       THROW(MsgException::SMS_PLG_ERROR, "CB Msg Size is over MAX [%d]", dataLen);
+
+                               SmsPluginUDCodec udCodec;
+                               int unpackLen = udCodec.unpack7bitChar((const unsigned char *)cbMessage, dataLen, 0, pCbPage->pageData + offset);
+                               offset += unpackLen;
+                       }
+                       pCbPage->pageLength = offset;
+               }
+               break;
+
+               case SMS_CHARSET_8BIT :
+               case SMS_CHARSET_UCS2 :
+               {
+#if 0
+                       char cbMessage[MAX_CBMSG_PAGE_SIZE]= {0,};
+
+                       for(int i = 0; i < pCbPage->pageHeader.totalPages; ++i)
+                       {
+                               dataLen = cbData[7+(i+1)*82 + i];
+                               memcpy(cbMessage + offset, &cbData[7+(i*82)+ i], dataLen);
+                               offset += dataLen;
+                       }
+                       dataLen = offset;
+
+                       if(pCbPage->pageHeader.dcs.iso639Lang[0])
+                       {
+                               int tmpDataLen = (dataLen > 2)?(dataLen - 2):0;
+                               memcpy(pCbPage->pageData, cbMessage + 2, tmpDataLen);
+                               pCbPage->pageLength = tmpDataLen;
+                       } else {
+                               memcpy(pCbPage->pageData, cbMessage, dataLen);
+                               pCbPage->pageLength = dataLen;
+                       }
+#else
+                       char cbMessage[MAX_CBMSG_PAGE_SIZE]= {0,};
+
+                       for(int i = 0; i < pCbPage->pageHeader.totalPages; ++i)
+                       {
+                               if(pCbPage->pageHeader.dcs.iso639Lang[0])
+                               {
+                                       dataLen = cbData[7+(i+1)*82 + i] - 2;
+                                       memcpy(cbMessage + offset, &cbData[7+(i*82)+ i + 2], dataLen);
+                                       offset += dataLen;
+                               } else {
+                                       dataLen = cbData[7+(i+1)*82 + i];
+                                       memcpy(cbMessage + offset, &cbData[7+(i*82)+ i], dataLen);
+                                       offset += dataLen;
+                               }
+                       }
+                       dataLen = offset;
+                       memcpy(pCbPage->pageData, cbMessage, dataLen);
+                       pCbPage->pageLength = dataLen;
+#endif
+               }
+               break;
+       }
+       pCbPage->pageHeader.totalPages = 1;
+
+       MSG_DEBUG("Page Length : [%d], Page Data : [%s]", pCbPage->pageLength, pCbPage->pageData);
 }
 
+unsigned short SmsPluginCbMsgHandler::encodeCbSerialNum ( SMS_CBMSG_SERIAL_NUM_S snFields )
+{
+       unsigned short serialNum = 0;
+
+       serialNum = ((snFields.geoScope & 0x03) << 14) | ((snFields.msgCode&0x03FF) << 4) | (snFields.updateNum&0x0F);
+       MSG_DEBUG ("serialNum (%x), geo(%x), mc(%x), un(%x)\n", serialNum, snFields.geoScope, snFields.msgCode, snFields.updateNum);
+
+       return serialNum;
+}
 
-bool SmsPluginCbMsgHandler::checkCbOpt(SMS_CBMSG_PAGE_S CbPage, bool *pJavaMsg)
+int SmsPluginCbMsgHandler::CMAS_class(unsigned short message_id)
+{
+       int ret = 0;
+
+       switch (message_id)
+       {
+               case 4370 :
+               case 4383 :
+                       ret = MSG_CMAS_PRESIDENTIAL;
+                       break;
+               case 4371 :
+               case 4372 :
+               case 4384 :
+               case 4385 :
+                       ret = MSG_CMAS_EXTREME;
+                       break;
+               case 4373 :
+               case 4374 :
+               case 4375 :
+               case 4376 :
+               case 4377 :
+               case 4378 :
+               case 4386 :
+               case 4387 :
+               case 4388 :
+               case 4389 :
+               case 4390 :
+               case 4391 :
+                       ret = MSG_CMAS_SEVERE;
+                       break;
+               case 4379 :
+               case 4392 :
+                       ret = MSG_CMAS_AMBER;
+                       break;
+               case 4380 :
+               case 4381 :
+               case 4393 :
+               case 4394 :
+                       ret = MSG_CMAS_TEST;
+                       break;
+               case 4382 :
+               case 4395 :
+                       ret = MSG_CMAS_OPERATOR_DEFINED;
+                       break;
+               default :
+                       break;
+       }
+
+       return ret;
+}
+
+bool SmsPluginCbMsgHandler::checkCbOpt(SMS_CBMSG_PAGE_S *CbPage, bool *pJavaMsg, msg_sim_slot_id_t simIndex)
 {
        bool bReceive = false;
-       MsgSettingGetBool(CB_RECEIVE, &bReceive);
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", CB_RECEIVE, simIndex);
+       MsgSettingGetBool(keyName, &bReceive);
 
        // Receive CB Msg = FALSE
        if (!bReceive)
@@ -274,11 +584,11 @@ bool SmsPluginCbMsgHandler::checkCbOpt(SMS_CBMSG_PAGE_S CbPage, bool *pJavaMsg)
                return false;
        }
 
-       char keyName[128];
-
+#if 0
+       char keyname[128];
        // check Language
        memset(keyName, 0x00, sizeof(keyName));
-       sprintf(keyName, "%s/%d", CB_LANGUAGE, MSG_CBLANG_TYPE_ALL);
+       snprintf(keyName, sizeof(keyname), "%s/%d", CB_LANGUAGE, MSG_CBLANG_TYPE_ALL);
 
        bool bAllLang = false;
        MsgSettingGetBool(keyName, &bAllLang);
@@ -288,7 +598,7 @@ bool SmsPluginCbMsgHandler::checkCbOpt(SMS_CBMSG_PAGE_S CbPage, bool *pJavaMsg)
                MSG_DEBUG("ALL LANGUAGE = FALSE");
 
                memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_LANGUAGE, CbPage.pageHeader.langType);
+               snprintf(keyName, sizeof(keyname), "%s/%d", CB_LANGUAGE, CbPage.pageHeader.langType);
 
                bool bLang = false;
 
@@ -300,32 +610,27 @@ bool SmsPluginCbMsgHandler::checkCbOpt(SMS_CBMSG_PAGE_S CbPage, bool *pJavaMsg)
                        return false;
                }
        }
-
-       int MsgIdCnt = MsgSettingGetInt(CB_CHANNEL_COUNT);
+#endif
 
        bool bActivate = false;
        int MsgId_from = 0, MsgId_to = 0;
+       MSG_CB_CHANNEL_S cbChannelInfo = {0,};
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       for (int i = 0; i < MsgIdCnt; i++)
-       {
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ACTIVATE, i);
-
-               MsgSettingGetBool(keyName, &bActivate);
-
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ID_FROM, i);
-
-               MsgId_from = MsgSettingGetInt(keyName);
-
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ID_TO, i);
+       err = MsgStoGetCBChannelInfo(dbHandle, &cbChannelInfo, simIndex);
+       if (err != MSG_SUCCESS)
+               MSG_ERR("Error value of MsgStoGetCBChannelInfo [%d]", err);
 
-               MsgId_to = MsgSettingGetInt(keyName);
+       for (int i = 0; i < cbChannelInfo.channelCnt; i++)
+       {
+               bActivate = cbChannelInfo.channelInfo[i].bActivate;
+               MsgId_from = cbChannelInfo.channelInfo[i].from;
+               MsgId_to = cbChannelInfo.channelInfo[i].to;
 
-               if (bActivate == true && CbPage.pageHeader.msgId >= MsgId_from && CbPage.pageHeader.msgId <= MsgId_to)
+               if (bActivate == true && CbPage->pageHeader.msgId >= MsgId_from && CbPage->pageHeader.msgId <= MsgId_to)
                {
-                       MSG_DEBUG("FIND CHANNEL = [%d]", CbPage.pageHeader.msgId);
+                       MSG_DEBUG("FIND CHANNEL = [%d]", CbPage->pageHeader.msgId);
                        return true;
                }
        }
@@ -333,24 +638,36 @@ bool SmsPluginCbMsgHandler::checkCbOpt(SMS_CBMSG_PAGE_S CbPage, bool *pJavaMsg)
        return false;
 }
 
-
-unsigned char SmsPluginCbMsgHandler::checkCbPage(SMS_CBMSG_PAGE_S CbPage)
+unsigned char SmsPluginCbMsgHandler::checkCbPage(SMS_CBMSG_PAGE_S *CbPage)
 {
        unsigned char currPageCnt = 0;
 
        bool bFind = false;
 
-       if (CbPage.pageHeader.totalPages > 1)
+#if 0
+       msg_error_t err = MSG_SUCCESS;
+
+       SmsPluginStorage *storageHandler = SmsPluginStorage::instance();
+       err = storageHandler->isReceivedCBMessage(CbPage);
+       // check existing message with cb internal table;
+       if(err != MSG_ERR_DB_NORECORD)
+       {
+               MSG_DEBUG("already received message: [%d]", CbPage.pageHeader.msgId);
+               return 0;
+       }
+#endif
+
+       if (CbPage->pageHeader.totalPages > 0)
        {
                for (unsigned int i = 0; i < pageList.size(); i++)
                {
-                       if (pageList[i].geoScope == CbPage.pageHeader.serialNum.geoScope && pageList[i].msgCode == CbPage.pageHeader.serialNum.msgCode)
+                       if (pageList[i].geoScope == CbPage->pageHeader.serialNum.geoScope && pageList[i].msgCode == CbPage->pageHeader.serialNum.msgCode)
                        {
                                MSG_DEBUG("geoScope [%d], msgCode [%d]", pageList[i].geoScope, pageList[i].msgCode);
 
-                               if (pageList[i].msgId == CbPage.pageHeader.msgId)
+                               if (pageList[i].msgId == CbPage->pageHeader.msgId)
                                {
-                                       int updateNum = CbPage.pageHeader.serialNum.updateNum - pageList[i].updateNum;
+                                       int updateNum = CbPage->pageHeader.serialNum.updateNum - pageList[i].updateNum;
 
                                        if (updateNum > 0) // New Message Content
                                        {
@@ -358,20 +675,20 @@ unsigned char SmsPluginCbMsgHandler::checkCbPage(SMS_CBMSG_PAGE_S CbPage)
                                        }
                                        else if (updateNum == 0) // Same Message Content
                                        {
-                                               if (pageList[i].data.count(CbPage.pageHeader.page) != 0)
+                                               if (pageList[i].data.count(CbPage->pageHeader.page) != 0)
                                                {
-                                                       MSG_DEBUG("The Page Number already exists [%d]", CbPage.pageHeader.page);
+                                                       MSG_DEBUG("The Page Number already exists [%d]", CbPage->pageHeader.page);
                                                        return 0;
                                                }
 
-                                               pair<unsigned char, string> newData(CbPage.pageHeader.page, CbPage.pageData);
+                                               pair<unsigned char, SMS_CBMSG_PAGE_S> newData(CbPage->pageHeader.page, *CbPage);
                                                pageList[i].data.insert(newData);
 
-                                               MSG_DEBUG("PAGE DATA : %s", CbPage.pageData);
-                                               MSG_DEBUG("PAIR DATA [%d] : %s", newData.first, newData.second.c_str());
+                                               MSG_DEBUG("PAGE DATA : %s", CbPage->pageData);
+                                               MSG_DEBUG("PAIR DATA [%d] : %s", newData.first, newData.second.pageData);
 
                                                pageList[i].pageCnt++;
-                                               pageList[i].totalSize += CbPage.pageLength;
+                                               pageList[i].totalSize += CbPage->pageLength;
 
                                                currPageCnt = pageList[i].pageCnt;
 
@@ -388,9 +705,9 @@ unsigned char SmsPluginCbMsgHandler::checkCbPage(SMS_CBMSG_PAGE_S CbPage)
                }
        }
 
-       if (bFind == false || CbPage.pageHeader.totalPages == 1)
+       if (bFind == false || CbPage->pageHeader.totalPages == 1)
        {
-               addToPageLiat(CbPage);
+               addToPageList(CbPage);
                return 1;
        }
 
@@ -398,57 +715,69 @@ unsigned char SmsPluginCbMsgHandler::checkCbPage(SMS_CBMSG_PAGE_S CbPage)
 }
 
 
-void SmsPluginCbMsgHandler::MakeCbMsg(SMS_CBMSG_PAGE_S CbPage, SMS_CBMSG_S *pCbMsg)
+void SmsPluginCbMsgHandler::MakeCbMsg(SMS_CBMSG_PAGE_S *CbPage, SMS_CBMSG_S *pCbMsg)
 {
-       pCbMsg->cbMsgType = CbPage.cbMsgType;
-       pCbMsg->msgId = CbPage.pageHeader.msgId;
-       pCbMsg->classType = CbPage.pageHeader.dcs.classType;
-       pCbMsg->codingScheme = CbPage.pageHeader.dcs.codingScheme;
-       pCbMsg->recvTime = CbPage.pageHeader.recvTime;
+       pCbMsg->cbMsgType = CbPage->cbMsgType;
+       pCbMsg->msgId = CbPage->pageHeader.msgId;
+       pCbMsg->classType = CbPage->pageHeader.dcs.classType;
+       pCbMsg->codingScheme = CbPage->pageHeader.dcs.codingScheme;
+       pCbMsg->recvTime = CbPage->pageHeader.recvTime;
 
        cbPageMap::iterator it;
-       string tmpStr ("");
+       int offset = 0;
 
        for (unsigned int i = 0; i < pageList.size(); i++)
        {
-               if (pageList[i].geoScope == CbPage.pageHeader.serialNum.geoScope && pageList[i].msgCode == CbPage.pageHeader.serialNum.msgCode)
+               if (pageList[i].geoScope == CbPage->pageHeader.serialNum.geoScope && pageList[i].msgCode == CbPage->pageHeader.serialNum.msgCode)
                {
                        MSG_DEBUG("geoScope [%d], msgCode [%d]", pageList[i].geoScope, pageList[i].msgCode);
 
-                       if (pageList[i].msgId == CbPage.pageHeader.msgId)
+                       if (pageList[i].msgId == CbPage->pageHeader.msgId)
                        {
+
                                for (it = pageList[i].data.begin(); it != pageList[i].data.end(); it++)
                                {
-                                       tmpStr += it->second;
+                                       memcpy(pCbMsg->msgData + offset, it->second.pageData, it->second.pageLength);
+                                       pCbMsg->msgLength += it->second.pageLength;
+                                       offset = pCbMsg->msgLength;
                                }
                        }
                }
        }
 
+#if 0
        pCbMsg->msgLength = tmpStr.size();
 
        memcpy(pCbMsg->msgData, tmpStr.c_str(), tmpStr.size());
        pCbMsg->msgData[tmpStr.size()] = '\0';
 
        MSG_DEBUG("SIZE : [%d] TOTAL MSG : %s", tmpStr.size(), tmpStr.c_str());
+#endif
 }
 
 
-void SmsPluginCbMsgHandler::convertCbMsgToMsginfo(SMS_CBMSG_S cbMsg, MSG_MESSAGE_INFO_S *pMsgInfo)
+void SmsPluginCbMsgHandler::convertCbMsgToMsginfo(SMS_CBMSG_S *pCbMsg, MSG_MESSAGE_INFO_S *pMsgInfo, msg_sim_slot_id_t simIndex)
 {
-       pMsgInfo->msgId = (msg_message_id_t)cbMsg.msgId;
+       pMsgInfo->msgId = (msg_message_id_t)pCbMsg->msgId;
 
        pMsgInfo->folderId = MSG_CBMSGBOX_ID;
 
        // Convert Type values
        pMsgInfo->msgType.mainType = MSG_SMS_TYPE;
 
-       if (cbMsg.cbMsgType == SMS_CBMSG_TYPE_CBS)
-               pMsgInfo->msgType.subType = MSG_CB_SMS;
-       else if (cbMsg.cbMsgType == SMS_CBMSG_TYPE_JAVACBS)
+       if (pCbMsg->cbMsgType == SMS_CBMSG_TYPE_CBS) {
+               int cmas_class = CMAS_class(pCbMsg->msgId);
+
+               if (cmas_class == 0)
+                       pMsgInfo->msgType.subType = MSG_CB_SMS;
+               else
+                       pMsgInfo->msgType.subType = (MSG_SUB_TYPE_T)cmas_class;
+       }
+       else if (pCbMsg->cbMsgType == SMS_CBMSG_TYPE_JAVACBS) {
                pMsgInfo->msgType.subType = MSG_JAVACB_SMS;
+       }
 
-       switch(cbMsg.classType)
+       switch(pCbMsg->classType)
        {
                case SMS_MSG_CLASS_0:
                        pMsgInfo->msgType.classType = MSG_CLASS_0;
@@ -464,6 +793,7 @@ void SmsPluginCbMsgHandler::convertCbMsgToMsginfo(SMS_CBMSG_S cbMsg, MSG_MESSAGE
                        break;
                default:
                        pMsgInfo->msgType.classType = MSG_CLASS_NONE;
+                       break;
        }
 
        pMsgInfo->storageId = MSG_STORAGE_PHONE;
@@ -476,49 +806,59 @@ void SmsPluginCbMsgHandler::convertCbMsgToMsginfo(SMS_CBMSG_S cbMsg, MSG_MESSAGE
        // Temporary
        pMsgInfo->nAddressCnt = 1;
 
+       pMsgInfo->addressList =  (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+       memset(pMsgInfo->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
        pMsgInfo->addressList[0].addressType = MSG_ADDRESS_TYPE_UNKNOWN;
        pMsgInfo->addressList[0].recipientType = MSG_RECIPIENTS_TYPE_UNKNOWN;
+       pMsgInfo->sim_idx = simIndex;
+
+       //      TODO :: MSG ID should be used to get CB message type
+       getDisplayName(pCbMsg->msgId, pMsgInfo->addressList[0].addressVal, simIndex);
+       MSG_SEC_DEBUG("%s", pMsgInfo->addressList[0].addressVal);
 
-       getDisplayName(cbMsg.msgId, pMsgInfo->addressList[0].addressVal);
-       MSG_DEBUG("%s", pMsgInfo->addressList[0].addressVal);
 
        pMsgInfo->msgPort.valid = false;
        pMsgInfo->msgPort.dstPort = 0;
        pMsgInfo->msgPort.srcPort = 0;
 
-       pMsgInfo->displayTime = cbMsg.recvTime;
-       MSG_DEBUG("recvTime is %s", ctime(&pMsgInfo->displayTime));
+       pMsgInfo->displayTime = pCbMsg->recvTime;
+       MSG_DEBUG("recvTime is %d", pMsgInfo->displayTime);
 
-       int bufSize = cbMsg.msgLength*2;
+       int bufSize = pCbMsg->msgLength*2;
 
        char tmpBuf[bufSize];
        memset(tmpBuf, 0x00, sizeof(tmpBuf));
 
-       MSG_DEBUG("LENGTH %d CB MSG %s", cbMsg.msgLength, cbMsg.msgData);
-
-       SMS_LANG_INFO_S langInfo = {0};
+       while (pCbMsg->msgLength > 0) {
+               if (pCbMsg->msgData[pCbMsg->msgLength-1] == ' ' ||
+                               pCbMsg->msgData[pCbMsg->msgLength-1] == '\r' ||
+                               pCbMsg->msgData[pCbMsg->msgLength-1] == '\n') {
+                       pCbMsg->msgLength--;
+               }
+               else {
+                       break;
+               }
+       }
+       pCbMsg->msgData[pCbMsg->msgLength] = '\0';
 
-       langInfo.bSingleShift = false;
-       langInfo.bLockingShift = false;
+       MSG_DEBUG("LENGTH %d CB MSG %s", pCbMsg->msgLength, pCbMsg->msgData);
 
        // Convert Data values
-       if (cbMsg.codingScheme == SMS_CHARSET_7BIT)
-               pMsgInfo->dataSize = SmsPluginTextConvert::instance()->convertGSM7bitToUTF8((unsigned char*)tmpBuf, bufSize, (unsigned char*)cbMsg.msgData, cbMsg.msgLength, &langInfo);
-       else if (cbMsg.codingScheme == SMS_CHARSET_UCS2)
-               pMsgInfo->dataSize = SmsPluginTextConvert::instance()->convertUCS2ToUTF8((unsigned char*)tmpBuf, bufSize, (unsigned char*)cbMsg.msgData, cbMsg.msgLength);
+       pMsgInfo->dataSize = convertTextToUtf8((unsigned char*)tmpBuf, bufSize, pCbMsg);
 
        if (pMsgInfo->dataSize > MAX_MSG_TEXT_LEN)
        {
                pMsgInfo->bTextSms = false;
 
                // Save Message Data into File
-               char fileName[MAX_COMMON_INFO_SIZE+1];
+               char fileName[MSG_FILENAME_LEN_MAX+1];
                memset(fileName, 0x00, sizeof(fileName));
 
                if (MsgCreateFileName(fileName) == false)
                        THROW(MsgException::FILE_ERROR, "MsgCreateFileName error");
 
-               MSG_DEBUG("Save Message Data into file : size[%d] name[%s]\n", pMsgInfo->dataSize, fileName);
+               MSG_SEC_DEBUG("Save Message Data into file : size[%d] name[%s]\n", pMsgInfo->dataSize, fileName);
                if (MsgWriteIpcFile(fileName, tmpBuf, pMsgInfo->dataSize) == false)
                        THROW(MsgException::FILE_ERROR, "MsgWriteIpcFile error");
 
@@ -530,44 +870,113 @@ void SmsPluginCbMsgHandler::convertCbMsgToMsginfo(SMS_CBMSG_S cbMsg, MSG_MESSAGE
 
                memset(pMsgInfo->msgText, 0x00, sizeof(pMsgInfo->msgText));
                memcpy(pMsgInfo->msgText, tmpBuf, pMsgInfo->dataSize);
+               pMsgInfo->dataSize = strlen(pMsgInfo->msgText);
+               MSG_SEC_DEBUG("CB MSG %s", pMsgInfo->msgText);
        }
 }
 
 
-void SmsPluginCbMsgHandler::addToPageLiat(SMS_CBMSG_PAGE_S CbPage)
+void SmsPluginCbMsgHandler::convertEtwsMsgToMsginfo(SMS_CBMSG_PAGE_S *EtwsMsg, MSG_MESSAGE_INFO_S *pMsgInfo, msg_sim_slot_id_t simIndex)
+{
+       pMsgInfo->msgId = (msg_message_id_t)EtwsMsg->pageHeader.msgId;
+
+       pMsgInfo->folderId = MSG_CBMSGBOX_ID;
+
+       // Convert Type values
+       pMsgInfo->msgType.mainType = MSG_SMS_TYPE;
+
+       if (EtwsMsg->cbMsgType == SMS_CBMSG_TYPE_ETWS)
+               pMsgInfo->msgType.subType = MSG_ETWS_SMS;
+
+       pMsgInfo->storageId = MSG_STORAGE_PHONE;
+       pMsgInfo->networkStatus = MSG_NETWORK_RECEIVED;
+       pMsgInfo->bRead = false;
+       pMsgInfo->bProtected = false;
+       pMsgInfo->priority = MSG_MESSAGE_PRIORITY_NORMAL;
+       pMsgInfo->direction = MSG_DIRECTION_TYPE_MT;
+
+       // Temporary
+       pMsgInfo->nAddressCnt = 1;
+
+       pMsgInfo->addressList[0].addressType = MSG_ADDRESS_TYPE_UNKNOWN;
+       pMsgInfo->addressList[0].recipientType = MSG_RECIPIENTS_TYPE_UNKNOWN;
+
+       getDisplayName(EtwsMsg->pageHeader.msgId, pMsgInfo->addressList[0].addressVal, simIndex);
+       MSG_SEC_DEBUG("%s", pMsgInfo->addressList[0].addressVal);
+
+       pMsgInfo->msgPort.valid = false;
+       pMsgInfo->msgPort.dstPort = 0;
+       pMsgInfo->msgPort.srcPort = 0;
+
+       pMsgInfo->displayTime = EtwsMsg->pageHeader.recvTime;
+       MSG_DEBUG("recvTime is %d", pMsgInfo->displayTime);
+       MSG_DEBUG("LENGTH %d", EtwsMsg->pageLength);
+       pMsgInfo->bTextSms = true;
+       pMsgInfo->dataSize = EtwsMsg->pageLength;
+       memset(pMsgInfo->msgData, 0x00, sizeof(pMsgInfo->msgData));
+       memcpy(pMsgInfo->msgData, EtwsMsg->pageData, pMsgInfo->dataSize);
+}
+
+int SmsPluginCbMsgHandler::convertTextToUtf8 (unsigned char* outBuf, int outBufSize, SMS_CBMSG_S* pCbMsg)
+{
+       int     convertedTextSize = 0;
+       MSG_LANG_INFO_S langInfo = {0,};
+
+       MsgTextConvert *textCvt = MsgTextConvert::instance();
+
+       if (!outBuf || !pCbMsg)
+       {
+               MSG_DEBUG ("invalid param.\n");
+               return 0;
+       }
+
+       langInfo.bSingleShift = false;
+       langInfo.bLockingShift = false;
+
+
+       // Convert Data values
+       if (pCbMsg->codingScheme == SMS_CHARSET_7BIT)
+               convertedTextSize = textCvt->convertGSM7bitToUTF8(outBuf, outBufSize, (unsigned char*)pCbMsg->msgData, pCbMsg->msgLength, &langInfo);
+       else if (pCbMsg->codingScheme == SMS_CHARSET_UCS2)
+               convertedTextSize = textCvt->convertUCS2ToUTF8(outBuf, outBufSize, (unsigned char*)pCbMsg->msgData, pCbMsg->msgLength);
+
+       return convertedTextSize;
+}
+
+void SmsPluginCbMsgHandler::addToPageList(SMS_CBMSG_PAGE_S *CbPage)
 {
        CB_PAGE_INFO_S tmpInfo;
 
-       tmpInfo.geoScope = CbPage.pageHeader.serialNum.geoScope;
-       tmpInfo.msgCode = CbPage.pageHeader.serialNum.msgCode;
-       tmpInfo.updateNum = CbPage.pageHeader.serialNum.updateNum;
-       tmpInfo.msgId = CbPage.pageHeader.msgId;
-       tmpInfo.totalPages = CbPage.pageHeader.totalPages;
+       tmpInfo.geoScope = CbPage->pageHeader.serialNum.geoScope;
+       tmpInfo.msgCode = CbPage->pageHeader.serialNum.msgCode;
+       tmpInfo.updateNum = CbPage->pageHeader.serialNum.updateNum;
+       tmpInfo.msgId = CbPage->pageHeader.msgId;
+       tmpInfo.totalPages = CbPage->pageHeader.totalPages;
 
        tmpInfo.pageCnt = 1;
-       tmpInfo.totalSize = CbPage.pageLength;
+       tmpInfo.totalSize = CbPage->pageLength;
 
-       pair<unsigned char, string> newData(CbPage.pageHeader.page, CbPage.pageData);
+       pair<unsigned char, SMS_CBMSG_PAGE_S> newData(CbPage->pageHeader.page, *CbPage);
        tmpInfo.data.insert(newData);
 
-       MSG_DEBUG("MSG DATA : %s", CbPage.pageData);
-       MSG_DEBUG("PAIR DATA [%d] : %s", newData.first, newData.second.c_str());
+       MSG_DEBUG("MSG DATA : %s", CbPage->pageData);
+       MSG_DEBUG("PAIR DATA [%d] : %s", newData.first, newData.second.pageData);
 
        pageList.push_back(tmpInfo);
 }
 
 
-void SmsPluginCbMsgHandler::removeFromPageList(SMS_CBMSG_PAGE_S CbPage)
+void SmsPluginCbMsgHandler::removeFromPageList(SMS_CBMSG_PAGE_S *CbPage)
 {
        unsigned int index;
 
        for (index = 0; index < pageList.size(); index++)
        {
-               if (pageList[index].geoScope == CbPage.pageHeader.serialNum.geoScope && pageList[index].msgCode == CbPage.pageHeader.serialNum.msgCode)
+               if (pageList[index].geoScope == CbPage->pageHeader.serialNum.geoScope && pageList[index].msgCode == CbPage->pageHeader.serialNum.msgCode)
                {
                        MSG_DEBUG("geoScope [%d], msgCode [%d]", pageList[index].geoScope, pageList[index].msgCode);
 
-                       if (pageList[index].msgId == CbPage.pageHeader.msgId) break;
+                       if (pageList[index].msgId == CbPage->pageHeader.msgId) break;
                }
        }
 
@@ -608,20 +1017,20 @@ void SmsPluginCbMsgHandler::decodeCbMsgDCS(unsigned char dcsData, const unsigned
                                pDcs->codingGroup = SMS_CBMSG_CODGRP_GENERAL_DCS;
                                pDcs->codingScheme = (dcsData & 0x01) ? SMS_CHARSET_UCS2 : SMS_CHARSET_7BIT;
                                pDcs->langType = SMS_CBMSG_LANG_ISO639;
-
-                               if (pMsgData != NULL)
+                               MSG_DEBUG("codingScheme: [%d]", pDcs->codingScheme);
+                               if (pMsgData[0] && pMsgData[1])
                                {
                                        pDcs->iso639Lang[0] = pMsgData[0] & 0x7F;
-                                       pDcs->iso639Lang[1] = (pMsgData[0] & 0x80) >> 7;
-                                       pDcs->iso639Lang[1] |= (pMsgData[1] & 0x3F) << 1;
-                                       pDcs->iso639Lang[2]  = 0x13; /* CR char in GSM 7-bit Alphabet */
+                                       pDcs->iso639Lang[1] = (pMsgData[0] & 0X80) >> 7;
+                                       pDcs->iso639Lang[1] |= (pMsgData[1] & 0X3F) << 1;
+                                       pDcs->iso639Lang[2] = 0x13;  /* CR */
                                }
                                else
                                {
-                                       /* Default it to English if pMsgData is NULL */
-                                       pDcs->iso639Lang[0] = 0x45;  /* E */
-                                       pDcs->iso639Lang[1] = 0x4E;  /* N */
-                                       pDcs->iso639Lang[2] = 0x13;  /* CR */
+                                       /* Default it to English if pMsgData is NULL */
+                                       pDcs->iso639Lang[0] = 0x45;  /* E */
+                                       pDcs->iso639Lang[1] = 0x4E;  /* N */
+                                       pDcs->iso639Lang[2] = 0x13;  /* CR */
                                }
                        }
                }
@@ -639,29 +1048,49 @@ void SmsPluginCbMsgHandler::decodeCbMsgDCS(unsigned char dcsData, const unsigned
                        if (dcsData & 0x10)
                                pDcs->classType = (SMS_MSG_CLASS_T)(dcsData & 0x03);
 
-                       pDcs->codingScheme = (SMS_CODING_SCHEME_T)(dcsData & 0x0C);
+                       unsigned char tmpScheme = (dcsData & 0x0C) >> 2;
+
+                       switch (tmpScheme) {
+                               case 0x00:
+                                       pDcs->codingScheme = SMS_CHARSET_7BIT;
+                                       break;
+                               case 0x01:
+                                       pDcs->codingScheme = SMS_CHARSET_8BIT;
+                                       break;
+                               case 0x02:
+                                       pDcs->codingScheme = SMS_CHARSET_UCS2;
+                                       break;
+                               default:
+                                       MSG_DEBUG("tmpScheme: [%d]", tmpScheme);
+                                       break;
+                       }
                }
                break;
 
                case 0x09 :
                {
                        pDcs->bUDH = true;
+                       pDcs->classType = (MSG_CLASS_TYPE_T)(dcsData & 0x03);
+                       pDcs->codingScheme = (SMS_CODING_SCHEME_T)((dcsData & 0x0C) >> 2);
                }
                break;
 
-               case 0x14 :
+               case 0x0E :
                {
                        pDcs->codingGroup = SMS_CBMSG_CODGRP_WAP;
                }
                break;
 
-               case 0x15 :
+               case 0x0F :
                {
                        pDcs->codingGroup = SMS_CBMSG_CODGRP_CLASS_CODING;
-                       pDcs->codingScheme = (dcsData & 0x04) ? SMS_CHARSET_UCS2 : SMS_CHARSET_7BIT;
+                       pDcs->codingScheme = (dcsData & 0x04) ? SMS_CHARSET_8BIT : SMS_CHARSET_7BIT;
                        pDcs->classType = (MSG_CLASS_TYPE_T)(dcsData & 0x03);
                }
                break;
+               default:
+                       MSG_DEBUG("codingGrp: [0x%x]", codingGrp);
+               break;
        }
 }
 
@@ -723,54 +1152,44 @@ unsigned long SmsPluginCbMsgHandler::getRecvTime()
 }
 
 
-void SmsPluginCbMsgHandler::getDisplayName(unsigned short      MsgId, char *pDisplayName)
+void SmsPluginCbMsgHandler::getDisplayName(unsigned short      MsgId, char *pDisplayName, msg_sim_slot_id_t simIndex)
 {
-       int MsgIdCnt = MsgSettingGetInt(CB_CHANNEL_COUNT);
+       MSG_CB_CHANNEL_S cbChannelInfo = {0,};
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       char keyName[128];
-       char from[128];
-       char to[128];
-       char strTmp[CB_CHANNEL_NAME_MAX+1];
+       err = MsgStoGetCBChannelInfo(dbHandle, &cbChannelInfo, simIndex);
+       MSG_DEBUG("MsgStoGetCBChannelInfo [err = %d]", err);
 
-       for (int i = 0; i < MsgIdCnt; i++)
+       for (int i = 0; i < cbChannelInfo.channelCnt; i++)
        {
-               memset(from, 0x00, sizeof(from));
-               sprintf(from, "%s/%d", CB_CHANNEL_ID_FROM, i);
-
-               memset(to, 0x00, sizeof(to));
-               sprintf(to, "%s/%d", CB_CHANNEL_ID_TO, i);
-
-               if (MsgId >= MsgSettingGetInt(from) && MsgId <= MsgSettingGetInt(to))
+               if (MsgId >= cbChannelInfo.channelInfo[i].from && MsgId <= cbChannelInfo.channelInfo[i].to)
                {
-                       char *channelName = NULL;
                        MSG_DEBUG("FIND MSG ID = [%d]", MsgId);
 #if 0
-                       memset(keyName, 0x00, sizeof(keyName));
-                       sprintf(keyName, "%s/%d", CB_CHANNEL_NAME, i);
-
+                       char strTmp[CB_CHANNEL_NAME_MAX + 1];
                        memset(strTmp, 0x00, sizeof(strTmp));
 
-                       channelName = MsgSettingGetString(keyName);
-
-                       strncpy(strTmp, channelName, CB_CHANNEL_NAME_MAX);
-
-                       if (channelName) {
-                               free(channelName);
-                               channelName = NULL;
-                       }
+                       strncpy(strTmp, cbChannelInfo.channelInfo[i].name, CB_CHANNEL_NAME_MAX);
 
                        if (strlen(strTmp) > 0)
-                               sprintf(pDisplayName, "[%s]", strTmp);
+                               snprintf(pDisplayName, sizeof(strTmp), "[%s]", strTmp);
                        else
-                               sprintf(pDisplayName, "[%d]", MsgId);
+                               snprintf(pDisplayName, sizeof(unsigned short), "[%d]", MsgId);
 #else
-                       sprintf(pDisplayName, "[%d]", MsgId);
+
+#ifdef MSG_NOTI_INTEGRATION
+                       snprintf(pDisplayName, MAX_ADDRESS_VAL_LEN + 1, "CB message");
+#else
+                       snprintf(pDisplayName, MAX_ADDRESS_VAL_LEN + 1, "[%d]", MsgId);
+#endif
+
 #endif
 
                        return;
                }
        }
 
-       sprintf(pDisplayName, "[%d]", MsgId);
+       snprintf(pDisplayName, MAX_ADDRESS_VAL_LEN + 1, "[%d]", MsgId);
 }
 
index a19fbd4..8a6183c 100755 (executable)
@@ -1,28 +1,32 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
+#include "MsgException.h"
 #include "MsgCppTypes.h"
 #include "MsgUtilFile.h"
-#include "SmsPluginTextConvert.h"
+#include "MsgGconfWrapper.h"
+#include "MsgNotificationWrapper.h"
 #include "SmsPluginStorage.h"
 #include "SmsPluginTransport.h"
 #include "SmsPluginEventHandler.h"
 #include "SmsPluginWapPushHandler.h"
 #include "SmsPluginConcatHandler.h"
+#include "SmsPluginSimMsg.h"
+#include "SmsPluginDSHandler.h"
 
 /*==================================================================================================
                                      IMPLEMENTATION OF SmsPluginConcatHandler - Member Functions
@@ -72,7 +76,7 @@ bool SmsPluginConcatHandler::IsConcatMsg(SMS_USERDATA_S *pUserData)
 }
 
 
-void SmsPluginConcatHandler::handleConcatMsg(SMS_TPDU_S *pTpdu)
+void SmsPluginConcatHandler::handleConcatMsg(struct tapi_handle *handle, SMS_TPDU_S *pTpdu)
 {
        MSG_BEGIN();
 
@@ -86,6 +90,8 @@ void SmsPluginConcatHandler::handleConcatMsg(SMS_TPDU_S *pTpdu)
 
        SMS_CONCAT_MSG_S msg = {0};
 
+       msg.simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
        for (int i = 0; i < pTpdu->data.deliver.userData.headerCnt; i++) {
                if (pTpdu->data.deliver.userData.header[i].udhType == SMS_UDH_CONCAT_8BIT) {
                        msg.msgRef = (unsigned short)pTpdu->data.deliver.userData.header[i].udh.concat8bit.msgRef;
@@ -96,11 +102,12 @@ void SmsPluginConcatHandler::handleConcatMsg(SMS_TPDU_S *pTpdu)
                        memcpy(&(msg.originAddress), &(pTpdu->data.deliver.originAddress), sizeof(SMS_ADDRESS_S));
                        memcpy(&(msg.dcs), &(pTpdu->data.deliver.dcs), sizeof(SMS_DCS_S));
 
+#if 0
                        if (msg.totalSeg > MAX_SEGMENT_NUM) {
                                MSG_DEBUG("Total Segment Count is over Maximum [%d]", msg.totalSeg);
                                return;
                        }
-
+#endif
                        /**  check noneConcatTypeHeader */
                        noneConcatTypeHeader = false;
 
@@ -113,11 +120,12 @@ void SmsPluginConcatHandler::handleConcatMsg(SMS_TPDU_S *pTpdu)
                        memcpy(&(msg.timeStamp.time.absolute), &(pTpdu->data.deliver.timeStamp.time.absolute), sizeof(SMS_TIME_ABS_S));
                        memcpy(&(msg.originAddress), &(pTpdu->data.deliver.originAddress), sizeof(SMS_ADDRESS_S));
                        memcpy(&(msg.dcs), &(pTpdu->data.deliver.dcs), sizeof(SMS_DCS_S));
-
+#if 0
                        if (msg.totalSeg > MAX_SEGMENT_NUM) {
                                MSG_DEBUG("Total Segment Count is over Maximum [%d]", msg.totalSeg);
                                return;
                        }
+#endif
 
                        /**  check noneConcatTypeHeader */
                        noneConcatTypeHeader = false;
@@ -136,30 +144,80 @@ void SmsPluginConcatHandler::handleConcatMsg(SMS_TPDU_S *pTpdu)
 
                int dataSize = 0;
                char* pUserData = NULL;
-               AutoPtr<char> dataBuf(&pUserData);
+               bool simSlotSizeOver = false;
+               unique_ptr<char*, void(*)(char**)> dataBuf(&pUserData, unique_ptr_deleter);
 
                MSG_MESSAGE_INFO_S msgInfo = {0};
 
-               dataSize = makeConcatUserData(msg.msgRef, &pUserData);
+               msgInfo.addressList = NULL;
+               unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+               msgInfo.sim_idx = msg.simIndex;
+
+               dataSize = makeConcatUserData(msg.msgRef, msg.simIndex, &pUserData);
 
                if (dataSize > 0) {
                        if (SmsPluginWapPushHandler::instance()->IsWapPushMsg(&(pTpdu->data.deliver.userData)) == true) {
                                SmsPluginWapPushHandler::instance()->copyDeliverData(&(pTpdu->data.deliver));
-                               SmsPluginWapPushHandler::instance()->handleWapPushMsg(pUserData, dataSize);
+                               msgInfo.msgType.mainType = MSG_SMS_TYPE;
+                               if (err == MSG_SUCCESS) {
+                                       SmsPluginWapPushHandler::instance()->handleWapPushMsg(pUserData, dataSize, msg.simIndex);
+                               }
                        } else {
                                convertConcatToMsginfo(&(pTpdu->data.deliver), pUserData, dataSize, &msgInfo);
 
+                               if (msgInfo.msgType.classType == MSG_CLASS_2) {
+                                       msgInfo.storageId = MSG_STORAGE_SIM;
+                                       SmsPluginSimMsg::instance()->setSmsTpduTotalSegCount(msg.totalSeg);
+                               }
+
+                               if (msgInfo.msgPort.valid == true) {
+                                       if ((msgInfo.msgPort.dstPort >= 0x23F4 && msgInfo.msgPort.dstPort <= 0x23F7) || /** Check unsupported message (Vcalendar WAP push) **/
+                                               (msgInfo.msgPort.dstPort == 0x1581)) { /** Check unsupported message (ringtone smart message) **/
+                                               memset(msgInfo.msgText, 0x00, sizeof(msgInfo.msgText));
+                                               snprintf(msgInfo.msgText, sizeof(msgInfo.msgText), "<<Content not supported>>");
+                                               msgInfo.dataSize = strlen(msgInfo.msgText);
+                                               msgInfo.msgPort.valid = false;
+                                       }
+                               }
+
                                if (msgInfo.msgPort.valid == false) {
                                        /** Add Concat Msg into DB */
-                                       err = SmsPluginStorage::instance()->addMessage(&msgInfo);
+
+                                       /* check Class2 Normal SMS is longer than SIM slot full size and send DeliveryReport SUCCESS because that Class2 msg cannot be saved on SIM
+                                        * It MUST be done before calling addClass2Message(thread) beause 10+ page message body ipc file is deleted after SmsPluginTransport::instance()->msgInfoToSubmitData() */
+                                       if (msgInfo.msgType.subType == MSG_NORMAL_SMS && msgInfo.msgType.classType == MSG_CLASS_2 &&
+                                               (SmsPluginSimMsg::instance()->checkSimMsgFull(msg.simIndex, segCnt) == true)) {
+                                               char keyName[MAX_VCONFKEY_NAME_LEN];
+                                               memset(keyName, 0x00, sizeof(keyName));
+                                               snprintf(keyName, sizeof(keyName), "%s/%d", SIM_TOTAL_COUNT, msg.simIndex);
+                                               int totalCnt = MsgSettingGetInt(keyName);
+
+                                               if (segCnt > totalCnt) {
+                                                       //send DeliveryResport as MSG_SUCCESS and return when total sim storage cnt is less than segment cnt.
+                                                       MSG_INFO("SIM slot total count [%d] is less than total sement count of Class2 message [%d], send delivery report as SUCCESS and save it only PHONE", totalCnt, segCnt);
+
+                                                       SmsPluginTransport::instance()->sendDeliverReport(handle, MSG_SUCCESS);
+
+                                                       MsgInsertTicker("Message is too large to store as a single message to SIM card.", SMS_MESSAGE_SIZE_OVER_SIM_SLOT_SIZE, false, 0);
+
+                                                       simSlotSizeOver = true;
+                                               }
+                                       } else {
+                                               err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
+                                       }
                                }
 
                                if (err == MSG_SUCCESS) {
-                                       /** Callback */
-                                       err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+                                       if (simSlotSizeOver || (msgInfo.msgType.classType != MSG_CLASS_2)) {
+                                               if (simSlotSizeOver)
+                                                       msgInfo.storageId = MSG_STORAGE_PHONE;
+
+                                               /** Callback */
+                                               err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
 
-                                       if (err != MSG_SUCCESS) {
-                                               MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+                                               if (err != MSG_SUCCESS) {
+                                                       MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+                                               }
                                        }
                                } else {
                                        MSG_DEBUG("addMessage() Error !! [%d]", err);
@@ -167,16 +225,393 @@ void SmsPluginConcatHandler::handleConcatMsg(SMS_TPDU_S *pTpdu)
                        }
                }
 
-               removeFromConcatList(msg.msgRef);
+               removeFromConcatList(msg.msgRef, msg.simIndex);
        }
 
        /** Send Deliver Report */
-       SmsPluginTransport::instance()->sendDeliverReport(err);
+       SmsPluginTransport::instance()->sendDeliverReport(handle, err);
+
+       MSG_END();
+}
+
+void SmsPluginConcatHandler::handleSimConcatMsg(struct tapi_handle *handle, SMS_TPDU_S *pTpdu, int msgId, int bRead, int *simIdList)
+{
+       MSG_BEGIN();
+
+       bool noneConcatTypeHeader = true;
+
+       if (pTpdu->tpduType == SMS_TPDU_DELIVER) {
+               SMS_CONCAT_MSG_S msg = {0};
+
+               msg.simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+               for (int i = 0; i < pTpdu->data.deliver.userData.headerCnt; i++) {
+                       if (pTpdu->data.deliver.userData.header[i].udhType == SMS_UDH_CONCAT_8BIT) {
+                               msg.msgRef = (unsigned short)pTpdu->data.deliver.userData.header[i].udh.concat8bit.msgRef;
+                               msg.totalSeg = pTpdu->data.deliver.userData.header[i].udh.concat8bit.totalSeg;
+                               msg.seqNum = pTpdu->data.deliver.userData.header[i].udh.concat8bit.seqNum;
+                               msg.simId = msgId;
+                               memcpy(&(msg.timeStamp.time.absolute), &(pTpdu->data.deliver.timeStamp.time.absolute), sizeof(SMS_TIME_ABS_S));
+                               memcpy(&(msg.originAddress), &(pTpdu->data.deliver.originAddress), sizeof(SMS_ADDRESS_S));
+                               memcpy(&(msg.dcs), &(pTpdu->data.deliver.dcs), sizeof(SMS_DCS_S));
+
+
+                               /**  check noneConcatTypeHeader */
+                               noneConcatTypeHeader = false;
+
+                               break;
+                       } else if (pTpdu->data.deliver.userData.header[i].udhType == SMS_UDH_CONCAT_16BIT) {
+                               msg.msgRef = (unsigned short)pTpdu->data.deliver.userData.header[i].udh.concat16bit.msgRef;
+                               msg.totalSeg = pTpdu->data.deliver.userData.header[i].udh.concat16bit.totalSeg;
+                               msg.seqNum = pTpdu->data.deliver.userData.header[i].udh.concat16bit.seqNum;
+                               msg.simId = msgId;
+                               memcpy(&(msg.timeStamp.time.absolute), &(pTpdu->data.deliver.timeStamp.time.absolute), sizeof(SMS_TIME_ABS_S));
+                               memcpy(&(msg.originAddress), &(pTpdu->data.deliver.originAddress), sizeof(SMS_ADDRESS_S));
+                               memcpy(&(msg.dcs), &(pTpdu->data.deliver.dcs), sizeof(SMS_DCS_S));
+
+                               /**  check noneConcatTypeHeader */
+                               noneConcatTypeHeader = false;
+
+                               break;
+                       }
+               }
+
+               unsigned char segCnt = checkConcatMsg(&msg, &(pTpdu->data.deliver.userData));
+               MSG_DEBUG("segCnt [%d]", segCnt);
+               MSG_DEBUG("msg.totalSeg [%d]", msg.totalSeg);
+
+               if ((segCnt == msg.totalSeg) || noneConcatTypeHeader) {
+                       MSG_DEBUG("RECEIVED LAST CONCAT : %d", segCnt);
+
+                       int dataSize = 0;
+                       char* pUserData = NULL;
+                       unique_ptr<char*, void(*)(char**)> dataBuf(&pUserData, unique_ptr_deleter);
+
+                       MSG_MESSAGE_INFO_S msgInfo = {0};
+
+                       msgInfo.addressList = NULL;
+                       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+                       msgInfo.sim_idx = msg.simIndex;
+
+                       dataSize = makeConcatUserData(msg.msgRef, msg.simIndex, &pUserData);
+
+                       if (dataSize > 0) {
+
+                               convertConcatToMsginfo(&(pTpdu->data.deliver), pUserData, dataSize, &msgInfo);
+                               // set Sim Message ID
+                               msgInfo.msgId = msgId;
+
+                               // set read status
+                               msgInfo.bRead = bRead;
+                               // set storage id
+                               msgInfo.storageId = MSG_STORAGE_SIM;
+                       }
+                       for (int index = concatList.size(); index >= 0 ; index--) {
+                               if (concatList[index].msgRef == msg.msgRef && concatList[index].simIndex == msg.simIndex) {
+                                       memcpy(simIdList, concatList[index].simIdList, sizeof(int) * MAX_SIM_SMS_NUM);
+                                       for (int i = 0; i < 255; ++i)
+                                       {
+                                               MSG_DEBUG("sim id [%d]", simIdList[i]);
+                                       }
+                                       break;
+                               }
+                       }
+                       removeFromConcatList(msg.msgRef, msg.simIndex);
+                       SmsPluginSimMsg::instance()->setSimMsgEvent(handle, &msgInfo, true); // Call Event Handler
+                       return;
+               }
+               SmsPluginSimMsg::instance()->setSimMsgEvent(handle, NULL, false); // Call Event Handler
+       } else {
+               SMS_CONCAT_MSG_S msg = {0};
+
+               msg.simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+               for (int i = 0; i < pTpdu->data.submit.userData.headerCnt; i++) {
+                       if (pTpdu->data.submit.userData.header[i].udhType == SMS_UDH_CONCAT_8BIT) {
+                               msg.msgRef = (unsigned short)pTpdu->data.submit.userData.header[i].udh.concat8bit.msgRef;
+                               msg.totalSeg = pTpdu->data.submit.userData.header[i].udh.concat8bit.totalSeg;
+                               msg.seqNum = pTpdu->data.submit.userData.header[i].udh.concat8bit.seqNum;
+                               msg.simId = msgId;
+                               memcpy(&(msg.originAddress), &(pTpdu->data.submit.destAddress), sizeof(SMS_ADDRESS_S));
+                               memcpy(&(msg.dcs), &(pTpdu->data.submit.dcs), sizeof(SMS_DCS_S));
+
+
+                               /**  check noneConcatTypeHeader */
+                               noneConcatTypeHeader = false;
+
+                               break;
+                       } else if (pTpdu->data.submit.userData.header[i].udhType == SMS_UDH_CONCAT_16BIT) {
+                               msg.msgRef = (unsigned short)pTpdu->data.submit.userData.header[i].udh.concat16bit.msgRef;
+                               msg.totalSeg = pTpdu->data.submit.userData.header[i].udh.concat16bit.totalSeg;
+                               msg.seqNum = pTpdu->data.submit.userData.header[i].udh.concat16bit.seqNum;
+                               msg.simId = msgId;
+                               memcpy(&(msg.originAddress), &(pTpdu->data.submit.destAddress), sizeof(SMS_ADDRESS_S));
+                               memcpy(&(msg.dcs), &(pTpdu->data.submit.dcs), sizeof(SMS_DCS_S));
+
+                               /**  check noneConcatTypeHeader */
+                               noneConcatTypeHeader = false;
+
+                               break;
+                       }
+               }
+
+               unsigned char segCnt = checkConcatMsg(&msg, &(pTpdu->data.submit.userData));
+
+               MSG_DEBUG("segCnt [%d]", segCnt);
+               MSG_DEBUG("msg.totalSeg [%d]", msg.totalSeg);
+
+               if ((segCnt == msg.totalSeg) || noneConcatTypeHeader) {
+                       MSG_DEBUG("RECEIVED LAST CONCAT : %d", segCnt);
+
+                       int dataSize = 0;
+                       char* pUserData = NULL;
+                       unique_ptr<char*, void(*)(char**)> dataBuf(&pUserData, unique_ptr_deleter);
+
+                       MSG_MESSAGE_INFO_S msgInfo = {0};
+
+                       msgInfo.addressList = NULL;
+                       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+                       msgInfo.sim_idx = msg.simIndex;
+
+                       dataSize = makeConcatUserData(msg.msgRef, msg.simIndex, &pUserData);
+
+                       if (dataSize > 0) {
+                               convertConcatToMsginfo(&(pTpdu->data.submit), pUserData, dataSize, &msgInfo);
+
+                               // set Sim Message ID
+                               msgInfo.msgId = msgId;
+                               // set read status
+                               msgInfo.bRead = bRead;
+
+                               msgInfo.msgType.subType = MSG_CONCAT_SIM_SMS;
+
+                               // set storage id
+                               msgInfo.storageId = MSG_STORAGE_SIM;
+                       }
+                       for (int index = concatList.size(); index >= 0 ; index--) {
+                               if (concatList[index].msgRef == msg.msgRef && concatList[index].simIndex == msg.simIndex) {
+                                       memcpy(simIdList, concatList[index].simIdList, sizeof(int) * MAX_SIM_SMS_NUM);
+                                       break;
+                               }
+                       }
+                       SmsPluginSimMsg::instance()->setSimMsgEvent(handle, &msgInfo, true); // Call Event Handler
+                       removeFromConcatList(msg.msgRef, msg.simIndex);
+                       return;
+               }
+               SmsPluginSimMsg::instance()->setSimMsgEvent(handle, NULL, false); // Call Event Handler
+       }
+
+       MSG_END();
+}
+
+#ifdef CONCAT_SIM_MSG_OPERATION
+void SmsPluginConcatHandler::handleConcatMsg(SMS_TPDU_S *pTpdu, msg_sim_id_t SimMsgId, bool bRead)
+{
+       MSG_BEGIN();
+
+       if (pTpdu->tpduType != SMS_TPDU_DELIVER)
+       {
+               MSG_DEBUG("The TPDU type is not deliver [%d]", pTpdu->tpduType);
+               return;
+       }
+
+       SMS_CONCAT_MSG_S msg;
+       memset(&msg, 0x00, sizeof(SMS_CONCAT_MSG_S));
+
+       for (int i = 0; i < pTpdu->data.deliver.userData.headerCnt; i++)
+       {
+               if (pTpdu->data.deliver.userData.header[i].udhType == SMS_UDH_CONCAT_8BIT)
+               {
+                       msg.msgRef = (unsigned short)pTpdu->data.deliver.userData.header[i].udh.concat8bit.msgRef;
+                       msg.totalSeg = pTpdu->data.deliver.userData.header[i].udh.concat8bit.totalSeg;
+                       msg.seqNum = pTpdu->data.deliver.userData.header[i].udh.concat8bit.seqNum;
+
+                       memcpy(&(msg.timeStamp.time.absolute), &(pTpdu->data.deliver.timeStamp.time.absolute), sizeof(SMS_TIME_ABS_S));
+                       memcpy(&(msg.originAddress), &(pTpdu->data.deliver.originAddress), sizeof(SMS_ADDRESS_S));
+                       memcpy(&(msg.dcs), &(pTpdu->data.deliver.dcs), sizeof(SMS_DCS_S));
+
+                       msg.bRead = bRead;
+
+                       if (msg.totalSeg > MAX_SEGMENT_NUM)
+                       {
+                               MSG_DEBUG("Total Segment Count is over Maximum [%d]", msg.totalSeg);
+                               return;
+                       }
+
+                       break;
+               }
+               else if (pTpdu->data.deliver.userData.header[i].udhType == SMS_UDH_CONCAT_16BIT)
+               {
+                       msg.msgRef = (unsigned short)pTpdu->data.deliver.userData.header[i].udh.concat16bit.msgRef;
+                       msg.totalSeg = pTpdu->data.deliver.userData.header[i].udh.concat16bit.totalSeg;
+                       msg.seqNum = pTpdu->data.deliver.userData.header[i].udh.concat16bit.seqNum;
+
+                       memcpy(&(msg.timeStamp.time.absolute), &(pTpdu->data.deliver.timeStamp.time.absolute), sizeof(SMS_TIME_ABS_S));
+                       memcpy(&(msg.originAddress), &(pTpdu->data.deliver.originAddress), sizeof(SMS_ADDRESS_S));
+                       memcpy(&(msg.dcs), &(pTpdu->data.deliver.dcs), sizeof(SMS_DCS_S));
+
+                       msg.bRead = bRead;
+
+                       if (msg.totalSeg > MAX_SEGMENT_NUM)
+                       {
+                               MSG_DEBUG("Total Segment Count is over Maximum [%d]", msg.totalSeg);
+                               return;
+                       }
+
+                       break;
+               }
+       }
+
+       unsigned char segCnt = checkConcatMsg(&msg, &(pTpdu->data.deliver.userData));
+
+       addToSimIdList(msg.msgRef, SimMsgId);
+
+       if (segCnt == msg.totalSeg)
+       {
+               MSG_DEBUG("RECEIVED LAST CONCAT : %d", segCnt);
+
+               int dataSize = 0;
+               char* pUserData = NULL;
+               unique_ptr<char*, void(*)(char**)> dataBuf(&pUserData, unique_ptr_deleter);
+
+               MSG_MESSAGE_INFO_S msgInfo = {0};
+
+               dataSize = makeConcatUserData(msg.msgRef, &pUserData);
+
+               if (dataSize >= 0)
+               {
+                       MSG_DEBUG("TOTAL DATA : %s", pUserData);
+
+                       convertSimMsgToMsginfo(&msg, pUserData, dataSize, &msgInfo);
+
+                       // set Sim Message ID
+                       msgInfo.msgId = SimMsgId;
+
+                       // set read status
+                       msgInfo.bRead = bRead;
+
+                       /// Print MSG_MESSAGE_INFO_S
+                       MSG_DEBUG("############# Convert  tpdu values to Message Info values ####################");
+
+                       MSG_DEBUG("msgInfo.msgId : %d", msgInfo.msgId);
+                       MSG_DEBUG("msgInfo.nAddressCnt : %d", msgInfo.nAddressCnt);
+                       MSG_DEBUG("msgInfo.addressList[0].addressType : %d", msgInfo.addressList[0].addressType);
+                       MSG_SEC_DEBUG("msgInfo.addressList[0].addressVal : %s", msgInfo.addressList[0].addressVal);
+                       MSG_DEBUG("msgInfo.priority : %d", msgInfo.priority);
+                       MSG_DEBUG("msgInfo.bProtected : %d", msgInfo.bProtected);
+                       MSG_DEBUG("msgInfo.bRead : %d", msgInfo.bRead);
+                       MSG_DEBUG("msgInfo.bTextSms : %d", msgInfo.bTextSms);
+                       MSG_DEBUG("msgInfo.direction : %d", msgInfo.direction);
+                       MSG_DEBUG("msgInfo.msgType.mainType : %d", msgInfo.msgType.mainType);
+                       MSG_DEBUG("msgInfo.msgType.subType : %d", msgInfo.msgType.subType);
+                       MSG_DEBUG("msgInfo.msgType.classType : %d", msgInfo.msgType.classType);
+                       MSG_DEBUG("msgInfo.displayTime : %s", ctime(&msgInfo.displayTime));
+                       MSG_DEBUG("msgInfo.dataSize : %d", msgInfo.dataSize);
+
+                       if (msgInfo.bTextSms == true)
+                               MSG_SEC_DEBUG("msgInfo.msgText : %s", msgInfo.msgText);
+                       else
+                               MSG_SEC_DEBUG("msgInfo.msgData : %s", msgInfo.msgData);
+
+                       MSG_DEBUG("###############################################################");
+
+                       // Remove from List
+                       removeFromConcatList(msg.msgRef);
+                       removeFromSimIdList(msg.msgRef);
+
+                       //add msgInfo to msg list
+                       SmsPluginStorage::instance()->addSimMsgToList(&msgInfo, true);
+
+                       // Callback to MSG FW
+                       SmsPluginEventHandler::instance()->callbackGetSimMsg();
+               }
+       }
+       else
+       {
+               //add index count to msg list
+               SmsPluginStorage::instance()->addSimMsgToList(NULL, false);
+
+               // Callback to MSG FW
+               SmsPluginEventHandler::instance()->callbackGetSimMsg();
+       }
 
        MSG_END();
 }
 
 
+void SmsPluginConcatHandler::handleBrokenMsg()
+{
+       if (concatList.size() <= 0 || simIdList.size() <= 0)
+       {
+               MSG_DEBUG("No Broken Concatenated Message");
+               return;
+       }
+
+       do
+       {
+               int index = 0, dataSize = 0;
+               char* pUserData = NULL;
+               unique_ptr<char*, void(*)(char**)> dataBuf(&pUserData, unique_ptr_deleter);
+
+               MSG_MESSAGE_INFO_S msgInfo = {0};
+
+               dataSize = makeConcatUserData(concatList[index].msgRef, &pUserData);
+
+               if (dataSize > 0)
+               {
+                       MSG_DEBUG("TOTAL DATA : %s", pUserData);
+
+                       SMS_CONCAT_MSG_S msg;
+                       memset(&msg, 0x00, sizeof(SMS_CONCAT_MSG_S));
+
+                       msg.msgRef = concatList[index].msgRef;
+                       msg.totalSeg = concatList[index].totalSeg;
+
+                       memcpy(&(msg.timeStamp.time.absolute), &(concatList[index].timeStamp.time.absolute), sizeof(SMS_TIME_ABS_S));
+                       memcpy(&(msg.originAddress), &(concatList[index].originAddress), sizeof(SMS_ADDRESS_S));
+                       memcpy(&(msg.dcs), &(concatList[index].dcs), sizeof(SMS_DCS_S));
+
+                       convertSimMsgToMsginfo(&msg, pUserData, dataSize, &msgInfo);
+
+                       // set Sim Message ID
+                       msgInfo.msgId = 0;
+
+                       // set read status
+                       msgInfo.bRead = concatList[index].bRead;
+
+                       /// Print MSG_MESSAGE_INFO_S
+                       MSG_DEBUG("############# Convert  tpdu values to Message Info values ####################");
+                       MSG_DEBUG("msgInfo.msgId : %d", msgInfo.msgId);
+                       MSG_DEBUG("msgInfo.nAddressCnt : %d", msgInfo.nAddressCnt);
+                       MSG_DEBUG("msgInfo.addressList[0].addressType : %d", msgInfo.addressList[0].addressType);
+                       MSG_SEC_DEBUG("msgInfo.addressList[0].addressVal : %s", msgInfo.addressList[0].addressVal);
+                       MSG_DEBUG("msgInfo.priority : %d", msgInfo.priority);
+                       MSG_DEBUG("msgInfo.bProtected : %d", msgInfo.bProtected);
+                       MSG_DEBUG("msgInfo.bRead : %d", msgInfo.bRead);
+                       MSG_DEBUG("msgInfo.bTextSms : %d", msgInfo.bTextSms);
+                       MSG_DEBUG("msgInfo.direction : %d", msgInfo.direction);
+                       MSG_DEBUG("msgInfo.msgType.mainType : %d", msgInfo.msgType.mainType);
+                       MSG_DEBUG("msgInfo.msgType.subType : %d", msgInfo.msgType.subType);
+                       MSG_DEBUG("msgInfo.msgType.classType : %d", msgInfo.msgType.classType);
+                       MSG_DEBUG("msgInfo.displayTime : %s", ctime(&msgInfo.displayTime));
+                       MSG_DEBUG("msgInfo.dataSize : %d", msgInfo.dataSize);
+                       if (msgInfo.bTextSms == true)
+                               MSG_SEC_DEBUG("msgInfo.msgText : %s", msgInfo.msgText);
+                       else
+                               MSG_SEC_DEBUG("msgInfo.msgData : %s", msgInfo.msgData);
+                       MSG_DEBUG("###############################################################");
+
+                       //add msgInfo to msg list
+                       SmsPluginStorage::instance()->addSimMsgToList(&msgInfo, true);
+               }
+
+               removeFromConcatList(concatList[index].msgRef);
+               removeFromSimIdList(concatList[index].msgRef);
+       }while (concatList.size() > 0);
+}
+#endif
+
+
 unsigned char SmsPluginConcatHandler::checkConcatMsg(SMS_CONCAT_MSG_S *pConcatMsg, SMS_USERDATA_S *pUserData)
 {
        if (pConcatMsg == NULL || pUserData == NULL) {
@@ -189,12 +624,11 @@ unsigned char SmsPluginConcatHandler::checkConcatMsg(SMS_CONCAT_MSG_S *pConcatMs
        bool bFind = false;
 
        for (unsigned int i = 0; i < concatList.size(); i++) {
-               if (concatList[i].msgRef == pConcatMsg->msgRef) {
+               if (concatList[i].msgRef == pConcatMsg->msgRef && concatList[i].simIndex == pConcatMsg->simIndex) {
                        if (concatList[i].data.count(pConcatMsg->seqNum) != 0) {
                                MSG_DEBUG("The Sequence Number already exists [%d]", pConcatMsg->seqNum);
                                return 0;
                        }
-
                        CONCAT_DATA_S concatData = {0};
 
                        memcpy(concatData.data, pUserData->data, pUserData->length);
@@ -202,13 +636,13 @@ unsigned char SmsPluginConcatHandler::checkConcatMsg(SMS_CONCAT_MSG_S *pConcatMs
 
                        pair<unsigned char, CONCAT_DATA_S> newData(pConcatMsg->seqNum, concatData);
                        concatList[i].data.insert(newData);
+                       concatList[i].simIdList[concatList[i].segCnt] = pConcatMsg->simId + 1;
 
                        MSG_DEBUG("MSG DATA : %s", pUserData->data);
                        MSG_DEBUG("PAIR DATA [%d] : %s", newData.first, newData.second.data);
 
                        concatList[i].segCnt++;
                        concatList[i].totalSize += pUserData->length;
-
                        currSegCnt = concatList[i].segCnt;
 
                        bFind = true;
@@ -220,16 +654,20 @@ unsigned char SmsPluginConcatHandler::checkConcatMsg(SMS_CONCAT_MSG_S *pConcatMs
        /** New Concat Msg */
        if (bFind == false) {
                SMS_CONCAT_INFO_S tmpInfo;
-
+               memset(tmpInfo.simIdList, 0x00, sizeof(int) * MAX_SIM_SMS_NUM);
                tmpInfo.msgRef = pConcatMsg->msgRef;
                tmpInfo.totalSeg = pConcatMsg->totalSeg;
                tmpInfo.segCnt = 1;
+               tmpInfo.simIdList[0] = pConcatMsg->simId + 1;
+               tmpInfo.simIndex = pConcatMsg->simIndex;
+               tmpInfo.bRead = false;
 
                memcpy(&(tmpInfo.timeStamp.time.absolute), &(pConcatMsg->timeStamp.time.absolute), sizeof(SMS_TIME_ABS_S));
                memcpy(&(tmpInfo.originAddress), &(pConcatMsg->originAddress), sizeof(SMS_ADDRESS_S));
                memcpy(&(tmpInfo.dcs), &(pConcatMsg->dcs), sizeof(SMS_DCS_S));
 
                tmpInfo.totalSize = pUserData->length;
+               tmpInfo.display_time = time(NULL);
 
                CONCAT_DATA_S concatData = {0};
 
@@ -251,14 +689,14 @@ unsigned char SmsPluginConcatHandler::checkConcatMsg(SMS_CONCAT_MSG_S *pConcatMs
 }
 
 
-int SmsPluginConcatHandler::makeConcatUserData(unsigned short MsgRef, char **ppTotalData)
+int SmsPluginConcatHandler::makeConcatUserData(unsigned short MsgRef, int simIndex, char **ppTotalData)
 {
        concatDataMap::iterator it;
 
        int totalSize = 0, offset = 0;
 
        for (unsigned int i = 0; i < concatList.size(); i++) {
-               if (concatList[i].msgRef == MsgRef) {
+               if (concatList[i].msgRef == MsgRef && concatList[i].simIndex == simIndex) {
                        totalSize = concatList[i].totalSize;
 
                        if (totalSize <= 0) {
@@ -285,11 +723,14 @@ void SmsPluginConcatHandler::convertConcatToMsginfo(const SMS_DELIVER_S *pTpdu,
 {
        /** Convert Type  values */
        pMsgInfo->msgType.mainType = MSG_SMS_TYPE;
-       pMsgInfo->msgType.subType = MSG_NORMAL_SMS;
+       pMsgInfo->msgType.subType = SmsPluginEventHandler::instance()->convertMsgSubType(pTpdu->pid);
 
-       /** set folder id (temporary) */
+       /** set folder id */
        pMsgInfo->folderId = MSG_INBOX_ID;
 
+       /** set storage id */
+       pMsgInfo->storageId = MSG_STORAGE_PHONE;
+
        switch(pTpdu->dcs.msgClass)
        {
                case SMS_MSG_CLASS_0:
@@ -306,6 +747,7 @@ void SmsPluginConcatHandler::convertConcatToMsginfo(const SMS_DELIVER_S *pTpdu,
                        break;
                default:
                        pMsgInfo->msgType.classType = MSG_CLASS_NONE;
+                       break;
        }
 
        pMsgInfo->networkStatus = MSG_NETWORK_RECEIVED;
@@ -317,10 +759,66 @@ void SmsPluginConcatHandler::convertConcatToMsginfo(const SMS_DELIVER_S *pTpdu,
 
        time_t rawtime = time(NULL);
 
+/*** Comment below lines to save local UTC time..... (it could be used later.)
+
+       if (pTpdu->timeStamp.format == SMS_TIME_ABSOLUTE) {
+
+               MSG_DEBUG("year : %d", pTpdu->timeStamp.time.absolute.year);
+               MSG_DEBUG("month : %d", pTpdu->timeStamp.time.absolute.month);
+               MSG_DEBUG("day : %d", pTpdu->timeStamp.time.absolute.day);
+               MSG_DEBUG("hour : %d", pTpdu->timeStamp.time.absolute.hour);
+               MSG_DEBUG("minute : %d", pTpdu->timeStamp.time.absolute.minute);
+               MSG_DEBUG("second : %d", pTpdu->timeStamp.time.absolute.second);
+               MSG_DEBUG("timezone : %d", pTpdu->timeStamp.time.absolute.timeZone);
+
+               char displayTime[32];
+               struct tm * timeTM;
+
+               struct tm timeinfo;
+               memset(&timeinfo, 0x00, sizeof(tm));
+
+               timeinfo.tm_year = (pTpdu->timeStamp.time.absolute.year + 100);
+               timeinfo.tm_mon = (pTpdu->timeStamp.time.absolute.month - 1);
+               timeinfo.tm_mday = pTpdu->timeStamp.time.absolute.day;
+               timeinfo.tm_hour = pTpdu->timeStamp.time.absolute.hour;
+               timeinfo.tm_min = pTpdu->timeStamp.time.absolute.minute;
+               timeinfo.tm_sec = pTpdu->timeStamp.time.absolute.second;
+               timeinfo.tm_isdst = 0;
+
+               rawtime = mktime(&timeinfo);
+
+               MSG_DEBUG("tzname[0] [%s]", tzname[0]);
+               MSG_DEBUG("tzname[1] [%s]", tzname[1]);
+               MSG_DEBUG("timezone [%d]", timezone);
+               MSG_DEBUG("daylight [%d]", daylight);
+
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", &timeinfo);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= (pTpdu->timeStamp.time.absolute.timeZone * (3600/4));
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= timezone;
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+       }
+
+***/
 
        pMsgInfo->displayTime = rawtime;
 
        /** Convert Address values */
+       pMsgInfo->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+       memset(pMsgInfo->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
        pMsgInfo->nAddressCnt = 1;
        pMsgInfo->addressList[0].addressType = MSG_ADDRESS_TYPE_PLMN;
        strncpy(pMsgInfo->addressList[0].addressVal, pTpdu->originAddress.address, MAX_ADDRESS_VAL_LEN);
@@ -342,44 +840,176 @@ void SmsPluginConcatHandler::convertConcatToMsginfo(const SMS_DELIVER_S *pTpdu,
                }
        }
 
-       int bufSize = (MAX_MSG_DATA_LEN*MAX_SEGMENT_NUM) + 1;
+       //int bufSize = (MAX_MSG_DATA_LEN*MAX_SEGMENT_NUM) + 1;
+       int bufSize = (DataSize*4) + 1; // For UTF8
 
        char tmpBuf[bufSize];
        memset(tmpBuf, 0x00, sizeof(tmpBuf));
 
        /** Convert Data values */
+       MsgTextConvert *textCvt = MsgTextConvert::instance();
        if (pTpdu->dcs.codingScheme == SMS_CHARSET_7BIT) {
-               SMS_LANG_INFO_S langInfo = {0};
+               MSG_LANG_INFO_S langInfo = {0,};
 
                langInfo.bSingleShift = false;
                langInfo.bLockingShift = false;
 
                pMsgInfo->encodeType = MSG_ENCODE_GSM7BIT;
-               pMsgInfo->dataSize = SmsPluginTextConvert::instance()->convertGSM7bitToUTF8((unsigned char*)tmpBuf, bufSize, (unsigned char*)pUserData, DataSize, &langInfo);
+               pMsgInfo->dataSize = textCvt->convertGSM7bitToUTF8((unsigned char*)tmpBuf, bufSize, (unsigned char*)pUserData, DataSize, &langInfo);
        } else if (pTpdu->dcs.codingScheme == SMS_CHARSET_8BIT) {
                pMsgInfo->encodeType = MSG_ENCODE_8BIT;
                memcpy(tmpBuf, pUserData, DataSize);
                pMsgInfo->dataSize = DataSize;
        } else if (pTpdu->dcs.codingScheme == SMS_CHARSET_UCS2) {
                pMsgInfo->encodeType = MSG_ENCODE_UCS2;
-               pMsgInfo->dataSize = SmsPluginTextConvert::instance()->convertUCS2ToUTF8((unsigned char*)tmpBuf, bufSize, (unsigned char*)pUserData, DataSize);
+               pMsgInfo->dataSize = textCvt->convertUCS2ToUTF8((unsigned char*)tmpBuf, bufSize, (unsigned char*)pUserData, DataSize);
        }
 
        MSG_DEBUG("Data Size [%d]", pMsgInfo->dataSize);
        MSG_DEBUG("Data [%s]", tmpBuf);
 
+#ifdef MSG_FW_FOR_DEBUG
+printf("\n");
+
+for (int i = 0; i < pMsgInfo->dataSize; i++)
+{
+       printf("[%02x]", tmpBuf[i]);
+}
+
+printf("\n");
+#endif
+
+       if (pMsgInfo->dataSize > MAX_MSG_TEXT_LEN) {
+               pMsgInfo->bTextSms = false;
+
+               /** Save Message Data into File */
+               char fileName[MSG_FILENAME_LEN_MAX+1];
+               memset(fileName, 0x00, sizeof(fileName));
+
+               if (MsgCreateFileName(fileName) == false)
+                       THROW(MsgException::FILE_ERROR, "########  MsgCreateFileName Fail !!! #######");
+
+               MSG_SEC_DEBUG("Save Message Data into file : size[%d] name[%s]\n", pMsgInfo->dataSize, fileName);
+               if (MsgWriteIpcFile(fileName, tmpBuf, pMsgInfo->dataSize) == false)
+                       THROW(MsgException::FILE_ERROR, "########  MsgWriteIpcFile Fail !!! #######");
+
+               strncpy(pMsgInfo->msgData, fileName, MAX_MSG_DATA_LEN);
+       } else {
+               pMsgInfo->bTextSms = true;
+
+               memset(pMsgInfo->msgText, 0x00, sizeof(pMsgInfo->msgText));
+               memcpy(pMsgInfo->msgText, tmpBuf, pMsgInfo->dataSize);
+       }
+}
+
+
+void SmsPluginConcatHandler::convertConcatToMsginfo(const SMS_SUBMIT_S *pTpdu, const char *pUserData, int DataSize, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       /** Convert Type  values */
+       pMsgInfo->msgType.mainType = MSG_SMS_TYPE;
+       pMsgInfo->msgType.subType = SmsPluginEventHandler::instance()->convertMsgSubType(pTpdu->pid);
+
+       /** set folder id */
+       pMsgInfo->folderId = MSG_INBOX_ID;
+
+       /** set storage id */
+       pMsgInfo->storageId = MSG_STORAGE_PHONE;
+
+       switch(pTpdu->dcs.msgClass)
+       {
+               case SMS_MSG_CLASS_0:
+                       pMsgInfo->msgType.classType = MSG_CLASS_0;
+                       break;
+               case SMS_MSG_CLASS_1:
+                       pMsgInfo->msgType.classType = MSG_CLASS_1;
+                       break;
+               case SMS_MSG_CLASS_2:
+                       pMsgInfo->msgType.classType = MSG_CLASS_2;
+                       break;
+               case SMS_MSG_CLASS_3:
+                       pMsgInfo->msgType.classType = MSG_CLASS_3;
+                       break;
+               default:
+                       pMsgInfo->msgType.classType = MSG_CLASS_NONE;
+                       break;
+       }
+
+       pMsgInfo->networkStatus = MSG_NETWORK_RECEIVED;
+       pMsgInfo->bRead = false;
+       pMsgInfo->bProtected = false;
+       pMsgInfo->priority = MSG_MESSAGE_PRIORITY_NORMAL;
+       pMsgInfo->direction = MSG_DIRECTION_TYPE_MT;
+
+
+       time_t rawtime = time(NULL);
+       pMsgInfo->displayTime = rawtime;
+
+       /** Convert Address values */
+       pMsgInfo->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+       memset(pMsgInfo->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+       pMsgInfo->nAddressCnt = 1;
+       pMsgInfo->addressList[0].addressType = MSG_ADDRESS_TYPE_PLMN;
+       strncpy(pMsgInfo->addressList[0].addressVal, pTpdu->destAddress.address, MAX_ADDRESS_VAL_LEN);
+
+       pMsgInfo->msgPort.valid = false;
+       pMsgInfo->msgPort.dstPort = 0;
+       pMsgInfo->msgPort.srcPort = 0;
+
+       for (int i = 0; i < pTpdu->userData.headerCnt; i++) {
+               /** Convert UDH values - Port Number */
+               if (pTpdu->userData.header[i].udhType == SMS_UDH_APP_PORT_8BIT) {
+                       pMsgInfo->msgPort.valid = true;
+                       pMsgInfo->msgPort.dstPort = pTpdu->userData.header[i].udh.appPort8bit.destPort;
+                       pMsgInfo->msgPort.srcPort = pTpdu->userData.header[i].udh.appPort8bit.originPort;
+               } else if (pTpdu->userData.header[i].udhType == SMS_UDH_APP_PORT_16BIT) {
+                       pMsgInfo->msgPort.valid = true;
+                       pMsgInfo->msgPort.dstPort = pTpdu->userData.header[i].udh.appPort16bit.destPort;
+                       pMsgInfo->msgPort.srcPort = pTpdu->userData.header[i].udh.appPort16bit.originPort;
+               }
+       }
+
+       //int bufSize = (MAX_MSG_DATA_LEN*MAX_SEGMENT_NUM) + 1;
+       int bufSize = (DataSize*4) + 1; // For UTF8
+
+       char tmpBuf[bufSize];
+       memset(tmpBuf, 0x00, sizeof(tmpBuf));
+
+       /** Convert Data values */
+       MsgTextConvert *textCvt = MsgTextConvert::instance();
+       if (pTpdu->dcs.codingScheme == SMS_CHARSET_7BIT) {
+               MSG_LANG_INFO_S langInfo = {0,};
+
+               langInfo.bSingleShift = false;
+               langInfo.bLockingShift = false;
+
+               pMsgInfo->encodeType = MSG_ENCODE_GSM7BIT;
+               pMsgInfo->dataSize = textCvt->convertGSM7bitToUTF8((unsigned char*)tmpBuf, bufSize, (unsigned char*)pUserData, DataSize, &langInfo);
+       } else if (pTpdu->dcs.codingScheme == SMS_CHARSET_8BIT) {
+               pMsgInfo->encodeType = MSG_ENCODE_8BIT;
+               memcpy(tmpBuf, pUserData, DataSize);
+               pMsgInfo->dataSize = DataSize;
+       } else if (pTpdu->dcs.codingScheme == SMS_CHARSET_UCS2) {
+               pMsgInfo->encodeType = MSG_ENCODE_UCS2;
+               pMsgInfo->dataSize = textCvt->convertUCS2ToUTF8((unsigned char*)tmpBuf, bufSize, (unsigned char*)pUserData, DataSize);
+       }
+
+       MSG_DEBUG("Data Size [%d]", pMsgInfo->dataSize);
+       MSG_DEBUG("Data [%s]", tmpBuf);
 
        if (pMsgInfo->dataSize > MAX_MSG_TEXT_LEN) {
                pMsgInfo->bTextSms = false;
 
                /** Save Message Data into File */
-               char fileName[MAX_COMMON_INFO_SIZE+1];
+               char fileName[MSG_FILENAME_LEN_MAX+1];
                memset(fileName, 0x00, sizeof(fileName));
 
-               MsgCreateFileName(fileName);
+               if (MsgCreateFileName(fileName) == false)
+                       THROW(MsgException::FILE_ERROR, "########  MsgCreateFileName Fail !!! #######");
 
-               MSG_DEBUG("Save Message Data into file : size[%d] name[%s]\n", pMsgInfo->dataSize, fileName);
-               MsgWriteIpcFile(fileName, tmpBuf, pMsgInfo->dataSize);
+               MSG_SEC_DEBUG("Save Message Data into file : size[%d] name[%s]\n", pMsgInfo->dataSize, fileName);
+               if (MsgWriteIpcFile(fileName, tmpBuf, pMsgInfo->dataSize) == false)
+                       THROW(MsgException::FILE_ERROR, "########  MsgWriteIpcFile Fail !!! #######");
 
                strncpy(pMsgInfo->msgData, fileName, MAX_MSG_DATA_LEN);
        } else {
@@ -390,14 +1020,208 @@ void SmsPluginConcatHandler::convertConcatToMsginfo(const SMS_DELIVER_S *pTpdu,
        }
 }
 
+#ifdef CONCAT_SIM_MSG_OPERATION
+void SmsPluginConcatHandler::convertSimMsgToMsginfo(const SMS_CONCAT_MSG_S *pConcatMsg, const char *pUserData, int DataSize, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       // Convert Type  values
+       pMsgInfo->msgType.mainType = MSG_SMS_TYPE;
+       pMsgInfo->msgType.subType = MSG_CONCAT_SIM_SMS;
+
+       // set folder id (temporary)
+       pMsgInfo->folderId = MSG_INBOX_ID;
+
+       pMsgInfo->storageId = MSG_STORAGE_SIM;
+
+       switch (pConcatMsg->dcs.msgClass)
+       {
+               case SMS_MSG_CLASS_0:
+                       pMsgInfo->msgType.classType = MSG_CLASS_0;
+                       break;
+               case SMS_MSG_CLASS_1:
+                       pMsgInfo->msgType.classType = MSG_CLASS_1;
+                       break;
+               case SMS_MSG_CLASS_2:
+                       pMsgInfo->msgType.classType = MSG_CLASS_2;
+                       break;
+               case SMS_MSG_CLASS_3:
+                       pMsgInfo->msgType.classType = MSG_CLASS_3;
+                       break;
+               default:
+                       pMsgInfo->msgType.classType = MSG_CLASS_NONE;
+       }
+
+       pMsgInfo->networkStatus = MSG_NETWORK_RECEIVED;
+       pMsgInfo->bRead = false;
+       pMsgInfo->bProtected = false;
+       pMsgInfo->priority = MSG_MESSAGE_PRIORITY_NORMAL;
+       pMsgInfo->direction = MSG_DIRECTION_TYPE_MT;
+
+       time_t rawtime = time(NULL);
+
+/*** Comment below lines to save local UTC time..... (it could be used later.)
+
+       if (pTpdu->timeStamp.format == SMS_TIME_ABSOLUTE) {
+
+               MSG_DEBUG("year : %d", pTpdu->timeStamp.time.absolute.year);
+               MSG_DEBUG("month : %d", pTpdu->timeStamp.time.absolute.month);
+               MSG_DEBUG("day : %d", pTpdu->timeStamp.time.absolute.day);
+               MSG_DEBUG("hour : %d", pTpdu->timeStamp.time.absolute.hour);
+               MSG_DEBUG("minute : %d", pTpdu->timeStamp.time.absolute.minute);
+               MSG_DEBUG("second : %d", pTpdu->timeStamp.time.absolute.second);
+               MSG_DEBUG("timezone : %d", pTpdu->timeStamp.time.absolute.timeZone);
+
+               char displayTime[32];
+               struct tm * timeTM;
+
+               struct tm timeinfo;
+               memset(&timeinfo, 0x00, sizeof(tm));
+
+               timeinfo.tm_year = (pTpdu->timeStamp.time.absolute.year + 100);
+               timeinfo.tm_mon = (pTpdu->timeStamp.time.absolute.month - 1);
+               timeinfo.tm_mday = pTpdu->timeStamp.time.absolute.day;
+               timeinfo.tm_hour = pTpdu->timeStamp.time.absolute.hour;
+               timeinfo.tm_min = pTpdu->timeStamp.time.absolute.minute;
+               timeinfo.tm_sec = pTpdu->timeStamp.time.absolute.second;
+               timeinfo.tm_isdst = 0;
+
+               rawtime = mktime(&timeinfo);
+
+               MSG_DEBUG("tzname[0] [%s]", tzname[0]);
+               MSG_DEBUG("tzname[1] [%s]", tzname[1]);
+               MSG_DEBUG("timezone [%d]", timezone);
+               MSG_DEBUG("daylight [%d]", daylight);
+
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", &timeinfo);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+               rawtime -= (pTpdu->timeStamp.time.absolute.timeZone * (3600/4));
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= timezone;
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+       }
+
+***/
+
+       pMsgInfo->displayTime = rawtime;
+
+       // Convert Address values
+       pMsgInfo->nAddressCnt = 1;
+       pMsgInfo->addressList[0].addressType = MSG_ADDRESS_TYPE_PLMN;
+       strncpy(pMsgInfo->addressList[0].addressVal, pConcatMsg->originAddress.address, MAX_ADDRESS_VAL_LEN);
+
+       pMsgInfo->msgPort.valid = false;
+       pMsgInfo->msgPort.dstPort = 0;
+       pMsgInfo->msgPort.srcPort = 0;
+
+       // Insert SMS_CONCAT_SIM_MSG_S into File
+       SMS_CONCAT_SIM_MSG_S concatSimMsg = {0};
+
+       for (unsigned int i = 0; i < simIdList.size(); i++)
+       {
+               if (simIdList[i].msgRef == pConcatMsg->msgRef)
+               {
+                       MSG_DEBUG("Get SIM ID [%d] - List Index [%d]", simIdList[i].simId, concatSimMsg.simIdCnt);
+
+                       concatSimMsg.simIdList[concatSimMsg.simIdCnt] = simIdList[i].simId;
+                       concatSimMsg.simIdCnt++;
+               }
+       }
+
+       int bufSize = (MAX_MSG_DATA_LEN*MAX_SEGMENT_NUM) + 1;
+
+       char tmpBuf[bufSize];
+       memset(tmpBuf, 0x00, sizeof(tmpBuf));
+
+       // Convert Data values
+       if (pConcatMsg->dcs.codingScheme == SMS_CHARSET_7BIT)
+       {
+               SMS_LANG_INFO_S langInfo = {0};
+
+               langInfo.bSingleShift = false;
+               langInfo.bLockingShift = false;
+
+               pMsgInfo->encodeType = MSG_ENCODE_GSM7BIT;
+               pMsgInfo->dataSize = SmsPluginTextConvert::instance()->convertGSM7bitToUTF8((unsigned char*)tmpBuf, bufSize, (unsigned char*)pUserData, DataSize, &langInfo);
+       }
+       else if (pConcatMsg->dcs.codingScheme == SMS_CHARSET_8BIT)
+       {
+               pMsgInfo->encodeType = MSG_ENCODE_8BIT;
+               memcpy(tmpBuf, pUserData, DataSize);
+               pMsgInfo->dataSize = DataSize;
+       }
+       else if (pConcatMsg->dcs.codingScheme == SMS_CHARSET_UCS2)
+       {
+               pMsgInfo->encodeType = MSG_ENCODE_UCS2;
+               pMsgInfo->dataSize = SmsPluginTextConvert::instance()->convertUCS2ToUTF8((unsigned char*)tmpBuf, bufSize, (unsigned char*)pUserData, DataSize);
+       }
+
+       MSG_DEBUG("Data Size [%d]", pMsgInfo->dataSize);
+
+       pMsgInfo->bTextSms = false;
+
+       if (pMsgInfo->dataSize > 0)
+               memcpy(concatSimMsg.msgData, tmpBuf, pMsgInfo->dataSize);
+
+       // Save Message Data into File
+       char fileName[MAX_COMMON_INFO_SIZE+1];
+       memset(fileName, 0x00, sizeof(fileName));
+
+       if (MsgCreateFileName(fileName) == false)
+               THROW(MsgException::FILE_ERROR, "MsgCreateFileName error");
+
+       if (MsgWriteIpcFile(fileName, (char*)(&concatSimMsg), sizeof(SMS_CONCAT_SIM_MSG_S)) == false)
+               THROW(MsgException::FILE_ERROR, "MsgWriteIpcFile error");
+
+       memset(pMsgInfo->msgData, 0x00, sizeof(pMsgInfo->msgData));
+       strncpy(pMsgInfo->msgData, fileName, MAX_MSG_DATA_LEN);
+
+       MSG_SEC_DEBUG("Save Message Data into file : size[%d] name[%s]", pMsgInfo->dataSize, fileName);
+}
+#endif
+
 
-void SmsPluginConcatHandler::removeFromConcatList(unsigned short MsgRef)
+void SmsPluginConcatHandler::removeFromConcatList(unsigned short MsgRef, int simIndex)
 {
-       for (int index = concatList.size(); index >= 0 ; index--) {
-               if (concatList[index].msgRef == MsgRef) {
+       for (int index = concatList.size()-1; index >= 0 ; index--) {
+               if (concatList[index].msgRef == MsgRef && concatList[index].simIndex == simIndex) {
                        MSG_DEBUG("remove concatlist of the index [%d]", index);
                        concatList.erase(concatList.begin()+index);
                        break;
                }
        }
 }
+
+#ifdef CONCAT_SIM_MSG_OPERATION
+void SmsPluginConcatHandler::addToSimIdList(unsigned short MsgRef, msg_sim_id_t SimMsgId)
+{
+       SMS_SIM_ID_S simIdStruct;
+
+       simIdStruct.msgRef = MsgRef;
+       simIdStruct.simId = SimMsgId;
+
+       simIdList.push_back(simIdStruct);
+}
+
+
+void SmsPluginConcatHandler::removeFromSimIdList(unsigned short MsgRef)
+{
+       for (int index = simIdList.size()-1; index >= 0 ; index--)
+       {
+               if (simIdList[index].msgRef == MsgRef)
+               {
+                       MSG_DEBUG("remove simIdList of the index [%d]", index);
+
+                       simIdList.erase(simIdList.begin()+index);
+               }
+       }
+}
+#endif
diff --git a/plugin/sms_plugin/SmsPluginDSHandler.cpp b/plugin/sms_plugin/SmsPluginDSHandler.cpp
new file mode 100755 (executable)
index 0000000..f064b0d
--- /dev/null
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include <errno.h>
+#include "MsgDebug.h"
+#include "MsgException.h"
+#include "SmsPluginDSHandler.h"
+#include "MsgGconfWrapper.h"
+
+extern "C"
+{
+       #include <tapi_common.h>
+       #include <TelNetwork.h>
+       #include <ITapiNetwork.h>
+       #include <ITapiSim.h>
+       #include <telephony_common.h>
+       #include <telephony_sim.h>
+}
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginCbMsgHandler - Member Functions
+==================================================================================================*/
+SmsPluginDSHandler* SmsPluginDSHandler::pInstance = NULL;
+
+
+SmsPluginDSHandler::SmsPluginDSHandler()
+{
+       cp_list = NULL;
+       memset(&handle_list, 0x00, sizeof(handle_list));
+}
+
+
+SmsPluginDSHandler::~SmsPluginDSHandler()
+{
+}
+
+
+SmsPluginDSHandler* SmsPluginDSHandler::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginDSHandler();
+
+       return pInstance;
+}
+
+int SmsPluginDSHandler::initTelHandle()
+{
+       int cnt = 0;
+       cp_list = tel_get_cp_name_list();
+
+       if (!cp_list) {
+               MSG_FATAL("tel_get_cp_name_list returns null");
+               goto FINISH;
+       }
+
+       while(cp_list[cnt] && cnt < MAX_TELEPHONY_HANDLE_CNT)
+       {
+               MSG_SEC_INFO("cp_list[%d]:[%s]", cnt, cp_list[cnt]);
+               handle_list.handle[cnt]= tel_init(cp_list[cnt]);
+               cnt++;
+       }
+
+       g_strfreev(cp_list);
+
+FINISH:
+       handle_list.count = cnt;
+       return cnt;
+}
+
+void SmsPluginDSHandler::deinitTelHandle()
+{
+       int ret = 0;
+
+       for (int i = 0; i < handle_list.count; i++)
+       {
+               ret = tel_deinit(handle_list.handle[i]);
+               MSG_DEBUG("tel_deinit ret=[%d]", ret);
+               handle_list.handle[i] = NULL;
+       }
+
+       handle_list.count = 0;
+       cp_list = NULL;
+
+       return;
+}
+
+struct tapi_handle *SmsPluginDSHandler::getTelHandle(int sim_idx)
+{
+       if (sim_idx > 0 && sim_idx < MAX_TELEPHONY_HANDLE_CNT)
+               return handle_list.handle[sim_idx-1];
+       else {
+               int SIM_Status = 0;
+               SIM_Status = MsgSettingGetInt(VCONFKEY_TELEPHONY_SIM_SLOT);
+               if (SIM_Status == 1) {
+                       return handle_list.handle[0];
+               }
+
+               SIM_Status = MsgSettingGetInt(VCONFKEY_TELEPHONY_SIM_SLOT2);
+               if (SIM_Status == 1) {
+                       return handle_list.handle[1];
+               }
+       }
+
+       return handle_list.handle[handle_list.count - 1];
+}
+
+int SmsPluginDSHandler::getSimIndex(struct tapi_handle *handle)
+{
+       for(int index=0; index < handle_list.count; ++index)
+       {
+               if(handle_list.handle[index] == handle)
+                       return index+1;
+       }
+       return 0;
+}
+
+
+void SmsPluginDSHandler::getDefaultNetworkSimId(int *simId)
+{
+       TelNetworkDefaultDataSubs_t defaultSimId;
+
+       int tapi_ret = TAPI_API_SUCCESS;
+
+       if (handle_list.count == 1) {
+               *simId = 1;
+               return;
+       }
+
+       tapi_ret = tel_get_network_default_data_subscription(handle_list.handle[0], &defaultSimId);
+
+       MSG_INFO("Default network subscription = [SIM %d]", (int)defaultSimId+1);
+
+       if (tapi_ret != TAPI_API_SUCCESS) {
+               *simId = 0;
+               THROW(MsgException::SMS_PLG_ERROR, "########  tel_get_network_default_data_subscription Fail !!! return : %d #######", tapi_ret);
+       } else {
+               *simId = (int)defaultSimId + 1;
+       }
+}
+
+
+int SmsPluginDSHandler::getTelHandleCount()
+{
+       return handle_list.count;
+}
+
+int SmsPluginDSHandler::getActiveSimCount()
+{
+       int active_count = 0;
+       int sim_status = VCONFKEY_TELEPHONY_SIM_UNKNOWN;
+
+       sim_status = MsgSettingGetInt(VCONFKEY_TELEPHONY_SIM_SLOT);
+       MSG_DEBUG("sim1 status : %d", sim_status);
+       if (sim_status == VCONFKEY_TELEPHONY_SIM_INSERTED)
+               active_count++;
+
+       sim_status = VCONFKEY_TELEPHONY_SIM_UNKNOWN;
+       sim_status = MsgSettingGetInt(VCONFKEY_TELEPHONY_SIM_SLOT2);
+
+       MSG_DEBUG("sim2 status : %d", sim_status);
+       if (sim_status == VCONFKEY_TELEPHONY_SIM_INSERTED)
+               active_count++;
+
+       MSG_DEBUG("active sim count : %d", active_count);
+
+       return active_count;
+}
index 20761af..dbaf933 100755 (executable)
@@ -1,33 +1,39 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-#include<time.h>
-#include<stdio.h>
-#include<stdlib.h>
+#include <time.h>
+#include <stdio.h>
+#include <stdlib.h>
 #include <errno.h>
 
 #include "MsgDebug.h"
 #include "MsgUtilFile.h"
+#include "MsgCppTypes.h"
+#include "MsgContact.h"
 #include "MsgGconfWrapper.h"
-#include "SmsPluginTextConvert.h"
+#include "MsgNotificationWrapper.h"
+#include "MsgDevicedWrapper.h"
 #include "SmsPluginTransport.h"
 #include "SmsPluginSimMsg.h"
 #include "SmsPluginStorage.h"
+#include "SmsPluginSetting.h"
 #include "SmsPluginConcatHandler.h"
 #include "SmsPluginEventHandler.h"
+#include "SmsPluginDSHandler.h"
+
 
 /*==================================================================================================
                                      IMPLEMENTATION OF SmsPluginEventHandler - Member Functions
@@ -39,9 +45,13 @@ SmsPluginEventHandler::SmsPluginEventHandler()
 {
        /**  Initialize global parameters */
        memset(&listener, 0x00, sizeof(MSG_PLUGIN_LISTENER_S));
+       memset(&sentInfo, 0x00, sizeof(SMS_SENT_INFO_S));
 
        pSimCnt = NULL;
        devStatus = false;
+       bUdhMwiMethod = false;
+       udhMwiCnt = 0;
+       devHandle = NULL;
 }
 
 
@@ -70,13 +80,21 @@ void SmsPluginEventHandler::handleSentStatus(msg_network_status_t NetStatus)
 {
        MSG_DEBUG("NetStatus[%d]", NetStatus);
 
-       SmsPluginTransport::instance()->setNetStatus(NetStatus);
-
        if (sentInfo.bLast == true || NetStatus != MSG_NETWORK_SEND_SUCCESS) {
                /** Update Msg Status */
-               if (sentInfo.reqInfo.msgInfo.msgPort.valid == false){
-                       SmsPluginStorage::instance()->updateSentMsg(&(sentInfo.reqInfo.msgInfo), NetStatus);
+               if (sentInfo.reqInfo.msgInfo.msgPort.valid == false) {
+//                     SmsPluginStorage::instance()->updateSentMsg(&(sentInfo.reqInfo.msgInfo), NetStatus);
+
                        sentInfo.reqInfo.msgInfo.networkStatus = NetStatus;
+
+                       if (NetStatus == MSG_NETWORK_SEND_SUCCESS) {
+                               MSG_DEBUG("Add phone log");
+                               MsgAddPhoneLog(&(sentInfo.reqInfo.msgInfo));
+                               sentInfo.reqInfo.msgInfo.folderId = MSG_SENTBOX_ID; // It should be set after adding phone log.
+                       } else {
+                               sentInfo.reqInfo.msgInfo.bRead = false;
+                       }
+
                        callbackStorageChange(MSG_STORAGE_CHANGE_UPDATE, &(sentInfo.reqInfo.msgInfo));
                }
 
@@ -84,7 +102,7 @@ void SmsPluginEventHandler::handleSentStatus(msg_network_status_t NetStatus)
                MSG_DEBUG("sentInfo.reqInfo.sendOptInfo.bKeepCopy [%d]", sentInfo.reqInfo.sendOptInfo.bKeepCopy);
                /** Check sending options */
                if (sentInfo.reqInfo.sendOptInfo.bSetting && !sentInfo.reqInfo.sendOptInfo.bKeepCopy && NetStatus == MSG_NETWORK_SEND_SUCCESS) {
-                       SmsPluginStorage::instance()->deleteSmsMessage(sentInfo.reqInfo.msgInfo.msgId);
+//                     SmsPluginStorage::instance()->deleteSmsMessage(sentInfo.reqInfo.msgInfo.msgId);
                        callbackStorageChange(MSG_STORAGE_CHANGE_DELETE, &(sentInfo.reqInfo.msgInfo));
                }
 
@@ -102,90 +120,255 @@ void SmsPluginEventHandler::handleSentStatus(msg_network_status_t NetStatus)
 }
 
 
-void SmsPluginEventHandler::handleMsgIncoming(SMS_TPDU_S *pTpdu)
+void SmsPluginEventHandler::handleMsgIncoming(struct tapi_handle *handle, SMS_TPDU_S *pTpdu)
 {
+
        /** Make MSG_MESSAGE_INFO_S */
        MSG_MESSAGE_INFO_S msgInfo;
 
        /** initialize msgInfo */
        memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
 
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+
+       if (pTpdu->tpduType == SMS_TPDU_DELIVER) {
+               /** check unsupported message */
+               if (pTpdu->data.deliver.dcs.codingScheme == SMS_CHARSET_8BIT && pTpdu->data.deliver.pid == 0x11) {
+                       MSG_DEBUG("Unsupported message!!");
+                       SmsPluginTransport::instance()->sendDeliverReport(handle, MSG_SUCCESS);
+                       return;
+               }
+       }
+
+       bUdhMwiMethod = false;
+       udhMwiCnt = 0;
+
+       if(pTpdu->data.deliver.dcs.msgClass == SMS_MSG_CLASS_2)
+               msgInfo.storageId = MSG_STORAGE_UNKNOWN;
+       else
+               msgInfo.storageId = MSG_STORAGE_PHONE;
+
+       msgInfo.sim_idx = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
        /** convert to msgInfo */
        convertTpduToMsginfo(pTpdu, &msgInfo);
 
+       if (msgInfo.msgPort.valid == true) {
+               if ((msgInfo.msgPort.dstPort >= 0x23F4 && msgInfo.msgPort.dstPort <= 0x23F7) || /** Check unsupported message (Vcard WAP push) **/
+                       (msgInfo.msgPort.dstPort == 0x1581)) { /** Check unsupported message (ringtone smart message) **/
+                       memset(msgInfo.msgText, 0x00, sizeof(msgInfo.msgText));
+                       snprintf(msgInfo.msgText, sizeof(msgInfo.msgText), "<Unsupported message>");
+                       msgInfo.dataSize = strlen(msgInfo.msgText);
+                       msgInfo.msgPort.valid = false;
+               }
+       }
+
+       if (bUdhMwiMethod == false) {
+               /** check MWI and set info to SIM for DCS & Address method */
+               if (pTpdu->tpduType == SMS_TPDU_DELIVER && pTpdu->data.deliver.dcs.bMWI == true) {
+                       MSG_DEBUG("MWI message - DCS method");
+
+                       if (pTpdu->data.deliver.dcs.bIndActive == false) {
+                               SmsPluginSetting::instance()->setMwiInfo(msgInfo.sim_idx, msgInfo.msgType.subType, 0);
+                               SmsPluginTransport::instance()->sendDeliverReport(handle, MSG_SUCCESS);
+                               return;
+                       } else {
+                               SmsPluginSetting::instance()->setMwiInfo(msgInfo.sim_idx, msgInfo.msgType.subType, 1);
+
+                               /* For address method */
+                               if (pTpdu->data.deliver.pid == 0x20 && pTpdu->data.deliver.originAddress.ton == SMS_TON_ALPHANUMERIC) {
+                                       MSG_DEBUG("MWI message - Address method");
+                                       char *voiceNumber = NULL;
+                                       char *voiceAlphaId = NULL;
+                                       char keyName[MAX_VCONFKEY_NAME_LEN];
+
+                                       memset(keyName, 0x00, sizeof(keyName));
+                                       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_NUMBER, msgInfo.sim_idx);
+                                       voiceNumber = MsgSettingGetString(keyName);
+
+                                       memset(keyName, 0x00, sizeof(keyName));
+                                       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_ALPHA_ID, msgInfo.sim_idx);
+                                       voiceAlphaId = MsgSettingGetString(keyName);
+
+                                       memset(msgInfo.addressList[0].addressVal, 0x00, sizeof(msgInfo.addressList[0].addressVal));
+                                       memset(msgInfo.addressList[0].displayName, 0x00, sizeof(msgInfo.addressList[0].displayName));
+
+                                       if (voiceNumber) {
+                                               snprintf(msgInfo.addressList[0].addressVal, sizeof(msgInfo.addressList[0].addressVal), "%s", voiceNumber);
+                                               free(voiceNumber);
+                                               voiceNumber = NULL;
+                                       }
+
+                                       if (voiceAlphaId) {
+                                               snprintf(msgInfo.addressList[0].displayName, sizeof(msgInfo.addressList[0].displayName), "%s", voiceAlphaId);
+                                               free(voiceAlphaId);
+                                               voiceAlphaId = NULL;
+                                       }
+
+                                       memset(msgInfo.msgText, 0x00, sizeof(msgInfo.msgText));
+                                       snprintf(msgInfo.msgText, sizeof(msgInfo.msgText), "New voice message");
+
+                               }
+                       }
+
+                       if (pTpdu->data.deliver.dcs.codingGroup == SMS_GROUP_DISCARD)
+                               msgInfo.bStore = false;
+               }
+       } else {
+               MSG_DEBUG("MWI message - UDH method");
+               if (udhMwiCnt <= 0) {
+                       MSG_DEBUG("MWI count is 0");
+                       SmsPluginSetting::instance()->setMwiInfo(msgInfo.sim_idx, msgInfo.msgType.subType, 0);
+                       SmsPluginTransport::instance()->sendDeliverReport(handle, MSG_SUCCESS);
+                       return;
+               }
+       }
+
        /** Short Message Type 0 - Just Send Deliver Report */
        if (msgInfo.msgType.subType == MSG_TYPE0_SMS) {
-               SmsPluginTransport::instance()->sendDeliverReport(MSG_SUCCESS);
+               SmsPluginTransport::instance()->sendDeliverReport(handle, MSG_SUCCESS);
                return;
        }
 
        /** Print MSG_MESSAGE_INFO_S */
        MSG_DEBUG("############# Convert  tpdu values to Message Info values ####################");
        MSG_DEBUG("msgInfo.nAddressCnt : %d", msgInfo.nAddressCnt);
-       MSG_DEBUG("msgInfo.addressList[0].addressType : %d", msgInfo.addressList[0].addressType);
-       MSG_DEBUG("msgInfo.addressList[0].addressVal : %s", msgInfo.addressList[0].addressVal);
+       if (msgInfo.nAddressCnt > 0) {
+               MSG_DEBUG("msgInfo.addressList[0].addressType : %d", msgInfo.addressList[0].addressType);
+               MSG_SEC_DEBUG("msgInfo.addressList[0].addressVal : %s", msgInfo.addressList[0].addressVal);
+               MSG_SEC_DEBUG("msgInfo.addressList[0].displayName : %s", msgInfo.addressList[0].displayName);
+       }
        MSG_DEBUG("msgInfo.priority : %d", msgInfo.priority);
        MSG_DEBUG("msgInfo.bProtected : %d", msgInfo.bProtected);
        MSG_DEBUG("msgInfo.bRead : %d", msgInfo.bRead);
        MSG_DEBUG("msgInfo.bTextSms : %d", msgInfo.bTextSms);
+       MSG_DEBUG("msgInfo.bStore : %d", msgInfo.bStore);
        MSG_DEBUG("msgInfo.direction : %d", msgInfo.direction);
        MSG_DEBUG("msgInfo.msgType.mainType : %d", msgInfo.msgType.mainType);
        MSG_DEBUG("msgInfo.msgType.subType : %d", msgInfo.msgType.subType);
        MSG_DEBUG("msgInfo.msgType.classType : %d", msgInfo.msgType.classType);
-       MSG_DEBUG("msgInfo.displayTime : %s", ctime(&msgInfo.displayTime));
+       MSG_DEBUG("msgInfo.displayTime : %d", msgInfo.displayTime);
        MSG_DEBUG("msgInfo.msgPort.valid : %d", msgInfo.msgPort.valid);
        MSG_DEBUG("msgInfo.encodeType : %d", msgInfo.encodeType);
        MSG_DEBUG("msgInfo.dataSize : %d", msgInfo.dataSize);
+       MSG_DEBUG("msgInfo.sim_idx : %d", msgInfo.sim_idx);
 
        if (msgInfo.bTextSms == true) {
-               MSG_DEBUG("msgInfo.msgText : %s", msgInfo.msgText);
+               MSG_SEC_DEBUG("msgInfo.msgText : %s", msgInfo.msgText);
        } else {
-               MSG_DEBUG("msgInfo.msgData : %s", msgInfo.msgData);
+               MSG_SEC_DEBUG("msgInfo.msgData : %s", msgInfo.msgData);
        }
 
        MSG_DEBUG("###############################################################");
 
        msg_error_t err = MSG_SUCCESS;
 
-       /** Update Status in Report Table */
        if (msgInfo.msgType.subType == MSG_STATUS_REPORT_SMS) {
-               err = SmsPluginStorage::instance()->addMessage(&msgInfo);
+               /** Status Report Message */
+               err = SmsPluginStorage::instance()->updateMsgDeliverStatus(&msgInfo, pTpdu->data.statusRep.msgRef);
 
-               if (err == MSG_SUCCESS) {
-                       MSG_DEBUG("callback to msg fw");
+               if (err == MSG_SUCCESS)
                        err = listener.pfMsgIncomingCb(&msgInfo);
-               }
+               else
+                       MSG_DEBUG("updateMsgDeliverStatus is failed [%d]", err);
 
                /** Handling of Fail Case ?? */
-               SmsPluginTransport::instance()->sendDeliverReport(MSG_SUCCESS);
+               SmsPluginTransport::instance()->sendDeliverReport(handle, MSG_SUCCESS);
        } else { /** SMS Deliver */
                /** Class 2 Msg */
                if (msgInfo.msgType.classType == MSG_CLASS_2) {
                        if (msgInfo.bTextSms == false) { /** Concat Msg cannot be saved in SIM */
                                msgInfo.msgType.classType = MSG_CLASS_NONE;
                                msgInfo.storageId = MSG_STORAGE_PHONE;
+                       } else {
+                               /** set total segment of Class2 message as 1 */
+                               SmsPluginSimMsg::instance()->setSmsTpduTotalSegCount(1);
                        }
                }
 
+               /** Add message to DB */
                if (msgInfo.msgPort.valid == false) {
-                       err = SmsPluginStorage::instance()->addMessage(&msgInfo);
+                       err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
                }
 
                /** Callback to MSG FW */
-               if (msgInfo.msgType.classType != MSG_CLASS_2) {
+               if (msgInfo.msgType.classType == MSG_CLASS_2) {
+                       if (((msgInfo.msgType.subType >= MSG_MWI_VOICE_SMS) && (msgInfo.msgType.subType <= MSG_MWI_OTHER_SMS)) &&
+                                       (msgInfo.bStore == false)) {
+                               if (listener.pfMsgIncomingCb(&msgInfo) != MSG_SUCCESS)
+                                       MSG_DEBUG("listener.pfMsgIncomingCb is failed!");
+
+                               SmsPluginTransport::instance()->sendDeliverReport(handle, MSG_SUCCESS);
+                       }
+               } else {
                        if (err == MSG_SUCCESS) {
                                MSG_DEBUG("callback to msg fw");
                                err = listener.pfMsgIncomingCb(&msgInfo);
+                       } else {
+                               if (msgInfo.msgType.classType == MSG_CLASS_0) {
+                                       MSG_DEBUG("callback for class0 message to msg fw");
+                                       if (listener.pfMsgIncomingCb(&msgInfo) != MSG_SUCCESS)
+                                               MSG_DEBUG("listener.pfMsgIncomingCb is failed!");
+                               }
                        }
 
                        /** Send Deliver Report */
-                       SmsPluginTransport::instance()->sendDeliverReport(err);
+                       if (msgInfo.msgType.classType == MSG_CLASS_0)
+                               SmsPluginTransport::instance()->sendClass0DeliverReport(handle, err);
+                       else
+                               SmsPluginTransport::instance()->sendDeliverReport(handle, err);
+               }
+
+               // Tizen Validation System
+               char *msisdn = NULL;
+               char keyName[MAX_VCONFKEY_NAME_LEN];
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_MSISDN, msgInfo.sim_idx);
+               msisdn = MsgSettingGetString(keyName);
+
+               MSG_SMS_VLD_INFO("%d, SMS Receive, %s->%s, %s",  msgInfo.msgId, \
+                                                                                                                               msgInfo.addressList[0].addressVal, \
+                                                                                                                               (msisdn == NULL)?"ME":msisdn, \
+                                                                                                                               (err == MSG_SUCCESS)?"Success":"Fail");
+
+               MSG_SMS_VLD_TXT("%d, [%s]", msgInfo.msgId, msgInfo.msgText);
+
+               if (msisdn) {
+                       free(msisdn);
+                       msisdn = NULL;
                }
        }
 }
 
+void SmsPluginEventHandler::handlePushMsgIncoming(char* pPushHeader, char* pPushBody, int pushBodyLen, char *application_id, char *content_type)
+{
+       MSG_PUSH_MESSAGE_DATA_S pushData;
 
-void SmsPluginEventHandler::handleSyncMLMsgIncoming(msg_syncml_message_type_t msgType, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen)
+       memset(&pushData, 0x00, sizeof(MSG_PUSH_MESSAGE_DATA_S));
+
+       /** set PUSH data */
+       memcpy(pushData.pushHeader, pPushHeader, strlen(pPushHeader));
+
+       pushData.pushBodyLen = pushBodyLen;
+       memcpy(pushData.pushBody, pPushBody, pushBodyLen);
+
+       memcpy(pushData.pushAppId, application_id, MAX_WAPPUSH_ID_LEN);
+       memcpy(pushData.pushContentType, content_type, MAX_WAPPUSH_CONTENT_TYPE_LEN);
+
+       /** Callback to MSG FW */
+       listener.pfPushMsgIncomingCb(&pushData);
+}
+
+
+void SmsPluginEventHandler::handleResendMessage(void)
+{
+       listener.pfResendMessageCb();
+}
+
+
+void SmsPluginEventHandler::handleSyncMLMsgIncoming(msg_syncml_message_type_t msgType, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen,int simIndex)
 {
        MSG_SYNCML_MESSAGE_DATA_S syncMLData;
 
@@ -194,6 +377,8 @@ void SmsPluginEventHandler::handleSyncMLMsgIncoming(msg_syncml_message_type_t ms
        /** set syncML data */
        syncMLData.syncmlType = msgType;
 
+       syncMLData.simIndex = simIndex;
+
        syncMLData.pushBodyLen = PushBodyLen;
        memcpy(syncMLData.pushBody, pPushBody, PushBodyLen);
 
@@ -212,7 +397,7 @@ void SmsPluginEventHandler::handleLBSMsgIncoming(char* pPushHeader, char* pPushB
        memset(&lBSData, 0x00, sizeof(MSG_LBS_MESSAGE_DATA_S));
 
        /** set LBA data */
-       memcpy(&lBSData.pushHeader, pPushHeader, strlen(pPushHeader));
+       memcpy(lBSData.pushHeader, pPushHeader, strlen(pPushHeader));
 
        lBSData.pushBodyLen = pushBodyLen;
        memcpy(lBSData.pushBody, pPushBody, pushBodyLen);
@@ -221,7 +406,6 @@ void SmsPluginEventHandler::handleLBSMsgIncoming(char* pPushHeader, char* pPushB
        listener.pfLBSMsgIncomingCb(&lBSData);
 }
 
-
 msg_error_t SmsPluginEventHandler::callbackMsgIncoming(MSG_MESSAGE_INFO_S *pMsgInfo)
 {
        MSG_BEGIN();
@@ -236,6 +420,20 @@ msg_error_t SmsPluginEventHandler::callbackMsgIncoming(MSG_MESSAGE_INFO_S *pMsgI
        return err;
 }
 
+msg_error_t SmsPluginEventHandler::callbackCBMsgIncoming(MSG_CB_MSG_S *pCbMsg, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       /** Callback to MSG FW */
+       err = listener.pfCBMsgIncomingCb(pCbMsg, pMsgInfo);
+
+       MSG_END();
+
+       return err;
+}
+
 
 msg_error_t SmsPluginEventHandler::callbackInitSimBySat()
 {
@@ -255,7 +453,6 @@ msg_error_t SmsPluginEventHandler::callbackStorageChange(msg_storage_change_type
 
 void SmsPluginEventHandler::convertTpduToMsginfo(SMS_TPDU_S *pTpdu, MSG_MESSAGE_INFO_S *msgInfo)
 {
-       memset(msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
 
        switch(pTpdu->tpduType)
        {
@@ -281,7 +478,7 @@ void SmsPluginEventHandler::convertSubmitTpduToMsginfo(const SMS_SUBMIT_S *pTpdu
        msgInfo->msgType.subType = convertMsgSubType(pTpdu->pid);
 
        /** set folder id (temporary) */
-       msgInfo->folderId = MSG_OUTBOX_ID;
+       msgInfo->folderId = MSG_SENTBOX_ID;
 
        switch(pTpdu->dcs.msgClass)
        {
@@ -299,52 +496,60 @@ void SmsPluginEventHandler::convertSubmitTpduToMsginfo(const SMS_SUBMIT_S *pTpdu
                        break;
                default:
                        msgInfo->msgType.classType = MSG_CLASS_NONE;
+                       break;
        }
 
        msgInfo->networkStatus = MSG_NETWORK_SEND_SUCCESS;
        msgInfo->bRead = false;
        msgInfo->bProtected = false;
        msgInfo->priority = MSG_MESSAGE_PRIORITY_NORMAL;
-       msgInfo->direction = MSG_DIRECTION_TYPE_MT;
+       msgInfo->direction = MSG_DIRECTION_TYPE_MO;
        msgInfo->bTextSms = true;
 
        memset(msgInfo->subject, 0x00, MAX_SUBJECT_LEN+1);
 
        /** What kind of time has to be saved?? (temporary store time) */
 
-       time_t curTime;
-       localtime(&curTime);
-
-       msgInfo->displayTime = curTime;
+//CID 315780 (#1 of 1): Other violation (DC.SECURE_CODING_CRITICAL)
+//dont_call: Calling localtime(time_t const *) is a DC.SECURE_CODING_CRITICAL defect.
+//     time_t curTime;
+//     localtime(&curTime);
 
        /** Convert Address values */
        msgInfo->nAddressCnt = 1;
+
+       msgInfo->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+       memset(msgInfo->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
        msgInfo->addressList[addressListCnt].addressType = MSG_ADDRESS_TYPE_PLMN;
        strncpy(msgInfo->addressList[addressListCnt].addressVal, pTpdu->destAddress.address, MAX_ADDRESS_VAL_LEN);
 
        /**exception operation for none userdata */
        if (pTpdu->userData.length == 0) {
-               sprintf(msgInfo->msgText, "[Broken Message]");
+               snprintf(msgInfo->msgText, sizeof(msgInfo->msgText), "[Broken Message]");
                msgInfo->dataSize = strlen(msgInfo->msgText);
                return;
        }
 
        /** Convert Data values */
+       MsgTextConvert *textCvt = MsgTextConvert::instance();
        if (pTpdu->dcs.codingScheme == SMS_CHARSET_7BIT) {
-               SMS_LANG_INFO_S langInfo = {0};
+               MSG_LANG_INFO_S langInfo = {0,};
 
                langInfo.bSingleShift = false;
                langInfo.bLockingShift = false;
 
-               msgInfo->dataSize = SmsPluginTextConvert::instance()->convertGSM7bitToUTF8((unsigned char*)msgInfo->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)pTpdu->userData.data, pTpdu->userData.length, &langInfo);
+               msgInfo->dataSize = textCvt->convertGSM7bitToUTF8((unsigned char*)msgInfo->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)pTpdu->userData.data, pTpdu->userData.length, &langInfo);
        } else if (pTpdu->dcs.codingScheme == SMS_CHARSET_UCS2) {
-               msgInfo->dataSize = SmsPluginTextConvert::instance()->convertUCS2ToUTF8((unsigned char*)msgInfo->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)pTpdu->userData.data, pTpdu->userData.length);
+               msgInfo->dataSize = textCvt->convertUCS2ToUTF8((unsigned char*)msgInfo->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)pTpdu->userData.data, pTpdu->userData.length);
        }
 }
 
 
 void SmsPluginEventHandler::convertDeliverTpduToMsginfo(const SMS_DELIVER_S *pTpdu, MSG_MESSAGE_INFO_S *msgInfo)
 {
+       MSG_BEGIN();
+
        /** Convert Type  values */
        msgInfo->msgType.mainType = MSG_SMS_TYPE;
        msgInfo->msgType.subType = convertMsgSubType(pTpdu->pid);
@@ -352,7 +557,65 @@ void SmsPluginEventHandler::convertDeliverTpduToMsginfo(const SMS_DELIVER_S *pTp
        /** set folder id (temporary) */
        msgInfo->folderId = MSG_INBOX_ID;
 
-       msgInfo->storageId = MSG_STORAGE_PHONE;
+       time_t rawtime = 0;
+       if(msgInfo->storageId == MSG_STORAGE_SIM)
+       {
+       /*** Comment below lines to save local UTC time..... (it could be used later.)
+       ***/
+               if (pTpdu->timeStamp.format == SMS_TIME_ABSOLUTE) {
+
+                       MSG_DEBUG("year : %d", pTpdu->timeStamp.time.absolute.year);
+                       MSG_DEBUG("month : %d", pTpdu->timeStamp.time.absolute.month);
+                       MSG_DEBUG("day : %d", pTpdu->timeStamp.time.absolute.day);
+                       MSG_DEBUG("hour : %d", pTpdu->timeStamp.time.absolute.hour);
+                       MSG_DEBUG("minute : %d", pTpdu->timeStamp.time.absolute.minute);
+                       MSG_DEBUG("second : %d", pTpdu->timeStamp.time.absolute.second);
+                       MSG_DEBUG("timezone : %d", pTpdu->timeStamp.time.absolute.timeZone);
+
+                       char displayTime[32];
+                       struct tm timeTM;
+
+                       struct tm timeinfo;
+                       memset(&timeinfo, 0x00, sizeof(tm));
+
+                       timeinfo.tm_year = (pTpdu->timeStamp.time.absolute.year + 100);
+                       timeinfo.tm_mon = (pTpdu->timeStamp.time.absolute.month - 1);
+                       timeinfo.tm_mday = pTpdu->timeStamp.time.absolute.day;
+                       timeinfo.tm_hour = pTpdu->timeStamp.time.absolute.hour;
+                       timeinfo.tm_min = pTpdu->timeStamp.time.absolute.minute;
+                       timeinfo.tm_sec = pTpdu->timeStamp.time.absolute.second;
+                       timeinfo.tm_isdst = 0;
+
+                       rawtime = mktime(&timeinfo);
+
+                       MSG_DEBUG("tzname[0] [%s]", tzname[0]);
+                       MSG_DEBUG("tzname[1] [%s]", tzname[1]);
+                       MSG_DEBUG("timezone [%d]", timezone);
+                       MSG_DEBUG("daylight [%d]", daylight);
+
+                       memset(displayTime, 0x00, sizeof(displayTime));
+                       strftime(displayTime, 32, "%Y-%02m-%02d %T %z", &timeinfo);
+                       MSG_DEBUG("displayTime [%s]", displayTime);
+
+                       rawtime -= (pTpdu->timeStamp.time.absolute.timeZone * (3600/4));
+
+                       localtime_r(&rawtime, &timeTM);
+                       memset(displayTime, 0x00, sizeof(displayTime));
+                       strftime(displayTime, 32, "%Y-%02m-%02d %T %z", &timeTM);
+                       MSG_DEBUG("displayTime [%s]", displayTime);
+
+                       rawtime -= timezone;
+
+                       localtime_r(&rawtime, &timeTM);
+                       memset(displayTime, 0x00, sizeof(displayTime));
+                       strftime(displayTime, 32, "%Y-%02m-%02d %T %z", &timeTM);
+                       MSG_DEBUG("displayTime [%s]", displayTime);
+               }
+       }
+       else
+               rawtime = time(NULL);
+
+       msgInfo->displayTime = rawtime;
 
        switch(pTpdu->dcs.msgClass)
        {
@@ -371,10 +634,20 @@ void SmsPluginEventHandler::convertDeliverTpduToMsginfo(const SMS_DELIVER_S *pTp
                        break;
                default:
                        msgInfo->msgType.classType = MSG_CLASS_NONE;
+                       break;
        }
 
        if (pTpdu->dcs.bMWI) {
-               msgInfo->msgType.subType = (pTpdu->dcs.indType + MSG_MWI_VOICE_SMS);
+               if (pTpdu->dcs.indType == SMS_VOICE_INDICATOR)
+                       msgInfo->msgType.subType = MSG_MWI_VOICE_SMS;
+               else if (pTpdu->dcs.indType == SMS_VOICE2_INDICATOR)
+                       msgInfo->msgType.subType = MSG_MWI_VOICE2_SMS;
+               else if (pTpdu->dcs.indType == SMS_FAX_INDICATOR)
+                       msgInfo->msgType.subType = MSG_MWI_FAX_SMS;
+               else if (pTpdu->dcs.indType == SMS_EMAIL_INDICATOR)
+                       msgInfo->msgType.subType = MSG_MWI_EMAIL_SMS;
+               else if (pTpdu->dcs.indType == SMS_OTHER_INDICATOR)
+                       msgInfo->msgType.subType = MSG_MWI_OTHER_SMS;
        }
 
        msgInfo->networkStatus = MSG_NETWORK_RECEIVED;
@@ -386,12 +659,12 @@ void SmsPluginEventHandler::convertDeliverTpduToMsginfo(const SMS_DELIVER_S *pTp
 
        memset(msgInfo->subject, 0x00, MAX_SUBJECT_LEN+1);
 
-       time_t rawtime = time(NULL);
-
-       msgInfo->displayTime = rawtime;
-
        /** Convert Address values */
        msgInfo->nAddressCnt = 1;
+
+       msgInfo->addressList =  (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+       memset(msgInfo->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
        msgInfo->addressList[0].addressType = MSG_ADDRESS_TYPE_PLMN;
        strncpy(msgInfo->addressList[0].addressVal, pTpdu->originAddress.address, MAX_ADDRESS_VAL_LEN);
 
@@ -411,15 +684,42 @@ void SmsPluginEventHandler::convertDeliverTpduToMsginfo(const SMS_DELIVER_S *pTp
                        msgInfo->msgPort.srcPort = pTpdu->userData.header[i].udh.appPort16bit.originPort;
                } else if (pTpdu->userData.header[i].udhType == SMS_UDH_SPECIAL_SMS) {
                        msgInfo->msgType.subType = (pTpdu->userData.header[i].udh.specialInd.msgInd+MSG_MWI_VOICE_SMS);
-
-                       if (pTpdu->userData.length == 0) {
-                               sprintf(msgInfo->msgText,"[MWI Message] Total %d Message is waiting.", pTpdu->userData.header[i].udh.specialInd.waitMsgNum);
+                       msgInfo->bStore = pTpdu->userData.header[i].udh.specialInd.bStore;
+
+                       bUdhMwiMethod = true;
+
+                       if (pTpdu->dcs.codingGroup == SMS_GROUP_DISCARD)
+                               msgInfo->bStore = false;
+
+                       udhMwiCnt = pTpdu->userData.header[i].udh.specialInd.waitMsgNum;
+                       MSG_DEBUG("Message waiting number : [%d]", udhMwiCnt);
+
+                       SmsPluginSetting::instance()->setMwiInfo(msgInfo->sim_idx, msgInfo->msgType.subType, udhMwiCnt);
+
+                       if (udhMwiCnt > 0 && (msgInfo->msgType.subType >= MSG_MWI_VOICE_SMS && msgInfo->msgType.subType <= MSG_MWI_OTHER_SMS)) {
+                               switch (msgInfo->msgType.subType) {
+                               case MSG_MWI_VOICE_SMS :
+                                       snprintf(msgInfo->msgText, sizeof(msgInfo->msgText), "%d", udhMwiCnt);
+                                       break;
+                               case MSG_MWI_FAX_SMS :
+                                       snprintf(msgInfo->msgText, sizeof(msgInfo->msgText), "%d new fax message", udhMwiCnt);
+                                       break;
+                               case MSG_MWI_EMAIL_SMS :
+                                       snprintf(msgInfo->msgText, sizeof(msgInfo->msgText), "%d new email message", udhMwiCnt);
+                                       break;
+                               default :
+                                       snprintf(msgInfo->msgText, sizeof(msgInfo->msgText), "%d new special message", udhMwiCnt);
+                                       break;
+                               }
                                msgInfo->dataSize = strlen(msgInfo->msgText);
                                return;
                        }
-
                } else if (pTpdu->userData.header[i].udhType == SMS_UDH_ALTERNATE_REPLY_ADDRESS) {
                        strncpy(msgInfo->addressList[0].addressVal, pTpdu->userData.header[i].udh.alternateAddress.address, MAX_ADDRESS_VAL_LEN);
+               } else if (pTpdu->userData.header[i].udhType >= SMS_UDH_EMS_FIRST && pTpdu->userData.header[i].udhType <= SMS_UDH_EMS_LAST) {
+                       snprintf(msgInfo->msgText, sizeof(msgInfo->msgText), "Unsupported Message");
+                       msgInfo->dataSize = strlen(msgInfo->msgText);
+                       return;
                }
        }
 
@@ -441,18 +741,20 @@ void SmsPluginEventHandler::convertDeliverTpduToMsginfo(const SMS_DELIVER_S *pTp
                                break;
                        default:
                                msgInfo->encodeType = MSG_ENCODE_8BIT;
+                               break;
                }
 
                return;
        } else if (pTpdu->userData.length > MAX_MSG_TEXT_LEN) {
-               sprintf(msgInfo->msgText, "[Broken Message]");
+               snprintf(msgInfo->msgText, sizeof(msgInfo->msgText), "[Broken Message]");
                msgInfo->dataSize = strlen(msgInfo->msgData);
                return;
        }
 
        /** Convert Data values */
+       MsgTextConvert *textCvt = MsgTextConvert::instance();
        if (pTpdu->dcs.codingScheme == SMS_CHARSET_7BIT) {
-               SMS_LANG_INFO_S langInfo = {0};
+               MSG_LANG_INFO_S langInfo = {0,};
 
                langInfo.bSingleShift = false;
                langInfo.bLockingShift = false;
@@ -468,19 +770,21 @@ void SmsPluginEventHandler::convertDeliverTpduToMsginfo(const SMS_DELIVER_S *pTp
                }
 
                msgInfo->encodeType = MSG_ENCODE_GSM7BIT;
-               msgInfo->dataSize = SmsPluginTextConvert::instance()->convertGSM7bitToUTF8((unsigned char*)msgInfo->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)pTpdu->userData.data, pTpdu->userData.length, &langInfo);
+               msgInfo->dataSize = textCvt->convertGSM7bitToUTF8((unsigned char*)msgInfo->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)pTpdu->userData.data, pTpdu->userData.length, &langInfo);
        } else if (pTpdu->dcs.codingScheme == SMS_CHARSET_8BIT) {
                msgInfo->encodeType = MSG_ENCODE_8BIT;
-               memcpy(msgInfo->msgText, pTpdu->userData.data, pTpdu->userData.length);
+               memcpy(msgInfo->msgText, pTpdu->userData.data, sizeof(pTpdu->userData.data));
                msgInfo->dataSize = pTpdu->userData.length;
        } else if (pTpdu->dcs.codingScheme == SMS_CHARSET_UCS2) {
                msgInfo->encodeType = MSG_ENCODE_UCS2;
-               msgInfo->dataSize = SmsPluginTextConvert::instance()->convertUCS2ToUTF8((unsigned char*)msgInfo->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)pTpdu->userData.data, pTpdu->userData.length);
+               msgInfo->dataSize = textCvt->convertUCS2ToUTF8((unsigned char*)msgInfo->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)pTpdu->userData.data, pTpdu->userData.length);
        } else if (pTpdu->dcs.codingScheme == SMS_CHARSET_EUCKR) {
                msgInfo->encodeType = MSG_ENCODE_8BIT;
-               msgInfo->dataSize = SmsPluginTextConvert::instance()->convertEUCKRToUTF8((unsigned char*)msgInfo->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)pTpdu->userData.data, pTpdu->userData.length);
+               msgInfo->dataSize = textCvt->convertEUCKRToUTF8((unsigned char*)msgInfo->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)pTpdu->userData.data, pTpdu->userData.length);
                return;
        }
+
+       MSG_END();
 }
 
 
@@ -490,9 +794,14 @@ void SmsPluginEventHandler::convertStatusRepTpduToMsginfo(const SMS_STATUS_REPOR
        msgInfo->msgType.mainType = MSG_SMS_TYPE;
        msgInfo->msgType.subType = MSG_STATUS_REPORT_SMS;
 
-       /** set folder id (temporary) */
+       /** set folder id */
        msgInfo->folderId = MSG_INBOX_ID;
 
+       /** set storage id */
+       if (msgInfo->storageId == MSG_STORAGE_UNKNOWN) {
+               msgInfo->storageId = MSG_STORAGE_PHONE;
+       }
+
        switch(pTpdu->dcs.msgClass)
        {
                case SMS_MSG_CLASS_0:
@@ -509,13 +818,25 @@ void SmsPluginEventHandler::convertStatusRepTpduToMsginfo(const SMS_STATUS_REPOR
                        break;
                default:
                        msgInfo->msgType.classType = MSG_CLASS_NONE;
+                       break;
        }
 
        MSG_DEBUG("delivery status : [%d]", pTpdu->status);
 
-       if (pTpdu->status == SMS_STATUS_RECEIVE_SUCCESS) {
+       if (pTpdu->status == SMS_STATUS_RECEIVE_SUCCESS)
+       {
                msgInfo->networkStatus = MSG_NETWORK_DELIVER_SUCCESS;
-       } else {
+       }
+       else if(pTpdu->status == SMS_STATUS_TRY_REQUEST_PENDING)
+       {
+               msgInfo->networkStatus = MSG_NETWORK_DELIVER_PENDING;
+       }
+       else if(pTpdu->status == SMS_STATUS_PERM_MSG_VAL_PERIOD_EXPIRED)
+       {
+               msgInfo->networkStatus = MSG_NETWORK_DELIVER_EXPIRED;
+       }
+       else
+       {
                msgInfo->networkStatus = MSG_NETWORK_DELIVER_FAIL;
        }
 
@@ -529,10 +850,68 @@ void SmsPluginEventHandler::convertStatusRepTpduToMsginfo(const SMS_STATUS_REPOR
 
        time_t rawtime = time(NULL);
 
+/*** Comment below lines to save local UTC time..... (it could be used later.)
+
+       if (pTpdu->timeStamp.format == SMS_TIME_ABSOLUTE) {
+
+               MSG_DEBUG("year : %d", pTpdu->timeStamp.time.absolute.year);
+               MSG_DEBUG("month : %d", pTpdu->timeStamp.time.absolute.month);
+               MSG_DEBUG("day : %d", pTpdu->timeStamp.time.absolute.day);
+               MSG_DEBUG("hour : %d", pTpdu->timeStamp.time.absolute.hour);
+               MSG_DEBUG("minute : %d", pTpdu->timeStamp.time.absolute.minute);
+               MSG_DEBUG("second : %d", pTpdu->timeStamp.time.absolute.second);
+               MSG_DEBUG("timezone : %d", pTpdu->timeStamp.time.absolute.timeZone);
+
+               char displayTime[32];
+               struct tm * timeTM;
+
+               struct tm timeinfo;
+               memset(&timeinfo, 0x00, sizeof(tm));
+
+               timeinfo.tm_year = (pTpdu->timeStamp.time.absolute.year + 100);
+               timeinfo.tm_mon = (pTpdu->timeStamp.time.absolute.month - 1);
+               timeinfo.tm_mday = pTpdu->timeStamp.time.absolute.day;
+               timeinfo.tm_hour = pTpdu->timeStamp.time.absolute.hour;
+               timeinfo.tm_min = pTpdu->timeStamp.time.absolute.minute;
+               timeinfo.tm_sec = pTpdu->timeStamp.time.absolute.second;
+               timeinfo.tm_isdst = 0;
+
+               rawtime = mktime(&timeinfo);
+
+               MSG_DEBUG("tzname[0] [%s]", tzname[0]);
+               MSG_DEBUG("tzname[1] [%s]", tzname[1]);
+               MSG_DEBUG("timezone [%d]", timezone);
+               MSG_DEBUG("daylight [%d]", daylight);
+
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", &timeinfo);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= (pTpdu->timeStamp.time.absolute.timeZone * (3600/4));
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= timezone;
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+       }
+
+***/
+
        msgInfo->displayTime = rawtime;
 
        /** Convert Address values */
        msgInfo->nAddressCnt = 1;
+
+       msgInfo->addressList =  (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+       memset(msgInfo->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
        msgInfo->addressList[0].addressType = MSG_ADDRESS_TYPE_PLMN;
        strncpy(msgInfo->addressList[0].addressVal, pTpdu->recipAddress.address, MAX_ADDRESS_VAL_LEN);
 
@@ -553,17 +932,17 @@ void SmsPluginEventHandler::convertStatusRepTpduToMsginfo(const SMS_STATUS_REPOR
                }
        }
 
-       memset(msgInfo->msgText, 0x00, sizeof(MAX_MSG_TEXT_LEN+1));
+       memset(msgInfo->msgText, 0x00, sizeof(msgInfo->msgText));
        msgInfo->dataSize = 0;
 
        if (pTpdu->status <= SMS_STATUS_SMSC_SPECIFIC_LAST) {
-               strncpy(msgInfo->msgText, "Message delivered.", MAX_MSG_TEXT_LEN);
+               strncpy(msgInfo->msgText, "IDS_MSGF_BODY_MESSAGE_DELIVERED", MAX_MSG_TEXT_LEN);
                msgInfo->dataSize = strlen(msgInfo->msgText);
        } else if (pTpdu->status == SMS_STATUS_TEMP_SERVICE_REJECTED) {
-               strncpy(msgInfo->msgText, "Message delivery rejected.", MAX_MSG_TEXT_LEN);
+               strncpy(msgInfo->msgText, "IDS_MSGF_BODY_MMSDELIVERYMSGREJECTED", MAX_MSG_TEXT_LEN);
                msgInfo->dataSize = strlen(msgInfo->msgText);
        } else if (pTpdu->status == SMS_STATUS_PERM_MSG_VAL_PERIOD_EXPIRED) {
-               strncpy(msgInfo->msgText, "Message delivery expired.", MAX_MSG_TEXT_LEN);
+               strncpy(msgInfo->msgText, "IDS_MSGF_BODY_MESSAGE_HAS_EXPIRED", MAX_MSG_TEXT_LEN);
                msgInfo->dataSize = strlen(msgInfo->msgText);
        } else {
                strncpy(msgInfo->msgText, "Message delivery failed.", MAX_MSG_TEXT_LEN);
@@ -611,29 +990,72 @@ void SmsPluginEventHandler::SetSentInfo(SMS_SENT_INFO_S *pSentInfo)
 }
 
 
-void SmsPluginEventHandler::setDeviceStatus()
+void SmsPluginEventHandler::setDeviceStatus(struct tapi_handle *handle)
 {
-       mx.lock();
-       devStatus = true;
-       cv.signal();
-       mx.unlock();
+       if (handle == devHandle) {
+               mx.lock();
+               devStatus = true;
+               cv.signal();
+               mx.unlock();
+       }
 }
 
 
-bool SmsPluginEventHandler::getDeviceStatus()
+bool SmsPluginEventHandler::getDeviceStatus(struct tapi_handle *handle)
 {
        int ret = 0;
 
        mx.lock();
-
-       ret = cv.timedwait(mx.pMutex(), 10);
-
-       mx.unlock();
+       devHandle = handle;
+       ret = cv.timedwait(mx.pMutex(), MAX_TAPI_SIM_API_TIMEOUT);
 
        if (ret == ETIMEDOUT) {
-               MSG_DEBUG("WARNING: DEVICE STATUS TIME-OUT");
+               MSG_WARN("WARNING: DEVICE STATUS TIME-OUT");
                devStatus = false;
        }
-
+       devHandle = NULL;
+       mx.unlock();
        return devStatus;
 }
+
+
+msg_error_t SmsPluginEventHandler::handleSimMsg(MSG_MESSAGE_INFO_S *pMsgInfo, int *simIdList, msg_message_id_t *retMsgId, int listSize)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       /** Callback to MSG FW */
+       err = listener.pfSimMsgIncomingCb(pMsgInfo, simIdList, retMsgId, listSize);
+
+       MSG_END();
+
+       return err;
+}
+
+msg_error_t SmsPluginEventHandler::updateIMSI(int sim_idx)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       /** Callback to MSG FW */
+       err = listener.pfSimInitImsiCb(sim_idx);
+
+       MSG_END();
+
+       return err;
+}
+
+void SmsPluginEventHandler::handleSimMemoryFull(int simIndex)
+{
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       bool bSimSst = true;
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_SERVICE_TABLE, simIndex);
+       if (MsgSettingGetBool(keyName, &bSimSst) != MSG_SUCCESS)
+               MSG_ERR("MsgSettingGetBool [%s] failed", keyName);
+
+       if (bSimSst == true)
+               MsgInsertTicker("Sim memory full. Delete some items", SMS_MESSAGE_SIM_MESSAGE_FULL, true, 0);
+}
index d405b7e..6cd6d0d 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
@@ -29,6 +29,8 @@
 #include "SmsPluginEventHandler.h"
 #include "SmsPluginUAManager.h"
 #include "SmsPluginMain.h"
+#include "SmsPluginDSHandler.h"
+#include <gio/gio.h>
 
 extern "C"
 {
@@ -39,21 +41,27 @@ extern "C"
        #include <ITapiNetText.h>
 }
 
-struct tapi_handle *pTapiHandle = NULL;
+#define BUS_NAME "org.tizen.system.deviced"
+#define PATH_NAME "/Org/Tizen/System/DeviceD/Lowmem"
+#define INTERFACE_NAME BUS_NAME".lowmem"
+#define MEMBER_NAME "Full"
+
+GDBusConnection *gdbus_conn = NULL;
+GDBusProxy *gdbus_proxy = NULL;
+gint subs_id = 0;
+
+bool isMemAvailable = true;
 
 Mutex mx;
 CndVar cv;
 
+
+void MsgResourceMonitorInit(void);
+void MsgResourceMonitorDeinit(void);
+
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
-static void MsgTapiInitCB(keynode_t *key, void* data)
-{
-       MSG_DEBUG("MsgTapiInitCB is called.");
-       mx.lock();
-       cv.signal();
-       mx.unlock();
-}
 
 msg_error_t MsgPlgCreateHandle(MSG_PLUGIN_HANDLER_S *pPluginHandle)
 {
@@ -67,19 +75,15 @@ msg_error_t MsgPlgCreateHandle(MSG_PLUGIN_HANDLER_S *pPluginHandle)
                pPluginHandle->pfInitialize = SmsPlgInitialize;
                pPluginHandle->pfFinalize = SmsPlgFinalize;
                pPluginHandle->pfRegisterListener = SmsPlgRegisterListener;
-               pPluginHandle->pfCheckSimStatus = SmsPlgCheckSimStatus;
-               pPluginHandle->pfCheckDeviceStatus = SmsPlgCheckDeviceStatus;
                pPluginHandle->pfSubmitRequest = SmsPlgSubmitRequest;
-               pPluginHandle->pfInitSimMessage = SmsPlgInitSimMessage;
                pPluginHandle->pfSaveSimMessage = SmsPlgSaveSimMessage;
                pPluginHandle->pfDeleteSimMessage = SmsPlgDeleteSimMessage;
                pPluginHandle->pfSetReadStatus = SmsPlgSetReadStatus;
                pPluginHandle->pfSetMemoryStatus = SmsPlgSetMemoryStatus;
-               pPluginHandle->pfInitConfigData = SmsPlgInitConfigData;
                pPluginHandle->pfSetConfigData = SmsPlgSetConfigData;
                pPluginHandle->pfGetConfigData = SmsPlgGetConfigData;
-
-               pPluginHandle->pfRestoreMsg = NULL;
+               pPluginHandle->pfAddMessage = SmsPlgAddMessage;
+               pPluginHandle->pfGetDefaultNetworkSimId = SmsPlgGetDefaultNetworkSimId;
 
                MSG_DEBUG("SMS plugin: create handler OK");
                MSG_DEBUG ("SMS plugin %p", pPluginHandle);
@@ -107,40 +111,51 @@ msg_error_t SmsPlgInitialize()
 {
        MSG_BEGIN();
 
-       MSG_DEBUG("set MSG_SIM_CHANGED to MSG_SIM_STATUS_NOT_FOUND.");
-       MsgSettingSetInt(MSG_SIM_CHANGED, MSG_SIM_STATUS_NOT_FOUND);
+       bool bReady = false;
 
-       bool bReady;
-       MsgSettingGetBool(VCONFKEY_TELEPHONY_READY, &bReady);
-       MSG_DEBUG("Get VCONFKEY_TELEPHONY_READY [%d].", bReady);
+       for (int i = 0; i < 100; i++) {
+               MsgSettingGetBool(VCONFKEY_TELEPHONY_READY, &bReady);
+               MSG_DEBUG("Get VCONFKEY_TELEPHONY_READY [%d].", bReady ? 1 : 0);
 
-       int ret = 0;
+               if (bReady)
+                       break;
 
-       if(!bReady) {
-               MsgSettingRegVconfCBCommon(VCONFKEY_TELEPHONY_READY, MsgTapiInitCB);
-               mx.lock();
-               ret = cv.timedwait(mx.pMutex(), 90);
-               mx.unlock();
+               sleep(1);
        }
 
-       try
-       {
-               if (ret != ETIMEDOUT) {
-                       pTapiHandle = tel_init(NULL);
-                       SmsPluginCallback::instance()->registerEvent();
-               }
+       if (!bReady) {
+               MSG_ERR("Fail to wait telephony init complete.");
+               return MSG_ERR_PLUGIN_TAPIINIT;
        }
-       catch (MsgException& e)
-       {
-               MSG_FATAL("%s", e.what());
-               return MSG_ERR_PLUGIN_REGEVENT;
+
+       int simCnt = 0;
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+
+       SmsPluginDSHandler::instance()->initTelHandle();
+       simCnt = SmsPluginDSHandler::instance()->getTelHandleCount();
+
+       MSG_DEBUG("simCnt [%d]", simCnt);
+
+       for (int i = 1; i <= simCnt; i++) {
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, i);
+               MSG_DEBUG("set MSG_SIM_CHANGED to MSG_SIM_STATUS_NOT_FOUND.");
+               if (MsgSettingSetInt(keyName, MSG_SIM_STATUS_NOT_FOUND) != MSG_SUCCESS)
+                       MSG_DEBUG("MsgSettingSetInt is failed!!");
        }
-       catch (exception& e)
+
+       SmsPluginCallback::instance()->registerEvent();
+
+       for(int i=1; i <= simCnt; ++i)
        {
-               MSG_FATAL("%s", e.what());
-               return MSG_ERR_PLUGIN_REGEVENT;
+               struct tapi_handle *handle;
+               handle = SmsPluginDSHandler::instance()->getTelHandle(i);
+               SmsPluginSetting::instance()->setSimChangeStatus(handle, true);
        }
 
+       // set resource monitor
+       MsgResourceMonitorInit();
+
        MSG_END();
 
        return MSG_SUCCESS;
@@ -151,12 +166,11 @@ msg_error_t SmsPlgFinalize()
 {
        MSG_BEGIN();
 
-       if (!pTapiHandle)
-               return MSG_ERR_PLUGIN_TAPIINIT;
+       MsgResourceMonitorDeinit();
 
        SmsPluginCallback::instance()->deRegisterEvent();
 
-       tel_deinit(pTapiHandle);
+       SmsPluginDSHandler::instance()->deinitTelHandle();
 
        MSG_END();
 
@@ -176,152 +190,37 @@ msg_error_t SmsPlgRegisterListener(MSG_PLUGIN_LISTENER_S *pListener)
 }
 
 
-msg_error_t SmsPlgCheckSimStatus(MSG_SIM_STATUS_T *pStatus)
+msg_error_t SmsPlgSubmitRequest(MSG_REQUEST_INFO_S *pReqInfo)
 {
-       MSG_BEGIN();
-
-       if (!pTapiHandle)
-               return MSG_ERR_PLUGIN_TAPIINIT;
-
-       int tryNum = 0, tapiRet = TAPI_API_SUCCESS;
-
-       TelSimCardStatus_t status = TAPI_SIM_STATUS_CARD_ERROR;
-       int cardChanged = 0;
-
-       // initialize pStatus.
-       *pStatus = MSG_SIM_STATUS_NOT_FOUND;
-
-       // Check SIM Status
-       while (1)
-       {
-               if (tryNum > 30) return MSG_ERR_PLUGIN_TAPIINIT;
-
-               tapiRet = tel_get_sim_init_info(pTapiHandle, &status, &cardChanged);
-
-               if (tapiRet == TAPI_API_SUCCESS) {
-                       if (status == TAPI_SIM_STATUS_SIM_PIN_REQUIRED || status == TAPI_SIM_STATUS_SIM_PUK_REQUIRED) {
-                               MSG_DEBUG("PIN or PUK is required [%d]", status);
+       msg_error_t err = MSG_SUCCESS;
 
-                               sleep(3);
+       // Add Submit SMS into DB
+       if (pReqInfo->msgInfo.msgId == 0) {
+               if (pReqInfo->msgInfo.msgPort.valid == false) {
+                       err = SmsPluginStorage::instance()->checkMessage(&(pReqInfo->msgInfo));
 
-                               continue;
+                       if (err != MSG_SUCCESS) {
+                               MSG_DEBUG("########  checkMessage Fail !! [err=%d]", err);
+                               return MSG_ERR_PLUGIN_STORAGE;
                        }
 
-                       if (status == TAPI_SIM_STATUS_SIM_INIT_COMPLETED) {
-                               MSG_DEBUG("SIM status is OK [%d]", status);
-
-                               MSG_DEBUG("SIM Changed [%d]", cardChanged);
-
-                               if (cardChanged == 1)
-                                       *pStatus = MSG_SIM_STATUS_CHANGED;
-                               else
-                                       *pStatus = MSG_SIM_STATUS_NORMAL;
-
-                               break;
-                       } else if (status == TAPI_SIM_STATUS_CARD_NOT_PRESENT) {
-                               MSG_DEBUG("SIM is not present [%d]", status);
-                               break;
-                       } else {
-                               MSG_DEBUG("SIM status is not OK [%d]", status);
-                               tryNum++;
-
-                               sleep(3);
+                       err = SmsPluginStorage::instance()->addSmsMessage(&(pReqInfo->msgInfo));
+                       if (err != MSG_SUCCESS) {
+                               MSG_DEBUG("########  addSmsMessage Fail !! [err=%d]", err);
+                               return MSG_ERR_PLUGIN_STORAGE;
                        }
-               } else if (tapiRet == TAPI_API_SIM_NOT_FOUND) {
-                       MSG_DEBUG("tel_get_sim_init_info() result is TAPI_API_SIM_NOT_FOUND");
-                       break;
-               } else {
-                       MSG_DEBUG("tel_get_sim_init_info() result is unknown!!!!!!!!!! [%d]", tapiRet);
-                       tryNum++;
-
-                       sleep(3);
-               }
-       }
-
-
-       char imsi[7];
-       memset(imsi, 0x00, sizeof(imsi));
-
-       // Get IMSI
-       if (*pStatus != MSG_SIM_STATUS_NOT_FOUND)
-       {
-               // Get IMSI
-               TelSimImsiInfo_t imsiInfo = {0};
 
-               tapiRet = tel_get_sim_imsi(pTapiHandle, &imsiInfo);
-
-               if (tapiRet == TAPI_API_SUCCESS)
-               {
-                       MSG_DEBUG("tel_get_sim_imsi() Success - MCC [%s], MNC [%s]", imsiInfo.szMcc, imsiInfo.szMnc);
-
-                       sprintf(imsi, "%03d%03d", atoi(imsiInfo.szMcc), atoi(imsiInfo.szMnc));
-
-                       MSG_DEBUG("IMSI [%d]", atoi(imsi));
-               }
-               else
-               {
-                       MSG_DEBUG("tel_get_sim_imsi() Error![%d]", tapiRet);
-               }
-       }
-
-       MsgSettingSetString(MSG_SIM_IMSI, imsi);
-
-       MSG_END();
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t SmsPlgCheckDeviceStatus()
-{
-       MSG_BEGIN();
-
-       if (!pTapiHandle)
-               return MSG_ERR_PLUGIN_TAPIINIT;
-
-       int status = 0, tapiRet = TAPI_API_SUCCESS;
-
-       tapiRet = tel_check_sms_device_status(pTapiHandle, &status);
-
-       if (tapiRet != TAPI_API_SUCCESS)
-       {
-               MSG_DEBUG("tel_check_sms_device_status() Error! [%d], Status [%d]", tapiRet, status);
-
-               return MSG_ERR_PLUGIN_TAPI_FAILED;
-       }
-
-       if (status == 1)
-       {
-               MSG_DEBUG("Device Is Ready");
-               return MSG_SUCCESS;
-       }
-       else if (status == 0)
-       {
-               MSG_DEBUG("Device Is Not Ready.. Waiting For Ready Callback");
-
-               if (SmsPluginEventHandler::instance()->getDeviceStatus() == true)
-               {
-                       MSG_DEBUG("Device Is Ready");
-                       return MSG_SUCCESS;
-               }
-       }
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t SmsPlgSubmitRequest(MSG_REQUEST_INFO_S *pReqInfo)
-{
-       // Add Submit SMS into DB
-       if ((pReqInfo->msgInfo.msgId == 0) && pReqInfo->msgInfo.msgPort.valid == false) {
-               if (SmsPluginStorage::instance()->addMessage(&(pReqInfo->msgInfo)) != MSG_SUCCESS) {
-                       MSG_DEBUG("########  addMessage Fail !!");
-                       return MSG_ERR_PLUGIN_STORAGE;
+                       if (SmsPluginStorage::instance()->addSmsSendOption(&(pReqInfo->msgInfo), &(pReqInfo->sendOptInfo)) != MSG_SUCCESS) {
+                               MSG_DEBUG("########  addSmsSendOption Fail !!");
+                               return MSG_ERR_PLUGIN_STORAGE;
+                       }
                }
        }
 
        // Check SIM is present or not
-       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
+       char keyName[MAX_VCONFKEY_NAME_LEN] = {0,};
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, pReqInfo->msgInfo.sim_idx);
+       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
 
        if (simStatus == MSG_SIM_STATUS_NOT_FOUND)
        {
@@ -334,33 +233,45 @@ msg_error_t SmsPlgSubmitRequest(MSG_REQUEST_INFO_S *pReqInfo)
                return MSG_ERR_NO_SIM;
        }
 
-       SMS_REQUEST_INFO_S request = {};
+       SMS_REQUEST_INFO_S *request = NULL;
+
+       request = (SMS_REQUEST_INFO_S *)calloc(1, sizeof(SMS_REQUEST_INFO_S));
 
-       request.reqId = pReqInfo->reqId;
+       if (request != NULL) {
+               request->reqId = pReqInfo->reqId;
 
-       memcpy(&(request.msgInfo), &(pReqInfo->msgInfo), sizeof(MSG_MESSAGE_INFO_S));
-       memcpy(&(request.sendOptInfo), &(pReqInfo->sendOptInfo), sizeof(MSG_SENDINGOPT_INFO_S));
+               memcpy(&(request->msgInfo), &(pReqInfo->msgInfo), sizeof(MSG_MESSAGE_INFO_S));
+               memcpy(&(request->sendOptInfo), &(pReqInfo->sendOptInfo), sizeof(MSG_SENDINGOPT_INFO_S));
+
+               /* Add Request into Queue and Start UA Manger */
+               SmsPluginUAManager::instance()->addReqEntity(request);
+
+               free(request);
+       }
 
-       // Add Request into Queue and Start UA Manger
-       SmsPluginUAManager::instance()->addReqEntity(request);
 
        return MSG_SUCCESS;
 }
 
 
-msg_error_t SmsPlgInitSimMessage()
+msg_error_t SmsPlgSaveSimMessage(const MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList)
 {
        // Check SIM is present or not
-       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, pMsgInfo->sim_idx);
+       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
 
        if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
                MSG_DEBUG("SIM is not present..");
                return MSG_ERR_NO_SIM;
        }
 
+       msg_error_t err = MSG_SUCCESS;
+
        try
        {
-               SmsPluginSimMsg::instance()->initSimMessage();
+               err = SmsPluginSimMsg::instance()->saveSimMessage(pMsgInfo, pSimIdList);
        }
        catch (MsgException& e)
        {
@@ -373,32 +284,16 @@ msg_error_t SmsPlgInitSimMessage()
                return MSG_ERR_PLUGIN_STORAGE;
        }
 
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t SmsPlgSaveSimMessage(const MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList)
-{
-       // Check SIM is present or not
-       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
-
-       if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
-               MSG_DEBUG("SIM is not present..");
-               return MSG_ERR_NO_SIM;
-       }
-
-       msg_error_t err = MSG_SUCCESS;
-
-       err = SmsPluginSimMsg::instance()->saveSimMessage(pMsgInfo, pSimIdList);
-
        return err;
 }
 
 
-msg_error_t SmsPlgDeleteSimMessage(msg_sim_id_t SimMsgId)
+msg_error_t SmsPlgDeleteSimMessage(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId)
 {
        // Check SIM is present or not
-       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
+       char keyName[MAX_VCONFKEY_NAME_LEN]={0,};
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, sim_idx);
+       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
 
        if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
                MSG_DEBUG("SIM is not present..");
@@ -407,7 +302,7 @@ msg_error_t SmsPlgDeleteSimMessage(msg_sim_id_t SimMsgId)
 
        try
        {
-               SmsPluginSimMsg::instance()->deleteSimMessage(SimMsgId);
+               SmsPluginSimMsg::instance()->deleteSimMessage(sim_idx, SimMsgId);
        }
        catch (MsgException& e)
        {
@@ -424,10 +319,12 @@ msg_error_t SmsPlgDeleteSimMessage(msg_sim_id_t SimMsgId)
 }
 
 
-msg_error_t SmsPlgSetReadStatus(msg_sim_id_t SimMsgId)
+msg_error_t SmsPlgSetReadStatus(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId)
 {
        // Check SIM is present or not
-       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
+       char keyName[MAX_VCONFKEY_NAME_LEN]={0,};
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, sim_idx);
+       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
 
        if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
                MSG_DEBUG("SIM is not present..");
@@ -436,7 +333,7 @@ msg_error_t SmsPlgSetReadStatus(msg_sim_id_t SimMsgId)
 
        try
        {
-               SmsPluginSimMsg::instance()->setReadStatus(SimMsgId);
+               SmsPluginSimMsg::instance()->setReadStatus(sim_idx, SimMsgId);
        }
        catch (MsgException& e)
        {
@@ -453,17 +350,21 @@ msg_error_t SmsPlgSetReadStatus(msg_sim_id_t SimMsgId)
 }
 
 
-msg_error_t SmsPlgSetMemoryStatus(msg_error_t Error)
+msg_error_t SmsPlgSetMemoryStatus(msg_sim_slot_id_t simIndex, msg_error_t Error)
 {
        // Check SIM is present or not
-       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, simIndex);
+       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
 
        if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
                MSG_DEBUG("SIM is not present..");
                return MSG_ERR_NO_SIM;
        }
 
-       int tapiRet = TAPI_API_SUCCESS, reqId = 0;
+       int tapiRet = TAPI_API_SUCCESS;
        int status = TAPI_NETTEXT_PDA_MEMORY_STATUS_AVAILABLE;
 
        if (Error == MSG_ERR_SIM_STORAGE_FULL || Error == MSG_ERR_MESSAGE_COUNT_FULL)
@@ -473,34 +374,49 @@ msg_error_t SmsPlgSetMemoryStatus(msg_error_t Error)
 
        MSG_DEBUG("Set Status : [%d]", status);
 
-       tapiRet = tel_set_sms_memory_status(pTapiHandle, status, NULL, NULL);
+       struct tapi_handle *handle = SmsPluginDSHandler::instance()->getTelHandle(simIndex);
+
+       tapiRet = tel_set_sms_memory_status(handle, status, TapiEventMemoryStatus, NULL);
 
        if (tapiRet == TAPI_API_SUCCESS)
        {
-               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! req Id : [%d] #######", reqId);
+               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
        }
        else
        {
-               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! req Id : [%d] return : [%d] #######", reqId, tapiRet);
+               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! return : [%d] #######", tapiRet);
        }
 
        return MSG_SUCCESS;
 }
 
 
-msg_error_t SmsPlgInitConfigData(MSG_SIM_STATUS_T SimStatus)
+msg_error_t SmsPlgSetConfigData(const MSG_SETTING_S *pSetting)
 {
-       // Check SIM is present or not
-       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
-
-       if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
-               MSG_DEBUG("SIM is not present..");
-               return MSG_ERR_NO_SIM;
+       try
+       {
+               SmsPluginSetting::instance()->setConfigData(pSetting);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_SETTING;
        }
+       catch (exception& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_SETTING;
+       }
+
+       return MSG_SUCCESS;
+}
+
 
+msg_error_t SmsPlgGetConfigData(MSG_SETTING_S *pSetting)
+{
        try
        {
-               SmsPluginSetting::instance()->initConfigData(SimStatus);
+               SmsPluginSetting::instance()->getConfigData(pSetting);
        }
        catch (MsgException& e)
        {
@@ -517,19 +433,15 @@ msg_error_t SmsPlgInitConfigData(MSG_SIM_STATUS_T SimStatus)
 }
 
 
-msg_error_t SmsPlgSetConfigData(const MSG_SETTING_S *pSetting)
+msg_error_t SmsPlgAddMessage(MSG_MESSAGE_INFO_S *pMsgInfo,  MSG_SENDINGOPT_INFO_S* pSendOptInfo, char* pFileData)
 {
-       // Check SIM is present or not
-       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
-
-       if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
-               MSG_DEBUG("SIM is not present..");
-               return MSG_ERR_NO_SIM;
-       }
 
+       int *simIdList = (int*)pFileData;
        try
        {
-               SmsPluginSetting::instance()->setConfigData(pSetting);
+               SmsPluginStorage::instance()->addSmsSendOption(pMsgInfo, pSendOptInfo);
+               if (simIdList)
+                       SmsPluginStorage::instance()->addSimMessage(pMsgInfo, simIdList);
        }
        catch (MsgException& e)
        {
@@ -546,19 +458,12 @@ msg_error_t SmsPlgSetConfigData(const MSG_SETTING_S *pSetting)
 }
 
 
-msg_error_t SmsPlgGetConfigData(MSG_SETTING_S *pSetting)
+msg_error_t SmsPlgGetDefaultNetworkSimId(int *simId)
 {
-       // Check SIM is present or not
-       MSG_SIM_STATUS_T simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(MSG_SIM_CHANGED);
-
-       if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
-               MSG_DEBUG("SIM is not present..");
-               return MSG_ERR_NO_SIM;
-       }
 
        try
        {
-               SmsPluginSetting::instance()->getConfigData(pSetting);
+               SmsPluginDSHandler::instance()->getDefaultNetworkSimId(simId);
        }
        catch (MsgException& e)
        {
@@ -574,3 +479,103 @@ msg_error_t SmsPlgGetConfigData(MSG_SETTING_S *pSetting)
        return MSG_SUCCESS;
 }
 
+
+static void on_change_received(GDBusConnection *connection, const gchar *sender_name,
+               const gchar *object_path, const gchar *interface_name, const gchar *signal_name,
+               GVariant *parameters, gpointer user_data)
+{
+       MSG_DEBUG("signal_name = [%s]", signal_name);
+
+       if (g_strcmp0(signal_name, MEMBER_NAME) == 0) {
+               gint memStatus;
+               g_variant_get(parameters, "(i)", &memStatus);
+               MSG_DEBUG("memStatus = [%d]", memStatus);
+               if(memStatus == 0) {
+                       int sim_count = SmsPluginDSHandler::instance()->getTelHandleCount();
+
+                       for (int i = 0; i < sim_count; i++) {
+                               SmsPlgSetMemoryStatus(i, MSG_SUCCESS);
+                       }
+               }
+       }
+}
+
+void MsgResourceMonitorInit(void)
+{
+    MSG_BEGIN();
+
+       GError *error = NULL;
+
+       if (gdbus_conn) {
+               g_object_unref(gdbus_conn);
+               gdbus_conn = NULL;
+       }
+
+       gdbus_conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
+       if (error) {
+               MSG_FATAL("g_bus_get_sync() failed : %s", error->message);
+               g_error_free(error);
+               error = NULL;
+               goto _DBUS_ERROR;
+       }
+
+       if (gdbus_proxy) {
+               g_object_unref(gdbus_proxy);
+               gdbus_proxy = NULL;
+       }
+
+       gdbus_proxy = g_dbus_proxy_new_sync(gdbus_conn, G_DBUS_PROXY_FLAGS_NONE,
+                                                       NULL, BUS_NAME, PATH_NAME, INTERFACE_NAME, NULL, &error);
+       if (error) {
+               MSG_FATAL("g_dbus_proxy_new_sync() failed : %s", error->message);
+               g_error_free(error);
+               error = NULL;
+               goto _DBUS_ERROR;
+       }
+
+       subs_id = g_dbus_connection_signal_subscribe(gdbus_conn, NULL,
+                                                       INTERFACE_NAME, MEMBER_NAME, PATH_NAME,
+                                                       NULL, G_DBUS_SIGNAL_FLAGS_NONE,
+                                                       on_change_received,
+                                                       NULL, NULL);
+       MSG_END();
+       return;
+
+_DBUS_ERROR:
+       if (gdbus_conn) {
+               g_object_unref(gdbus_conn);
+               gdbus_conn = NULL;
+       }
+
+       if (gdbus_proxy) {
+               g_object_unref(gdbus_proxy);
+               gdbus_proxy = NULL;
+       }
+
+       MSG_END();
+       return;
+
+}
+
+
+void MsgResourceMonitorDeinit(void)
+{
+       MSG_BEGIN();
+
+       if (subs_id) {
+               g_dbus_connection_signal_unsubscribe(gdbus_conn, subs_id);
+               subs_id = 0;
+       }
+
+       if (gdbus_conn) {
+               g_object_unref(gdbus_conn);
+               gdbus_conn = NULL;
+       }
+
+       if (gdbus_proxy) {
+               g_object_unref(gdbus_proxy);
+               gdbus_proxy = NULL;
+       }
+
+       MSG_END();
+}
index 6ae49d9..ca1e7e7 100755 (executable)
@@ -1,25 +1,25 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
 #include <string.h>
 
 #include "MsgDebug.h"
+#include "MsgTextConvert.h"
 #include "SmsPluginUDCodec.h"
-#include "SmsPluginTextConvert.h"
 #include "SmsPluginParamCodec.h"
 
 
@@ -261,6 +261,7 @@ int SmsPluginParamCodec::encodeSMSC(const SMS_ADDRESS_S *pAddress, unsigned char
 int SmsPluginParamCodec::decodeAddress(const unsigned char *pTpdu, SMS_ADDRESS_S *pAddress)
 {
        int offset = 0, addrLen = 0, bcdLen = 0;
+       MsgTextConvert *textCvt = MsgTextConvert::instance();
        memset(pAddress->address, 0x00, sizeof(pAddress->address));
 
        addrLen = (int)pTpdu[offset++];
@@ -283,19 +284,23 @@ MSG_DEBUG("npi [%d]", pAddress->npi);
                char* tmpAddress = new char[MAX_ADDRESS_LEN];
                int tmplength = 0;
 
-               tmplength = SmsPluginUDCodec::unpack7bitChar(&(pTpdu[offset]), bcdLen, 0, tmpAddress);
+               tmplength = SmsPluginUDCodec::unpack7bitChar(&(pTpdu[offset]), (addrLen*4 )/7, 0, tmpAddress);
 
-               SMS_LANG_INFO_S langInfo = {0};
+               MSG_LANG_INFO_S langInfo = {0,};
 
                langInfo.bSingleShift = false;
                langInfo.bLockingShift = false;
 
-               SmsPluginTextConvert::instance()->convertGSM7bitToUTF8((unsigned char*)pAddress->address, MAX_ADDRESS_LEN, (unsigned char*)tmpAddress, tmplength, &langInfo);
+               textCvt->convertGSM7bitToUTF8((unsigned char*)pAddress->address, MAX_ADDRESS_LEN, (unsigned char*)tmpAddress, tmplength, &langInfo);
+
+               if (tmpAddress)
+                       delete[] tmpAddress;
        }
        else if (pAddress->ton == SMS_TON_INTERNATIONAL)
        {
-               (pAddress->address)[0] = '+';
                convertBcdToDigit(&(pTpdu[offset]), bcdLen, &((pAddress->address)[1]));
+               if (pAddress->address[1] != '\0')
+                       pAddress->address[0] = '+';
        }
        else
        {
@@ -389,7 +394,7 @@ int SmsPluginParamCodec::decodeDCS(const unsigned char *pTpdu, SMS_DCS_S *pDCS)
                pDCS->msgClass = SMS_MSG_CLASS_NONE;
 
                pDCS->bMWI = true;
-               pDCS->bIndActive = (((dcs & 0x08) >> 3) == 1)? false:true;
+               pDCS->bIndActive = (((dcs & 0x08) >> 3) == 1)? true:false;
                pDCS->indType = (SMS_INDICATOR_TYPE_T)(dcs & 0x03);
        }
        else if (((dcs & 0xF0) >> 4) == 0x0D)
@@ -400,7 +405,7 @@ int SmsPluginParamCodec::decodeDCS(const unsigned char *pTpdu, SMS_DCS_S *pDCS)
                pDCS->msgClass = SMS_MSG_CLASS_NONE;
 
                pDCS->bMWI = true;
-               pDCS->bIndActive = (((dcs & 0x08) >> 3) == 1)? false:true;
+               pDCS->bIndActive = (((dcs & 0x08) >> 3) == 1)? true:false;
                pDCS->indType = (SMS_INDICATOR_TYPE_T)(dcs & 0x03);
        }
        else if (((dcs & 0xF0) >> 4) == 0x0E)
@@ -411,7 +416,7 @@ int SmsPluginParamCodec::decodeDCS(const unsigned char *pTpdu, SMS_DCS_S *pDCS)
                pDCS->msgClass = SMS_MSG_CLASS_NONE;
 
                pDCS->bMWI = true;
-               pDCS->bIndActive = (((dcs & 0x08) >> 3) == 1)? false:true;
+               pDCS->bIndActive = (((dcs & 0x08) >> 3) == 1)? true:false;
                pDCS->indType = (SMS_INDICATOR_TYPE_T)(dcs & 0x03);
        }
        else
@@ -523,3 +528,25 @@ int SmsPluginParamCodec::convertBcdToDigit(const unsigned char *pBcd, int BcdLen
        return offset;
 }
 
+bool SmsPluginParamCodec::checkCphsVmiMsg(const unsigned char *pTpdu, int *setType, int *indType)
+{
+       bool ret = false;
+
+       int offset = 0;
+       int addrLen = 0;
+
+       addrLen = (int)pTpdu[offset++];
+
+       if (addrLen == 0x04 && pTpdu[offset++] == 0xD0) {
+               if (pTpdu[offset] == 0x11 || pTpdu[offset] == 0x10) {
+                       MSG_DEBUG("####### VMI msg ######");
+                       *setType = (int)(pTpdu[offset] & 0x01); // 0 : clear, 1 : set
+
+                       *indType = (int)(pTpdu[offset+1] & 0x01); // 0 : indicator 1, 1 : indicator 2
+
+                       ret = true;
+               }
+       }
+
+       return ret;
+}
index 180dcb1..1ca9df7 100755 (executable)
@@ -1,30 +1,35 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
+#include <errno.h>
 #include "MsgDebug.h"
 #include "MsgCppTypes.h"
 #include "MsgException.h"
 #include "MsgGconfWrapper.h"
+#include "MsgNotificationWrapper.h"
+#include "MsgUtilStorage.h"
 #include "SmsPluginParamCodec.h"
 #include "SmsPluginUDCodec.h"
+#include "SmsPluginTpduCodec.h"
 #include "SmsPluginSetting.h"
 #include "SmsPluginTransport.h"
 #include "SmsPluginCallback.h"
 #include "SmsPluginEventHandler.h"
 #include "SmsPluginSatHandler.h"
+#include "SmsPluginDSHandler.h"
 
 extern "C"
 {
@@ -35,7 +40,6 @@ extern "C"
        #include <ITapiSat.h>
 }
 
-extern struct tapi_handle *pTapiHandle;
 /*==================================================================================================
                                      IMPLEMENTATION OF SmsPluginCbMsgHandler - Member Functions
 ==================================================================================================*/
@@ -46,7 +50,6 @@ SmsPluginSatHandler::SmsPluginSatHandler()
 {
        commandId = 0;
 
-       bSendSms = false;
        bInitSim = false;
        bSMSPChanged = false;
        bCBMIChanged = false;
@@ -68,17 +71,77 @@ SmsPluginSatHandler* SmsPluginSatHandler::instance()
 }
 
 
-void SmsPluginSatHandler::refreshSms(void *pData)
+void SmsPluginSatHandler::refreshSms(struct tapi_handle *handle, void *pData)
 {
+       /*
+       TelSatRefreshInd_t* pRefreshData = (TelSatRefreshInd_t*)pData;
+
+       if (pRefreshData->appType != TAPI_SAT_REFRESH_MSG)
+       {
+               MSG_DEBUG("App Type is wrong. [%d]", pRefreshData->appType);
+               return;
+       }
+
+       commandId = pRefreshData->commandId;
+
+       switch (pRefreshData->refreshMode)
+       {
+               case TAPI_SAT_REFRESH_SIM_INIT_AND_FULL_FCN :
+               case TAPI_SAT_REFRESH_SIM_INIT_AND_FCN :
+               {
+                       for (int i = 0; i < pRefreshData->fileCount; i++)
+                       {
+                               if ((SMS_SIM_EFILE_NAME_T)pRefreshData->fileId[i].FileName == SMS_SIM_EFILE_USIM_SMSP ||
+                                       (SMS_SIM_EFILE_NAME_T)pRefreshData->fileId[i].FileName == SMS_SIM_EFILE_SMSP)
+                               {
+                                       bSMSPChanged = true;
+                               }
+                               else if ((SMS_SIM_EFILE_NAME_T)pRefreshData->fileId[i].FileName == SMS_SIM_EFILE_USIM_CBMI ||
+                                       (SMS_SIM_EFILE_NAME_T)pRefreshData->fileId[i].FileName == SMS_SIM_EFILE_CBMI)
+                               {
+                                       bCBMIChanged = true;
+                               }
+                       }
+
+                       initSim();
+               }
+               break;
+
+               case TAPI_SAT_REFRESH_FCN :
+               {
+                       for (int i = 0; i < pRefreshData->fileCount; i++)
+                       {
+                               if ((SMS_SIM_EFILE_NAME_T)pRefreshData->fileId[i].FileName == SMS_SIM_EFILE_USIM_SMSP ||
+                                       (SMS_SIM_EFILE_NAME_T)pRefreshData->fileId[i].FileName == SMS_SIM_EFILE_SMSP)
+                               {
+                                       bSMSPChanged = true;
+                               }
+                               else if ((SMS_SIM_EFILE_NAME_T)pRefreshData->fileId[i].FileName == SMS_SIM_EFILE_USIM_CBMI ||
+                                       (SMS_SIM_EFILE_NAME_T)pRefreshData->fileId[i].FileName == SMS_SIM_EFILE_CBMI)
+                               {
+                                       bCBMIChanged = true;
+                               }
+                       }
+               }
+               break;
+
+               case TAPI_SAT_REFRESH_SIM_INIT :
+               {
+                       initSim();
+               }
+               break;
+
+               default:
+               break;
+       }
+       */
 }
 
 
-void SmsPluginSatHandler::sendSms(void *pData)
+void SmsPluginSatHandler::sendSms(struct tapi_handle *handle, void *pData)
 {
        TelSatSendSmsIndSmsData_t* pSmsData = (TelSatSendSmsIndSmsData_t*)pData;
 
-       bSendSms = true;
-
        commandId = pSmsData->commandId;
 
        MSG_DEBUG("commandId [%d]", commandId);
@@ -94,9 +157,16 @@ void SmsPluginSatHandler::sendSms(void *pData)
        // Modify Parameters, Pack User Data
        tpduLen = handleSatTpdu(tpdu, pSmsData->smsTpdu.dataLen, pSmsData->bIsPackingRequired);
 
-       if (tpduLen <= 0 || tpduLen > MAX_TPDU_DATA_LEN)
-       {
-               sendResult(SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_BEYOND_ME_CAPABILITIES);
+       if (tpduLen <= 0) {
+               sendResult(handle, SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_SUCCESS);
+               return;
+       } //else if (tpduLen > MAX_TPDU_DATA_LEN) {
+       else if (tpduLen > MAX_SAT_TPDU_LEN) {  //CID 358478: replacing check against MAX_TPDU_DATA_LEN (255) with check
+                                                                                       //                      against MAX_SAT_TPDU_LEN (175).
+                                                                                       //                      as mentioned above "The TPDU Maximum Length at SAT side is 175".
+                                                                                       //                      Earlier MAX_TPDU_DATA_LEN was increased from 165 to 255 which creates confusion for prevent tool.
+                                                                                       //                      Prevent tool thinks that it can take value of 255 and cause buffer overflow during memcpy below.
+               sendResult(handle, SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_BEYOND_ME_CAPABILITIES);
                return;
        }
 
@@ -109,29 +179,31 @@ void SmsPluginSatHandler::sendSms(void *pData)
 
        pkgInfo.szData[tpduLen] = '\0';
        pkgInfo.MsgLength = tpduLen;
+       pkgInfo.format = TAPI_NETTEXT_NETTYPE_3GPP;
 
        // Set SMSC Address
-       SMS_ADDRESS_S smsc;
+       SMS_ADDRESS_S smsc = {0,};
+       int simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
 
        if (pSmsData->address.diallingNumberLen > 0)
        {
                smsc.ton = pSmsData->address.ton;
                smsc.npi = pSmsData->address.npi;
-               memcpy(smsc.address, pSmsData->address.diallingNumber, pSmsData->address.diallingNumberLen);
-               smsc.address[pSmsData->address.diallingNumberLen] = '\0';
+               snprintf(smsc.address, sizeof(smsc.address), "%s", pSmsData->address.diallingNumber);
 
-               MSG_DEBUG("SCA TON[%d], NPI[%d], LEN[%d], ADDR[%s]", smsc.ton, smsc.npi, strlen(smsc.address), smsc.address);
+               MSG_SEC_DEBUG("SCA TON[%d], NPI[%d], LEN[%d], ADDR[%s]", smsc.ton, smsc.npi, strlen(smsc.address), smsc.address);
        }
        else
        {
                // Set SMSC Options
-               SmsPluginTransport::instance()->setSmscOptions(&smsc);
+               SmsPluginTransport::instance()->setSmscOptions(simIndex, &smsc);
        }
 
        unsigned char smscAddr[MAX_SMSC_LEN];
-       memset(smscAddr, 0x00, sizeof(smscAddr));
+       int smscLen = 0;
 
-       int smscLen = SmsPluginParamCodec::encodeSMSC(&smsc, smscAddr);
+       memset(smscAddr, 0x00, sizeof(smscAddr));
+       smscLen = SmsPluginParamCodec::encodeSMSC(&smsc, smscAddr);
 
        if (smscLen <= 0) return;
 
@@ -140,27 +212,48 @@ void SmsPluginSatHandler::sendSms(void *pData)
        memcpy((void*)pkgInfo.Sca, smscAddr, smscLen);
        pkgInfo.Sca[smscLen] = '\0';
 
-       int reqId = 0, tapiRet = TAPI_API_SUCCESS;
+       int tapiRet = TAPI_API_SUCCESS;
 
        // Send SMS
-       tapiRet = tel_send_sms(pTapiHandle, &pkgInfo, 0, TapiEventSentStatus, &reqId);
+       tapiRet = tel_send_sms(handle, &pkgInfo, 0, TapiEventSatSmsSentStatus, NULL);
 
        if (tapiRet == TAPI_API_SUCCESS)
        {
                MSG_DEBUG("########  TelTapiSmsSend Success !!! return : %d #######", tapiRet);
+
        }
        else
        {
                MSG_DEBUG("########  TelTapiSmsSend Fail !!! return : %d #######", tapiRet);
-               sendResult(SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_BEYOND_ME_CAPABILITIES);
+               sendResult(handle, SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_BEYOND_ME_CAPABILITIES);
        }
 }
 
 
-void SmsPluginSatHandler::ctrlSms(void *pData)
+void SmsPluginSatHandler::ctrlSms(struct tapi_handle *handle, void *pData)
 {
+       if (!pData) {
+               MSG_DEBUG("pData is NULL");
+               return;
+       }
+
        TelSatMoSmCtrlIndData_t* pCtrlData = (TelSatMoSmCtrlIndData_t*)pData;
 
+#if 0 // sangkoo 13.11.28
+       if (bSendSmsbySat == true) {// Send SMS By SAT
+               MSG_DEBUG("Event Noti for sending message by SAT : result = [%d]", pCtrlData->moSmsCtrlResult);
+       } else { // Send SMS By APP
+               SmsPluginTransport::instance()->setMoCtrlStatus(pCtrlData);
+       }
+#else
+       if (pCtrlData->moSmsCtrlResult == TAPI_SAT_CALL_CTRL_R_NOT_ALLOWED) {
+               MsgInsertTicker("Sending message failed : blocked by call control", NULL, true, 0);
+       }
+#endif
+
+       return;
+
+#if 0
        if (bSendSms == true) // Send SMS By SAT
        {
                if (pCtrlData->moSmsCtrlResult == TAPI_SAT_CALL_CTRL_R_NOT_ALLOWED)
@@ -196,29 +289,43 @@ void SmsPluginSatHandler::ctrlSms(void *pData)
                // Call Event Handler
                SmsPluginEventHandler::instance()->handleSentStatus(netStatus);
        }
+#endif
 }
 
 
-void SmsPluginSatHandler::ctrlSms(msg_network_status_t netStatus)
+void SmsPluginSatHandler::ctrlSms(struct tapi_handle *handle, SMS_NETWORK_STATUS_T smsStatus)
 {
-       if (bSendSms == true) // Send SMS By SAT
-       {
-               if (netStatus == MSG_NETWORK_SEND_SUCCESS)
-               {
-                       MSG_DEBUG("Sending SMS by SAT is OK");
-
-                       sendResult(SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_SUCCESS);
-               }
-               else if (netStatus == MSG_NETWORK_SEND_FAIL)
-               {
-                       MSG_DEBUG("Sending SMS by SAT is failed");
+       MSG_DEBUG("SMS network status = [%d]", smsStatus);
+
+       if (smsStatus == SMS_NETWORK_SEND_SUCCESS) {
+               MSG_DEBUG("Sending SMS by SAT is OK");
+               sendResult(handle, SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_SUCCESS);
+       } else if (smsStatus == SMS_NETWORK_SEND_FAIL) {
+               MSG_ERR("Sending SMS by SAT is failed");
+               sendResult(handle, SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_SMS_RP_ERROR);
+       } else if (smsStatus == SMS_NETWORK_SEND_FAIL_MANDATORY_INFO_MISSING){
+               MSG_ERR("Sending SMS by SAT is failed, but result is 'success'");
+               //sendResult(SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_ERROR_REQUIRED_VALUES_ARE_MISSING);
+               sendResult(handle, SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_SUCCESS);
+       } else if (smsStatus == SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_NOT_ALLOWED){
+               MSG_ERR("Sending SMS is failed by MO control");
+               sendResult(handle, SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_INTRCTN_WITH_CC_OR_SMS_CTRL_PRMNT_PRBLM);
+       } else if (smsStatus == SMS_NETWORK_SEND_FAIL_NO_ROUTING){
+               MSG_ERR("Sending SMS is failed by no routing");
+               sendResult(handle, SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_NETWORK_UNABLE_TO_PROCESS_COMMAND);
+       } else { /*Default case*/
+               MSG_ERR("Sending SMS by SAT is failed");
+               sendResult(handle, SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_SMS_RP_ERROR);
+       }
 
-                       sendResult(SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_SMS_RP_ERROR);
-               }
+#if 0 //P150109-07114 : no ticker and sound for sending SAT sms failure case.
+       if (smsStatus != SMS_NETWORK_SEND_SUCCESS) {
+               MsgInsertTicker("Sending SMS is failed", SMS_MESSAGE_SENDING_FAIL, true, 0);
        }
+#endif
 }
 
-
+#if 0
 void SmsPluginSatHandler::finishSimMsgInit(msg_error_t Err)
 {
        // SAT Handler is initializing SIM now
@@ -289,11 +396,11 @@ void      SmsPluginSatHandler::initSMSCList()
                MSG_DEBUG("pid[%d]", settingData.option.smscList.smscData[i].pid);
 //             MSG_DEBUG("dcs[%d]", settingData.option.smscList.smscData[i].dcs);
                MSG_DEBUG("val_period[%d]", settingData.option.smscList.smscData[i].valPeriod);
-               MSG_DEBUG("name[%s]", settingData.option.smscList.smscData[i].name);
+               MSG_SEC_DEBUG("name[%s]", settingData.option.smscList.smscData[i].name);
 
                MSG_DEBUG("ton[%d]", settingData.option.smscList.smscData[i].smscAddr.ton);
                MSG_DEBUG("npi[%d]", settingData.option.smscList.smscData[i].smscAddr.npi);
-               MSG_DEBUG("address[%s]", settingData.option.smscList.smscData[i].smscAddr.address);
+               MSG_SEC_DEBUG("address[%s]", settingData.option.smscList.smscData[i].smscAddr.address);
        }
 
        if (MsgSettingSetInt(SMSC_SELECTED, settingData.option.smscList.selected) != MSG_SUCCESS)
@@ -308,43 +415,51 @@ void      SmsPluginSatHandler::initSMSCList()
                return;
        }
 
-       char keyName[128];
+       char keyName[MAX_VCONFKEY_NAME_LEN];
        msg_error_t err = MSG_SUCCESS;
 
        for (int i = 0; i < settingData.option.smscList.totalCnt; i++)
        {
                memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_PID, i);
+               snprintf(keyName, sizeof(keyName), "%s/%d", SMSC_PID, i);
 
                if ((err = MsgSettingSetInt(keyName, (int)settingData.option.smscList.smscData[i].pid)) != MSG_SUCCESS)
                        break;
 
+#if 0
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", SMSC_DCS, i);
+
+               if ((err = MsgSettingSetInt(keyName, (int)settingData.option.smscList.smscData[i].dcs)) != MSG_SUCCESS)
+                       break;
+#endif
+
                memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_VAL_PERIOD, i);
+               snprintf(keyName, sizeof(keyName), "%s/%d", SMSC_VAL_PERIOD, i);
 
                if ((err = MsgSettingSetInt(keyName, (int)settingData.option.smscList.smscData[i].valPeriod)) != MSG_SUCCESS)
                        break;
 
                memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_NAME, i);
+               snprintf(keyName, sizeof(keyName), "%s/%d", SMSC_NAME, i);
 
                if ((err = MsgSettingSetString(keyName, settingData.option.smscList.smscData[i].name)) != MSG_SUCCESS)
                        break;
 
                memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_TON, i);
+               snprintf(keyName, sizeof(keyName), "%s/%d", SMSC_TON, i);
 
                if ((err = MsgSettingSetInt(keyName, (int)settingData.option.smscList.smscData[i].smscAddr.ton)) != MSG_SUCCESS)
                        break;
 
                memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_NPI, i);
+               snprintf(keyName, sizeof(keyName), "%s/%d", SMSC_NPI, i);
 
                if ((err = MsgSettingSetInt(keyName, (int)settingData.option.smscList.smscData[i].smscAddr.npi)) != MSG_SUCCESS)
                        break;
 
                memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_ADDRESS, i);
+               snprintf(keyName, sizeof(keyName), "%s/%d", SMSC_ADDRESS, i);
 
                if ((err = MsgSettingSetString(keyName, settingData.option.smscList.smscData[i].smscAddr.address)) != MSG_SUCCESS)
                        break;
@@ -361,6 +476,9 @@ void        SmsPluginSatHandler::initCBConfig()
 {
        MSG_SETTING_S settingData;
 
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
+
        settingData.type = MSG_CBMSG_OPT;
 
        // Get Data From SIM
@@ -378,48 +496,15 @@ void      SmsPluginSatHandler::initCBConfig()
                return;
        }
 
-       if (MsgSettingSetInt(CB_CHANNEL_COUNT, settingData.option.cbMsgOpt.channelData.channelCnt) != MSG_SUCCESS)
-       {
-               THROW(MsgException::SMS_PLG_ERROR, "Error to set config data [%s]", CB_CHANNEL_COUNT);
-               return;
-       }
-
-       char keyName[128];
-       msg_error_t err = MSG_SUCCESS;
-
-       for (int i = 0; i < settingData.option.cbMsgOpt.channelData.channelCnt; i++)
-       {
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ACTIVATE, i);
-
-               if ((err = MsgSettingSetBool(keyName, settingData.option.cbMsgOpt.channelData.channelInfo[i].bActivate)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ID_FROM, i);
-
-               if ((err = MsgSettingSetInt(keyName, settingData.option.cbMsgOpt.channelData.channelInfo[i].from)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ID_TO, i);
-
-               if ((err = MsgSettingSetInt(keyName, settingData.option.cbMsgOpt.channelData.channelInfo[i].to)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_NAME, i);
-
-               if ((err = MsgSettingSetString(keyName, settingData.option.cbMsgOpt.channelData.channelInfo[i].name)) != MSG_SUCCESS)
-                       break;
-       }
+       err = MsgStoAddCBChannelInfo(dbHandle, &(settingData.option.cbMsgOpt.channelData), settingData.option.cbMsgOpt.simIndex);
+       MSG_DEBUG("MsgStoAddCBChannelInfo : err=[%d]", err);
 
        if (err != MSG_SUCCESS)
        {
-               THROW(MsgException::SMS_PLG_ERROR, "Error to set config data [%s]", keyName);
+               THROW(MsgException::SMS_PLG_ERROR, "Error to set config data");
        }
 }
-
+#endif
 
 int SmsPluginSatHandler::handleSatTpdu(unsigned char *pTpdu, unsigned char TpduLen, int bIsPackingRequired)
 {
@@ -430,7 +515,7 @@ int SmsPluginSatHandler::handleSatTpdu(unsigned char *pTpdu, unsigned char TpduL
 
        // TP-MTI, TP-RD, TP-VPF,  TP-RP, TP-UDHI, TP-SRR
        // TP-VPF
-       SMS_VPF_T vpf = (SMS_VPF_T)(pTpdu[pos++] & 0x18);
+       SMS_VPF_T vpf = (SMS_VPF_T)(pTpdu[pos++] & 0x18) >> 3;
 
        // TP-MR
        unsigned char tmpRef = pTpdu[pos];
@@ -465,7 +550,7 @@ int SmsPluginSatHandler::handleSatTpdu(unsigned char *pTpdu, unsigned char TpduL
                dcs.codingScheme = SMS_CHARSET_7BIT;
 
                char* pDcs = NULL;
-               AutoPtr<char> dcsBuf(&pDcs);
+               unique_ptr<char*, void(*)(char**)> dcsBuf(&pDcs, unique_ptr_deleter);
 
                SmsPluginParamCodec::encodeDCS(&dcs, &pDcs);
 
@@ -486,7 +571,6 @@ int SmsPluginSatHandler::handleSatTpdu(unsigned char *pTpdu, unsigned char TpduL
 
        // TP-UDL
        int udl = pTpdu[pos];
-
        int retLen = 0;
 
        if (bIsPackingRequired == true)
@@ -498,7 +582,7 @@ int SmsPluginSatHandler::handleSatTpdu(unsigned char *pTpdu, unsigned char TpduL
                memcpy(userData.data, &pTpdu[pos+1], udl);
                userData.data[udl] = '\0';
 
-MSG_DEBUG("user data : %s", userData.data);
+MSG_DEBUG("user data : [%s]", userData.data);
 
                int encodeSize = SmsPluginUDCodec::encodeUserData(&userData, dcs.codingScheme, (char*)&pTpdu[pos]);
 
@@ -513,9 +597,10 @@ MSG_DEBUG("user data : %s", userData.data);
 }
 
 
-void SmsPluginSatHandler::sendResult(SMS_SAT_CMD_TYPE_T CmdType, int ResultType)
+void SmsPluginSatHandler::sendResult(struct tapi_handle *handle, SMS_SAT_CMD_TYPE_T CmdType, int ResultType)
 {
        TelSatAppsRetInfo_t satRetInfo;
+       memset(&satRetInfo, 0, sizeof(TelSatAppsRetInfo_t));
 
        satRetInfo.commandId = commandId;
 
@@ -537,7 +622,7 @@ void SmsPluginSatHandler::sendResult(SMS_SAT_CMD_TYPE_T CmdType, int ResultType)
 
        int tapiRet = TAPI_API_SUCCESS;
 
-       tapiRet = tel_send_sat_app_exec_result(pTapiHandle, &satRetInfo);
+       tapiRet = tel_send_sat_app_exec_result(handle, &satRetInfo);
 
        if (tapiRet == TAPI_API_SUCCESS)
        {
@@ -548,9 +633,7 @@ void SmsPluginSatHandler::sendResult(SMS_SAT_CMD_TYPE_T CmdType, int ResultType)
                MSG_DEBUG("TelTapiSatSendAppExecutionResult() FAIL [%d]", tapiRet);
        }
 
-       bSendSms = false;
        bInitSim = false;
        bSMSPChanged = false;
        bCBMIChanged = false;
 }
-
index 520e3f4..461aa03 100755 (executable)
@@ -1,28 +1,40 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
+#include <pthread.h>
 
 #include "MsgDebug.h"
+#include "MsgCppTypes.h"
 #include "MsgException.h"
 #include "MsgGconfWrapper.h"
+#include "MsgNotificationWrapper.h"
+#include "MsgSoundPlayer.h"
+#include "MsgContact.h"
+#include "MsgUtilStorage.h"
+#include "MsgTextConvert.h"
+#include "MsgDevicedWrapper.h"
+
 #include "SmsPluginParamCodec.h"
 #include "SmsPluginCallback.h"
+#include "SmsPluginEventHandler.h"
+#include "SmsPluginSimMsg.h"
+#include "SmsPluginMain.h"
 #include "SmsPluginSetting.h"
-
+#include "SmsPluginDSHandler.h"
 
 extern "C"
 {
@@ -30,12 +42,17 @@ extern "C"
        #include <TelSms.h>
        #include <TapiUtility.h>
        #include <ITapiNetText.h>
+       #include <ITapiSim.h>
+       #include <ITapiModem.h>
 }
 
-extern struct tapi_handle *pTapiHandle;
+/*==================================================================================================
+                                  INTERNAL FUNCTION
+==================================================================================================*/
+
 
 /*==================================================================================================
-                                     IMPLEMENTATION OF SmsPluginSetting - Member Functions
+                   IMPLEMENTATION OF SmsPluginSetting - Member Functions
 ==================================================================================================*/
 SmsPluginSetting* SmsPluginSetting::pInstance = NULL;
 
@@ -43,12 +60,23 @@ SmsPluginSetting* SmsPluginSetting::pInstance = NULL;
 SmsPluginSetting::SmsPluginSetting()
 {
        // Initialize member variables
-       memset(&smscData, 0x00, sizeof(MSG_SMSC_DATA_S));
-       memset(&cbOpt, 0x00, sizeof(MSG_CBMSG_OPT_S));
+       for (int i = 0; i <= MAX_TELEPHONY_HANDLE_CNT; i++) {
+               memset(&smscList[i], 0x00, sizeof(MSG_SMSC_LIST_S));
+               memset(&smscData[i], 0x00, sizeof(MSG_SMSC_DATA_S));
+               memset(&cbOpt[i], 0x00, sizeof(MSG_CBMSG_OPT_S));
+               memset(&simMailboxList[i], 0x00, sizeof(SMS_SIM_MAILBOX_LIST_S));
+               memset(&simMwiInfo[i], 0x00, sizeof(SMS_SIM_MWI_INFO_S));
+               simStatus[i] = MSG_SIM_STATUS_NOT_FOUND;
+       }
+       memset(&meImei, 0x00, sizeof(meImei));
 
        bTapiResult = false;
        paramCnt = 0;
        selectedParam = 0;
+       selectedSimIndex = 0;
+
+       for (int i = 0; i < MAX_TELEPHONY_HANDLE_CNT; i++)
+               bMbdnEnable[i] = false;
 }
 
 
@@ -68,27 +96,138 @@ SmsPluginSetting* SmsPluginSetting::instance()
 }
 
 
-void SmsPluginSetting::initConfigData(MSG_SIM_STATUS_T SimStatus)
+void* SmsPluginSetting::initSimInfo(void *data)
+{
+       static Mutex mm;
+       MutexLocker lock(mm);
+
+       SmsPluginSetting::instance()->processInitSimInfo(data);
+
+       return NULL;
+}
+
+void* SmsPluginSetting::processInitSimInfo(void *data)
+{
+       MSG_BEGIN();
+
+       //Handle sim info initialization separately
+       struct tapi_handle *handle = (struct tapi_handle *)data;
+       instance()->updateSimStatus(handle);
+
+       MSG_END();
+       return NULL;
+}
+
+
+void SmsPluginSetting::updateSimStatus(struct tapi_handle *handle)
+{
+       MSG_BEGIN();
+
+       if (!handle) {
+               MSG_DEBUG("handle is NULL.");
+               return;
+       }
+
+       int status = 0;
+       int tapiRet = TAPI_API_SUCCESS;
+
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       memset(keyName, 0x00, sizeof(keyName));
+
+       int simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+       // Get IMSI
+       char imsi[17];
+       memset(imsi, 0x00, sizeof(imsi));
+
+       TelSimImsiInfo_t imsiInfo;
+       memset(&imsiInfo, 0x00, sizeof(TelSimImsiInfo_t));
+
+       tapiRet = tel_get_sim_imsi(handle, &imsiInfo);
+
+       if (tapiRet == TAPI_API_SUCCESS) {
+               MSG_SEC_DEBUG("tel_get_sim_imsi() Success - MCC [%s], MNC [%s], MSIN [%s]", imsiInfo.szMcc, imsiInfo.szMnc, imsiInfo.szMsin);
+
+               snprintf(imsi, sizeof(imsi), "%03d%03d%s", atoi(imsiInfo.szMcc), atoi(imsiInfo.szMnc), imsiInfo.szMsin);
+               MSG_SEC_DEBUG("IMSI [%s]", imsi);
+       } else {
+               MSG_DEBUG("tel_get_sim_imsi() Error![%d]", tapiRet);
+               snprintf(keyName, sizeof(keyName), "%s/%d", MSG_NATIONAL_SIM, simIndex);
+               if (MsgSettingSetBool(keyName, false) != MSG_SUCCESS)
+                       MSG_DEBUG("Fail MsgSettingSetBool");
+       }
+
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_IMSI, simIndex);
+       if (MsgSettingSetString(keyName, imsi) != MSG_SUCCESS)
+               MSG_DEBUG("Fail MsgSettingSetString");
+
+       /* Check device status */
+       tapiRet = tel_check_sms_device_status(handle, &status);
+
+       if (tapiRet != TAPI_API_SUCCESS) {
+               MSG_DEBUG("tel_check_sms_device_status() Error! [%d], Status [%d]", tapiRet, status);
+               return;
+       }
+
+       if (status == TAPI_NETTEXT_READY_STATUS_3GPP) {
+               MSG_DEBUG("Device Is Ready");
+       } else {
+               MSG_DEBUG("Device Is Not Ready.. Waiting For Ready Callback");
+
+               if (SmsPluginEventHandler::instance()->getDeviceStatus(handle) == true) {
+                       MSG_DEBUG("Device Is Ready");
+               } else {
+                       MSG_DEBUG("Device Is Not Ready.");
+                       return;
+               }
+       }
+
+       // init config data.
+       initConfigData(handle);
+
+       try
+       {
+               // init sim messages.
+               SmsPluginSimMsg::instance()->initSimMessage(handle);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+
+
+       MSG_END();
+
+       return;
+}
+
+
+void SmsPluginSetting::initConfigData(struct tapi_handle *handle)
 {
        MSG_BEGIN();
 
-       msg_error_t     err = MSG_SUCCESS;
+       char keyName[MAX_VCONFKEY_NAME_LEN];
 
+       int sim_idx = SmsPluginDSHandler::instance()->getSimIndex(handle);
+       /*==================== SMSC setting ====================*/
        // Init SMS Parameter
        int paramCnt = 0;
        int failCnt = 0;
+       bool bSelectedFound = false;
+       bool bAPReceive = false;
 
-       paramCnt = getParamCount();
+       paramCnt = getParamCount(handle);
 
-       MSG_DEBUG("Parameter Count [%d]", paramCnt);
+       MSG_INFO("Parameter Count [%d]", paramCnt);
 
        MSG_SMSC_DATA_S tmpSmscData = {};
-       MSG_SMSC_LIST_S tmpSmscList = {};
+       MSG_SMSC_LIST_S tmpSmscList = {0,};
 
        for (int index = 0; index < paramCnt; index++)
        {
-               if (getParam(index, &tmpSmscData) == false)
-               {
+               memset(&tmpSmscData, 0x00, sizeof(MSG_SMSC_DATA_S));
+               if (getParam(handle, index, &tmpSmscData) == false) {
                        failCnt++;
                        continue;
                }
@@ -97,85 +236,186 @@ void SmsPluginSetting::initConfigData(MSG_SIM_STATUS_T SimStatus)
 
                MSG_DEBUG("pid[%d]", tmpSmscList.smscData[index].pid);
                MSG_DEBUG("val_period[%d]", tmpSmscList.smscData[index].valPeriod);
-               MSG_DEBUG("name[%s]", tmpSmscList.smscData[index].name);
+               MSG_SEC_DEBUG("name[%s]", tmpSmscList.smscData[index].name);
 
                MSG_DEBUG("ton[%d]", tmpSmscList.smscData[index].smscAddr.ton);
                MSG_DEBUG("npi[%d]", tmpSmscList.smscData[index].smscAddr.npi);
-               MSG_DEBUG("address[%s]", tmpSmscList.smscData[index].smscAddr.address);
+               MSG_SEC_DEBUG("address[%s]", tmpSmscList.smscData[index].smscAddr.address);
+
+               //First smsc is selected index
+               if (!bSelectedFound) {
+                       tmpSmscList.selected = selectedParam;
+                       bSelectedFound = !bSelectedFound;
+               }
        }
 
        tmpSmscList.totalCnt = (paramCnt - failCnt);
-       tmpSmscList.selected = selectedParam;
-
-       if (paramCnt > 0)
-       {
-               err = addSMSCList(&tmpSmscList);
+       tmpSmscList.simIndex = sim_idx;
 
-               if (err == MSG_SUCCESS)
-               {
-                       MSG_DEBUG("########  Add SMSC List Success !!! #######");
-               }
-               else
-               {
-                       MSG_DEBUG("########  Add SMSC List Fail !!! return : %d #######", err);
-               }
+       if (paramCnt > 0) {
+               MSG_DEBUG("########  Add SMSC ist #######");
+               addSMSCList(&tmpSmscList);
        }
 
-       // Init CB Config
-       if (SimStatus == MSG_SIM_STATUS_CHANGED)
+       /*==================== CB configuration ====================*/
+       if (simStatus[sim_idx] != MSG_SIM_STATUS_NOT_FOUND)
        {
-               MSG_DEBUG("simStatus == MSG_SIM_STATUS_CHANGED");
+               MSG_DEBUG("simStatus == [%d]", simStatus[sim_idx]);
 
-               MSG_CBMSG_OPT_S cbMsgOpt = {};
+               MSG_CBMSG_OPT_S cbMsgOpt = {0,};
+               cbMsgOpt.simIndex = sim_idx;
 
-               if (getCbConfig(&cbMsgOpt) == true)
-               {
-                       err = addCbOpt(&cbMsgOpt);
+               if (getCbConfig(&cbMsgOpt) == true) {
+                       cbMsgOpt.simIndex = sim_idx;
 
-                       if (err == MSG_SUCCESS)
-                       {
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", CB_RECEIVE, sim_idx);
+                       MsgSettingGetBool(keyName, &bAPReceive);
+
+                       if (cbMsgOpt.bReceive == false && bAPReceive == false) {
+                               MSG_DEBUG("CB is off in CP and in AP. No need to send CB request to CP. ");
+                       }
+                       else {
                                MSG_DEBUG("########  Add CB Option Success !!! #######");
+                               MSG_SETTING_S cbSetting;
+                               getCbOpt(&cbSetting, sim_idx);
+                               setCbConfig(&(cbSetting.option.cbMsgOpt));
                        }
-                       else
-                       {
-                               MSG_DEBUG("########  Add CB Option Fail !!! return : %d #######", err);
+               } else {
+                       MSG_WARN("########  getCbConfig Fail !!! #######");
+
+#if 0
+                       // CSC doesn't support CB Info any longer
+                       if (MsgCscGetCBInfo(&cbMsgOpt) == true) {
+                               err = addCbOpt(&cbMsgOpt);
+
+                               if (err == MSG_SUCCESS) {
+                                       MSG_DEBUG("########  Add CB Option From CSC Success !!! #######");
+                               } else {
+                                       MSG_DEBUG("########  Add CB Option from CSC Fail !!! return : %d #######", err);
+                               }
+                       } else {
+                               MSG_DEBUG("########  MsgCscGetCBInfo Fail !!! #######");
                        }
+#endif
+               }
+
+               /*==================== Default Voice mail Setting ====================*/
+               if (simStatus[sim_idx] == MSG_SIM_STATUS_CHANGED) {
+                       char keyName[MAX_VCONFKEY_NAME_LEN];
+
+                       MSG_DEBUG("=================SIM CHANGED===================");
+
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_NUMBER, sim_idx);
+                       if (MsgSettingSetString(keyName, VOICEMAIL_DEFAULT_NUMBER) != MSG_SUCCESS)
+                               MSG_DEBUG("MsgSettingSetString is failed!!");
+
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_COUNT, sim_idx);
+                       if (MsgSettingSetInt(keyName, 0) != MSG_SUCCESS)
+                               MSG_DEBUG("MsgSettingSetInt is failed!!");
+
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_ALPHA_ID, sim_idx);
+                       if (MsgSettingSetString(keyName, VOICEMAIL_DEFAULT_ALPHA_ID) != MSG_SUCCESS)
+                               MSG_DEBUG("MsgSettingSetString is failed!!");
+
+                       MsgDeleteNoti(MSG_NOTI_TYPE_VOICE_1, sim_idx);
+                       MsgDeleteNoti(MSG_NOTI_TYPE_VOICE_2, sim_idx);
+               }
+
+
+               /*==================== Voice mail information update ====================*/
+               if (getVoiceMailInfo(handle) == true) {
+                       MSG_DEBUG("########  getVoiceMailInfo Success !!! #######");
+               } else {
+                       MSG_WARN("########  getVoiceMailInfo Fail !!! #######");
                }
-       }
-       else if (SimStatus == MSG_SIM_STATUS_NORMAL)
-       {
-               MSG_DEBUG("simStatus == MSG_SIM_STATUS_NORMAL");
 
-               // Set CB Data into SIM in case of same SIM
-               MSG_SETTING_S cbSetting;
-               cbSetting.type = MSG_CBMSG_OPT;
+               /*==================== Voice mail count update ====================*/
+               if (getMwiInfo(handle) == true) {
+                       MSG_DEBUG("########  getMwiInfo Success !!! #######");
+               } else {
+                       MSG_WARN("########  getMwiInfo Fail !!! #######");
+
+                       // Get MWI from vconf and insert notification
+                       int mwiCnt = 0;
+                       char keyName[MAX_VCONFKEY_NAME_LEN];
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_COUNT, sim_idx);
+                       if ((mwiCnt = MsgSettingGetInt(keyName)) > 0)
+                               deliverVoiceMsgNoti(sim_idx, mwiCnt);
+               }
 
-               getCbOpt(&cbSetting);
+               /*==================== MSISDN update ====================*/
+               if (getMsisdnInfo(handle) == true) {
+                       MSG_DEBUG("########  getMsisdnInfo Success !!! #######");
+               } else {
+                       MSG_WARN("########  getMsisdnInfo Fail !!! #######");
+               }
 
-               setCbConfig(&(cbSetting.option.cbMsgOpt));
+               /*==================== SST(SIM Service Table) update ====================*/
+               if (getSimServiceTable(handle) == true) {
+                       MSG_DEBUG("########  getSimServiceTable Success !!! #######");
+               } else {
+                       MSG_WARN("########  getSimServiceTable Fail !!! #######");
+               }
        }
 
        MSG_END();
 }
 
 
+void SmsPluginSetting::SimRefreshCb(struct tapi_handle *handle)
+{
+       pthread_t thd;
+
+       if (pthread_create(&thd, NULL, &init_config_data, handle) < 0) {
+               MSG_DEBUG("pthread_create() error");
+       }
+
+       pthread_detach(thd);
+
+}
+
+
+void* SmsPluginSetting::init_config_data(void *data)
+{
+       struct tapi_handle *handle = (struct tapi_handle *)data;
+
+       instance()->initConfigData(handle);
+       return NULL;
+}
+
+
 void SmsPluginSetting::setConfigData(const MSG_SETTING_S *pSetting)
 {
        MSG_DEBUG("Setting Type : [%d]", pSetting->type);
 
        switch (pSetting->type)
        {
+#if 0
+               case MSG_SMS_SENDOPT :
+                       setNetworkMode(&pSetting->option.smsSendOpt);
+                       break;
+#endif
                case MSG_SMSC_LIST :
                        setParamList(&pSetting->option.smscList);
-               break;
-
+                       addSMSCList((MSG_SMSC_LIST_S *)(&pSetting->option.smscList));
+//                     setSmscInfo(&pSetting->option.smscList);
+                       break;
                case MSG_CBMSG_OPT :
-                       setCbConfig(&pSetting->option.cbMsgOpt);
-               break;
-
+                       if (setCbConfig(&pSetting->option.cbMsgOpt) == false) {
+                               THROW(MsgException::SMS_PLG_ERROR, "Failed to set config.");
+                       }
+                       break;
+               case MSG_VOICEMAIL_OPT:
+                       setVoiceMailInfo(&pSetting->option.voiceMailOpt);
+                       break;
                default :
                        THROW(MsgException::SMS_PLG_ERROR, "The Setting type is not supported. [%d]", pSetting->type);
-               break;
+                       break;
        }
 }
 
@@ -187,11 +427,14 @@ void SmsPluginSetting::getConfigData(MSG_SETTING_S *pSetting)
        switch (pSetting->type)
        {
                case MSG_SMSC_LIST :
-                       getParamList(&pSetting->option.smscList);
+//                     getParamList(&pSetting->option.smscList);
+                       getSmscListInfo(pSetting->option.smscList.simIndex, &(pSetting->option.smscList));
                break;
 
                case MSG_CBMSG_OPT :
-                       getCbConfig(&pSetting->option.cbMsgOpt);
+                       if (getCbConfig(&pSetting->option.cbMsgOpt) == false) {
+                               THROW(MsgException::SMS_PLG_ERROR, "Get CB config option failed.");
+                       }
                break;
 
                default :
@@ -201,10 +444,13 @@ void SmsPluginSetting::getConfigData(MSG_SETTING_S *pSetting)
 }
 
 
-msg_error_t SmsPluginSetting::addSMSCList(MSG_SMSC_LIST_S *pSmscList)
+void SmsPluginSetting::addSMSCList(MSG_SMSC_LIST_S *pSmscList)
 {
-       msg_error_t err = MSG_SUCCESS;
+       MSG_BEGIN();
 
+       int sim_index = -1;
+
+       MSG_DEBUG("SIM index[%d]", pSmscList->simIndex);
        MSG_DEBUG("total_count[%d]", pSmscList->totalCnt);
        MSG_DEBUG("selected index[%d]", pSmscList->selected);
 
@@ -212,85 +458,67 @@ msg_error_t SmsPluginSetting::addSMSCList(MSG_SMSC_LIST_S *pSmscList)
        {
                MSG_DEBUG("pid[%d]", pSmscList->smscData[i].pid);
                MSG_DEBUG("val_period[%d]", pSmscList->smscData[i].valPeriod);
-               MSG_DEBUG("name[%s]", pSmscList->smscData[i].name);
+               MSG_SEC_DEBUG("name[%s]", pSmscList->smscData[i].name);
 
                MSG_DEBUG("ton[%d]", pSmscList->smscData[i].smscAddr.ton);
                MSG_DEBUG("npi[%d]", pSmscList->smscData[i].smscAddr.npi);
-               MSG_DEBUG("address[%s]", pSmscList->smscData[i].smscAddr.address);
-       }
-
-       char keyName[128];
-
-       if (MsgSettingSetInt(SMSC_TOTAL_COUNT, pSmscList->totalCnt) != MSG_SUCCESS)
-       {
-               MSG_DEBUG("Error to set config data [%s]", SMSC_TOTAL_COUNT);
-               return MSG_ERR_SET_SETTING;
+               MSG_SEC_DEBUG("address[%s]", pSmscList->smscData[i].smscAddr.address);
        }
 
-       if (MsgSettingSetInt(SMSC_SELECTED, pSmscList->selected) != MSG_SUCCESS)
-       {
-               MSG_DEBUG("Error to set config data [%s]", SMSC_SELECTED);
-               return MSG_ERR_SET_SETTING;
-       }
-
-       for (int i = 0; i < pSmscList->totalCnt; i++)
-       {
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_PID, i);
-
-               if ((err = MsgSettingSetInt(keyName, (int)pSmscList->smscData[i].pid)) != MSG_SUCCESS)
-                       break;
+       sim_index = pSmscList->simIndex;
 
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_VAL_PERIOD, i);
+       smscList[sim_index].simIndex = pSmscList->simIndex;
+       smscList[sim_index].totalCnt = pSmscList->totalCnt;
+       smscList[sim_index].selected = pSmscList->selected;
 
-               if ((err = MsgSettingSetInt(keyName, (int)pSmscList->smscData[i].valPeriod)) != MSG_SUCCESS)
-                       break;
+       for (int i = 0; i < pSmscList->totalCnt; i++) {
 
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_NAME, i);
+               smscList[sim_index].smscData[i].pid = pSmscList->smscData[i].pid;
+               smscList[sim_index].smscData[i].valPeriod = pSmscList->smscData[i].valPeriod;
 
-               if ((err = MsgSettingSetString(keyName, pSmscList->smscData[i].name)) != MSG_SUCCESS)
-                       break;
+               memset(smscList[sim_index].smscData[i].name, 0x00, SMSC_NAME_MAX+1);
+               memcpy(smscList[sim_index].smscData[i].name, pSmscList->smscData[i].name, SMSC_NAME_MAX);
 
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_TON, i);
+               memset(smscList[sim_index].smscData[i].smscAddr.address, 0x00, SMSC_ADDR_MAX+1);
+               memcpy(smscList[sim_index].smscData[i].smscAddr.address, pSmscList->smscData[i].smscAddr.address, SMSC_ADDR_MAX);
 
                if (pSmscList->smscData[i].smscAddr.address[0] == '+')
-                       pSmscList->smscData[i].smscAddr.ton = MSG_TON_INTERNATIONAL;
+                       smscList[sim_index].smscData[i].smscAddr.ton = MSG_TON_INTERNATIONAL;
                else
-                       pSmscList->smscData[i].smscAddr.ton = MSG_TON_NATIONAL;
-
-               if ((err = MsgSettingSetInt(keyName, (int)pSmscList->smscData[i].smscAddr.ton)) != MSG_SUCCESS)
-                       break;
+                       smscList[sim_index].smscData[i].smscAddr.ton = MSG_TON_NATIONAL;
 
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_NPI, i);
-
-               pSmscList->smscData[i].smscAddr.npi = MSG_NPI_ISDN; // app cannot set this value
+               smscList[sim_index].smscData[i].smscAddr.npi = MSG_NPI_ISDN; // app cannot set this value
+       }
 
-               if ((err = MsgSettingSetInt(keyName, (int)pSmscList->smscData[i].smscAddr.npi)) != MSG_SUCCESS)
-                       break;
+       MSG_END();
+}
 
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", SMSC_ADDRESS, i);
 
-               if ((err = MsgSettingSetString(keyName, pSmscList->smscData[i].smscAddr.address)) != MSG_SUCCESS)
-                       break;
+void SmsPluginSetting::getSmscListInfo(int simIndex, MSG_SMSC_LIST_S *pSmscList)
+{
+       if (pSmscList == NULL) {
+               MSG_DEBUG("pSmscList is NULL!");
+               return;
        }
 
-       if (err != MSG_SUCCESS)
-       {
-               MSG_DEBUG("Error to set config data [%s]", keyName);
+       if (simIndex <= 0) {
+               struct tapi_handle *handle = SmsPluginDSHandler::instance()->getTelHandle(simIndex);
+               simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
        }
 
-       return err;
+       if (simIndex == -1)
+               memset(pSmscList, 0x00, sizeof(MSG_SMSC_LIST_S));
+       else
+               memcpy(pSmscList, &smscList[simIndex], sizeof(MSG_SMSC_LIST_S));
+
+       return;
 }
 
 
 msg_error_t SmsPluginSetting::addCbOpt(MSG_CBMSG_OPT_S *pCbOpt)
 {
        msg_error_t err = MSG_SUCCESS;
+       char keyName[MAX_VCONFKEY_NAME_LEN];
 
        MSG_DEBUG("Receive [%d], Max SIM Count [%d]", pCbOpt->bReceive, pCbOpt->maxSimCnt);
 
@@ -301,105 +529,63 @@ msg_error_t SmsPluginSetting::addCbOpt(MSG_CBMSG_OPT_S *pCbOpt)
                MSG_DEBUG("Channel FROM [%d], Channel TO [%d]", pCbOpt->channelData.channelInfo[i].from, pCbOpt->channelData.channelInfo[i].to);
        }
 
+#if 0
        // Set Setting Data into Vconf
-       if (MsgSettingSetBool(CB_RECEIVE, pCbOpt->bReceive) != MSG_SUCCESS)
-       {
-               MSG_DEBUG("Error to set config data [%s]", CB_RECEIVE);
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", CB_RECEIVE, pCbOpt->simIndex);
+       if (MsgSettingSetBool(keyName, pCbOpt->bReceive) != MSG_SUCCESS) {
+               MSG_DEBUG("Error to set config data [%s]", keyName);
                return MSG_ERR_SET_SETTING;
        }
+#endif
 
-       if (MsgSettingSetInt(CB_MAX_SIM_COUNT, pCbOpt->maxSimCnt) != MSG_SUCCESS)
-       {
-               MSG_DEBUG("Error to set config data [%s]", CB_MAX_SIM_COUNT);
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", CB_MAX_SIM_COUNT, pCbOpt->simIndex);
+       if (MsgSettingSetInt(keyName, pCbOpt->maxSimCnt) != MSG_SUCCESS) {
+               MSG_DEBUG("Error to set config data [%s]", keyName);
                return MSG_ERR_SET_SETTING;
        }
 
-       if (MsgSettingSetInt(CB_CHANNEL_COUNT, pCbOpt->channelData.channelCnt) != MSG_SUCCESS)
-       {
-               MSG_DEBUG("Error to set config data [%s]", CB_CHANNEL_COUNT);
+#if 0
+       MsgDbHandler *dbHandle = getDbHandle();
+       err = MsgStoAddCBChannelInfo(dbHandle, &pCbOpt->channelData);
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("MsgStoGetCBChannelInfo is failed [%d]", err);
                return MSG_ERR_SET_SETTING;
        }
-
-       char keyName[128];
-
-       for (int i = 0; i < pCbOpt->channelData.channelCnt; i++)
-       {
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ACTIVATE, i);
-
-               if ((err = MsgSettingSetBool(keyName, pCbOpt->channelData.channelInfo[i].bActivate)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ID_FROM, i);
-
-               if ((err = MsgSettingSetInt(keyName, pCbOpt->channelData.channelInfo[i].from)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ID_TO, i);
-
-               if ((err = MsgSettingSetInt(keyName, pCbOpt->channelData.channelInfo[i].to)) != MSG_SUCCESS)
-                       break;
-
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_NAME, i);
-
-               if ((err = MsgSettingSetString(keyName, pCbOpt->channelData.channelInfo[i].name)) != MSG_SUCCESS)
-                       break;
-       }
+#endif
 
        return err;
 }
 
 
-void SmsPluginSetting::getCbOpt(MSG_SETTING_S *pSetting)
+void SmsPluginSetting::getCbOpt(MSG_SETTING_S *pSetting, int simIndex)
 {
-       char keyName[128];
-       char *tmpValue = NULL;
-
-       memset(&(pSetting->option.cbMsgOpt), 0x00, sizeof(MSG_CBMSG_OPT_S));
-
-       MsgSettingGetBool(CB_RECEIVE, &pSetting->option.cbMsgOpt.bReceive);
-
-       pSetting->option.cbMsgOpt.maxSimCnt = MsgSettingGetInt(CB_MAX_SIM_COUNT);
-
-       pSetting->option.cbMsgOpt.channelData.channelCnt = MsgSettingGetInt(CB_CHANNEL_COUNT);
-
-       for (int i = 0; i < pSetting->option.cbMsgOpt.channelData.channelCnt; i++)
-       {
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ACTIVATE, i);
+       char keyName[MAX_VCONFKEY_NAME_LEN];
 
-               MsgSettingGetBool(keyName, &pSetting->option.cbMsgOpt.channelData.channelInfo[i].bActivate);
-
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ID_FROM, i);
-
-               pSetting->option.cbMsgOpt.channelData.channelInfo[i].from = MsgSettingGetInt(keyName);
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
 
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_ID_TO, i);
+       memset(&(pSetting->option.cbMsgOpt), 0x00, sizeof(MSG_CBMSG_OPT_S));
 
-               pSetting->option.cbMsgOpt.channelData.channelInfo[i].to = MsgSettingGetInt(keyName);
+       pSetting->type = MSG_CBMSG_OPT;
+       pSetting->option.cbMsgOpt.simIndex = simIndex;
 
-               memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_CHANNEL_NAME, i);
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", CB_RECEIVE, simIndex);
+       MsgSettingGetBool(keyName, &pSetting->option.cbMsgOpt.bReceive);
 
-               tmpValue = MsgSettingGetString(keyName);
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", CB_MAX_SIM_COUNT, simIndex);
+       pSetting->option.cbMsgOpt.maxSimCnt = MsgSettingGetInt(keyName);
 
-               if (tmpValue != NULL)
-               {
-                       strncpy(pSetting->option.cbMsgOpt.channelData.channelInfo[i].name, tmpValue, CB_CHANNEL_NAME_MAX);
-                       free(tmpValue);
-                       tmpValue = NULL;
-               }
-       }
+       err = MsgStoGetCBChannelInfo(dbHandle, &pSetting->option.cbMsgOpt.channelData, simIndex);
+       if (err != MSG_SUCCESS)
+               MSG_ERR("MsgStoGetCBChannelInfo : err=[%d]", err);
 
-       for (int i = MSG_CBLANG_TYPE_ALL; i < MSG_CBLANG_TYPE_MAX; i++)
-       {
+       for (int i = MSG_CBLANG_TYPE_ALL; i < MSG_CBLANG_TYPE_MAX; i++) {
                memset(keyName, 0x00, sizeof(keyName));
-               sprintf(keyName, "%s/%d", CB_LANGUAGE, i);
+               snprintf(keyName, sizeof(keyName), "%s/%d", CB_LANGUAGE, i);
 
                MsgSettingGetBool(keyName, &pSetting->option.cbMsgOpt.bLanguage[i]);
        }
@@ -411,78 +597,78 @@ void SmsPluginSetting::setParamList(const MSG_SMSC_LIST_S *pSMSCList)
 {
        MSG_BEGIN();
 
+       MutexLocker lock(mx);
+
        TelSmsParams_t smsParam = {0};
 
        int ret = TAPI_API_SUCCESS;
-       int reqId = 0;
 
-       for (int index = 0; index < pSMSCList->totalCnt; index++)
-       {
-               /*Setting the SMSP Record index value*/
-               smsParam.RecordIndex = (unsigned char)index;
+       int index = pSMSCList->index;
+       MSG_DEBUG("SMSC Index to be set in SIM = %d", index);
 
-               /*Setting the SMSP Record Length value = 28 + alphaId_len*/
-               smsParam.RecordLen = 28 + strlen(pSMSCList->smscData[index].name);
+       /*Setting the SMSP Record index value*/
+       smsParam.RecordIndex = (unsigned char)index;
 
-               /*Setting the SMSP Alpha ID value*/
-               smsParam.AlphaIdLen = strlen(pSMSCList->smscData[index].name);
-               MSG_DEBUG("AlphaIdLen = %ld", smsParam.AlphaIdLen);
+       /*Setting the SMSP Record Length value = 28 + alphaId_len*/
+       smsParam.RecordLen = 28 + strlen(pSMSCList->smscData[index].name);
 
-               if (smsParam.AlphaIdLen > 0 &&  smsParam.AlphaIdLen <= SMSC_NAME_MAX)
-               {
-                       memcpy(smsParam.szAlphaId, pSMSCList->smscData[index].name, smsParam.AlphaIdLen);
-                       smsParam.szAlphaId[smsParam.AlphaIdLen] = '\0';
-                       MSG_DEBUG("szAlphaId = %s", smsParam.szAlphaId);
-               }
+       /*Setting the SMSP Alpha ID value*/
+       smsParam.AlphaIdLen = strlen(pSMSCList->smscData[index].name);
+       MSG_DEBUG("AlphaIdLen = %ld", smsParam.AlphaIdLen);
+
+       if (smsParam.AlphaIdLen > 0 &&  smsParam.AlphaIdLen <= SMSC_NAME_MAX) {
+               memcpy(smsParam.szAlphaId, pSMSCList->smscData[index].name, smsParam.AlphaIdLen);
+               smsParam.szAlphaId[smsParam.AlphaIdLen] = '\0';
+               MSG_DEBUG("szAlphaId = %s", smsParam.szAlphaId);
+       }
 
-               smsParam.ParamIndicator = 0x00;
+       smsParam.ParamIndicator = 0x00;
 
-               if (strlen(pSMSCList->smscData[index].smscAddr.address) > 0)
-               {
-                       smsParam.ParamIndicator |= 0x02 ;  //enable 2nd Bit
-                       MSG_DEBUG("ParamIndicator = [%02x]", smsParam.ParamIndicator);
+       if (strlen(pSMSCList->smscData[index].smscAddr.address) > 0) {
+               smsParam.ParamIndicator |= 0x02 ;  //enable 2nd Bit
+               MSG_DEBUG("ParamIndicator = [%02x]", smsParam.ParamIndicator);
 
-                       if (pSMSCList->smscData[index].smscAddr.address[0] == '+')
-                               smsParam.TpSvcCntrAddr.Ton = TAPI_SIM_TON_INTERNATIONAL;
-                       else
-                               smsParam.TpSvcCntrAddr.Ton = TAPI_SIM_TON_NATIONAL;
+               if (pSMSCList->smscData[index].smscAddr.address[0] == '+')
+                       smsParam.TpSvcCntrAddr.Ton = TAPI_SIM_TON_INTERNATIONAL;
+               else
+                       smsParam.TpSvcCntrAddr.Ton = TAPI_SIM_TON_NATIONAL;
 
-                       smsParam.TpSvcCntrAddr.Npi = TAPI_SIM_NPI_ISDN_TEL; // app cannot set this value
+               smsParam.TpSvcCntrAddr.Npi = TAPI_SIM_NPI_ISDN_TEL; // app cannot set this value
 
-                       MSG_DEBUG("SMSC TON = [%d] NPI = [%d]", smsParam.TpSvcCntrAddr.Ton, smsParam.TpSvcCntrAddr.Npi);
+               MSG_DEBUG("SMSC TON = [%d] NPI = [%d]", smsParam.TpSvcCntrAddr.Ton, smsParam.TpSvcCntrAddr.Npi);
 
-                       MSG_DEBUG("address = %s", pSMSCList->smscData[index].smscAddr.address);
+               MSG_SEC_DEBUG("address = %s", pSMSCList->smscData[index].smscAddr.address);
 
-                       smsParam.TpSvcCntrAddr.DialNumLen = SmsPluginParamCodec::encodeSMSC(pSMSCList->smscData[index].smscAddr.address, smsParam.TpSvcCntrAddr.szDiallingNum);
-               }
-               else
-               {
-                       MSG_DEBUG("SMSC Addr is not present");
-               }
+               smsParam.TpSvcCntrAddr.DialNumLen = SmsPluginParamCodec::encodeSMSC(pSMSCList->smscData[index].smscAddr.address, smsParam.TpSvcCntrAddr.szDiallingNum);
+       } else {
+               MSG_DEBUG("SMSC Addr is not present");
+       }
 
-               /*Setting the PID value*/
-               smsParam.ParamIndicator |= 0x04 ;  //enable 3nd Bit
-               MSG_DEBUG("ParamIndicator = [%02x]", smsParam.ParamIndicator);
+       /*Setting the PID value*/
+       smsParam.ParamIndicator |= 0x04 ;  //enable 3nd Bit
+       MSG_DEBUG("ParamIndicator = [%02x]", smsParam.ParamIndicator);
 
-               smsParam.TpProtocolId = (unsigned short)convertPid(pSMSCList->smscData[index].pid);
+       smsParam.TpProtocolId = (unsigned short)convertPid(pSMSCList->smscData[index].pid);
 
-               /*Setting the ValidityPeriod value*/
-               smsParam.ParamIndicator |= 0x10 ;  //enable 5nd Bit
-               MSG_DEBUG("ParamIndicator = [%02x]", smsParam.ParamIndicator);
+       /*Setting the ValidityPeriod value*/
+       smsParam.ParamIndicator |= 0x10 ;  //enable 5nd Bit
+       MSG_DEBUG("ParamIndicator = [%02x]", smsParam.ParamIndicator);
 
-               smsParam.TpValidityPeriod = (unsigned short)pSMSCList->smscData[index].valPeriod;
+       smsParam.TpValidityPeriod = (unsigned short)pSMSCList->smscData[index].valPeriod;
 
-               smsParam.ParamIndicator = ~(smsParam.ParamIndicator);
-               MSG_DEBUG("ParamIndicator = [%02x]", smsParam.ParamIndicator);
+       smsParam.ParamIndicator = ~(smsParam.ParamIndicator);
+       MSG_DEBUG("ParamIndicator = [%02x]", smsParam.ParamIndicator);
 
-               ret = tel_set_sms_parameters(pTapiHandle, (const TelSmsParams_t*)&smsParam, TapiEventSetConfigData, NULL);
+       /* Get TAPI handle */
+       struct tapi_handle *handle = SmsPluginDSHandler::instance()->getTelHandle(pSMSCList->simIndex);
 
-               if (ret != TAPI_API_SUCCESS)
-                       THROW(MsgException::SMS_PLG_ERROR, "tel_set_sms_parameters() Error. [%d]", ret);
+       ret = tel_set_sms_parameters(handle, (const TelSmsParams_t*)&smsParam, TapiEventSetConfigData, NULL);
 
-               if (!getResultFromSim())
-                       THROW(MsgException::SMS_PLG_ERROR, "tel_set_sms_parameters() Result Error.");
-       }
+       if (ret != TAPI_API_SUCCESS)
+               THROW(MsgException::SMS_PLG_ERROR, "tel_set_sms_parameters() Error. [%d]", ret);
+
+       if (!getResultFromSim())
+               THROW(MsgException::SMS_PLG_ERROR, "tel_set_sms_parameters() Result Error.");
 
        MSG_END();
 }
@@ -494,46 +680,40 @@ void SmsPluginSetting::getParamList(MSG_SMSC_LIST_S *pSMSCList)
 
        int paramCnt = 0;
 
-       paramCnt = getParamCount();
+       MSG_SEC_DEBUG("SIM index [%d]", pSMSCList->simIndex);
+       struct tapi_handle *handle = SmsPluginDSHandler::instance()->getTelHandle(pSMSCList->simIndex);
+       paramCnt = getParamCount(handle);
 
        MSG_DEBUG("Parameter Count [%d]", paramCnt);
 
        int ret = TAPI_API_SUCCESS;
-       int reqId = 0;
 
        MSG_SMSC_DATA_S tmpSmscData = {};
 
-       for (int index = 0; index < paramCnt; index++)
-       {
-               ret = tel_get_sms_parameters(pTapiHandle, index, TapiEventGetParam, NULL);
+       for (int index = 0; index < paramCnt; index++) {
+               ret = tel_get_sms_parameters(handle, index, TapiEventGetParam, NULL);
 
-               if (ret == TAPI_API_SUCCESS)
-               {
+               if (ret == TAPI_API_SUCCESS) {
                        MSG_DEBUG("######## tel_get_sms_parameters() Success !!! #######");
-               }
-               else
-               {
+               } else {
                        THROW(MsgException::SMS_PLG_ERROR, "######## tel_get_sms_parameters() Fail !!! return : %d #######", ret);
                }
 
-               if (getParamEvent(&tmpSmscData) == true)
-               {
+               if (getParamEvent(handle, &tmpSmscData) == true) {
                        MSG_DEBUG("######## Get Parameter was Successful !!! #######");
-               }
-               else
-               {
-                       THROW(MsgException::SMS_PLG_ERROR, "######## Get Parameter was Failed !!! #######");
-               }
 
-               memcpy(&(pSMSCList->smscData[index]), &tmpSmscData, sizeof(MSG_SMSC_DATA_S));
+                       memcpy(&(pSMSCList->smscData[index]), &tmpSmscData, sizeof(MSG_SMSC_DATA_S));
 
-               MSG_DEBUG("pid[%d]", pSMSCList->smscData[index].pid);
-               MSG_DEBUG("val_period[%d]", pSMSCList->smscData[index].valPeriod);
-               MSG_DEBUG("name[%s]", pSMSCList->smscData[index].name);
+                       MSG_DEBUG("pid[%d]", pSMSCList->smscData[index].pid);
+                       MSG_DEBUG("val_period[%d]", pSMSCList->smscData[index].valPeriod);
+                       MSG_SEC_DEBUG("name[%s]", pSMSCList->smscData[index].name);
 
-               MSG_DEBUG("ton[%d]", pSMSCList->smscData[index].smscAddr.ton);
-               MSG_DEBUG("npi[%d]", pSMSCList->smscData[index].smscAddr.npi);
-               MSG_DEBUG("address[%s]", pSMSCList->smscData[index].smscAddr.address);
+                       MSG_DEBUG("ton[%d]", pSMSCList->smscData[index].smscAddr.ton);
+                       MSG_DEBUG("npi[%d]", pSMSCList->smscData[index].smscAddr.npi);
+                       MSG_SEC_DEBUG("address[%s]", pSMSCList->smscData[index].smscAddr.address);
+               } else {
+                       MSG_DEBUG("######## Get Parameter was Failed !!! #######");
+               }
        }
 
        pSMSCList->totalCnt = paramCnt;
@@ -545,20 +725,15 @@ void SmsPluginSetting::getParamList(MSG_SMSC_LIST_S *pSMSCList)
 }
 
 
-int SmsPluginSetting::getParamCount()
+int SmsPluginSetting::getParamCount(struct tapi_handle *handle)
 {
-       int reqId = 0;
-
        int ret = TAPI_API_SUCCESS;
 
-       ret = tel_get_sms_parameter_count(pTapiHandle, TapiEventGetParamCnt, NULL);
+       ret = tel_get_sms_parameter_count(handle, TapiEventGetParamCnt, NULL);
 
-       if (ret == TAPI_API_SUCCESS)
-       {
+       if (ret == TAPI_API_SUCCESS) {
                MSG_DEBUG("######## tel_get_sms_parameter_count() Success !!! #######");
-       }
-       else
-       {
+       } else {
                THROW(MsgException::SMS_PLG_ERROR, "tel_get_sms_parameter_count() Error. [%d]", ret);
        }
 
@@ -566,31 +741,23 @@ int SmsPluginSetting::getParamCount()
 }
 
 
-bool SmsPluginSetting::getParam(int Index, MSG_SMSC_DATA_S *pSmscData)
+bool SmsPluginSetting::getParam(struct tapi_handle *handle, int Index, MSG_SMSC_DATA_S *pSmscData)
 {
-       int reqId = 0;
-
        int ret = TAPI_API_SUCCESS;
 
-       ret = tel_get_sms_parameters(pTapiHandle, Index, TapiEventGetParam, NULL);
+       ret = tel_get_sms_parameters(handle, Index, TapiEventGetParam, NULL);
 
-       if (ret == TAPI_API_SUCCESS)
-       {
+       if (ret == TAPI_API_SUCCESS) {
                MSG_DEBUG("######## tel_get_sms_parameters() Success !!! #######");
-       }
-       else
-       {
-               MSG_DEBUG("######## tel_get_sms_parameters() Fail !!! return : %d #######", ret);
+       } else {
+               MSG_ERR("######## tel_get_sms_parameters() Fail !!! return : %d #######", ret);
                return false;
        }
 
-       if (getParamEvent(pSmscData) == true)
-       {
+       if (getParamEvent(handle, pSmscData) == true) {
                MSG_DEBUG("######## Get Parameter was Successful !!! #######");
-       }
-       else
-       {
-               MSG_DEBUG("######## Get Parameter was Failed !!! #######");
+       } else {
+               MSG_ERR("######## Get Parameter was Failed !!! #######");
                return false;
        }
 
@@ -598,76 +765,554 @@ bool SmsPluginSetting::getParam(int Index, MSG_SMSC_DATA_S *pSmscData)
 }
 
 
-bool SmsPluginSetting::setCbConfig(const MSG_CBMSG_OPT_S *pCbOpt)
+void SmsPluginSetting::setSmscInfo(const MSG_SMSC_LIST_S *pSmscList)
 {
+       MSG_BEGIN();
+
+       MutexLocker lock(mx);
+
        int ret = TAPI_API_SUCCESS;
 
-       TelSmsCbConfig_t cbConfig = {};
+       struct tapi_handle *handle = NULL;
 
-       cbConfig.CBEnabled = (int)pCbOpt->bReceive;
-       cbConfig.Net3gppType = TAPI_NETTEXT_NETTYPE_3GPP;
-       cbConfig.MsgIdMaxCount = pCbOpt->maxSimCnt;
-       cbConfig.MsgIdRangeCount = pCbOpt->channelData.channelCnt;
+       handle = SmsPluginDSHandler::instance()->getTelHandle(pSmscList->simIndex);
 
-       for (int i = 0; i < cbConfig.MsgIdRangeCount; i++)
-       {
-               cbConfig.MsgIDs[i].Net3gpp.Selected = (unsigned short)pCbOpt->channelData.channelInfo[i].bActivate;
-               cbConfig.MsgIDs[i].Net3gpp.FromMsgId = (unsigned short)pCbOpt->channelData.channelInfo[i].from;
-               cbConfig.MsgIDs[i].Net3gpp.ToMsgId = (unsigned short)pCbOpt->channelData.channelInfo[i].to;
+       int select_id = pSmscList->selected;
+       const MSG_SMSC_DATA_S *pSmscData = (const MSG_SMSC_DATA_S *)&(pSmscList->smscData[select_id]);
 
-               MSG_DEBUG("FROM: %d, TO: %d", cbConfig.MsgIDs[i].Net3gpp.FromMsgId, cbConfig.MsgIDs[i].Net3gpp.ToMsgId);
-       }
-       MSG_DEBUG("CBEnabled: %d, range_count: %d", cbConfig.CBEnabled, cbConfig.MsgIdRangeCount);
+       MSG_DEBUG("Select SMSC id = [%d]", select_id);
 
-       ret = tel_set_sms_cb_config(pTapiHandle, &cbConfig, TapiEventSetConfigData, NULL);
+       TelSmsAddressInfo_t sca;
+       memset(&sca, 0x00, sizeof(TelSmsAddressInfo_t));
 
-       if (ret == TAPI_API_SUCCESS)
-       {
-               MSG_DEBUG("######## tel_set_sms_cb_config() Success !!! #######");
-       }
-       else
-       {
-               MSG_DEBUG("######## tel_set_sms_cb_config() Fail !!! return : %d #######", ret);
-               return false;
-       }
+       if (strlen(pSmscData->smscAddr.address) > 0) {
 
-       if (getResultFromSim() == true)
-       {
-               MSG_DEBUG("######## Set Cb Config was Successful !!! #######");
-       }
-       else
-       {
-               MSG_DEBUG("######## Set Cb Config was Failed !!! #######");
-               return false;
+               if (pSmscData->smscAddr.address[0] == '+')
+                       sca.Ton = TAPI_SIM_TON_INTERNATIONAL;
+               else
+                       sca.Ton = TAPI_SIM_TON_NATIONAL;
+
+               sca.Npi = TAPI_SIM_NPI_ISDN_TEL; // app cannot set this value
+
+               MSG_SEC_DEBUG("SMSC TON = [%d], NPI = [%d], Address = [%s]", sca.Ton, sca.Npi, pSmscData->smscAddr.address);
+
+               sca.DialNumLen = SmsPluginParamCodec::encodeSMSC(pSmscData->smscAddr.address, sca.szDiallingNum);
+       } else {
+               MSG_DEBUG("SMSC Addr is not present");
        }
 
-       return true;
+       ret = tel_set_sms_sca(handle, (const TelSmsAddressInfo_t *)&sca, 0, TapiEventSetSmscInfo, NULL);
+
+       if (ret != TAPI_API_SUCCESS)
+               THROW(MsgException::SMS_PLG_ERROR, "tel_set_sms_sca() Error. [%d]", ret);
+
+       if (!getResultFromSim())
+               THROW(MsgException::SMS_PLG_ERROR, "tel_set_sms_sca() Result Error.");
+
+       MSG_END();
 }
 
 
-bool SmsPluginSetting::getCbConfig(MSG_CBMSG_OPT_S *pCbOpt)
+bool SmsPluginSetting::setCbConfig(const MSG_CBMSG_OPT_S *pCbOpt)
 {
-       int ret = TAPI_API_SUCCESS;
+       struct tapi_handle *handle = NULL;
+       int simCnt = SmsPluginDSHandler::instance()->getTelHandleCount();
 
-       ret = tel_get_sms_cb_config(pTapiHandle, TapiEventGetCBConfig, NULL);
+       TelSmsCbConfig_t cbConfig = {};
 
-       if (ret == TAPI_API_SUCCESS)
-       {
-               MSG_DEBUG("######## tel_get_sms_cb_config() Success !!! #######");
+       int cbEnabled = 0;
+       int ret = TAPI_API_SUCCESS;
+
+       if (pCbOpt->bReceive == true)
+               cbEnabled = 2;// Need to get a Enumeration from TAPI, currently it is not available
+
+       MSG_DEBUG("simIndex:%d, cbEnabled:%d", pCbOpt->simIndex, cbEnabled);
+
+       if (pCbOpt->simIndex == 0) {
+               char keyName[MAX_VCONFKEY_NAME_LEN];
+               memset(keyName, 0x00, sizeof(keyName));
+               MSG_SIM_STATUS_T simStatus = MSG_SIM_STATUS_NOT_FOUND;
+
+               for (int i = 1; i <= simCnt; i++) {
+                       MutexLocker lock(mx);
+
+                       //if (i == pCbOpt->simIndex)
+                       //      continue;
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, i);
+                       simStatus = (MSG_SIM_STATUS_T)MsgSettingGetInt(keyName);
+
+                       if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
+                               MSG_DEBUG("SIM %d is not present..", i);
+                               continue;
+                       }
+
+                       handle = SmsPluginDSHandler::instance()->getTelHandle(i);
+                       memset(&cbConfig, 0x00, sizeof(TelSmsCbConfig_t));
+
+                       MSG_SETTING_S cbSetting;
+                       getCbOpt(&cbSetting, i);
+
+                       cbConfig.CBEnabled = cbEnabled;
+                       cbConfig.Net3gppType = TAPI_NETTEXT_NETTYPE_3GPP;
+
+                       /*cbConfig.CBEnabled = (int)pCbOpt->bReceive;
+                       cbConfig.Net3gppType = TAPI_NETTEXT_NETTYPE_3GPP;
+                       cbConfig.MsgIdMaxCount = cbSetting.option.cbMsgOpt.maxSimCnt;
+                       cbConfig.MsgIdRangeCount = cbSetting.option.cbMsgOpt.channelData.channelCnt;
+
+                       for (int i = 0; i < cbConfig.MsgIdRangeCount; i++) {
+                               cbConfig.MsgIDs[i].Net3gpp.Selected = (unsigned short)cbSetting.option.cbMsgOpt.channelData.channelInfo[i].bActivate;
+                               cbConfig.MsgIDs[i].Net3gpp.FromMsgId = (unsigned short)cbSetting.option.cbMsgOpt.channelData.channelInfo[i].from;
+                               cbConfig.MsgIDs[i].Net3gpp.ToMsgId = (unsigned short)cbSetting.option.cbMsgOpt.channelData.channelInfo[i].to;
+                       }*/
+
+                       ret = tel_set_sms_cb_config(handle, &cbConfig, TapiEventSetConfigData, NULL);
+
+                       if (ret == TAPI_API_SUCCESS) {
+                               MSG_DEBUG("######## tel_set_sms_cb_config() Success !!! #######");
+                       } else {
+                               MSG_ERR("######## tel_set_sms_cb_config() Fail !!! return : %d #######", ret);
+                               return false;
+                       }
+
+                       if (getResultFromSim() == true) {
+                               MSG_DEBUG("######## Set Cb Config was Successful !!! #######");
+                       } else {
+                               MSG_ERR("######## Set Cb Config was Failed !!! #######");
+                               return false;
+                       }
+
+                       msg_error_t err = MSG_SUCCESS;
+                       MsgDbHandler *dbHandle = getDbHandle();
+                       err = MsgStoAddCBChannelInfo(dbHandle, const_cast<MSG_CB_CHANNEL_S*>(&pCbOpt->channelData),i);
+                       if (err != MSG_SUCCESS) {
+                               MSG_DEBUG("MsgStoAddCBChannelInfo is failed [%d]", err);
+                               return MSG_ERR_SET_SETTING;
+                       }
+               }
+
+               MSG_DEBUG("SIM Index = [0], Set CB Receive is done");
+               return true;
+       } else {
+               MutexLocker lock(mx);
+
+               handle = SmsPluginDSHandler::instance()->getTelHandle(pCbOpt->simIndex);
+
+               memset(&cbConfig, 0x00, sizeof(TelSmsCbConfig_t));
+               cbConfig.CBEnabled = cbEnabled;
+               cbConfig.Net3gppType = TAPI_NETTEXT_NETTYPE_3GPP;
+       /*      cbConfig.CBEnabled = (int)pCbOpt->bReceive;
+               cbConfig.Net3gppType = TAPI_NETTEXT_NETTYPE_3GPP;
+               cbConfig.MsgIdMaxCount = pCbOpt->maxSimCnt;
+               cbConfig.MsgIdRangeCount = pCbOpt->channelData.channelCnt;
+
+               for (int i = 0; i < cbConfig.MsgIdRangeCount; i++) {
+                       cbConfig.MsgIDs[i].Net3gpp.Selected = (unsigned short)pCbOpt->channelData.channelInfo[i].bActivate;
+                       cbConfig.MsgIDs[i].Net3gpp.FromMsgId = (unsigned short)pCbOpt->channelData.channelInfo[i].from;
+                       cbConfig.MsgIDs[i].Net3gpp.ToMsgId = (unsigned short)pCbOpt->channelData.channelInfo[i].to;
+
+                       MSG_DEBUG("FROM: %d, TO: %d", cbConfig.MsgIDs[i].Net3gpp.FromMsgId, cbConfig.MsgIDs[i].Net3gpp.ToMsgId);
+               }
+               MSG_DEBUG("CBEnabled: %d, range_count: %d", cbConfig.CBEnabled, cbConfig.MsgIdRangeCount);*/
+
+               ret = tel_set_sms_cb_config(handle, &cbConfig, TapiEventSetConfigData, NULL);
+
+               if (ret == TAPI_API_SUCCESS) {
+                       MSG_DEBUG("######## tel_set_sms_cb_config() Success !!! #######");
+               } else {
+                       MSG_ERR("######## tel_set_sms_cb_config() Fail !!! return : %d #######", ret);
+                       return false;
+               }
+
+               if (getResultFromSim() == true) {
+                       MSG_DEBUG("######## Set Cb Config was Successful !!! #######");
+               } else {
+                       MSG_ERR("######## Set Cb Config was Failed !!! #######");
+                       return false;
+               }
        }
-       else
-       {
-               MSG_DEBUG("######## tel_get_sms_cb_config() Fail !!! return : %d #######", ret);
+
+       return true;
+}
+
+
+bool SmsPluginSetting::getCbConfig(MSG_CBMSG_OPT_S *pCbOpt)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       struct tapi_handle *handle = NULL;
+
+       if (pCbOpt->simIndex == 0) {
+               MSG_DEBUG("SIM Index for getCBConfig = 0, CANNOT get cbconfig from SIM 0");
                return false;
        }
 
-       if (getCbConfigEvent(pCbOpt) == true)
-       {
+       handle = SmsPluginDSHandler::instance()->getTelHandle(pCbOpt->simIndex);
+
+       ret = tel_get_sms_cb_config(handle, TapiEventGetCBConfig, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_get_sms_cb_config() Success !!! #######");
+       } else {
+               MSG_ERR("######## tel_get_sms_cb_config() Fail !!! return : %d #######", ret);
+               return false;
+       }
+
+       if (getCbConfigEvent(pCbOpt) == true) {
                MSG_DEBUG("######## Get Cb Config was Successful !!! #######");
+       } else {
+               MSG_ERR("######## Get Cb Config was Failed !!! #######");
+               return false;
        }
-       else
-       {
-               MSG_DEBUG("######## Get Cb Config was Failed !!! #######");
+
+       return true;
+}
+
+
+void SmsPluginSetting::setVoiceMailInfo(const MSG_VOICEMAIL_OPT_S *pVoiceOpt)
+{
+       MutexLocker lock(mx);
+
+       int ret = TAPI_API_SUCCESS;
+       bool *bShowError = NULL; //When invalid voicemail data exists on SIM, update error should not be handled.
+
+       int simIndex = pVoiceOpt->simIndex;
+
+       if (bMbdnEnable[simIndex] == false) {
+               MSG_DEBUG("MBDN service is disable.");
+               return;
+       }
+
+       TelSimMailBoxNumber_t mailboxInfo = {0,};
+       bool bExistVoicetype = false;
+       int i = 0;
+
+       if (simMailboxList[simIndex].count < 0) { /* Not available */
+               return;
+       }
+
+       bShowError = (bool*)calloc(1, sizeof(bool));
+       if (!bShowError)
+               return;
+
+       if (simMailboxList[simIndex].count == 0) {
+               char num[MAX_PHONE_NUMBER_LEN + 1] = {0,};
+
+               mailboxInfo.mb_type = TAPI_SIM_MAILBOX_VOICE;
+               mailboxInfo.rec_index = 1;
+               mailboxInfo.ton = TAPI_SIM_TON_UNKNOWN;
+
+               snprintf(num, sizeof(num), "%s", pVoiceOpt->mailNumber);
+               MSG_DEBUG("Mailbox number config [%s]", num);
+
+               if (num[0] == '+') {
+                       snprintf(mailboxInfo.num, sizeof(mailboxInfo.num), "%s", &(num[1]));
+                       mailboxInfo.ton = TAPI_SIM_TON_INTERNATIONAL;
+               } else {
+                       snprintf(mailboxInfo.num, sizeof(mailboxInfo.num), "%s", num);
+               }
+
+               MSG_SEC_DEBUG("Mailbox number to save sim [%s]", mailboxInfo.num);
+
+               *bShowError = false;
+
+       } else {
+               for (i = 0; i < simMailboxList[simIndex].count; i++) {
+                       if (simMailboxList[simIndex].list[i].mb_type == TAPI_SIM_MAILBOX_VOICE) {
+                               bExistVoicetype = true;
+                               break;
+                       }
+               }
+
+               if (bExistVoicetype == false) {
+                       *bShowError = false;
+                       /* There is no mailbox information for voicemail type on SIM. */
+                       for (i = 0; i < simMailboxList[simIndex].count; i++) {
+                               if (simMailboxList[simIndex].list[i].mb_type < TAPI_SIM_MAILBOX_VOICE || simMailboxList[simIndex].list[i].mb_type > TAPI_SIM_MAILBOX_OTHER) {
+                                       simMailboxList[simIndex].list[i].mb_type = TAPI_SIM_MAILBOX_VOICE;
+                                       break;
+                               }
+                       }
+               }
+
+               /* if strlen of voicemail number retrieved from SIM is zero, error is not shown */
+               if(simMailboxList[simIndex].list[i].num_len == 0) {
+                       MSG_DEBUG("In SIM voicemail does not exist");
+                       *bShowError = false;
+               }
+
+               MSG_INFO("bShowError = %d", *bShowError);
+
+               memset(&simMailboxList[simIndex].list[i].num, 0x00, sizeof(simMailboxList[simIndex].list[i].num));
+               snprintf(simMailboxList[simIndex].list[i].num, sizeof(simMailboxList[simIndex].list[i].num), "%s", pVoiceOpt->mailNumber);
+               MSG_DEBUG("Mailbox number config [%s]", simMailboxList[simIndex].list[i].num);
+
+               mailboxInfo.b_cphs = simMailboxList[simIndex].list[i].b_cphs;
+               mailboxInfo.alpha_id_max_len = simMailboxList[simIndex].list[i].alpha_id_max_len;
+               mailboxInfo.mb_type = (TelSimMailboxType_t)simMailboxList[simIndex].list[i].mb_type;
+               mailboxInfo.profile_num = simMailboxList[simIndex].list[i].profile_num;
+               mailboxInfo.rec_index = (simMailboxList[simIndex].list[i].rec_index == 0) ? 1 : simMailboxList[simIndex].list[i].rec_index;
+               mailboxInfo.ton = (TelSimTypeOfNum_t)simMailboxList[simIndex].list[i].ton;
+               mailboxInfo.npi = (TelSimNumberingPlanIdentity_t)simMailboxList[simIndex].list[i].npi;
+               snprintf(mailboxInfo.alpha_id, sizeof(mailboxInfo.alpha_id), "%s", simMailboxList[simIndex].list[i].alpha_id);
+
+               if (simMailboxList[simIndex].list[i].num[0] == '+') {
+                       snprintf(mailboxInfo.num, sizeof(mailboxInfo.num), "%s", &(simMailboxList[simIndex].list[i].num[1]));
+                       mailboxInfo.ton = TAPI_SIM_TON_INTERNATIONAL;
+               } else {
+                       snprintf(mailboxInfo.num, sizeof(mailboxInfo.num), "%s", simMailboxList[simIndex].list[i].num);
+               }
+               MSG_DEBUG("Mailbox number to save sim [%s]", mailboxInfo.num);
+
+               mailboxInfo.cc_id = simMailboxList[simIndex].list[i].cc_id;
+               mailboxInfo.ext1_id = simMailboxList[simIndex].list[i].ext1_id;
+       }
+
+       struct tapi_handle *handle = SmsPluginDSHandler::instance()->getTelHandle(simIndex);
+
+       ret = tel_set_sim_mailbox_info(handle, &mailboxInfo, TapiEventSetMailboxInfo, (void*)bShowError);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_set_sim_mailbox_info() Success !!! #######");
+       } else {
+               MSG_ERR("######## tel_set_sim_mailbox_info() Fail !!! return : %d #######", ret);
+       }
+
+       if (getResultFromSim() == true) {
+               MSG_DEBUG("######## Set mailbox info Success !!! #######");
+       } else {
+               if(bShowError)
+                       free(bShowError);
+               THROW(MsgException::SMS_PLG_ERROR, "########  Set mailbox info Failed !!!#######");
+               MSG_ERR("######## Set mailbox info Failed !!! #######");
+       }
+
+       if(bShowError)
+               free(bShowError);
+
+       return;
+}
+
+
+bool SmsPluginSetting::getVoiceMailInfo(struct tapi_handle *handle)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_get_sim_mailbox_info(handle, TapiEventGetMailboxInfo, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_get_sim_mailbox_info() Success !!! #######");
+       } else {
+               MSG_ERR("######## tel_get_sim_mailbox_info() Fail !!! return : %d #######", ret);
+               return false;
+       }
+
+       if (getMailboxInfoEvent() == true) {
+               MSG_DEBUG("######## Get mailbox info was Successful !!! #######");
+       } else {
+               MSG_ERR("######## Get mailbox info was Failed !!! #######");
+               return false;
+       }
+
+       return true;
+}
+
+
+void SmsPluginSetting::getMeImei(char *pImei)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       struct tapi_handle *handle = NULL;
+       handle = SmsPluginDSHandler::instance()->getTelHandle(1);
+
+       if (handle == NULL) {
+               MSG_DEBUG("Tapi Handle is NULL!");
+               return;
+       }
+
+       ret = tel_get_misc_me_imei(handle, TapiEventGetMeImei, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_SEC_DEBUG("######## tel_get_misc_me_imei() Success !!! #######");
+
+               if (getResultImei(pImei) == true) {
+                       MSG_SEC_DEBUG("######## Get ME IMEI was Successful !!! #######");
+               } else {
+                       MSG_SEC_DEBUG("######## Get ME IMEI was Failed !!! #######");
+               }
+       } else {
+               MSG_SEC_DEBUG("######## tel_get_misc_me_imei() Fail !!! return : %d #######", ret);
+       }
+}
+
+
+void SmsPluginSetting::setMwiInfo(int simIndex, MSG_SUB_TYPE_T type, int count)
+{
+       MSG_DEBUG("SET MWI INFO, type=[%d]", type);
+       MSG_DEBUG("SET MWI INFO, count=[%d]", count);
+
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_COUNT, simIndex);
+
+       if (MsgSettingSetInt(keyName, count) != MSG_SUCCESS)
+               MSG_DEBUG("MsgSettingSetInt is failed!!");
+
+       if (count <= 0) {
+               if (type == MSG_MWI_VOICE_SMS)
+                       MsgDeleteNoti(MSG_NOTI_TYPE_VOICE_1, simIndex);
+               else if (type == MSG_MWI_VOICE2_SMS)
+                       MsgDeleteNoti(MSG_NOTI_TYPE_VOICE_2, simIndex);
+       }
+
+       if (bMbdnEnable[simIndex] == false) {
+               MSG_DEBUG("MBDN service is disable.");
+               return;
+       }
+
+       int ret = TAPI_API_SUCCESS;
+       TelSimMessageWaitingReq_t mwReq = {0,};
+
+       MSG_DEBUG("SET MWI INFO, CPHS? [%s]", simMwiInfo[simIndex].b_cphs?"Yes":"No");
+
+       if (simMwiInfo[simIndex].b_cphs) {
+               if (type == MSG_MWI_VOICE_SMS)
+                       simMwiInfo[simIndex].cphs_mwi.b_voice1 = (count > 0 ? 1:0);
+               else if (type == MSG_MWI_VOICE2_SMS)
+                       simMwiInfo[simIndex].cphs_mwi.b_voice2 = (count > 0 ? 1:0);
+               else if (type == MSG_MWI_FAX_SMS)
+                       simMwiInfo[simIndex].cphs_mwi.b_fax = (count > 0 ? 1:0);
+               else {
+                       MSG_DEBUG("There is no type [%d] in CPHS.", type);
+                       return;
+               }
+
+               mwReq.mw_data_u.cphs_mw.b_voice1 = simMwiInfo[simIndex].cphs_mwi.b_voice1;
+               mwReq.mw_data_u.cphs_mw.b_voice2 = simMwiInfo[simIndex].cphs_mwi.b_voice2;
+               mwReq.mw_data_u.cphs_mw.b_fax = simMwiInfo[simIndex].cphs_mwi.b_fax;
+               mwReq.mw_data_u.cphs_mw.b_data = simMwiInfo[simIndex].cphs_mwi.b_data;
+
+               MSG_DEBUG("MWI voice 1 = [%d]", mwReq.mw_data_u.cphs_mw.b_voice1);
+               MSG_DEBUG("MWI voice 2 = [%d]", mwReq.mw_data_u.cphs_mw.b_voice2);
+               MSG_DEBUG("MWI fax = [%d]", mwReq.mw_data_u.cphs_mw.b_fax);
+               MSG_DEBUG("MWI data = [%d]", mwReq.mw_data_u.cphs_mw.b_data);
+
+       } else {
+               if (type == MSG_MWI_VOICE_SMS)
+                       simMwiInfo[simIndex].mwi_list.mw_info[0].voice_count = count;
+               else if (type == MSG_MWI_FAX_SMS)
+                       simMwiInfo[simIndex].mwi_list.mw_info[0].fax_count = count;
+               else if (type == MSG_MWI_EMAIL_SMS)
+                       simMwiInfo[simIndex].mwi_list.mw_info[0].email_count = count;
+               else // MSG_MWI_OTHER_SMS
+                       simMwiInfo[simIndex].mwi_list.mw_info[0].other_count = count;
+
+               mwReq.mw_data_u.mw.rec_index = simMwiInfo[simIndex].mwi_list.mw_info[0].rec_index;
+               mwReq.mw_data_u.mw.indicator_status = simMwiInfo[simIndex].mwi_list.mw_info[0].indicator_status;
+               mwReq.mw_data_u.mw.voice_count = simMwiInfo[simIndex].mwi_list.mw_info[0].voice_count;
+               mwReq.mw_data_u.mw.fax_count = simMwiInfo[simIndex].mwi_list.mw_info[0].fax_count;
+               mwReq.mw_data_u.mw.email_count = simMwiInfo[simIndex].mwi_list.mw_info[0].email_count;
+               mwReq.mw_data_u.mw.other_count = simMwiInfo[simIndex].mwi_list.mw_info[0].other_count;
+               mwReq.mw_data_u.mw.video_count = simMwiInfo[simIndex].mwi_list.mw_info[0].video_count;
+
+               MSG_DEBUG("MWI record index = [%d]", mwReq.mw_data_u.mw.rec_index);
+               MSG_DEBUG("MWI ind status = [%d]", mwReq.mw_data_u.mw.indicator_status);
+               MSG_DEBUG("MWI voice = [%d]", mwReq.mw_data_u.mw.voice_count);
+               MSG_DEBUG("MWI fax = [%d]", mwReq.mw_data_u.mw.fax_count);
+               MSG_DEBUG("MWI email = [%d]", mwReq.mw_data_u.mw.email_count);
+               MSG_DEBUG("MWI other = [%d]", mwReq.mw_data_u.mw.other_count);
+               MSG_DEBUG("MWI video = [%d]", mwReq.mw_data_u.mw.video_count);
+       }
+
+       mwReq.b_cphs = simMwiInfo[simIndex].b_cphs;
+
+       struct tapi_handle *handle = SmsPluginDSHandler::instance()->getTelHandle(simIndex);
+
+       ret = tel_set_sim_messagewaiting_info(handle, &mwReq, TapiEventSetMwiInfo, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_set_sim_messagewaiting_info() Success !!! #######");
+       } else {
+               MSG_DEBUG("######## tel_set_sim_messagewaiting_info() Fail !!! return : %d #######", ret);
+       }
+
+       return;
+}
+
+
+bool SmsPluginSetting::getMwiInfo(struct tapi_handle *handle)
+{
+       MutexLocker lock(mx);
+
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_get_sim_messagewaiting_info(handle, TapiEventGetMwiInfo, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_get_sim_messagewaiting_info() Success !!! #######");
+       } else {
+               MSG_DEBUG("######## tel_get_sim_messagewaiting_info() Fail !!! return : %d #######", ret);
+               return false;
+       }
+
+       if (getResultFromSim() == true) {
+               MSG_DEBUG("######## Get Mainbox info was Successful !!! #######");
+       } else {
+               MSG_DEBUG("######## Get Mainbox info was Failed !!! #######");
+               return false;
+       }
+
+       return true;
+}
+
+
+bool SmsPluginSetting::getMsisdnInfo(struct tapi_handle *handle)
+{
+       MutexLocker lock(mx);
+
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_get_sim_msisdn(handle, TapiEventGetMsisdnInfo, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_get_sim_msisdn() Success !!! #######");
+       } else {
+               MSG_DEBUG("######## tel_get_sim_msisdn() Fail !!! return : %d #######", ret);
+               return false;
+       }
+
+       if (getResultFromSim() == true) {
+               MSG_DEBUG("######## Get Sim msisdn was Successful !!! #######");
+       } else {
+               MSG_DEBUG("######## Get Sim msisdn was Failed !!! #######");
+               return false;
+       }
+
+       return true;
+}
+
+
+bool SmsPluginSetting::getSimServiceTable(struct tapi_handle *handle)
+{
+       MutexLocker lock(mx);
+
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_get_sim_service_table(handle, TapiEventGetSimServiceTable, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_get_sim_service_table() Success !!! #######");
+       } else {
+               MSG_DEBUG("######## tel_get_sim_service_table() Fail !!! return : %d #######", ret);
+               return false;
+       }
+
+       if (getResultFromSim() == true) {
+               MSG_DEBUG("######## Get SST info was Successful !!! #######");
+       } else {
+               MSG_DEBUG("######## Get SST info was Failed !!! #######");
                return false;
        }
 
@@ -693,13 +1338,12 @@ int SmsPluginSetting::getParamCntEvent()
 
        mx.lock();
 
-       ret = cv.timedwait(mx.pMutex(), 10);
+       ret = cv.timedwait(mx.pMutex(), MAX_TAPI_SIM_API_TIMEOUT);
 
        mx.unlock();
 
-       if (ret == ETIMEDOUT)
-       {
-               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+       if (ret == ETIMEDOUT) {
+               MSG_ERR("WARNING: TAPI callback TIME-OUT");
                return 0;
        }
 
@@ -707,21 +1351,22 @@ int SmsPluginSetting::getParamCntEvent()
 }
 
 
-void SmsPluginSetting::setParamEvent(const MSG_SMSC_DATA_S *pSmscData, int RecordIdx, bool bSuccess)
+void SmsPluginSetting::setParamEvent(struct tapi_handle *handle, const MSG_SMSC_DATA_S *pSmscData, int RecordIdx, bool bSuccess)
 {
        mx.lock();
 
        bTapiResult = bSuccess;
 
-       memset(&smscData, 0x00, sizeof(MSG_SMSC_DATA_S));
+       int sim_idx = SmsPluginDSHandler::instance()->getSimIndex(handle);
 
-       if (bTapiResult == true)
-       {
+       memset(&smscData[sim_idx], 0x00, sizeof(MSG_SMSC_DATA_S));
+
+       if (bTapiResult == true) {
                MSG_DEBUG("Success to get parameter data");
 
                selectedParam = RecordIdx;
 
-               memcpy(&smscData, pSmscData, sizeof(MSG_SMSC_DATA_S));
+               memcpy(&smscData[sim_idx], pSmscData, sizeof(MSG_SMSC_DATA_S));
        }
 
        cv.signal();
@@ -730,48 +1375,54 @@ void SmsPluginSetting::setParamEvent(const MSG_SMSC_DATA_S *pSmscData, int Recor
 }
 
 
-bool SmsPluginSetting::getParamEvent(MSG_SMSC_DATA_S *pSmscData)
+bool SmsPluginSetting::getParamEvent(struct tapi_handle *handle, MSG_SMSC_DATA_S *pSmscData)
 {
        int ret = 0;
 
-       bTapiResult = false;
-
        mx.lock();
 
-       ret = cv.timedwait(mx.pMutex(), 10);
+       bTapiResult = false;
+       ret = cv.timedwait(mx.pMutex(), MAX_TAPI_SIM_API_TIMEOUT);
 
        mx.unlock();
 
-       if (ret == ETIMEDOUT)
-       {
+       if (ret == ETIMEDOUT) {
                MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
                return false;
        }
 
        memset(pSmscData, 0x00, sizeof(MSG_SMSC_DATA_S));
 
-       if (bTapiResult == true)
-       {
-               memcpy(pSmscData, &smscData, sizeof(MSG_SMSC_DATA_S));
+       if (bTapiResult == true) {
+               int index = SmsPluginDSHandler::instance()->getSimIndex(handle);
+               memcpy(pSmscData, &smscData[index], sizeof(MSG_SMSC_DATA_S));
        }
 
        return bTapiResult;
 }
 
 
-void SmsPluginSetting::setCbConfigEvent(const MSG_CBMSG_OPT_S *pCbOpt, bool bSuccess)
+void SmsPluginSetting::setCbConfigEvent(struct tapi_handle *handle, const MSG_CBMSG_OPT_S *pCbOpt, bool bSuccess)
 {
        mx.lock();
 
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+
        bTapiResult = bSuccess;
 
-       memset(&cbOpt, 0x00, sizeof(MSG_CBMSG_OPT_S));
+       int simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+       memset(&cbOpt[simIndex], 0x00, sizeof(MSG_CBMSG_OPT_S));
 
-       if (bTapiResult == true)
-       {
+       if (bTapiResult == true) {
                MSG_DEBUG("Success to get cb config data");
 
-               memcpy(&cbOpt, pCbOpt, sizeof(MSG_CBMSG_OPT_S));
+               memcpy(&cbOpt[simIndex], pCbOpt, sizeof(MSG_CBMSG_OPT_S));
+
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", CB_MAX_SIM_COUNT, simIndex);
+               if (MsgSettingSetInt(keyName, pCbOpt->maxSimCnt) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", keyName);
+               }
        }
 
        cv.signal();
@@ -784,25 +1435,222 @@ bool SmsPluginSetting::getCbConfigEvent(MSG_CBMSG_OPT_S *pCbOpt)
 {
        int ret = 0;
 
+       mx.lock();
+
        bTapiResult = false;
+       ret = cv.timedwait(mx.pMutex(), MAX_TAPI_SIM_API_TIMEOUT);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT) {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return false;
+       }
+
+       int simIndex = pCbOpt->simIndex;
+
+       memset(pCbOpt, 0x00, sizeof(MSG_CBMSG_OPT_S));
+
+       if (bTapiResult == true) {
+               memcpy(pCbOpt, &cbOpt[simIndex], sizeof(MSG_CBMSG_OPT_S));
+       }
+
+       return bTapiResult;
+}
 
+
+void SmsPluginSetting::setMailboxInfoEvent(struct tapi_handle *handle, SMS_SIM_MAILBOX_LIST_S *pMailboxList, bool bSuccess, bool bMbdn)
+{
        mx.lock();
 
-       ret = cv.timedwait(mx.pMutex(), 10);
+       bTapiResult = bSuccess;
+
+       int simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+       bMbdnEnable[simIndex] = bMbdn;
+
+       memset(&simMailboxList[simIndex], 0x00, sizeof(SMS_SIM_MAILBOX_LIST_S));
+
+       if (bTapiResult == true) {
+               int i = 0;
+               bool bExistMailboxType = false;
+               char keyName[MAX_VCONFKEY_NAME_LEN];
+
+               if (pMailboxList && pMailboxList->count > 0) {
+                       memcpy(&simMailboxList[simIndex], pMailboxList, sizeof(SMS_SIM_MAILBOX_LIST_S));
+
+                       /* Temp :: Save voicemail number with VOICE1 line number */
+                       for (i = 0; i < pMailboxList->count ; i++) {
+                               MSG_SEC_DEBUG("Mailbox list[%d] type=[%d]", i, pMailboxList->list[i].mb_type);
+
+                               if (pMailboxList->list[i].mb_type == TAPI_SIM_MAILBOX_VOICE) {
+                                       bExistMailboxType = true;
+                                       break;
+                               }
+                       }
+
+                       if (bExistMailboxType == false) {
+                               MSG_DEBUG("There is no voice mailbox type.");
+                               for (i = 0; i < simMailboxList[simIndex].count; i++) {
+                                       if (pMailboxList->list[i].mb_type < TAPI_SIM_MAILBOX_VOICE || pMailboxList->list[i].mb_type > TAPI_SIM_MAILBOX_OTHER) {
+                                               pMailboxList->list[i].mb_type = TAPI_SIM_MAILBOX_VOICE;
+                                               break;
+                                       }
+                               }
+                       }
+
+                       char mailNumber[MAX_PHONE_NUMBER_LEN+1];
+                       memset(mailNumber, 0x00 , sizeof(mailNumber));
+
+                       MSG_SEC_DEBUG("Mailbox list[%d] ton=[%d], address=[%s], alpha_id=[%s]", \
+                                       i, simMailboxList[simIndex].list[i].ton, simMailboxList[simIndex].list[i].num, \
+                                       simMailboxList[simIndex].list[i].alpha_id);
+
+                       if (simMailboxList[simIndex].list[i].ton == MSG_TON_INTERNATIONAL && simMailboxList[simIndex].list[i].num[0] != '+') {
+                               snprintf(mailNumber, MAX_PHONE_NUMBER_LEN, "+%s", simMailboxList[simIndex].list[i].num);
+                               MSG_DEBUG("MSG_TON_INTERNATIONAL [%s]", mailNumber);
+                       } else {
+                               snprintf(mailNumber, MAX_PHONE_NUMBER_LEN, "%s", simMailboxList[simIndex].list[i].num);
+                               MSG_DEBUG("[%s]", mailNumber);
+                       }
+
+                       if (mailNumber[0] != '\0') {
+                               memset(keyName, 0x00, sizeof(keyName));
+                               snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_NUMBER, simIndex);
+                               if (MsgSettingSetString(keyName, mailNumber) != MSG_SUCCESS)
+                                       MSG_DEBUG("MsgSettingSetString is failed!!");
+                       }
+
+                       if (simMailboxList[simIndex].list[i].alpha_id[0] != '\0') {
+                               char unpackAlphaId[MAX_SIM_XDN_ALPHA_ID_LEN+8];
+                               int tmpLen = 0;
+                               MSG_LANG_INFO_S langInfo = {0,};
+
+                               memset(unpackAlphaId, 0x00, sizeof(unpackAlphaId));
+
+                               langInfo.bSingleShift = false;
+                               langInfo.bLockingShift = false;
+
+                               tmpLen = strlen(simMailboxList[simIndex].list[i].alpha_id);
+
+                               MsgTextConvert *textCvt = MsgTextConvert::instance();
+                               textCvt->convertGSM7bitToUTF8((unsigned char*)unpackAlphaId, sizeof(unpackAlphaId), (unsigned char*)simMailboxList[simIndex].list[i].alpha_id, tmpLen, &langInfo);
+
+                               MSG_DEBUG("UTF8 ALPHA_ID = [%s]", unpackAlphaId);
+
+                               memset(keyName, 0x00, sizeof(keyName));
+                               snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_ALPHA_ID, simIndex);
+                               if (MsgSettingSetString(keyName, unpackAlphaId) != MSG_SUCCESS)
+                                       MSG_DEBUG("MsgSettingSetString is failed!!");
+                       }
+               }
+       }
+
+       cv.signal();
 
        mx.unlock();
+}
 
-       if (ret == ETIMEDOUT)
-       {
+bool SmsPluginSetting::getMailboxInfoEvent()
+{
+       int ret = 0;
+
+       mx.lock();
+
+       bTapiResult = false;
+       ret = cv.timedwait(mx.pMutex(), MAX_TAPI_SIM_API_TIMEOUT);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT) {
                MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
                return false;
        }
 
-       memset(pCbOpt, 0x00, sizeof(MSG_CBMSG_OPT_S));
+       return bTapiResult;
+}
 
-       if (bTapiResult == true)
-       {
-               memcpy(pCbOpt, &cbOpt, sizeof(MSG_CBMSG_OPT_S));
+void SmsPluginSetting::setMwiInfoEvent(struct tapi_handle *handle, SMS_SIM_MWI_INFO_S *pMwiInfo, bool bSuccess)
+{
+       MSG_BEGIN();
+
+       mx.lock();
+
+       bTapiResult = bSuccess;
+
+       int index = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+       memset(&simMwiInfo[index], 0x00, sizeof(SMS_SIM_MWI_INFO_S));
+
+       if (bTapiResult == true) {
+               int mwiCnt = 0;
+               char keyName[MAX_VCONFKEY_NAME_LEN];
+
+               memcpy(&simMwiInfo[index], pMwiInfo, sizeof(SMS_SIM_MWI_INFO_S));
+
+               /* Save MW count with VOICE line1 number */
+               if (simMwiInfo[index].b_cphs == true) {
+                       mwiCnt = simMwiInfo[index].cphs_mwi.b_voice1;
+               } else {
+                       mwiCnt = simMwiInfo[index].mwi_list.mw_info[0].voice_count; // Normal case
+               }
+               // TODO :: Add operation for voice mail of line 2
+
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_COUNT, index);
+               if (MsgSettingSetInt(keyName, mwiCnt) != MSG_SUCCESS)
+                       MSG_DEBUG("MsgSettingSetInt is failed!!");
+
+               MSG_DEBUG("MWI count = [%d]", mwiCnt);
+
+               if (mwiCnt > 0) {
+                       deliverVoiceMsgNoti(index, mwiCnt);
+               }
+       }
+
+       cv.signal();
+
+       mx.unlock();
+
+       MSG_END();
+}
+
+
+void SmsPluginSetting::setResultImei(bool bResult, char *pImei)
+{
+       mx.lock();
+
+       bTapiResult = bResult;
+
+       memset(&meImei, 0x00, sizeof(meImei));
+
+       if (bTapiResult == true && pImei) {
+               snprintf(meImei, sizeof(meImei), "%s", pImei);
+       }
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+
+bool SmsPluginSetting::getResultImei(char *pImei)
+{
+       int ret = 0;
+
+       mx.lock();
+
+       ret = cv.timedwait(mx.pMutex(), MAX_TAPI_SIM_API_TIMEOUT);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT) {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return false;
+       }
+
+       if (bTapiResult == true && pImei) {
+               snprintf(pImei, sizeof(meImei), "%s", meImei);
        }
 
        return bTapiResult;
@@ -825,14 +1673,15 @@ bool SmsPluginSetting::getResultFromSim()
 {
        int ret = 0;
 
-       mx.lock();
+       MSG_DEBUG("getResultFromSim() is called .");
 
-       ret = cv.timedwait(mx.pMutex(), 10);
+       //mx.lock(); //  Caller of this function MUST acquire the mutex before calling the TAPI API
 
-       mx.unlock();
+       ret = cv.timedwait(mx.pMutex(), MAX_TAPI_SIM_API_TIMEOUT);
 
-       if (ret == ETIMEDOUT)
-       {
+       //mx.unlock();
+
+       if (ret == ETIMEDOUT) {
                MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
                return false;
        }
@@ -872,3 +1721,111 @@ SMS_PID_T SmsPluginSetting::convertPid(MSG_SMS_PID_T pid)
 
        return retPid;
 }
+
+
+void SmsPluginSetting::deliverVoiceMsgNoti(int simIndex, int mwiCnt)
+{
+       MSG_BEGIN();
+
+       MSG_MESSAGE_INFO_S msgInfo = {0,};
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       msgInfo.addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+       memset(msgInfo.addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+       msgInfo.nAddressCnt = 1;
+
+       msgInfo.displayTime = time(NULL);
+
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       char *voiceNum = NULL;
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", VOICEMAIL_NUMBER, simIndex);
+       voiceNum = MsgSettingGetString(keyName);
+
+       if (voiceNum) {
+               snprintf(msgInfo.addressList[0].addressVal, sizeof(msgInfo.addressList[0].addressVal),
+                               "%s", voiceNum);
+               free(voiceNum);
+               voiceNum = NULL;
+       }
+       memset(msgInfo.addressList[0].displayName, 0x00, sizeof(msgInfo.addressList[0].displayName));
+       msgInfo.msgType.mainType = MSG_SMS_TYPE;
+       msgInfo.msgType.subType = MSG_MWI_VOICE_SMS;
+       msgInfo.sim_idx = simIndex;
+
+#if 0
+       if (simMwiInfo.b_cphs == false) { // Normal case
+               snprintf(msgInfo.msgText, sizeof(msgInfo.msgText), "%d new voice message", mwiCnt);
+       } else {
+               snprintf(msgInfo.msgText, sizeof(msgInfo.msgText), "New voice message");
+       }
+#else
+       snprintf(msgInfo.msgText, sizeof(msgInfo.msgText), "%d", mwiCnt);
+#endif
+
+#if 0
+       if (SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo) != MSG_SUCCESS)
+               MSG_DEBUG("callbackIncoming is failed.");
+#else
+       MsgInsertNotification(&msgInfo);
+       MsgChangePmState();
+#endif
+
+       MSG_END();
+}
+
+
+void SmsPluginSetting::setSimChangeStatus(struct tapi_handle *handle, bool bInitializing)
+{
+       MSG_BEGIN();
+
+       int tapiRet = TAPI_API_SUCCESS;
+       TelSimCardStatus_t status = TAPI_SIM_STATUS_CARD_ERROR;
+
+       int cardChanged = 0;
+       int simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+       pthread_t thd;
+       char keyName[MAX_VCONFKEY_NAME_LEN] = {0,};
+
+       tapiRet = tel_get_sim_init_info(handle, &status, &cardChanged);
+       MSG_INFO("Tapi Ret=[%d], SIM index [%d], SIM status [%d], CardChanged [%d]", tapiRet, simIndex, status, cardChanged);
+
+       if (status == TAPI_SIM_STATUS_SIM_INIT_COMPLETED) {
+               if (simStatus[simIndex] == MSG_SIM_STATUS_NOT_FOUND) {
+                       if (cardChanged == 1) {
+                               snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, simIndex);
+                               MsgSettingSetInt(keyName, MSG_SIM_STATUS_CHANGED);
+                               simStatus[simIndex] = MSG_SIM_STATUS_CHANGED;
+                       } else {
+                               snprintf(keyName, sizeof(keyName),"%s/%d", MSG_SIM_CHANGED, simIndex);
+                               MsgSettingSetInt(keyName, MSG_SIM_STATUS_NORMAL);
+                               simStatus[simIndex] = MSG_SIM_STATUS_NORMAL;
+                       }
+//                     tel_handle_list.push_back(handle);
+                       // Modified to call initSimInfo for SIM separately
+                       MSG_DEBUG("calling initSimInfo");
+                       if (pthread_create(&thd, NULL, &initSimInfo, handle) < 0) {
+                               MSG_DEBUG("pthread_create() error");
+                       }
+                       pthread_detach(thd);
+
+               } else {
+                       MSG_DEBUG("SIM init was already done!");
+               }
+       } else {
+               MSG_DEBUG("It doesn't initialize yet!!");
+               snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_CHANGED, simIndex);
+               MSG_DEBUG("Set MSG_SIM_CHANGED to MSG_SIM_STATUS_NOT_FOUND");
+               if (MsgSettingSetInt(keyName, MSG_SIM_STATUS_NOT_FOUND) != MSG_SUCCESS)
+                       MSG_DEBUG("Fail to set MSG_SIM_CHANGED to MSG_SIM_STATUS_NOT_FOUND");
+
+               simStatus[simIndex] = MSG_SIM_STATUS_NOT_FOUND;
+
+       }
+
+       MSG_END();
+}
index 33af517..4a73e7b 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
 #include "SmsPluginStorage.h"
 #include "SmsPluginEventHandler.h"
 #include "SmsPluginCallback.h"
+#include "MsgUtilStorage.h"
+#include "MsgNotificationWrapper.h"
+
 #include "SmsPluginSimMsg.h"
+#include "SmsPluginDSHandler.h"
 
-extern struct tapi_handle *pTapiHandle;
 
 /*==================================================================================================
                                      IMPLEMENTATION OF SmsPluginSimMsg - Member Functions
@@ -40,10 +43,15 @@ SmsPluginSimMsg::SmsPluginSimMsg()
 {
        // Initialize member variables
        simMsgId = 0;
+       delSimMsgId = -1;
        usedCnt = 0;
        totalCnt = 0;
        bTapiResult = false;
-       bClass2Msg = false;
+       memset(&simMsgDataInfo, 0x00, sizeof(simMsgDataInfo));
+       memset(simIdList, 0, sizeof(int) * MAX_SIM_SMS_NUM);
+       memset(&simMsgCnt, 0x00, sizeof(simMsgCnt));
+       memset(&simMsgInfo, 0x00, sizeof(simMsgInfo));
+       memset(&simAddrInfo, 0x00, sizeof(simAddrInfo));
 }
 
 
@@ -63,28 +71,64 @@ SmsPluginSimMsg* SmsPluginSimMsg::instance()
 }
 
 
-void SmsPluginSimMsg::initSimMessage()
+void SmsPluginSimMsg::initSimMessage(struct tapi_handle *handle)
 {
        MSG_BEGIN();
 
+       char keyName[MAX_VCONFKEY_NAME_LEN] = {0,};
+       int sim_idx = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+       snprintf(keyName, sizeof(keyName), "%s/%d", SIM_USED_COUNT, sim_idx);
+       // Set SIM count of vconf to 0
+       if (MsgSettingSetInt(keyName, 0) != MSG_SUCCESS) {
+               MSG_DEBUG("Error to set config data [%s]", keyName);
+       }
+       memset(keyName, 0, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", SIM_TOTAL_COUNT, sim_idx);
+
+       if (MsgSettingSetInt(keyName, 0) != MSG_SUCCESS) {
+               MSG_DEBUG("Error to set config data [%s]", keyName);
+       }
+
        MSG_SIM_COUNT_S tmpMsgCnt;
        memset(&tmpMsgCnt, 0x00, sizeof(MSG_SIM_COUNT_S));
-
-       getSimMsgCount(&tmpMsgCnt);
+       getSimMsgCount(handle, &tmpMsgCnt);
 
        MSG_MESSAGE_INFO_S tmpMsgInfo;
-       memset(&tmpMsgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+       int simIdList[MAX_SIM_SMS_NUM];
+       int unreadSimMsg = 0;
 
        for (int i = 0; i < tmpMsgCnt.usedCount; i++)
        {
+               memset(&tmpMsgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+               memset(simIdList, 0, sizeof(int) * MAX_SIM_SMS_NUM);
+
                // Get SIM Msg
-               if (getSimMsg(tmpMsgCnt.indexList[i], &tmpMsgInfo) == false)
+               if (getSimMsg(handle, tmpMsgCnt.indexList[i], &tmpMsgInfo, simIdList) == false)
                        continue;
 
-               if (SmsPluginStorage::instance()->addSimMessage(&tmpMsgInfo) != MSG_SUCCESS)
-               {
-                       MSG_DEBUG("Fail to addSimMessage()");
+               if (tmpMsgInfo.bRead == false)
+                       unreadSimMsg++;
+
+               if (SmsPluginEventHandler::instance()->handleSimMsg(&tmpMsgInfo, simIdList, NULL, MAX_SIM_SMS_NUM) < 0) {
+                       MSG_DEBUG("Fail to handleSimMsg()");
                }
+
+               if (tmpMsgInfo.addressList) {
+                       free(tmpMsgInfo.addressList);
+                       tmpMsgInfo.addressList = NULL;
+               }
+       }
+
+       MSG_DEBUG("Unread SIM message count = [%d]", unreadSimMsg);
+#ifndef MSG_NOTI_INTEGRATION
+       if (unreadSimMsg > 0) {
+               MsgRefreshNotification(MSG_NOTI_TYPE_SIM, true, false);
+       }
+#endif
+
+       if (SmsPluginEventHandler::instance()->updateIMSI(sim_idx) != MSG_SUCCESS) {
+               MSG_ERR("Fail to handleSimMsg()");
        }
 
        MSG_END();
@@ -93,300 +137,420 @@ void SmsPluginSimMsg::initSimMessage()
 
 msg_error_t SmsPluginSimMsg::saveSimMessage(const MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList)
 {
+       bool bSimSst = true;
+
+       struct tapi_handle *handle = SmsPluginDSHandler::instance()->getTelHandle(pMsgInfo->sim_idx);
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_SERVICE_TABLE, pMsgInfo->sim_idx);
+       if (MsgSettingGetBool(keyName, &bSimSst) != MSG_SUCCESS)
+               MSG_DEBUG("MsgSettingGetBool [%s] failed", keyName);
+               /* No return, default value is true. */
+
+       if (bSimSst == false)
+               return MSG_ERR_STORE_RESTRICT;
+
        // Reset Out Parameter
        pSimIdList->count = 0;
 
        SMS_TPDU_S tpdu;
        memset(&tpdu, 0x00, sizeof(SMS_TPDU_S));
-
-       tpdu.tpduType = SMS_TPDU_DELIVER;
-
-       // Set SMS TPDU Options
-       setSmsOptions(&(tpdu.data.deliver));
-
-       // Set TimeStamp
-       convertTimeStamp(pMsgInfo, &(tpdu.data.deliver));
-
-       // Set SMSC Options
-       SMS_ADDRESS_S smsc;
-       memset(&smsc, 0x00, sizeof(SMS_ADDRESS_S));
-       SmsPluginTransport::instance()->setSmscOptions(&smsc);
-
-       // Make SMS_SUBMIT_DATA_S from MSG_REQUEST_INFO_S
-       SMS_SUBMIT_DATA_S submitData;
-       memset(&submitData, 0x00, sizeof(SMS_SUBMIT_DATA_S));
-       SmsPluginTransport::instance()->msgInfoToSubmitData(pMsgInfo, &submitData, &(tpdu.data.deliver.dcs.codingScheme), 0);
-
-       // Check sim message full.
-       if (checkSimMsgFull(submitData.segCount) == true)
+       if(pMsgInfo->direction == MSG_DIRECTION_TYPE_MO)
        {
-               MSG_DEBUG("SIM storage is full.");
-
-               return MSG_ERR_SIM_STORAGE_FULL;
+               tpdu.tpduType = SMS_TPDU_SUBMIT;
+               tpdu.data.submit.dcs.msgClass = SMS_MSG_CLASS_NONE;
+               //SmsPluginTransport::instance()->setSmsSendOptions(&(tpdu.data.submit));
+               tpdu.data.submit.vpf = SMS_VPF_NOT_PRESENT;
+       }
+       else
+       {
+               tpdu.tpduType = SMS_TPDU_DELIVER;
+               setSmsOptions(pMsgInfo, &(tpdu.data.deliver));
+               // Set TimeStamp
+               convertTimeStamp(pMsgInfo, &(tpdu.data.deliver));
        }
 
-       tpdu.data.deliver.userData.headerCnt = 0;
+       for(int i=0; i <pMsgInfo->nAddressCnt; ++i)
+       {
+               SMS_SUBMIT_DATA_S submitData;
+               memset(&submitData, 0x00, sizeof(SMS_SUBMIT_DATA_S));
+               int bufLen = 0;
+               char buf[MAX_TPDU_DATA_LEN];
 
-       if (submitData.segCount > 1)
-               tpdu.data.deliver.bHeaderInd = true;
+               if(pMsgInfo->direction == MSG_DIRECTION_TYPE_MO) // SUBMIT MSG
+               {
+                       SmsPluginTransport::instance()->msgInfoToSubmitData(pMsgInfo, &submitData, &(tpdu.data.submit.dcs.codingScheme), i);
 
-       int bufLen = 0, reqId = 0;
+                       int addLen = strlen(submitData.destAddress.address);
 
-       char buf[MAX_TPDU_DATA_LEN];
+                       tpdu.data.submit.destAddress.ton = submitData.destAddress.ton;
+                       tpdu.data.submit.destAddress.npi = submitData.destAddress.npi;
 
-       int addLen = strlen(submitData.destAddress.address);
+                       if (addLen < MAX_ADDRESS_LEN) {
+                               memcpy(tpdu.data.submit.destAddress.address, submitData.destAddress.address, addLen);
+                               tpdu.data.submit.destAddress.address[addLen] = '\0';
+                       } else {
+                               memcpy(tpdu.data.submit.destAddress.address, submitData.destAddress.address, MAX_ADDRESS_LEN);
+                               tpdu.data.submit.destAddress.address[MAX_ADDRESS_LEN] = '\0';
+                       }
 
-       tpdu.data.deliver.originAddress.ton = submitData.destAddress.ton;
-       tpdu.data.deliver.originAddress.npi = submitData.destAddress.npi;
+               } else { // DELIVER MSG
+                       SmsPluginTransport::instance()->msgInfoToSubmitData(pMsgInfo, &submitData, &(tpdu.data.deliver.dcs.codingScheme), i);
 
-       memcpy(tpdu.data.deliver.originAddress.address, submitData.destAddress.address, addLen);
-       tpdu.data.deliver.originAddress.address[addLen] = '\0';
+                       int addLen = strlen(submitData.destAddress.address);
 
-       for (unsigned int segCnt = 0; segCnt < submitData.segCount; segCnt++)
-       {
-               tpdu.data.deliver.userData.length = submitData.userData[segCnt].length;
-               memcpy(tpdu.data.deliver.userData.data, submitData.userData[segCnt].data, submitData.userData[segCnt].length);
+                       tpdu.data.deliver.originAddress.ton = submitData.destAddress.ton;
+                       tpdu.data.deliver.originAddress.npi = submitData.destAddress.npi;
 
-               memset(buf, 0x00, sizeof(buf));
+                       if (addLen < MAX_ADDRESS_LEN) {
+                               memcpy(tpdu.data.deliver.originAddress.address, submitData.destAddress.address, addLen);
+                               tpdu.data.deliver.originAddress.address[addLen] = '\0';
+                       } else {
+                               memcpy(tpdu.data.deliver.originAddress.address, submitData.destAddress.address, MAX_ADDRESS_LEN);
+                               tpdu.data.deliver.originAddress.address[MAX_ADDRESS_LEN] = '\0';
+                       }
+               }
 
-               // Encode SMS-DELIVER TPDU
-               bufLen = SmsPluginTpduCodec::encodeTpdu(&tpdu, buf);
+               // Check sim message full.
+               if (checkSimMsgFull(pMsgInfo->sim_idx, submitData.segCount) == true)
+               {
+                       MSG_DEBUG("SIM storage is full.");
+                       MsgInsertTicker("Sim memory full. Delete some items", SMS_MESSAGE_SIM_MESSAGE_FULL, true, 0);
 
-               // Make Telephony Structure
-               TelSmsData_t simSmsData;
-               memset((void*)&simSmsData, 0x00, sizeof(simSmsData));
+                       return MSG_ERR_SIM_STORAGE_FULL;
+               }
 
-               // Set TPDU data
-               memcpy((void*)simSmsData.SmsData.szData, buf, bufLen);
+               if(submitData.segCount > 1)
+               {
+                       if(pMsgInfo->direction == MSG_DIRECTION_TYPE_MO){ // SUBMIT MSG
+                               tpdu.data.submit.bHeaderInd = true;
+                       } else {
+                               tpdu.data.deliver.bHeaderInd = true;
+                       }
 
-               simSmsData.SmsData.szData[bufLen] = 0;
-               simSmsData.SmsData.MsgLength = bufLen;
+               }
 
-               MSG_DEBUG("Read Status [%d]", pMsgInfo->bRead);
+               for (unsigned int segCnt = 0; segCnt < submitData.segCount; segCnt++)
+               {
+                       if(pMsgInfo->direction == MSG_DIRECTION_TYPE_MO){
+                               memcpy(&(tpdu.data.submit.userData), &(submitData.userData[segCnt]), sizeof(SMS_USERDATA_S));
+                       } else {
+                               memcpy(&(tpdu.data.deliver.userData), &(submitData.userData[segCnt]), sizeof(SMS_USERDATA_S));
+                       }
 
-               if (pMsgInfo->bRead == true)
-                       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_READ;
-               else
-                       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_UNREAD;
+                       memset(buf, 0x00, sizeof(buf));
+
+                       // Encode SMS-DELIVER TPDU
+                       bufLen = SmsPluginTpduCodec::encodeTpdu(&tpdu, buf);
+
+                       // Make Telephony Structure
+                       TelSmsData_t simSmsData;
+                       memset((void*)&simSmsData, 0x00, sizeof(simSmsData));
+
+                       // Set TPDU data
+                       memcpy((void*)simSmsData.SmsData.szData, buf, bufLen);
+
+                       simSmsData.SmsData.szData[bufLen] = 0;
+                       simSmsData.SmsData.MsgLength = bufLen;
+                       simSmsData.SmsData.format = TAPI_NETTEXT_NETTYPE_3GPP;
+
+                       if(pMsgInfo->direction == MSG_DIRECTION_TYPE_MT) { // MT messages
+                               if (pMsgInfo->bRead == true)
+                                       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_READ;
+                               else
+                                       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_UNREAD;
+                       } else { // MO messages
+                               if (pMsgInfo->networkStatus == MSG_NETWORK_SEND_SUCCESS)
+                                       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_SENT;
+                               else if (pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_SUCCESS)
+                                       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_DELIVERED;
+                               else if (pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_FAIL)
+                                       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_DELIVERY_UNCONFIRMED;
+                               else
+                                       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_UNSENT;
+                       }
 
-               // Save SMS in SIM
-               int ret = 0;
+                       // Save SMS in SIM
+                       int ret = 0;
 
-               ret = tel_write_sms_in_sim(pTapiHandle, &simSmsData, TapiEventSaveSimMsg, NULL);
+                       ret = tel_write_sms_in_sim(handle, &simSmsData, TapiEventSaveSimMsg, NULL);
 
-               if (ret == TAPI_API_SUCCESS)
-               {
-                       MSG_DEBUG("########  tel_write_sms_in_sim Success !!! req Id : [%d] #######", reqId);
-               }
-               else
-               {
-                       MSG_DEBUG("########  tel_write_sms_in_sim Fail !!! req Id : [%d] return : [%d] #######", reqId, ret);
+                       if (ret == TAPI_API_SUCCESS)
+                       {
+                               MSG_DEBUG("########  tel_write_sms_in_sim Success !!!#######");
+                       }
+                       else
+                       {
+                               MSG_DEBUG("########  tel_write_sms_in_sim Fail !!! return : [%d] #######", ret);
 
-                       return MSG_ERR_PLUGIN_STORAGE;
-               }
+                               return MSG_ERR_PLUGIN_STORAGE;
+                       }
 
-               msg_sim_id_t SimId = 0;
+                       msg_sim_id_t SimId = 0;
 
-               bool bResult = false;
+                       bool bResult = false;
 
-               bResult = getSimEvent(&SimId);
+                       bResult = getSimEvent(&SimId);
 
-               int usedCnt = 0;
+                       int usedCnt = 0;
 
-               if (bResult == true)
-               {
-                       MSG_DEBUG("########  Saving Msg was Successful !!! req Id : [%d] SIM ID : [%d] #######", reqId, SimId);
+                       if (bResult == true)
+                       {
+                               MSG_DEBUG("########  Saving Msg was Successful !!! SIM ID : [%d] #######", SimId);
 
-                       usedCnt = MsgSettingGetInt(SIM_USED_COUNT);
+                               char keyName[MAX_VCONFKEY_NAME_LEN];
+                               memset(keyName, 0x00, sizeof(keyName));
+                               snprintf(keyName, sizeof(keyName), "%s/%d", SIM_USED_COUNT, pMsgInfo->sim_idx);
+                               usedCnt = MsgSettingGetInt(keyName);
 
-                       usedCnt++;
+                               usedCnt++;
 
-                       if (MsgSettingSetInt(SIM_USED_COUNT, usedCnt) != MSG_SUCCESS)
-                       {
-                               MSG_DEBUG("Error to set config data [%s]", SIM_USED_COUNT);
-                       }
+                               if (MsgSettingSetInt(keyName, usedCnt) != MSG_SUCCESS)
+                               {
+                                       MSG_DEBUG("Error to set config data [%s]", SIM_USED_COUNT);
+                               }
 
-                       pSimIdList->simId[pSimIdList->count] = SimId;
-                       pSimIdList->count++;
-               }
-               else
-               {
-                       MSG_DEBUG("########  Saving Msg was Failed !!! req Id : [%d] SIM ID : [%d] #######", reqId, SimId);
+                               pSimIdList->simId[pSimIdList->count] = SimId;
+                               pSimIdList->count++;
+                       }
+                       else
+                       {
+                               MSG_DEBUG("########  Saving Msg was Failed !!! SIM ID : [%d] #######", SimId);
 
-                       return MSG_ERR_PLUGIN_STORAGE;
+                               return MSG_ERR_PLUGIN_STORAGE;
+                       }
                }
        }
-
        return MSG_SUCCESS;
 }
 
 
 msg_error_t SmsPluginSimMsg::saveClass2Message(const MSG_MESSAGE_INFO_S *pMsgInfo)
 {
-       // Reset Flag
-       bClass2Msg = false;
 
+       msg_error_t err = MSG_SUCCESS;
+       bool bSimSst = true;
+       int tapiRet = TAPI_API_SUCCESS;
+       int simId = -1;
+       int replaceSimId = -1;
+       int replaceMsgId = 0;
+
+       struct tapi_handle *handle = SmsPluginDSHandler::instance()->getTelHandle(pMsgInfo->sim_idx);
+
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_SERVICE_TABLE, pMsgInfo->sim_idx);
+       if (MsgSettingGetBool(keyName, &bSimSst) != MSG_SUCCESS)
+               MSG_DEBUG("MsgSettingGetBool [%s] failed", keyName);
+       /* No return, default value is true. */
+
+       if (bSimSst == false)
+       {
+               SmsPluginTransport::instance()->sendDeliverReport(handle, MSG_SUCCESS);
+               return MSG_SUCCESS;
+       }
+
+       // Reset Flag
        SMS_TPDU_S tpdu;
 
        tpdu.tpduType = SMS_TPDU_DELIVER;
 
-       // Set SMS TPDU Options
-       setSmsOptions(&(tpdu.data.deliver));
-
-       // Set TimeStamp
        convertTimeStamp(pMsgInfo, &(tpdu.data.deliver));
 
-       // Set SMSC Options
-       SMS_ADDRESS_S smsc;
-       SmsPluginTransport::instance()->setSmscOptions(&smsc);
+       // Set SMS TPDU Options
+       setSmsOptions(pMsgInfo, &(tpdu.data.deliver));
 
-       // Make SMS_SUBMIT_DATA_S from MSG_REQUEST_INFO_S
        SMS_SUBMIT_DATA_S submitData;
-       SmsPluginTransport::instance()->msgInfoToSubmitData(pMsgInfo, &submitData, &(tpdu.data.deliver.dcs.codingScheme), 0);
+       int bufLen = 0;
+       char buf[MAX_TPDU_DATA_LEN];
 
-       // Check sim message full.
-       if (checkSimMsgFull(submitData.segCount) == true)
-       {
-               MSG_DEBUG("SIM storage is full.");
+       SmsPluginTransport::instance()->msgInfoToSubmitData(pMsgInfo, &submitData, &(tpdu.data.deliver.dcs.codingScheme), 0);
 
-               return MSG_ERR_SIM_STORAGE_FULL;
+       if (pMsgInfo->msgType.subType >= MSG_REPLACE_TYPE1_SMS && pMsgInfo->msgType.subType <= MSG_REPLACE_TYPE7_SMS) {
+               err = SmsPluginStorage::instance()->getReplaceSimMsg(pMsgInfo, &replaceMsgId, &replaceSimId);
+               MSG_DEBUG("getReplaceSimMsg(): err=[%d], Replace Sim Id = [%d], Replace message id = [%d]", err, replaceSimId, replaceMsgId);
+               if (replaceMsgId < 0)
+                       replaceMsgId = 0;
        }
 
-       tpdu.data.deliver.userData.headerCnt = 0;
+       // Check SIM ID
+       if (replaceSimId < 0) { // Normal message type
+               // Check sim message full.
+               if (checkSimMsgFull(pMsgInfo->sim_idx, submitData.segCount) == true)
+               {
+                       MSG_DEBUG("SIM storage is full.");
 
-       int bufLen = 0, reqId = 0;
+                       SmsPluginTransport::instance()->sendDeliverReport(handle, MSG_ERR_SIM_STORAGE_FULL);
 
-       char buf[MAX_TPDU_DATA_LEN];
+                       return MSG_ERR_SIM_STORAGE_FULL;
+               }
 
-       int addrLen = strlen(submitData.destAddress.address);
+               int addLen = strlen(submitData.destAddress.address);
 
-       tpdu.data.deliver.originAddress.ton = submitData.destAddress.ton;
-       tpdu.data.deliver.originAddress.npi = submitData.destAddress.npi;
+               tpdu.data.deliver.originAddress.ton = submitData.destAddress.ton;
+               tpdu.data.deliver.originAddress.npi = submitData.destAddress.npi;
 
-       memcpy(tpdu.data.deliver.originAddress.address, submitData.destAddress.address, addrLen);
-       tpdu.data.deliver.originAddress.address[addrLen] = '\0';
+               if (addLen < MAX_ADDRESS_LEN) {
+                       memcpy(tpdu.data.deliver.originAddress.address, submitData.destAddress.address, addLen);
+                       tpdu.data.deliver.originAddress.address[addLen] = '\0';
+               } else {
+                       memcpy(tpdu.data.deliver.originAddress.address, submitData.destAddress.address, MAX_ADDRESS_LEN);
+                       tpdu.data.deliver.originAddress.address[MAX_ADDRESS_LEN] = '\0';
+               }
+
+               if (submitData.segCount > 1)
+                       tpdu.data.deliver.bHeaderInd = true;
+       } else { // Replace message type
+               tapiRet = tel_delete_sms_in_sim(handle, replaceSimId, TapiEventDeleteSimMsg, NULL);
 
-       tpdu.data.deliver.userData.length = submitData.userData[0].length;
-       memcpy(tpdu.data.deliver.userData.data, submitData.userData[0].data, submitData.userData[0].length);
+               if (tapiRet == TAPI_API_SUCCESS) {
+                       MSG_DEBUG("########  tel_delete_sms_in_sim Success !!! #######");
 
-       memset(buf, 0x00, sizeof(buf));
+                       simId = -1;
+                       if(getDelSimEvent(&simId) == true) {
+                               err = SmsPluginStorage::instance()->deleteSimMessage(pMsgInfo->sim_idx, replaceSimId);
+                       }
+                       MSG_DEBUG("tel_delete_sms_in_sim() : Err=[%d], Replace Sim Id=[%d], Result Sim id=[%d]", err, replaceSimId, simId);
 
-       // Encode SMS-DELIVER TPDU
-       bufLen = SmsPluginTpduCodec::encodeTpdu(&tpdu, buf);
+               } else {
+                       MSG_DEBUG("########  tel_delete_sms_in_sim Fail !!! return : [%d] #######", tapiRet);
+               }
+       }
 
-       // Make Telephony Structure
-       TelSmsData_t simSmsData;
-       memset((void*)&simSmsData, 0x00, sizeof(simSmsData));
+       for (unsigned int segCnt = 0; segCnt < submitData.segCount; segCnt++) {
+               // Create TelSmsData_t data
+               TelSmsData_t simSmsData = {0,};
 
-       // Set TPDU data
-       memcpy((void*)simSmsData.SmsData.szData, buf, bufLen);
+               if (submitData.segCount == 1) {
+                       memcpy(&simSmsData.SmsData.Sca, &simMsgDataInfo.sca, sizeof(simSmsData.SmsData.Sca));
+                       memcpy(&simSmsData.SmsData.szData, &simMsgDataInfo.szData, sizeof(simSmsData.SmsData.szData)-1);
+                       simSmsData.SmsData.MsgLength = simMsgDataInfo.msgLength;
 
-       simSmsData.SmsData.szData[bufLen] = 0;
-       simSmsData.SmsData.MsgLength = bufLen;
+               } else {
+                       memcpy(&(tpdu.data.deliver.userData), &(submitData.userData[segCnt]), sizeof(SMS_USERDATA_S));
 
-       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_UNREAD;
+                       memset(buf, 0x00, sizeof(buf));
 
-       // Save Class 2 Msg in SIM
-       int tapiRet = TAPI_API_SUCCESS;
+                       // Encode SMS-DELIVER TPDU
+                       bufLen = SmsPluginTpduCodec::encodeTpdu(&tpdu, buf);
 
-       tapiRet = tel_write_sms_in_sim(pTapiHandle, &simSmsData, TapiEventSaveSimMsg, NULL);
+                       // Set TPDU data
+                       memcpy((void*)simSmsData.SmsData.Sca, &simMsgDataInfo.sca, sizeof(simSmsData.SmsData.Sca));
+                       memcpy((void*)simSmsData.SmsData.szData, buf, bufLen);
+                       simSmsData.SmsData.szData[bufLen] = 0;
+                       simSmsData.SmsData.MsgLength = bufLen;
+               }
 
-       if (tapiRet == TAPI_API_SUCCESS)
-       {
-               MSG_DEBUG("########  tel_write_sms_in_sim Success !!! req Id : [%d] #######", reqId);
+               simSmsData.SmsData.format = TAPI_NETTEXT_NETTYPE_3GPP;
+               simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_UNREAD;
 
-               // Set Flag
-               bClass2Msg = true;
+               MSG_MESSAGE_INFO_S *tmpSimMsgInfo = (MSG_MESSAGE_INFO_S *)calloc(1, sizeof(MSG_MESSAGE_INFO_S));
+               if (tmpSimMsgInfo) {
+                       memcpy(tmpSimMsgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
 
-               memset(&simMsgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
-               memcpy(&simMsgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+                       tmpSimMsgInfo->msgId = replaceMsgId;
 
-               usedCnt = MsgSettingGetInt(SIM_USED_COUNT);
+                       tmpSimMsgInfo->addressList = NULL;
+                       tmpSimMsgInfo->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+                       memcpy(&tmpSimMsgInfo->addressList[0], &pMsgInfo->addressList[0], sizeof(MSG_ADDRESS_INFO_S));
 
-               usedCnt++;
+                       tapiRet = tel_write_sms_in_sim(handle, &simSmsData, TapiEventSaveClass2Msg, tmpSimMsgInfo);
 
-               if (MsgSettingSetInt(SIM_USED_COUNT, usedCnt) != MSG_SUCCESS)
-               {
-                       MSG_DEBUG("Error to set config data [%s]", SIM_USED_COUNT);
-               }
-       }
-       else
-       {
-               MSG_DEBUG("########  tel_write_sms_in_sim Fail !!! req Id : [%d] return : [%d] #######", reqId, tapiRet);
+                       if (tapiRet == TAPI_API_SUCCESS) {
+                               MSG_DEBUG("########  tel_write_sms_in_sim Success !!!, segNum = [%d] #######", segCnt);
+                       } else {
+                               MSG_DEBUG("########  tel_write_sms_in_sim Fail !!! return : [%d] #######", tapiRet);
 
-               SmsPluginTransport::instance()->sendDeliverReport(MSG_ERR_STORAGE_ERROR);
+                               SmsPluginTransport::instance()->sendDeliverReport(handle, MSG_ERR_STORAGE_ERROR);
 
-               return MSG_ERR_PLUGIN_STORAGE;
+                               return MSG_ERR_PLUGIN_STORAGE;
+                       }
+               }
+               msg_sim_id_t retSimId;
+               if (!getSimEvent(&retSimId))
+                       return MSG_ERR_PLUGIN_STORAGE;
        }
 
        return MSG_SUCCESS;
 }
 
 
-void SmsPluginSimMsg::deleteSimMessage(msg_sim_id_t SimMsgId)
+void SmsPluginSimMsg::deleteSimMessage(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId)
 {
        int tapiRet = TAPI_API_SUCCESS;
-       int reqId = 0;
 
-       tapiRet = tel_delete_sms_in_sim(pTapiHandle, (int)SimMsgId, TapiEventDeleteSimMsg, NULL);
+       struct tapi_handle *handle = SmsPluginDSHandler::instance()->getTelHandle(sim_idx);
+       tapiRet = tel_delete_sms_in_sim(handle, (int)SimMsgId, TapiEventDeleteSimMsg, NULL);
 
        if (tapiRet == TAPI_API_SUCCESS)
        {
-               MSG_DEBUG("########  tel_delete_sms_in_sim Success !!! req Id : [%d] #######", reqId);
+               MSG_DEBUG("########  tel_delete_sms_in_sim Success !!! #######");
        }
        else
        {
-               THROW(MsgException::SMS_PLG_ERROR, "########  tel_delete_sms_in_sim Fail !!! req Id : [%d] return : [%d] #######", reqId, tapiRet);
+               THROW(MsgException::SMS_PLG_ERROR, "########  tel_delete_sms_in_sim Fail !!! return : [%d] #######", tapiRet);
        }
 
-       msg_sim_id_t SimId = 0;
+       int SimId = 0;
        bool bResult = false;
 
-       bResult = getSimEvent(&SimId);
+       bResult = getDelSimEvent(&SimId);
 
        int usedCnt = 0, totalCnt = 0;
 
        if (bResult == true)
        {
-               MSG_DEBUG("########  Deleting Msg was Successful !!! req Id : [%d] SIM ID : [%d] #######", reqId, SimId);
-
-               usedCnt = MsgSettingGetInt(SIM_USED_COUNT);
-               totalCnt = MsgSettingGetInt(SIM_TOTAL_COUNT);
+               MSG_DEBUG("########  Deleting Msg was Successful !!! SIM ID : [%d] #######", SimId);
+               char keyName[MAX_VCONFKEY_NAME_LEN];
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", SIM_USED_COUNT, sim_idx);
+               usedCnt = MsgSettingGetInt(keyName);
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", SIM_TOTAL_COUNT, sim_idx);
+               totalCnt = MsgSettingGetInt(keyName);
 
                if (usedCnt == totalCnt)
                {
-                       tapiRet = tel_set_sms_memory_status(pTapiHandle, TAPI_NETTEXT_PDA_MEMORY_STATUS_AVAILABLE, NULL, NULL);
+                       tapiRet = tel_set_sms_memory_status(handle, TAPI_NETTEXT_PDA_MEMORY_STATUS_AVAILABLE, NULL, NULL);
 
                        if (tapiRet == TAPI_API_SUCCESS)
                        {
-                               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! req Id : [%d] #######", reqId);
+                               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
                        }
                        else
                        {
-                               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! req Id : [%d] return : [%d] #######", reqId, tapiRet);
+                               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! return : [%d] #######", tapiRet);
                        }
                }
 
                usedCnt--;
 
-               if (MsgSettingSetInt(SIM_USED_COUNT, usedCnt) != MSG_SUCCESS)
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, sizeof(keyName), "%s/%d", SIM_USED_COUNT, sim_idx);
+
+               if (MsgSettingSetInt(keyName, usedCnt) != MSG_SUCCESS)
                {
-                       MSG_DEBUG("Error to set config data [%s]", SIM_USED_COUNT);
+                       MSG_DEBUG("Error to set config data [%s]", keyName);
                }
        }
        else
        {
-               THROW(MsgException::SMS_PLG_ERROR, "########  Deleting Msg was Failed !!! req Id : [%d] SIM ID : [%d] #######", reqId, SimId);
+               THROW(MsgException::SMS_PLG_ERROR, "########  Deleting Msg was Failed !!! SIM ID : [%d] #######", SimId);
        }
 }
 
 
-bool SmsPluginSimMsg::checkSimMsgFull(unsigned int SegCnt)
+bool SmsPluginSimMsg::checkSimMsgFull(msg_sim_slot_id_t sim_idx, unsigned int SegCnt)
 {
        int usedCnt = 0, totalCnt = 0;
 
-       usedCnt = MsgSettingGetInt(SIM_USED_COUNT);
-       totalCnt = MsgSettingGetInt(SIM_TOTAL_COUNT);
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", SIM_USED_COUNT, sim_idx);
+       usedCnt = MsgSettingGetInt(keyName);
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", SIM_TOTAL_COUNT, sim_idx);
+       totalCnt = MsgSettingGetInt(keyName);
 
        MSG_DEBUG("Segment Count [%d]", SegCnt);
        MSG_DEBUG("usedCnt [%d], totalCnt [%d]", usedCnt, totalCnt);
@@ -398,13 +562,14 @@ bool SmsPluginSimMsg::checkSimMsgFull(unsigned int SegCnt)
 }
 
 
-void SmsPluginSimMsg::setReadStatus(msg_sim_id_t SimMsgId)
+void SmsPluginSimMsg::setReadStatus(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId)
 {
        MSG_DEBUG("Sim Message ID [%d]", SimMsgId);
 
        int ret = TAPI_API_SUCCESS;
+       struct tapi_handle *handle = SmsPluginDSHandler::instance()->getTelHandle(sim_idx);
 
-       ret = tel_set_sms_message_status(pTapiHandle, (int)SimMsgId, TAPI_NETTEXT_STATUS_READ, NULL, NULL);
+       ret = tel_set_sms_message_status(handle, (int)SimMsgId, TAPI_NETTEXT_STATUS_READ, TapiEventSetMsgStatus, (void *)&SimMsgId);
 
        if (ret == TAPI_API_SUCCESS)
        {
@@ -422,7 +587,7 @@ void SmsPluginSimMsg::setReadStatus(msg_sim_id_t SimMsgId)
 
        if (bResult == true)
        {
-               MSG_DEBUG("######## Setting Read Status was Successful !!! #######");
+               MSG_DEBUG("######## Setting Read Status was Successful !!!, sim id=[%d] #######", SimId);
        }
        else
        {
@@ -431,13 +596,11 @@ void SmsPluginSimMsg::setReadStatus(msg_sim_id_t SimMsgId)
 }
 
 
-void SmsPluginSimMsg::getSimMsgCount(MSG_SIM_COUNT_S *pSimMsgCnt)
+void SmsPluginSimMsg::getSimMsgCount(struct tapi_handle *handle, MSG_SIM_COUNT_S *pSimMsgCnt)
 {
-       int reqId = 0;
-
        int ret = TAPI_API_SUCCESS;
 
-       ret = tel_get_sms_count(pTapiHandle, TapiEventGetSimMsgCnt, NULL);
+       ret = tel_get_sms_count(handle, TapiEventGetSimMsgCnt, NULL);
 
        if (ret == TAPI_API_SUCCESS)
        {
@@ -448,7 +611,7 @@ void SmsPluginSimMsg::getSimMsgCount(MSG_SIM_COUNT_S *pSimMsgCnt)
                THROW(MsgException::SMS_PLG_ERROR, "########  tel_get_sms_count() Fail !!! return : %d #######", ret);
        }
 
-       if (getSimMsgCntEvent(pSimMsgCnt) == true)
+       if (getSimMsgCntEvent(handle, pSimMsgCnt) == true)
        {
                MSG_DEBUG("######## Get Sim Msg Count was Successful !!! #######");
        }
@@ -459,13 +622,11 @@ void SmsPluginSimMsg::getSimMsgCount(MSG_SIM_COUNT_S *pSimMsgCnt)
 }
 
 
-bool SmsPluginSimMsg::getSimMsg(msg_sim_id_t SimMsgId, MSG_MESSAGE_INFO_S *pMsgInfo)
+bool SmsPluginSimMsg::getSimMsg(struct tapi_handle *handle, msg_sim_id_t SimMsgId, MSG_MESSAGE_INFO_S *pMsgInfo, int *simIdList)
 {
-       int reqId = 0;
-
        int ret = TAPI_API_SUCCESS;
 
-       ret = tel_read_sms_in_sim(pTapiHandle, SimMsgId, TapiEventGetSimMsg, NULL);
+       ret = tel_read_sms_in_sim(handle, SimMsgId, TapiEventGetSimMsg, simIdList);
 
        if (ret == TAPI_API_SUCCESS)
        {
@@ -477,7 +638,7 @@ bool SmsPluginSimMsg::getSimMsg(msg_sim_id_t SimMsgId, MSG_MESSAGE_INFO_S *pMsgI
                return false;
        }
 
-       if (getSimMsgEvent(pMsgInfo) == true)
+       if (getSimMsgEvent(handle, pMsgInfo) == true)
        {
                MSG_DEBUG("######## Get Sim Msg was Successful !!! #######");
        }
@@ -491,7 +652,7 @@ bool SmsPluginSimMsg::getSimMsg(msg_sim_id_t SimMsgId, MSG_MESSAGE_INFO_S *pMsgI
 }
 
 
-void SmsPluginSimMsg::setSmsOptions(SMS_DELIVER_S *pDeliver)
+void SmsPluginSimMsg::setSmsOptions(const MSG_MESSAGE_INFO_S* pMsgInfo, SMS_DELIVER_S *pDeliver)
 {
        pDeliver->bMoreMsg = false;
        pDeliver->bStatusReport = false;
@@ -502,7 +663,9 @@ void SmsPluginSimMsg::setSmsOptions(SMS_DELIVER_S *pDeliver)
        pDeliver->dcs.msgClass = SMS_MSG_CLASS_NONE;
        pDeliver->dcs.codingGroup = SMS_GROUP_GENERAL;
 
-       pDeliver->dcs.codingScheme = (SMS_CODING_SCHEME_T)MsgSettingGetInt(SMS_SEND_DCS);
+       /* use encoding type of received message instead of message settings */
+       //pDeliver->dcs.codingScheme = (SMS_CODING_SCHEME_T)MsgSettingGetInt(SMS_SEND_DCS);
+       pDeliver->dcs.codingScheme = pMsgInfo->encodeType;
 
        MSG_DEBUG("DCS : %d", pDeliver->dcs.codingScheme);
 
@@ -521,7 +684,8 @@ void SmsPluginSimMsg::convertTimeStamp(const MSG_MESSAGE_INFO_S* pMsgInfo, SMS_D
 
        // encode absolute time
        struct tm timeinfo = {0,};
-       gmtime_r(&pMsgInfo->displayTime, &timeinfo);
+       tzset();
+       localtime_r(&pMsgInfo->displayTime, &timeinfo);
 
        pDeliver->timeStamp.time.absolute.year = timeinfo.tm_year - 100;
        MSG_DEBUG("pDeliver->timeStamp.time.absolute.year is %d",pDeliver->timeStamp.time.absolute.year);
@@ -548,23 +712,29 @@ void SmsPluginSimMsg::convertTimeStamp(const MSG_MESSAGE_INFO_S* pMsgInfo, SMS_D
 }
 
 
-void SmsPluginSimMsg::setSimMsgCntEvent(const MSG_SIM_COUNT_S *pSimMsgCnt)
+void SmsPluginSimMsg::setSimMsgCntEvent(struct tapi_handle *handle, const MSG_SIM_COUNT_S *pSimMsgCnt)
 {
        mx.lock();
 
        MSG_DEBUG("Sim Message Count is %d.", pSimMsgCnt->usedCount);
 
+       int sim_idx = SmsPluginDSHandler::instance()->getSimIndex(handle);
+       char keyName[MAX_VCONFKEY_NAME_LEN]= {0,};
+
        for (int i=0; i < pSimMsgCnt->usedCount; i++)
        {
                MSG_DEBUG("Sim Message Index is %d.", pSimMsgCnt->indexList[i]);
        }
 
-       if (MsgSettingSetInt(SIM_USED_COUNT, pSimMsgCnt->usedCount) != MSG_SUCCESS)
+       snprintf(keyName, sizeof(keyName), "%s/%d", SIM_USED_COUNT, sim_idx);
+       if (MsgSettingSetInt(keyName, pSimMsgCnt->usedCount) != MSG_SUCCESS)
        {
                MSG_DEBUG("Error to set config data [%s]", SIM_USED_COUNT);
        }
 
-       if (MsgSettingSetInt(SIM_TOTAL_COUNT, (int)pSimMsgCnt->totalCount) != MSG_SUCCESS)
+       memset(keyName, 0, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", SIM_TOTAL_COUNT, sim_idx);
+       if (MsgSettingSetInt(keyName, (int)pSimMsgCnt->totalCount) != MSG_SUCCESS)
        {
                MSG_DEBUG("Error to set config data [%s]", SIM_TOTAL_COUNT);
        }
@@ -578,7 +748,7 @@ void SmsPluginSimMsg::setSimMsgCntEvent(const MSG_SIM_COUNT_S *pSimMsgCnt)
 }
 
 
-bool SmsPluginSimMsg::getSimMsgCntEvent(MSG_SIM_COUNT_S *pSimMsgCnt)
+bool SmsPluginSimMsg::getSimMsgCntEvent(struct tapi_handle *handle, MSG_SIM_COUNT_S *pSimMsgCnt)
 {
        int ret = 0;
 
@@ -599,20 +769,22 @@ bool SmsPluginSimMsg::getSimMsgCntEvent(MSG_SIM_COUNT_S *pSimMsgCnt)
        return true;
 }
 
-
-void SmsPluginSimMsg::setSimMsgEvent(const MSG_MESSAGE_INFO_S *pMsgInfo, bool bSuccess)
+void SmsPluginSimMsg::setSimMsgEvent(struct tapi_handle *handle, const MSG_MESSAGE_INFO_S *pMsgInfo, bool bSuccess)
 {
        mx.lock();
 
        bTapiResult = bSuccess;
 
        memset(&simMsgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+       memset(&simAddrInfo, 0x00, sizeof(MSG_ADDRESS_INFO_S));
 
        if (bTapiResult  == true)
        {
                MSG_DEBUG("Success to get sim msg - Id : [%d]", pMsgInfo->msgId);
 
                memcpy(&simMsgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+               simMsgInfo.addressList = &simAddrInfo;
+               memcpy(&simAddrInfo,pMsgInfo->addressList, sizeof(MSG_ADDRESS_INFO_S));
        }
 
        cv.signal();
@@ -621,14 +793,13 @@ void SmsPluginSimMsg::setSimMsgEvent(const MSG_MESSAGE_INFO_S *pMsgInfo, bool bS
 }
 
 
-bool SmsPluginSimMsg::getSimMsgEvent(MSG_MESSAGE_INFO_S *pMsgInfo)
+bool SmsPluginSimMsg::getSimMsgEvent(struct tapi_handle *handle, MSG_MESSAGE_INFO_S *pMsgInfo)
 {
        int ret = 0;
 
-       bTapiResult = false;
-
        mx.lock();
 
+       bTapiResult = false;
        ret = cv.timedwait(mx.pMutex(), 10);
 
        mx.unlock();
@@ -644,56 +815,139 @@ bool SmsPluginSimMsg::getSimMsgEvent(MSG_MESSAGE_INFO_S *pMsgInfo)
        if (bTapiResult == true)
        {
                memcpy(pMsgInfo, &simMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+               pMsgInfo->addressList = (MSG_ADDRESS_INFO_S *)calloc(1, sizeof(MSG_ADDRESS_INFO_S));
+               memset(pMsgInfo->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+               memcpy(pMsgInfo->addressList, simMsgInfo.addressList, sizeof(MSG_ADDRESS_INFO_S));
+               pMsgInfo->sim_idx = SmsPluginDSHandler::instance()->getSimIndex(handle);
        }
 
+
        return bTapiResult;
 }
 
 
-void SmsPluginSimMsg::setSimEvent(msg_sim_id_t SimId, bool bResult)
+void SmsPluginSimMsg::setSaveSimMsgEvent(struct tapi_handle *handle, int simId, int result)
 {
-       if (bClass2Msg == true)
-       {
-               msg_error_t err = MSG_SUCCESS;
+       msg_error_t err = MSG_SUCCESS;
 
-               simMsgInfo.msgId = SimId;
+       mx.lock();
 
-               // Add Deliver Class2 Msg into DB
-               err = SmsPluginStorage::instance()->addSmsMessage(&simMsgInfo);
+       if (result != TAPI_NETTEXT_SENDSMS_SUCCESS) {
+               if (result == TAPI_NETTEXT_ROUTING_NOT_AVAILABLE || result == TAPI_NETTEXT_SIM_FULL)
+                       err = MSG_ERR_SIM_STORAGE_FULL;
+               else
+                       err = MSG_ERR_UNKNOWN;
+       }
 
-               if (err == MSG_SUCCESS)
-               {
-                       MSG_DEBUG("addMessage() Success !!");
+       if (err == MSG_SUCCESS)
+               bTapiResult = true;
+       else
+               bTapiResult = false;
+
+       simMsgId = simId;
+
+       cv.signal();
+
+       mx.unlock();
+
+       int tapiRet = TAPI_API_SUCCESS;
+
+       if (err == MSG_SUCCESS) {
+               tapiRet = tel_set_sms_memory_status(handle, TAPI_NETTEXT_PDA_MEMORY_STATUS_AVAILABLE, TapiEventMemoryStatus, NULL);
+       } else if (err == MSG_ERR_SIM_STORAGE_FULL) {
+               tapiRet = tel_set_sms_memory_status(handle, TAPI_NETTEXT_PDA_MEMORY_STATUS_FULL, TapiEventMemoryStatus, NULL);
+       } else {
+               return;
+       }
+
+       if (tapiRet == TAPI_API_SUCCESS) {
+               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
+       } else {
+               MSG_DEBUG("########  tel_set_sms_memory_status() Failed !!! return : [%d] #######", tapiRet);
+       }
+}
+
+
+void SmsPluginSimMsg::setSaveClass2MsgEvent(struct tapi_handle *handle, int simId, int result, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+//     int sim_idx = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+       if (result == TAPI_NETTEXT_SENDSMS_SUCCESS && simId >= 0 && pMsgInfo) {
+               bool isNewSimMsg = true;
+
+               for (int i = 0; i < MAX_SIM_SMS_NUM; i++) {
+                       if (simIdList[i] != 0) {
+                               MSG_DEBUG("simIdList[%d] is exist [%d]", i, simIdList[i]);
+                               continue;
+                       } else {
+                               simIdList[i] = simId + 1;
+                               MSG_DEBUG("simIdList[%d] is assigned [%d]", i, simId + 1);
+                               break;
+                       }
+               }
+
+               if (pMsgInfo->msgType.subType >= MSG_REPLACE_TYPE1_SMS && pMsgInfo->msgType.subType <= MSG_REPLACE_TYPE7_SMS) {
+                       if (pMsgInfo->msgId > 0) {
+                               isNewSimMsg = false;
+                       }
+               }
+
+               if (simMsgDataInfo.totalSegment >= 1 && simIdList[simMsgDataInfo.totalSegment-1] != 0) {
+                       msg_message_id_t saved_msg_id = 0;
+                       SmsPluginEventHandler::instance()->handleSimMsg(pMsgInfo, simIdList, &saved_msg_id, MAX_SIM_SMS_NUM);
+
+                       MSG_DEBUG("Saved message ID = [%d]", saved_msg_id);
 
-                       // Callback
-                       err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&simMsgInfo);
+                       if (saved_msg_id > 0)
+                               pMsgInfo->msgId = saved_msg_id;
+
+                       err = SmsPluginEventHandler::instance()->callbackMsgIncoming(pMsgInfo);
 
                        if (err != MSG_SUCCESS)
                        {
                                MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
                        }
                }
-               else
-               {
-                       MSG_DEBUG("addMessage() Error !! [%d]", err);
-               }
 
-               // Send Deliver Report
-               SmsPluginTransport::instance()->sendDeliverReport(err);
+               if (isNewSimMsg == true) {
+                       char keyName[MAX_VCONFKEY_NAME_LEN];
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, sizeof(keyName), "%s/%d", SIM_USED_COUNT, pMsgInfo->sim_idx);
+                       usedCnt = MsgSettingGetInt(keyName);
+                       usedCnt++;
+
+                       if (MsgSettingSetInt(keyName, usedCnt) != MSG_SUCCESS)
+                       {
+                               MSG_DEBUG("Error to set config data [%s]", SIM_USED_COUNT);
+                       }
+               }
 
-               bClass2Msg = false;
+               if (simMsgDataInfo.totalSegment >= 1 && simIdList[simMsgDataInfo.totalSegment-1] != 0) {
+                       memset(simIdList, 0, sizeof(int) * MAX_SIM_SMS_NUM);
+               }
+       } else {
+               if (result == TAPI_NETTEXT_SIM_FULL)
+                       err = MSG_ERR_SIM_STORAGE_FULL;
+               else
+                       err = MSG_ERR_UNKNOWN;
        }
-       else
-       {
-               mx.lock();
 
-               simMsgId = SimId;
-               bTapiResult = bResult;
+       // Send Deliver Report
+       SmsPluginTransport::instance()->sendDeliverReport(handle, err);
+}
 
-               cv.signal();
 
-               mx.unlock();
-       }
+void SmsPluginSimMsg::setSimEvent(msg_sim_id_t SimId, bool bResult)
+{
+       mx.lock();
+
+       simMsgId = SimId;
+       bTapiResult = bResult;
+
+       cv.signal();
+
+       mx.unlock();
 }
 
 
@@ -701,10 +955,9 @@ bool SmsPluginSimMsg::getSimEvent(msg_sim_id_t *pSimId)
 {
        int ret = 0;
 
-       bTapiResult = false;
-
        mx.lock();
 
+       bTapiResult = false;
        ret = cv.timedwait(mx.pMutex(), 10);
 
        mx.unlock();
@@ -721,3 +974,62 @@ bool SmsPluginSimMsg::getSimEvent(msg_sim_id_t *pSimId)
 
        return bTapiResult;
 }
+
+
+void SmsPluginSimMsg::setDelSimEvent(int SimId, bool bResult)
+{
+       mx.lock();
+
+       delSimMsgId = SimId;
+       bTapiResult = bResult;
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+
+bool SmsPluginSimMsg::getDelSimEvent(int *pSimId)
+{
+       int ret = 0;
+
+       mx.lock();
+
+       delSimMsgId = -1;
+       bTapiResult = false;
+       ret = cv.timedwait(mx.pMutex(), 10);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT)
+       {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return false;
+       }
+
+       *pSimId = delSimMsgId;
+
+       MSG_DEBUG("Returned delSimMsgId is %d.", delSimMsgId);
+
+       return bTapiResult;
+}
+
+
+void SmsPluginSimMsg::setSmsData(const char *sca, const char *szData, int msgLength)
+{
+       MSG_DEBUG("Set SMS data(class2 message)");
+
+       memset(&simMsgDataInfo, 0x00, sizeof(simMsgDataInfo));
+
+       memcpy(&simMsgDataInfo.sca, sca, sizeof(simMsgDataInfo.sca)-1);
+       memcpy(&simMsgDataInfo.szData, szData, sizeof(simMsgDataInfo.szData)-1);
+       simMsgDataInfo.msgLength = msgLength;
+}
+
+void SmsPluginSimMsg::setSmsTpduTotalSegCount(int totalSeg)
+{
+       MSG_DEBUG("Set SMS Segements Info");
+
+       simMsgDataInfo.totalSegment = totalSeg;
+}
+
index 26fc681..2b51956 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
@@ -22,6 +22,7 @@
 #include "MsgContact.h"
 #include "MsgUtilFile.h"
 #include "MsgUtilStorage.h"
+#include "MsgUtilFunction.h"
 #include "MsgGconfWrapper.h"
 #include "MsgNotificationWrapper.h"
 #include "SmsPluginMain.h"
@@ -37,15 +38,14 @@ SmsPluginStorage* SmsPluginStorage::pInstance = NULL;
 
 SmsPluginStorage::SmsPluginStorage()
 {
-
+       memset(&msgInfo, 0x00, sizeof(msgInfo));
+       memset(&addrInfo, 0x00, sizeof(addrInfo));
 }
 
 
 SmsPluginStorage::~SmsPluginStorage()
 {
-       if (dbHandle.disconnect() != MSG_SUCCESS) {
-               MSG_DEBUG("DB Disconnect Fail");
-       }
+
 }
 
 
@@ -60,10 +60,157 @@ SmsPluginStorage* SmsPluginStorage::instance()
 }
 
 
+msg_error_t SmsPluginStorage::insertMsgRef(MSG_MESSAGE_INFO_S *pMsg, unsigned char msgRef, int index)
+{
+       MSG_BEGIN();
+
+       time_t curTime = time(NULL);
+
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       char *normalNum = NULL;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       normalNum = msg_normalize_number(pMsg->addressList[index].addressVal);
+
+       MSG_SEC_DEBUG("Insert MsgID=[%d], Address=[%s], MsgRef=[%d], Time=[%d]", \
+                       pMsg->msgId, normalNum, (int)msgRef, (int)curTime);
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %s, %d, 0, -1, %d);",
+                       MSGFW_SMS_REPORT_TABLE_NAME, pMsg->msgId, normalNum, (int)msgRef, (int)curTime);
+
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgExecQuery() : [%s]", sqlQuery);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+
+}
+
+
+msg_error_t SmsPluginStorage::updateMsgDeliverStatus(MSG_MESSAGE_INFO_S *pMsgInfo, unsigned char msgRef)
+{
+       MSG_BEGIN();
+
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       msg_message_id_t msgId = 0;
+       int rowCnt = 0;
+       char *normalNum = NULL;
+
+       normalNum = msg_normalize_number(pMsgInfo->addressList[0].addressVal);
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE ADDRESS_VAL = %s AND MSG_REF > 0 ORDER BY TIME ASC;",
+                       MSGFW_SMS_REPORT_TABLE_NAME, normalNum);
+       MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW)
+               msgId = dbHandle->columnInt(0);
+
+       dbHandle->finalizeQuery();
+
+       pMsgInfo->msgId = msgId;
+
+       /** Update Status - MSG_MESSAGE_TABLE */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT * FROM %s WHERE MSG_ID = %d AND MSG_REF > 0;",
+                       MSGFW_SMS_REPORT_TABLE_NAME, msgId);
+
+       if (dbHandle->getTable(sqlQuery, &rowCnt, NULL) != MSG_SUCCESS) {
+               dbHandle->freeTable();
+               return MSG_ERR_DB_GETTABLE;
+       }
+
+       dbHandle->freeTable();
+
+       MSG_DEBUG("Selected row count = [%d]", rowCnt);
+
+       if (rowCnt == 1 && pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_SUCCESS) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET NETWORK_STATUS = %d WHERE MSG_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, (int)pMsgInfo->networkStatus, msgId);
+               MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+                       return MSG_ERR_DB_EXEC;
+               }
+       }
+
+       /** Update Status - MSG_REPORT_TABLE */
+       if (pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_SUCCESS) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MSG_REF = -1, STATUS = %d, TIME = %d WHERE MSG_ID = %d and ADDRESS_VAL = '%s';",
+                               MSGFW_SMS_REPORT_TABLE_NAME, 1, (int)pMsgInfo->displayTime, msgId, normalNum);
+               MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+                       return MSG_ERR_DB_EXEC;
+               }
+       } else if(pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_EXPIRED) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MSG_REF = -1, STATUS = %d, TIME = %d WHERE MSG_ID = %d and ADDRESS_VAL = '%s';",
+                               MSGFW_SMS_REPORT_TABLE_NAME, 0, (int)pMsgInfo->displayTime, msgId, normalNum);
+               MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+                       return MSG_ERR_DB_EXEC;
+               }
+       } else if(pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_PENDING) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MSG_REF = -1, STATUS = %d, TIME = %d WHERE MSG_ID = %d and ADDRESS_VAL = '%s';",
+                               MSGFW_SMS_REPORT_TABLE_NAME, 3, (int)pMsgInfo->displayTime, msgId, normalNum);
+               MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+                       return MSG_ERR_DB_EXEC;
+               }
+       } else if(pMsgInfo->networkStatus == MSG_NETWORK_DELIVER_FAIL) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MSG_REF = -1, STATUS = %d, TIME = %d WHERE MSG_ID = %d and ADDRESS_VAL = '%s';",
+                               MSGFW_SMS_REPORT_TABLE_NAME, 8, (int)pMsgInfo->displayTime, msgId, normalNum);
+               MSG_DEBUG("[SQL Query] %s", sqlQuery);
+
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+                       return MSG_ERR_DB_EXEC;
+               }
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
 msg_error_t SmsPluginStorage::updateSentMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_network_status_t status)
 {
        MSG_BEGIN();
 
+       if (!pMsgInfo || (pMsgInfo && pMsgInfo->msgId <= 0)) {
+               MSG_DEBUG("Invalid message id");
+               return MSG_ERR_INVALID_MESSAGE_ID;
+       }
+
+/***  Comment below line to not save the time value after sent status (it could be used later.)
+       time_t curTime = time(NULL);
+***/
+       MsgDbHandler *dbHandle = getDbHandle();
+
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
@@ -75,11 +222,11 @@ msg_error_t SmsPluginStorage::updateSentMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_ne
                snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET NETWORK_STATUS = %d, FOLDER_ID = %d WHERE MSG_ID = %d;",
                                        MSGFW_MESSAGE_TABLE_NAME, status, MSG_SENTBOX_ID, pMsgInfo->msgId);
        } else {
-               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET NETWORK_STATUS = %d WHERE MSG_ID = %d;",
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET NETWORK_STATUS = %d, READ_STATUS = 0 WHERE MSG_ID = %d;",
                                        MSGFW_MESSAGE_TABLE_NAME, status, pMsgInfo->msgId);
        }
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
                MSG_DEBUG("MsgExecQuery() : [%s]", sqlQuery);
                return MSG_ERR_DB_EXEC;
        }
@@ -94,133 +241,225 @@ msg_error_t SmsPluginStorage::updateSentMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_ne
        return MSG_SUCCESS;
 }
 
+#ifdef SMS_REPORT_OPERATION
+msg_error_t SmsPluginStorage::updateMsgRef(msg_message_id_t MsgId, unsigned char MsgRef)
+{
+       MSG_BEGIN();
+
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MSG_REF = %d WHERE MSG_ID = %d;",
+                               MSGFW_REPORT_TABLE_NAME, (int)MsgRef, MsgId);
+
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       /** Set Message Reference for updating report table */
+       tmpMsgRef = MsgRef;
+
+       MSG_DEBUG("MsgRef : %d", MsgRef);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
 
-msg_error_t SmsPluginStorage::addSimMessage(MSG_MESSAGE_INFO_S *pSimMsgInfo)
+msg_error_t SmsPluginStorage::updateStatusReport(unsigned char MsgRef, msg_delivery_report_status_t Status, time_t DeliveryTime)
 {
-       msg_error_t err = MSG_SUCCESS;
+       MSG_BEGIN();
 
-       msg_message_id_t msgId = 0;
-       msg_thread_id_t convId = 0;
-       unsigned int simId = 0;
+       MSG_DEBUG("tmpMsgRef : %d", tmpMsgRef);
+
+       MsgDbHandler *dbHandle = getDbHandle();
 
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       dbHandle.beginTrans();
+       /** Get Msg Id for Quickpanel Noti */
+       msg_message_id_t msgId = 0;
 
-       err = MsgStoAddAddress(&dbHandle, pSimMsgInfo, &convId);
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE MSG_REF = %d;",
+                                       MSGFW_REPORT_TABLE_NAME, (int)tmpMsgRef);
 
-       if (err != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return err;
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW)
+               msgId = dbHandle->columnInt(0);
+
+       dbHandle->finalizeQuery();
+
+       /** Update Status */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET MSG_REF = -1, DELIVERY_REPORT_STATUS = %d, DELIVERY_REPORT_TIME = %lu WHERE MSG_REF = %d;",
+                                       MSGFW_REPORT_TABLE_NAME, Status, DeliveryTime, (int)tmpMsgRef);
+
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Query Failed : [%s]", sqlQuery);
+               return MSG_ERR_DB_EXEC;
        }
 
-       err = dbHandle.getRowId(MSGFW_MESSAGE_TABLE_NAME, &msgId);
+       /** Insert Quickpanel Noti */
+       msg_error_t ret = MSG_SUCCESS;
 
-       if (err != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return err;
+       ret = MsgInsertSmsNotiToQuickpanel(dbHandle, msgId, Status);
+
+       if (ret != MSG_SUCCESS) {
+               MSG_DEBUG("MsgInsertSmsNotiToQuickpanel() Failed : [%d]", ret);
+               return ret;
        }
 
-       simId = pSimMsgInfo->msgId;
-       pSimMsgInfo->msgId = msgId;
+       MSG_END();
 
-       SMS_CONCAT_SIM_MSG_S concatSimMsg = {0};
+       return MSG_SUCCESS;
+}
+#endif
 
-       /** Get Data from Concat SIM Msg */
-       if (pSimMsgInfo->msgType.subType == MSG_CONCAT_SIM_SMS && pSimMsgInfo->bTextSms == false) {
+msg_error_t SmsPluginStorage::addSimMessage(MSG_MESSAGE_INFO_S *pSimMsgInfo, int *simIdList)
+{
+       msg_error_t err = MSG_SUCCESS;
 
-               int fileSize = 0;
+       unsigned int simId = 0;
+       MsgDbHandler *dbHandle = getDbHandle();
 
-               char* pFileData = NULL;
-               AutoPtr<char> buf(&pFileData);
+       char sqlQuery[MAX_QUERY_LEN+1];
 
-               if (MsgOpenAndReadFile(pSimMsgInfo->msgData, &pFileData, &fileSize) == false) {
-                       dbHandle.endTrans(false);
-                       return MSG_ERR_STORAGE_ERROR;
-               }
+//     dbHandle->beginTrans();
+
+# if 0
+       msg_message_id_t msgId = 0;
+       msg_thread_id_t convId = 0;
 
+       err = MsgStoAddAddress(dbHandle, pSimMsgInfo, &convId);
 
-               memcpy(&concatSimMsg, (SMS_CONCAT_SIM_MSG_S*)pFileData, fileSize);
+       if (err != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return err;
+       }
+
+       pSimMsgInfo->threadId = convId;
 
-               /** Delete temporary file */
-               MsgDeleteFile(pSimMsgInfo->msgData); /** ipc */
+       err = dbHandle->getRowId(MSGFW_MESSAGE_TABLE_NAME, &msgId);
 
-               MSG_DEBUG("SIM ID [%d], MSG DATA [%s]", concatSimMsg.simIdCnt, concatSimMsg.msgData);
+       if (err != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return err;
        }
 
+       //simId = pSimMsgInfo->msgId;
+       pSimMsgInfo->msgId = msgId;
+
        /**  Add Message */
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, %d, %d, %ld, %d, %d, %d, %d, %d, %d, %ld, %d, ?, '', '', ?, %d, 0, %d, 0, 0);",
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, %d, %d, %ld, %d, %d, %d, %d, %d, %d, %ld, %d, ?, '', '', ?, 0, 0, 0);",
                        MSGFW_MESSAGE_TABLE_NAME, msgId, convId, pSimMsgInfo->folderId, pSimMsgInfo->storageId,
                        pSimMsgInfo->msgType.mainType, pSimMsgInfo->msgType.subType, pSimMsgInfo->displayTime, pSimMsgInfo->dataSize,
                        pSimMsgInfo->networkStatus, pSimMsgInfo->bRead, pSimMsgInfo->bProtected, pSimMsgInfo->priority,
-                       pSimMsgInfo->direction, 0, pSimMsgInfo->bBackup, MSG_DELIVERY_REPORT_NONE, MSG_READ_REPORT_NONE);
+                       pSimMsgInfo->direction, 0, pSimMsgInfo->bBackup);
 
        MSG_DEBUG("QUERY : %s", sqlQuery);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_PREPARE;
        }
 
-       dbHandle.bindText(pSimMsgInfo->subject, 1);
+       dbHandle->bindText(pSimMsgInfo->subject, 1);
 
-       if (pSimMsgInfo->msgType.subType == MSG_CONCAT_SIM_SMS && pSimMsgInfo->bTextSms == false)
-               dbHandle.bindText(concatSimMsg.msgData, 2);
-       else
-               dbHandle.bindText(pSimMsgInfo->msgText, 2);
+       dbHandle->bindText(pSimMsgInfo->msgText, 2);
 
-       if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
-               dbHandle.endTrans(false);
+       if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
+#endif
+       if(simIdList) {
+               MSG_DEBUG("simIdList exist.");
+               for(int i=0; i < MAX_SIM_SMS_NUM; ++i)
+               {
+                       if(simIdList[i]) {
+                               simId = simIdList[i] - 1;
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d);",
+                                               MSGFW_SIM_MSG_TABLE_NAME, simId, pSimMsgInfo->msgId);
+
+                               MSG_DEBUG("QUERY : %s", sqlQuery);
+
+                               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+//                                     dbHandle->endTrans(false);
+                                       return MSG_ERR_DB_EXEC;
+                               }
+                       } else
+                               break;
+               }
+       }
 
-       /** Insert to Sim table */
-       if (pSimMsgInfo->msgType.subType == MSG_CONCAT_SIM_SMS && pSimMsgInfo->bTextSms == false) {
+//     dbHandle->endTrans(true);
 
-               MSG_DEBUG("sim count : %d", concatSimMsg.simIdCnt);
+       return err;
 
-               for (unsigned int i = 0; i < concatSimMsg.simIdCnt; i++) {
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d);",
-                                       MSGFW_SIM_MSG_TABLE_NAME, msgId, concatSimMsg.simIdList[i]);
+}
 
-                       MSG_DEBUG("QUERY : %s", sqlQuery);
 
-                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.endTrans(false);
-                               return MSG_ERR_DB_EXEC;
-                       }
-               }
-       } else {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d);",
-                               MSGFW_SIM_MSG_TABLE_NAME, msgId, simId);
+msg_error_t SmsPluginStorage::insertSimMessage(int simId, int msgId)
+{
+       MSG_BEGIN();
 
-               MSG_DEBUG("QUERY : %s", sqlQuery);
+       MsgDbHandler *dbHandle = getDbHandle();
 
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
-                       return MSG_ERR_DB_EXEC;
-               }
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       dbHandle->beginTrans();
+
+       /** Insert Message into msg_sim table */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d);", MSGFW_SIM_MSG_TABLE_NAME, simId, msgId);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
        }
 
-       /**  Update conversation table. */
-       if (MsgStoUpdateConversation(&dbHandle, convId) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return MSG_ERR_STORAGE_ERROR;
+       dbHandle->endTrans(true);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPluginStorage::deleteSimMessage(int sim_idx, int simId)
+{
+       MSG_BEGIN();
+
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       dbHandle->beginTrans();
+
+       /** Delete Message from msg_sim table */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE SIM_ID = %d AND SIM_SLOT_ID = %d;", MSGFW_SIM_MSG_TABLE_NAME, simId, sim_idx);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
        }
 
-       dbHandle.endTrans(true);
+       dbHandle->endTrans(true);
 
-       return err;
+       return MSG_SUCCESS;
 }
 
 
-msg_error_t SmsPluginStorage::addMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
+msg_error_t SmsPluginStorage::checkMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
 {
        MSG_BEGIN();
 
@@ -230,66 +469,59 @@ msg_error_t SmsPluginStorage::addMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
        err = checkStorageStatus(pMsgInfo);
 
        if (err != MSG_SUCCESS) {
+               if (pMsgInfo->msgType.classType == MSG_CLASS_0) {
+                       pMsgInfo->folderId = 0;
+                       err = MSG_SUCCESS;
+               }
+               else if(pMsgInfo->msgType.classType == MSG_CLASS_2 &&
+                               (pMsgInfo->msgType.subType == MSG_NORMAL_SMS || pMsgInfo->msgType.subType == MSG_REJECT_SMS)) {
+                       err = addClass2Message(pMsgInfo);
+               }
+               else if (pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS){
+                       err = MSG_SUCCESS;
+               }
                return err;
        }
 
+       /**  Amend message information for type **/
        if (pMsgInfo->msgType.subType == MSG_NORMAL_SMS || pMsgInfo->msgType.subType == MSG_REJECT_SMS) {
 
-               MSG_DEBUG("Add Normal SMS");
+               MSG_DEBUG("Normal SMS");
 
                if (pMsgInfo->msgType.classType == MSG_CLASS_2) {
-                       err = SmsPluginSimMsg::instance()->saveClass2Message(pMsgInfo);
-
-                       if (err == MSG_SUCCESS) {
-                               MSG_DEBUG("Success to saveSimMessage.");
-                       } else {
-                               MSG_DEBUG("Fail to saveSimMessage : [%d]", err);
-                       }
-               } else {
+                       err = addClass2Message(pMsgInfo);
+               } else if (pMsgInfo->msgType.classType == MSG_CLASS_0) {
                        /** Class 0 Msg should be saved in hidden folder */
-                       if (pMsgInfo->msgType.classType == MSG_CLASS_0) {
-                               pMsgInfo->folderId = 0;
-                       }
-
-                       /**  Add into DB */
-                       err = addSmsMessage(pMsgInfo);
+                       pMsgInfo->folderId = 0;
                }
 
-       } else if ((pMsgInfo->msgType.subType == MSG_CB_SMS) || (pMsgInfo->msgType.subType == MSG_JAVACB_SMS)) {
-               MSG_DEBUG("Add CB Message");
-               err = addCbMessage(pMsgInfo);
        } else if ((pMsgInfo->msgType.subType >= MSG_REPLACE_TYPE1_SMS) && (pMsgInfo->msgType.subType <= MSG_REPLACE_TYPE7_SMS)) {
-               MSG_DEBUG("Add Replace SM Type [%d]", pMsgInfo->msgType.subType-3);
-               err = addReplaceTypeMsg(pMsgInfo);
+               MSG_DEBUG("Replace SM Type [%d]", pMsgInfo->msgType.subType-3);
+
+               if (pMsgInfo->msgType.classType == MSG_CLASS_2) {
+                       err = addClass2Message(pMsgInfo);
+               } else if (pMsgInfo->msgType.classType == MSG_CLASS_0) {
+                       /** Class 0 Msg should be saved in hidden folder */
+                       pMsgInfo->folderId = 0;
+                       pMsgInfo->msgType.subType = MSG_NORMAL_SMS;
+               }
+
        } else if ((pMsgInfo->msgType.subType >= MSG_MWI_VOICE_SMS) && (pMsgInfo->msgType.subType <= MSG_MWI_OTHER_SMS)) {
-               MSG_DEBUG("Add MWI Message");
-               err = addSmsMessage(pMsgInfo);
-       } else if ((pMsgInfo->msgType.subType == MSG_WAP_SI_SMS) || (pMsgInfo->msgType.subType == MSG_WAP_CO_SMS)) {
-               MSG_DEBUG("Add WAP Push Message");
-               switch (pMsgInfo->msgType.subType)
-               {
-                       case MSG_WAP_SI_SMS:
-                       {
-                               // save push message information
-                               err = addWAPMessage(pMsgInfo);
-                       }
-                       break;
+               if (pMsgInfo->bStore == true) {
+                       MSG_DEBUG("MWI Message");
 
-                       case MSG_WAP_CO_SMS:
-                       {
-                               err = handleCOWAPMessage(pMsgInfo);
+                       if (pMsgInfo->msgType.classType == MSG_CLASS_2) {
+                               err = addClass2Message(pMsgInfo);
                        }
-                       break;
                }
-       } else if (pMsgInfo->msgType.subType == MSG_STATUS_REPORT_SMS) {
-               MSG_DEBUG("Add Status Report");
-               err = addSmsMessage(pMsgInfo);
+       } else {
+               MSG_DEBUG("No matching type [%d]", pMsgInfo->msgType.subType);
        }
 
        if (err == MSG_SUCCESS) {
-               MSG_DEBUG("Success to add message !!");
+               MSG_DEBUG("Success to check message !!");
        } else {
-               MSG_DEBUG("fail to add message !! : [%d]", err);
+               MSG_DEBUG("fail to check message !! : [%d]", err);
        }
 
        return err;
@@ -303,16 +535,16 @@ msg_error_t SmsPluginStorage::addSmsMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
        unsigned int rowId = 0;
        msg_thread_id_t convId = 0;
 
-       char sqlQuery[MAX_QUERY_LEN+1];
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       dbHandle.beginTrans();
+       dbHandle->beginTrans();
 
        if (pMsgInfo->nAddressCnt > 0) {
 
-               err = MsgStoAddAddress(&dbHandle, pMsgInfo, &convId);
+               err = MsgStoAddAddress(dbHandle, pMsgInfo, &convId);
 
                if (err != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+                       dbHandle->endTrans(false);
                        return err;
                }
 
@@ -320,113 +552,29 @@ msg_error_t SmsPluginStorage::addSmsMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
        }
 
        /**  Add Message Table */
-       rowId = MsgStoAddMessageTable(&dbHandle, pMsgInfo);
+       rowId = MsgStoAddMessageTable(dbHandle, pMsgInfo);
 
        if (rowId <= 0) {
-               dbHandle.endTrans(false);
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_ROW;
        }
 
        /** Update conversation table */
-       err = MsgStoUpdateConversation(&dbHandle, convId);
+       err = MsgStoUpdateConversation(dbHandle, convId);
 
        if (err != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+               dbHandle->endTrans(false);
                return err;
        }
 
-       dbHandle.endTrans(true);
-
-       pMsgInfo->msgId = (msg_message_id_t)rowId;
-
-       MSG_END();
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t SmsPluginStorage::updateSmsMessage(MSG_MESSAGE_INFO_S *pMsg)
-{
-       msg_error_t err = MSG_SUCCESS;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       msg_thread_id_t convId = 0;
-
-       dbHandle.beginTrans();
-
-       if (pMsg->nAddressCnt > 0) {
-
-               err = MsgStoAddAddress(&dbHandle, pMsg, &convId);
-
-               if (err != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
-                       return err;
-               }
-       }
-
-       int fileSize = 0;
-
-       char* pFileData = NULL;
-       AutoPtr<char> buf(&pFileData);
-
-       /**  Get File Data */
-       if (pMsg->bTextSms == false) {
-               if (MsgOpenAndReadFile(pMsg->msgData, &pFileData, &fileSize) == false) {
-                       dbHandle.endTrans(false);
-                       return MSG_ERR_STORAGE_ERROR;
-               }
-       }
-
-       /**  Update Message */
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET ADDRESS_ID = %d, FOLDER_ID = %d, STORAGE_ID = %d, MAIN_TYPE = %d, SUB_TYPE = %d, \
-                       DISPLAY_TIME = %lu, DATA_SIZE = %d, NETWORK_STATUS = %d, READ_STATUS = %d, PROTECTED = %d, PRIORITY = %d, MSG_DIRECTION = %d, \
-                       BACKUP = %d, SUBJECT = ?, MSG_DATA = ?, THUMB_PATH = ?, MSG_TEXT = ? WHERE MSG_ID = %d;",
-                               MSGFW_MESSAGE_TABLE_NAME, convId, pMsg->folderId, pMsg->storageId, pMsg->msgType.mainType, pMsg->msgType.subType, pMsg->displayTime, pMsg->dataSize,
-                               pMsg->networkStatus, pMsg->bRead, pMsg->bProtected, pMsg->priority, pMsg->direction, pMsg->bBackup, pMsg->msgId);
-
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return MSG_ERR_DB_EXEC;
-       }
-
-       dbHandle.bindText(pMsg->subject, 1);
-
-       dbHandle.bindText(pMsg->msgData, 2);
-
-       dbHandle.bindText(pMsg->thumbPath, 3);
-
-       if (pMsg->msgType.mainType == MSG_SMS_TYPE && pMsg->bTextSms == false)
-               dbHandle.bindText(pFileData, 4);
-       else
-               dbHandle.bindText(pMsg->msgText, 4);
-
-       MSG_DEBUG("%s", sqlQuery);
-
-       if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
-               dbHandle.endTrans(false);
-               return MSG_ERR_DB_EXEC;
-       }
-
-       dbHandle.finalizeQuery();
-
-       err = MsgStoUpdateConversation(&dbHandle, convId);
-
+       err = dbHandle->endTrans(true);
        if (err != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return MSG_ERR_STORAGE_ERROR;
+               return err;
        }
 
-       err = MsgStoClearConversationTable(&dbHandle);
-
-       if (err != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return MSG_ERR_STORAGE_ERROR;
-       }
+       pMsgInfo->msgId = (msg_message_id_t)rowId;
 
-       dbHandle.endTrans(true);
+       MSG_END();
 
        return MSG_SUCCESS;
 }
@@ -436,47 +584,49 @@ msg_error_t SmsPluginStorage::deleteSmsMessage(msg_message_id_t msgId)
 {
        MSG_BEGIN();
 
-       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
 
        char sqlQuery[MAX_QUERY_LEN+1];
 
         /**  Get SUB_TYPE, STORAGE_ID */
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MAIN_TYPE, SUB_TYPE, FOLDER_ID, ADDRESS_ID \
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MAIN_TYPE, SUB_TYPE, FOLDER_ID, CONV_ID, SIM_INDEX \
                        FROM %s WHERE MSG_ID = %d;",
                        MSGFW_MESSAGE_TABLE_NAME, msgId);
 
-       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return MSG_ERR_DB_PREPARE;
 
        MSG_MESSAGE_TYPE_S msgType;
        msg_folder_id_t folderId;
 
        msg_thread_id_t convId;
+       msg_sim_slot_id_t simIndex;
 
-       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-               msgType.mainType = dbHandle.columnInt(0);
-               msgType.subType = dbHandle.columnInt(1);
-               folderId = dbHandle.columnInt(2);
-               convId = dbHandle.columnInt(3);
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               msgType.mainType = dbHandle->columnInt(0);
+               msgType.subType = dbHandle->columnInt(1);
+               folderId = dbHandle->columnInt(2);
+               convId = dbHandle->columnInt(3);
+               simIndex = dbHandle->columnInt(4);
 
                MSG_DEBUG("Main Type:[%d] SubType:[%d] FolderId:[%d] ConversationId:[%d]", msgType.mainType, msgType.subType, folderId, convId);
        } else {
                MSG_DEBUG("MsgStepQuery() Error [%s]", sqlQuery);
-               dbHandle.finalizeQuery();
+               dbHandle->finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
-       dbHandle.finalizeQuery();
+       dbHandle->finalizeQuery();
 
-       dbHandle.beginTrans();
+       dbHandle->beginTrans();
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
        snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_SMS_SENDOPT_TABLE_NAME, msgId);
 
        /**  Delete SMS Send Option */
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
@@ -485,8 +635,8 @@ msg_error_t SmsPluginStorage::deleteSmsMessage(msg_message_id_t msgId)
                snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_CB_MSG_TABLE_NAME, msgId);
 
                /** Delete Push Message from push table */
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_EXEC;
                }
        } else if (msgType.subType >= MSG_WAP_SI_SMS && msgType.subType <= MSG_WAP_CO_SMS) {
@@ -494,8 +644,8 @@ msg_error_t SmsPluginStorage::deleteSmsMessage(msg_message_id_t msgId)
                snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_PUSH_MSG_TABLE_NAME, msgId);
 
                /**  Delete Push Message from push table */
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_EXEC;
                }
        } else if (msgType.subType == MSG_SYNCML_CP) {
@@ -503,541 +653,434 @@ msg_error_t SmsPluginStorage::deleteSmsMessage(msg_message_id_t msgId)
                snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_SYNCML_MSG_TABLE_NAME, msgId);
 
                /**  Delete SyncML Message from syncML table */
-               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_EXEC;
                }
        }
 
+       /** Delete Message from msg table */
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
        snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, msgId);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
 
-       /** Delete Message from msg table */
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       /** Delete Message from msg_report table */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_SMS_REPORT_TABLE_NAME, msgId);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       /** Delete Message from msg_sim table */
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_SIM_MSG_TABLE_NAME, msgId);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
        /**  Clear Conversation table */
-       if (MsgStoClearConversationTable(&dbHandle) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (MsgStoClearConversationTable(dbHandle) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
        /**  Update conversation table.*/
-       if (MsgStoUpdateConversation(&dbHandle, convId) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
+       if (MsgStoUpdateConversation(dbHandle, convId) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
                return MSG_ERR_STORAGE_ERROR;
        }
 
-       dbHandle.endTrans(true);
+       dbHandle->endTrans(true);
 
        if (folderId == MSG_INBOX_ID) {
                msgType.classType = MSG_CLASS_NONE;
 
                /**  Set memory status in SIM */
-               if (MsgStoCheckMsgCntFull(&dbHandle, &msgType, folderId) == MSG_SUCCESS) {
+               if (MsgStoCheckMsgCntFull(dbHandle, &msgType, folderId) == MSG_SUCCESS) {
                        MSG_DEBUG("Set Memory Status");
-                       SmsPlgSetMemoryStatus(MSG_SUCCESS);
+                       SmsPlgSetMemoryStatus(simIndex, MSG_SUCCESS);
                }
        }
 
-       int smsCnt = 0, mmsCnt = 0;
-
-       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
-       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
-
-       MsgSettingHandleNewMsg(smsCnt, mmsCnt);
-       MsgDeleteNotiByMsgId(msgId);
+       MsgRefreshAllNotification(true, false, false);
 
        return MSG_SUCCESS;
 }
 
 
-msg_error_t SmsPluginStorage::addCbMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
+msg_error_t SmsPluginStorage::addClass2Message(MSG_MESSAGE_INFO_S *pMsgInfo)
 {
-       msg_error_t err = MSG_SUCCESS;
-
-       unsigned int rowId = 0;
-       msg_thread_id_t convId = 0;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       dbHandle.beginTrans();
+       MSG_BEGIN();
 
-       if (pMsgInfo->nAddressCnt > 0) {
-               err = MsgStoAddAddress(&dbHandle, pMsgInfo, &convId);
+       msg_error_t err = MSG_SUCCESS;
+       pthread_t thd;
+       memset(&msgInfo, 0, sizeof(MSG_MESSAGE_INFO_S));
+       memset(&addrInfo, 0, sizeof(MSG_ADDRESS_INFO_S));
+       memcpy(&msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+       memcpy(&addrInfo, pMsgInfo->addressList, sizeof(MSG_ADDRESS_INFO_S));
+       msgInfo.addressList = &addrInfo;
 
-               if (err != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
-                       return err;
-               }
+       if(pthread_create(&thd, NULL, &class2_thread, (void *)&msgInfo) < 0)
+       {
+               MSG_DEBUG("pthread_create() error");
 
-               pMsgInfo->threadId = convId;
        }
+       //pthread_join(thd, (void **)&err);
+       pthread_detach(thd);
 
-       /**  Add Message Table */
-       rowId = MsgStoAddMessageTable(&dbHandle, pMsgInfo);
+#if 0
+       err = SmsPluginSimMsg::instance()->saveClass2Message(pMsgInfo);
 
-       if (rowId <= 0) {
-               dbHandle.endTrans(false);
-               return MSG_ERR_DB_ROW;
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Success to saveClass2Message.");
+       } else {
+               MSG_DEBUG("Fail to saveClass2Message : [%d]", err);
        }
+#endif
 
-       /**  Get CB Msg ID */
-       unsigned short cbMsgId = (unsigned short)pMsgInfo->msgId;
+       MSG_END();
 
-       /** Add CB Msg in MSG_CBMSG_TABLE */
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       return err;
+}
 
-       sprintf(sqlQuery, "INSERT INTO %s VALUES (%d, %d);",
-                       MSGFW_CB_MSG_TABLE_NAME, rowId, cbMsgId);
+void* SmsPluginStorage::class2_thread(void *data)
+{
+       MSG_BEGIN();
 
-       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return MSG_ERR_DB_EXEC;
-       }
+       msg_error_t err = MSG_SUCCESS;
+       MSG_MESSAGE_INFO_S *pMsgInfo = (MSG_MESSAGE_INFO_S *)data;
 
-       /**  Update conversation table. */
-       if (MsgStoUpdateConversation(&dbHandle, convId) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return MSG_ERR_STORAGE_ERROR;
+       err = SmsPluginSimMsg::instance()->saveClass2Message(pMsgInfo);
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Success to saveClass2Message.");
+       } else {
+               MSG_DEBUG("Fail to saveClass2Message : [%d]", err);
        }
 
-       dbHandle.endTrans(true);
-
-       /** Assign Msg ID */
-       pMsgInfo->msgId = (msg_message_id_t)rowId;
-
-       return err;
+       MSG_END();
+       return (void *)err;
 }
 
 
-msg_error_t SmsPluginStorage::addReplaceTypeMsg(MSG_MESSAGE_INFO_S *pMsgInfo)
+msg_error_t SmsPluginStorage::getReplaceSimMsg(const MSG_MESSAGE_INFO_S *pMsg, int *pMsgId, int *pSimId)
 {
-       msg_error_t err = MSG_SUCCESS;
+       MSG_BEGIN();
 
-       char sqlQuery[MAX_QUERY_LEN+1];
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       unsigned int retCnt = 0;
+       char sqlQuery[MAX_QUERY_LEN+1];
        msg_thread_id_t convId = 0;
+       msg_message_id_t msgId = 0;
+
+       dbHandle->beginTrans();
 
-       /** Check if new address or not */
-       if (MsgExistAddress(&dbHandle, pMsgInfo, &convId) == true) {
+       if (MsgExistAddress(dbHandle, pMsg, &convId) == true) {
                MSG_DEBUG("Address Info. exists [%d]", convId);
 
-               /**  Find Replace Type Msg : Same Replace Type, Same Origin Address */
+               /**  Find Replace Type Msg : Same Replace Type, Same Origin Address, Same Storage ID */
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*), MSG_ID FROM %s WHERE SUB_TYPE = %d AND B.CONV_ID = %d;",
-                               MSGFW_MESSAGE_TABLE_NAME, pMsgInfo->msgType.subType, convId);
-
-               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s \
+                                                       WHERE CONV_ID = %d AND SUB_TYPE = %d AND STORAGE_ID = %d \
+                                                       ORDER BY DISPLAY_TIME ASC;",
+                               MSGFW_MESSAGE_TABLE_NAME, (int)convId, pMsg->msgType.subType, MSG_STORAGE_SIM);
+
+               MSG_DEBUG("Query=[%s]", sqlQuery);
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_PREPARE;
+               }
 
-               if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
-                       retCnt = dbHandle.columnInt(0);
-                       pMsgInfo->msgId = dbHandle.columnInt(1);
+               if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+                       *pMsgId = dbHandle->columnInt(0);
                } else {
-                       dbHandle.finalizeQuery();
+                       dbHandle->finalizeQuery();
+                       dbHandle->endTrans(false);
                        return MSG_ERR_DB_STEP;
                }
 
-               dbHandle.finalizeQuery();
-       }
+               dbHandle->finalizeQuery();
 
-       /** Update New Replace Type Msg */
-       if (retCnt == 1) {
-               MSG_DEBUG("Update Replace Type Msg");
-               err = updateSmsMessage(pMsgInfo);
-       } else if (retCnt == 0) { /** Insert New Replace Type Msg */
-               MSG_DEBUG("Insert Replace Type Msg");
-               err = addSmsMessage(pMsgInfo);
+       } else {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_NORECORD;
        }
 
-       return err;
-}
-
-
-msg_error_t SmsPluginStorage::addWAPMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
-{
-       msg_error_t err = MSG_SUCCESS;
-
-       MSG_PUSH_MESSAGE_S pushMsg = {};
-
-       char sqlQuery[MAX_QUERY_LEN+1];
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       int fileSize = 0;
-
-       char* pFileData = NULL;
-       AutoPtr<char> buf(&pFileData);
-
-       if (MsgOpenAndReadFile(pMsgInfo->msgData, &pFileData, &fileSize) == false)
-               return MSG_ERR_STORAGE_ERROR;
-
-       MSG_DEBUG("fileSize : %d", fileSize);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT SIM_ID FROM %s \
+                       WHERE MSG_ID = %d;",
+                       MSGFW_SIM_MSG_TABLE_NAME, *pMsgId);
 
-       memcpy(&pushMsg, pFileData, fileSize);
-
-       /** Delete temporary file */
-       MsgDeleteFile(pMsgInfo->msgData);
-
-       /** check pPushMsg data */
-
-       MSG_DEBUG("check pushMsg data");
-       MSG_DEBUG("pushMsg.action : [%d]", pushMsg.action);
-       MSG_DEBUG("pushMsg.received : [%d]", pushMsg.received);
-       MSG_DEBUG("pushMsg.created : [%d]", pushMsg.created);
-       MSG_DEBUG("pushMsg.expires : [%d]", pushMsg.expires);
-       MSG_DEBUG("pushMsg.id : [%s]", pushMsg.id);
-       MSG_DEBUG("pushMsg.href : [%s]", pushMsg.href);
-       MSG_DEBUG("pushMsg.contents : [%s]", pushMsg.contents);
-
-       bool bProceed = true;
-
-       /**  check validation of contents */
-       if (checkPushMsgValidation(&pushMsg, &bProceed) != MSG_SUCCESS) {
-               MSG_DEBUG("Fail to check Push Message validation.");
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_PREPARE;
        }
 
-       /**  if validation check value is false */
-       /** return and drop message. */
-       if (bProceed == false)
-               return MSG_ERR_INVALID_MESSAGE;
-
-       /**  update subject */
-       int len = strlen(pushMsg.contents);
-
-       if (len > MAX_SUBJECT_LEN) {
-               memcpy(pMsgInfo->subject, pushMsg.contents, MAX_SUBJECT_LEN);
-               pMsgInfo->subject[MAX_SUBJECT_LEN] = '\0';
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               *pSimId = dbHandle->columnInt(0);
        } else {
-               strncpy(pMsgInfo->subject, pushMsg.contents, MAX_SUBJECT_LEN);
+               dbHandle->finalizeQuery();
+               dbHandle->endTrans(false);
+               return MSG_ERR_DB_STEP;
        }
 
-       /**  Update Msg Text - remove */
-       strncpy(pMsgInfo->msgText, pushMsg.href, MAX_MSG_TEXT_LEN);
-       pMsgInfo->dataSize = strlen(pMsgInfo->msgText);
-
-       pMsgInfo->bTextSms = true;
-       pMsgInfo->folderId = MSG_INBOX_ID;
-       pMsgInfo->storageId = MSG_STORAGE_PHONE;
-
-       msg_thread_id_t convId = 0;
-
-       dbHandle.beginTrans();
+       MSG_DEBUG("Replace Msg Id=[%d], Sim Id=[%d]", *pMsgId, *pSimId);
 
-       if (pMsgInfo->nAddressCnt > 0) {
+       dbHandle->finalizeQuery();
 
-               err = MsgStoAddAddress(&dbHandle, pMsgInfo, &convId);
+       dbHandle->endTrans(true);
 
-               if (err != MSG_SUCCESS) {
-                       dbHandle.endTrans(false);
-                       return err;
-               }
-       }
+       MSG_END();
 
-       /**  get last row count for Message id */
-       unsigned int rowId = 0;
+       return msgId;
+}
 
-       /** Add Message Table */
-       rowId = MsgStoAddMessageTable(&dbHandle, pMsgInfo);
+msg_error_t SmsPluginStorage::addSmsSendOption(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo)
+{
+       MSG_BEGIN();
 
-       if (rowId <= 0) {
-               dbHandle.endTrans(false);
-               return MSG_ERR_DB_ROW;
-       }
+       msg_error_t err = MSG_SUCCESS;
 
-       /**  add msg_push_table */
-       snprintf (sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %lu, %lu, ?, ?, ?)",
-                       MSGFW_PUSH_MSG_TABLE_NAME, pMsgInfo->msgId, pushMsg.action, pushMsg.created, pushMsg.expires);
+       if (pSendOptInfo->bSetting == false) {
+               MsgSettingGetBool(SMS_SEND_DELIVERY_REPORT, &pSendOptInfo->bDeliverReq);
+               MsgSettingGetBool(SMS_SEND_REPLY_PATH, &pSendOptInfo->option.smsSendOptInfo.bReplyPath);
 
-       if ((err = dbHandle.prepareQuery(sqlQuery)) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return err;
+//             if (pSendOptInfo->bDeliverReq || pSendOptInfo->option.smsSendOptInfo.bReplyPath) {
+//                     pSendOptInfo->bSetting = true;
+                       MsgSettingGetBool(MSG_KEEP_COPY, &pSendOptInfo->bKeepCopy);
+//             }
        }
 
-       dbHandle.bindText(pushMsg.id, 1);
-
-       dbHandle.bindText(pushMsg.href, 2);
+//     if (pSendOptInfo->bSetting == true) {
+               MsgDbHandler *dbHandle = getDbHandle();
 
-       dbHandle.bindText(pushMsg.contents, 3);
+               char sqlQuery[MAX_QUERY_LEN+1];
 
-       if ((err = dbHandle.stepQuery()) != MSG_ERR_DB_DONE) {
-               dbHandle.endTrans(false);
-               return err;
-       }
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, %d);",
+                               MSGFW_SMS_SENDOPT_TABLE_NAME, pMsg->msgId, pSendOptInfo->bDeliverReq,
+                               pSendOptInfo->bKeepCopy, pSendOptInfo->option.smsSendOptInfo.bReplyPath, pMsg->encodeType);
 
-       /** Update conversation table. */
-       if (MsgStoUpdateConversation(&dbHandle, convId) != MSG_SUCCESS) {
-               dbHandle.endTrans(false);
-               return MSG_ERR_STORAGE_ERROR;
-       }
+               MSG_DEBUG("Query = [%s]", sqlQuery);
 
-       dbHandle.endTrans(true);
+               if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       err = MSG_ERR_DB_EXEC;
+               }
+//     }
 
-       pMsgInfo->msgId = (msg_message_id_t)rowId;
+       MSG_END();
 
-       return MSG_SUCCESS;
+       return err;
 }
 
 
-msg_error_t SmsPluginStorage::handleCOWAPMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
+msg_error_t SmsPluginStorage::checkStorageStatus(MSG_MESSAGE_INFO_S *pMsgInfo)
 {
        msg_error_t err = MSG_SUCCESS;
 
-       char href[MAX_PUSH_CACHEOP_MAX_URL_LEN+1];
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       int fileSize = 0;
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       char* pFileData = NULL;
-       AutoPtr<char> buf(&pFileData);
-
-       if (MsgOpenAndReadFile(pMsgInfo->msgData, &pFileData, &fileSize) == false)
-               return MSG_ERR_STORAGE_ERROR;
-
-       MSG_PUSH_CACHEOP_S *pPushMsg;
-
-       pPushMsg = (MSG_PUSH_CACHEOP_S*)pFileData;
-
-       for (int i = 0; i < pPushMsg->invalObjectCnt; i++) {
-
-               int msgid = -1;
-
-               memset(href, 0x00, sizeof(href));
-               strncpy(href, &(pPushMsg->invalObjectUrl[i][0]), MAX_PUSH_CACHEOP_MAX_URL_LEN);
-
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf (sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE HREF LIKE '%%%s%%';", MSGFW_PUSH_MSG_TABLE_NAME, href);
+       err = MsgStoCheckMsgCntFull(dbHandle, &(pMsgInfo->msgType), pMsgInfo->folderId);
 
-               dbHandle.beginTrans();
+       if (err != MSG_SUCCESS) {
 
-               err = dbHandle.prepareQuery(sqlQuery);
+               if (err == MSG_ERR_MESSAGE_COUNT_FULL) {
+                       bool bAutoErase = false;
 
-               if ((dbHandle.stepQuery() == MSG_ERR_DB_ROW) && err == MSG_SUCCESS) {
+                       MsgSettingGetBool(MSG_AUTO_ERASE, &bAutoErase);
 
-                       msgid = dbHandle.getColumnToInt(1);
+                       MSG_DEBUG("bAutoErase: %d", bAutoErase);
 
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID= %d;", MSGFW_PUSH_MSG_TABLE_NAME, msgid);
+                       if (bAutoErase == true) {
+                               msg_message_id_t msgId;
 
-                       /** Delete Message from Push table */
-                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.finalizeQuery();
-                               dbHandle.endTrans(false);
-                               continue;
-                       }
+                               /** Find the oldest message's msgId */
+                               err = MsgStoGetOldestMessage(dbHandle, pMsgInfo, &msgId);
 
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, msgid);
+                               if (err != MSG_SUCCESS)
+                                       return err;
 
-                       /** Delete Message from msg table */
-                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.finalizeQuery();
-                               dbHandle.endTrans(false);
-                               continue;
+                               /** Delete the corresponding message. */
+                               err = deleteSmsMessage(msgId);
                        }
+               }
 
-                       /** Update all Address */
-                       if (updateAllAddress() != MSG_SUCCESS) {
-                               dbHandle.finalizeQuery();
-                               dbHandle.endTrans(false);
-                               continue;
-                       }
+               return err;
+       }
 
-                       /** Clear Conversation table */
-                       if (MsgStoClearConversationTable(&dbHandle) != MSG_SUCCESS) {
-                               dbHandle.finalizeQuery();
-                               dbHandle.endTrans(false);
-                               continue;
-                       }
-               }
+       return err;
+}
 
-               dbHandle.finalizeQuery();
 
-               dbHandle.endTrans(true);
-       }
+#if 0
 
-       for (int i = 0; i < pPushMsg->invalServiceCnt; i++) {
+msg_error_t SmsPluginStorage::isReceivedCBMessage(SMS_CBMSG_PAGE_S CbPage)
+{
+       msg_error_t err = MSG_SUCCESS;
 
-               int msgid = -1;
+       int rowCnt = 0;
 
-               memset(href, 0x00, sizeof(href));
-               strncpy(href, &(pPushMsg->invalObjectUrl[i][0]), MAX_PUSH_CACHEOP_MAX_URL_LEN);
+       MsgDbHandler *dbHandle = getDbHandle();
 
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE HREF LIKE '%%%s%%'", MSGFW_PUSH_MSG_TABLE_NAME, href);
+       char sqlQuery[MAX_QUERY_LEN+1] = {0, };
 
-               dbHandle.beginTrans();
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-               err = dbHandle.prepareQuery(sqlQuery);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT * FROM %s WHERE GEO_SCOPE = %d AND MSG_CODE = %d AND MESSAGE_ID = %d AND UPDATE_NUM = %d",
+                       MSGFW_RECEIVED_CB_MSG_TABLE_NAME, CbPage.pageHeader.serialNum.geoScope,
+                       CbPage.pageHeader.serialNum.msgCode,CbPage.pageHeader.msgId, CbPage.pageHeader.serialNum.updateNum);
 
-               if ((dbHandle.stepQuery() == MSG_ERR_DB_ROW) && err == MSG_SUCCESS) {
+       err = dbHandle->getTable(sqlQuery, &rowCnt, NULL);
+       MSG_DEBUG("rowCnt: %d", rowCnt);
 
-                       msgid = dbHandle.getColumnToInt(1);
+       dbHandle->freeTable();
+       return err;
+}
 
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                       sprintf(sqlQuery, "DELETE FROM %s WHERE MSG_ID='%d'", MSGFW_PUSH_MSG_TABLE_NAME, msgid);
+msg_error_t SmsPluginStorage::insertReceivedCBMessage(SMS_CBMSG_PAGE_S CbPage)
+{
 
-                       /** Delete Message from Push table */
-                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.finalizeQuery();
-                               dbHandle.endTrans(false);
-                               continue;
-                       }
+       msg_error_t err = MSG_SUCCESS;
 
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-                       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, msgid);
+       unsigned int rowId = 0;
 
-                       /** Delete Message from msg table */
-                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
-                               dbHandle.finalizeQuery();
-                               dbHandle.endTrans(false);
-                               continue;
-                       }
+       MsgDbHandler *dbHandle = getDbHandle();
 
-                       /**  Update all Address */
-                       if (updateAllAddress() != MSG_SUCCESS) {
-                               dbHandle.finalizeQuery();
-                               dbHandle.endTrans(false);
-                               continue;
-                       }
+       char sqlQuery[MAX_QUERY_LEN+1];
 
-                       /** Clear Address table */
-                       if (MsgStoClearConversationTable(&dbHandle) != MSG_SUCCESS) {
-                               dbHandle.finalizeQuery();
-                               dbHandle.endTrans(false);
-                               continue;
-                       }
-               }
+       err = dbHandle->getRowId(MSGFW_RECEIVED_CB_MSG_TABLE_NAME, &rowId);
 
-               dbHandle.finalizeQuery();
+       if (err != MSG_SUCCESS)
+               return err;
 
-               dbHandle.endTrans(true);
-       }
+       // Add Folder
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, %d);",
+                       MSGFW_RECEIVED_CB_MSG_TABLE_NAME, rowId, CbPage.pageHeader.serialNum.geoScope,
+                       CbPage.pageHeader.serialNum.msgCode,CbPage.pageHeader.msgId, CbPage.pageHeader.serialNum.updateNum);
 
-       /** delete temporary file */
-       MsgDeleteFile(pMsgInfo->msgData);
+       if (dbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
 
        return MSG_SUCCESS;
+
 }
 
+#endif
 
-msg_error_t SmsPluginStorage::checkPushMsgValidation(MSG_PUSH_MESSAGE_S *pPushMsg, bool *pbProceed)
+msg_error_t SmsPluginStorage::getRegisteredPushEvent(char* pPushHeader, int *count, char *application_id, int app_id_len, char *content_type, int content_type_len)
 {
        msg_error_t err = MSG_SUCCESS;
 
-       unsigned long oldExpireTime = 0;
-       int rowCnt = 0;
+       int rowCnt = 0, index = 0;
 
-       char sqlQuery[MAX_QUERY_LEN+1];
+       MsgDbHandler *dbHandle = getDbHandle();
 
-       /**  is push message is expired?? */
-       if (pPushMsg->received > pPushMsg->expires) {
-               MSG_DEBUG("Push Message is expired.");
-               pbProceed = false;
-               return err;
-       }
+       char sqlQuery[MAX_QUERY_LEN+1] = {0, };
 
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       if (pPushMsg->action == MSG_PUSH_SL_ACTION_EXECUTE_LOW) {
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT EXPIRES FROM %s WHERE ID = '%s' AND ACTION = %d",
-                               MSGFW_PUSH_MSG_TABLE_NAME, pPushMsg->id, pPushMsg->action);
-       } else {
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT EXPIRES FROM %s WHERE ID = '%s'",
-                               MSGFW_PUSH_MSG_TABLE_NAME, pPushMsg->id);
-       }
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CONTENT_TYPE, APP_ID, APPCODE FROM %s", MSGFW_PUSH_CONFIG_TABLE_NAME);
 
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
+       err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+       MSG_DEBUG("rowCnt: %d", rowCnt);
 
-       if (rowCnt < 1) {
-               dbHandle.freeTable();
+       if (err == MSG_ERR_DB_NORECORD) {
+               dbHandle->freeTable();
                return MSG_SUCCESS;
        }
-
-       oldExpireTime = dbHandle.getColumnToInt(1);
-
-       dbHandle.freeTable();
-
-       if (pPushMsg->created < oldExpireTime) {
-               MSG_DEBUG("Push Message is expired.");
-               pbProceed = false;
+       else if ( err != MSG_SUCCESS) {
+               dbHandle->freeTable();
                return err;
        }
 
-       return err;
-}
-
-
-msg_error_t SmsPluginStorage::checkStorageStatus(MSG_MESSAGE_INFO_S *pMsgInfo)
-{
-       msg_error_t err = MSG_SUCCESS;
-
-       err = MsgStoCheckMsgCntFull(&dbHandle, &(pMsgInfo->msgType), pMsgInfo->folderId);
-
-       if (err != MSG_SUCCESS) {
+       char contentType[MAX_WAPPUSH_CONTENT_TYPE_LEN + 1] = {0,};
+       char appId[MAX_WAPPUSH_ID_LEN + 1] = {0,};
+       int appcode = 0, default_appcode = 0;
+       bool found = false;
+       char *_content_type = NULL, *_app_id = NULL;
+       *count = 0;
 
-               if (err == MSG_ERR_MESSAGE_COUNT_FULL) {
-                       bool bAutoErase = false;
 
-                       MsgSettingGetBool(MSG_AUTO_ERASE, &bAutoErase);
-
-                       MSG_DEBUG("bAutoErase: %d", bAutoErase);
-
-                       if (bAutoErase == true) {
-                               msg_message_id_t msgId;
-
-                               /** Find the oldest message's msgId */
-                               err = MsgStoGetOldestMessage(&dbHandle, pMsgInfo, &msgId);
-
-                               if (err != MSG_SUCCESS)
-                                       return err;
-
-                               /** Delete the corresponding message. */
-                               err = deleteSmsMessage(msgId);
+       for (int i = 0; i < rowCnt; i++) {
+               memset(contentType, 0, MAX_WAPPUSH_CONTENT_TYPE_LEN);
+               memset(appId, 0, MAX_WAPPUSH_ID_LEN);
+
+               dbHandle->getColumnToString(index++, MAX_WAPPUSH_CONTENT_TYPE_LEN + 1, contentType);
+               dbHandle->getColumnToString(index++, MAX_WAPPUSH_ID_LEN + 1, appId);
+               appcode = dbHandle->getColumnToInt(index++);
+
+               //MSG_DEBUG("content_type: %s, app_id: %s", content_type, app_id);
+               _content_type = strcasestr(pPushHeader, contentType);
+               if(_content_type) {
+                       _app_id = strcasestr(pPushHeader, appId);
+                       if(appcode)
+                               default_appcode = appcode;
+
+                       if(_app_id) {
+                               PUSH_APPLICATION_INFO_S pInfo = {0, };
+                               pInfo.appcode = appcode;
+                               MSG_SEC_DEBUG("appcode: %d, app_id: %s", pInfo.appcode, appId);
+                               snprintf(application_id, app_id_len, "%s", appId);
+                               snprintf(content_type, content_type_len, "%s", contentType);
+                               pushAppInfoList.push_back(pInfo);
+                               (*count)++;
+                               found = true;
                        }
                }
+       }
 
-               return err;
+       if(!found && default_appcode != SMS_WAP_APPLICATION_LBS)
+       {
+               // perform default action.
+               PUSH_APPLICATION_INFO_S pInfo = {0, };
+               pInfo.appcode = default_appcode;
+               memset(appId, 0, MAX_WAPPUSH_ID_LEN + 1);
+               snprintf(application_id, app_id_len, "%s", appId);
+               snprintf(content_type, content_type_len, "%s", contentType);
+               pushAppInfoList.push_back(pInfo);
+               *count = 1;
        }
+       dbHandle->freeTable();
 
        return err;
 }
 
 
-msg_error_t SmsPluginStorage::updateAllAddress()
+msg_error_t SmsPluginStorage::getnthPushEvent(int index, int *appcode)
 {
        msg_error_t err = MSG_SUCCESS;
-
-       int rowCnt = 0, index = 1;
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT ADDRESS_ID FROM %s", MSGFW_ADDRESS_TABLE_NAME);
-
-       err = dbHandle.getTable(sqlQuery, &rowCnt);
-
-       if (err == MSG_ERR_DB_NORECORD) {
-               dbHandle.freeTable();
-               return MSG_SUCCESS;
-       } else if ( err != MSG_SUCCESS) {
-               dbHandle.freeTable();
-               return err;
+       if((unsigned int)index > pushAppInfoList.size() - 1)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       std::list<PUSH_APPLICATION_INFO_S>::iterator it = pushAppInfoList.begin();
+       int count = 0;
+       for (; it != pushAppInfoList.end(); it++)
+       {
+               if(index == count){
+                       *appcode = it->appcode;
+                       break;
+               }
+               count++;
        }
 
+       return err;
+}
 
-       for (int i = 0; i < rowCnt; i++) {
-
-               err = MsgStoUpdateConversation(&dbHandle, index++);
 
-               if (err != MSG_SUCCESS)
-                       break;
-       }
+msg_error_t SmsPluginStorage::releasePushEvent()
+{
+       msg_error_t err = MSG_SUCCESS;
+       std::list<PUSH_APPLICATION_INFO_S>::iterator it = pushAppInfoList.begin();
 
-       dbHandle.freeTable();
+       for (; it != pushAppInfoList.end(); it++)
+               it = pushAppInfoList.erase(it);
 
        return err;
 }
diff --git a/plugin/sms_plugin/SmsPluginTextConvert.cpp b/plugin/sms_plugin/SmsPluginTextConvert.cpp
deleted file mode 100755 (executable)
index 8db889d..0000000
+++ /dev/null
@@ -1,951 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include <glib.h>
-
-#include "MsgDebug.h"
-#include "SmsPluginTextConvert.h"
-
-
-/*==================================================================================================
-                                     IMPLEMENTATION OF MsgConvertText - Member Functions
-==================================================================================================*/
-SmsPluginTextConvert* SmsPluginTextConvert::pInstance = NULL;
-
-
-SmsPluginTextConvert* SmsPluginTextConvert::instance()
-{
-       if (!pInstance)
-               pInstance = new SmsPluginTextConvert();
-
-       return pInstance;
-}
-
-
-int SmsPluginTextConvert::convertUTF8ToGSM7bit(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, OUT SMS_LANGUAGE_ID_T *pLangId)
-{
-       int utf8Length = 0;
-       int gsm7bitLength = 0;
-       int ucs2Length = 0;
-
-       if (srcTextLen <= 0)
-       {
-               utf8Length = strlen((char*)pSrcText);
-               srcTextLen = utf8Length;
-       }
-       else
-       {
-               utf8Length = srcTextLen;
-       }
-
-       int maxUCS2Length = utf8Length;         // max # of UCS2 chars, NOT bytes. when all utf8 chars are only one byte, UCS2Length is maxUCS2 Length. otherwise (ex: 2 bytes of UTF8 is one char) UCS2Length must be  less than utf8Length
-       WCHAR pUCS2Text[maxUCS2Length];
-       memset(pUCS2Text, 0x00, maxUCS2Length * sizeof(WCHAR));
-
-       MSG_DEBUG("srcTextLen = %d", srcTextLen);
-       MSG_DEBUG("temp buffer size = %d", maxUCS2Length * sizeof(WCHAR));
-       MSG_DEBUG("max dest Length = %d", maxLength);
-
-       ucs2Length = convertUTF8ToUCS2((unsigned char*)pUCS2Text, maxUCS2Length * sizeof(WCHAR), pSrcText, srcTextLen);
-       gsm7bitLength = convertUCS2ToGSM7bit(pDestText, maxLength, (unsigned char*)pUCS2Text, ucs2Length, pLangId);
-
-       return gsm7bitLength;
-}
-
-
-/**
-       if srcTextLen ispSrcText should be null terminated
-return :
-               byte length of converted UCS2 characters
-                       -1 : converting error
-*/
-int SmsPluginTextConvert::convertUTF8ToUCS2(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen)
-{
-       int i, j;
-       int textLen;
-       unsigned char *unicodeTemp = (unsigned char*)pDestText;
-       int ucs2Length = 0;
-       int remainedBuffer = maxLength;
-
-#ifdef CONVERT_DUMP
-       int srcLen = srcTextLen;
-       const unsigned char * pTempSrcText = pSrcText;
-       const unsigned char * pTempDestText = pDestText;
-#endif
-
-       i = j = 0;
-
-       if(maxLength == 0 || pSrcText == NULL || pDestText ==  NULL)
-       {
-               MSG_DEBUG("UTF8 to UCS2 Failed as text length is 0\n");
-               return -1;
-       }
-
-       // null terminated string
-       if ( srcTextLen == -1 )
-       {
-               textLen = strlen((char*)pSrcText);
-               srcTextLen = textLen;
-       }
-       else
-       {
-               textLen = srcTextLen;
-       }
-
-       GIConv cd;
-       int err=0;
-
-       cd = g_iconv_open("UCS-2BE", "UTF8");
-
-       if (cd > 0)
-       {
-               err = g_iconv(cd, (char**)&pSrcText, (gsize*)&textLen, (char**)&unicodeTemp, (gsize*)&remainedBuffer);
-       }
-
-       if(err < 0)
-       {
-               MSG_DEBUG("Error in g_iconv.");
-               ucs2Length = -1;
-       }
-       else
-       {
-               ucs2Length = maxLength - remainedBuffer;
-       }
-
-#ifdef CONVERT_DUMP
-       MSG_DEBUG("\n########## Dump UTF8 -> UCS2\n");
-       convertDumpTextToHex((unsigned char*)pTempSrcText, srcLen);
-       convertDumpTextToHex((unsigned char*)pTempDestText, ucs2Length);
-#endif
-
-       g_iconv_close(cd);
-
-       return ucs2Length;
-}
-
-
-int SmsPluginTextConvert::convertUTF8ToAuto(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, OUT msg_encode_type_t *pCharType)
-{
-       int utf8Length = 0;
-       int gsm7bitLength = 0;
-       int ucs2Length = 0;
-
-       bool bUnknown = false;
-
-       utf8Length = srcTextLen;
-
-       int maxUCS2Length = utf8Length;         // max # of UCS2 chars, NOT bytes. when all utf8 chars are only one byte, UCS2Length is maxUCS2 Length. otherwise (ex: 2 bytes of UTF8 is one char) UCS2Length must be  less than utf8Length
-       WCHAR pUCS2Text[maxUCS2Length];
-       memset(pUCS2Text, 0x00, maxUCS2Length * sizeof(WCHAR));
-
-       MSG_DEBUG("srcTextLen = %d", srcTextLen);
-       MSG_DEBUG("temp buffer size = %d", maxUCS2Length * sizeof(WCHAR));
-       MSG_DEBUG("max dest Length = %d", maxLength);
-
-       ucs2Length = convertUTF8ToUCS2((unsigned char*)pUCS2Text, maxUCS2Length * sizeof(WCHAR), pSrcText, srcTextLen);
-
-       if(ucs2Length < 0)
-       {
-               *pCharType = MSG_ENCODE_8BIT;
-
-               memcpy(pDestText, pSrcText, srcTextLen);
-               return srcTextLen;
-       }
-       else
-       {
-               gsm7bitLength = convertUCS2ToGSM7bitAuto(pDestText, maxLength, (unsigned char*)pUCS2Text, ucs2Length, &bUnknown);
-
-               if (bUnknown == true)
-               {
-                       *pCharType = MSG_ENCODE_UCS2;
-
-                       if (ucs2Length > 0)
-                               memcpy(pDestText, pUCS2Text, ucs2Length);
-
-                       return ucs2Length;
-               }
-               else
-               {
-                       *pCharType = MSG_ENCODE_GSM7BIT;
-               }
-
-               return gsm7bitLength;
-       }
-}
-
-
-/**
-return:
-               bytelength of UTF8 text
-*/
-int SmsPluginTextConvert::convertGSM7bitToUTF8(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, IN SMS_LANG_INFO_S *pLangInfo)
-{
-       int utf8Length = 0;
-       int ucs2Length = 0;
-       int maxUCS2Length = srcTextLen;         // max # of UCS2 chars, NOT bytes. when all gsm7 chars are only one byte(-there is no extenstion), UCS2Length is maxUCS2 Length. otherwise(ex: gsm7 char starts with 0x1b) UCS2Length must be less than gsm7 legnth
-
-       WCHAR pUCS2Text[maxUCS2Length];
-       memset(pUCS2Text, 0x00, maxUCS2Length * sizeof(WCHAR));
-
-       MSG_DEBUG("srcTextLen = %d\n", srcTextLen);
-       MSG_DEBUG("max dest Length = %d\n", maxLength);
-
-       ucs2Length = convertGSM7bitToUCS2((unsigned char*)pUCS2Text, maxUCS2Length * sizeof(WCHAR), pSrcText, srcTextLen, pLangInfo);
-       utf8Length = convertUCS2ToUTF8(pDestText, maxLength, (unsigned char*)pUCS2Text, ucs2Length);
-
-       return utf8Length;
-}
-
-
-/**
-args:
-       OUT unsigned char *pDestText
-       IN int maxLength                : max byte length of destination text
-       IN const unsigned char *pSrcText
-       IN  int srcTextLen              : byte length of UCS2 source text
-return :
-               byte length of converted UTF8 characters
-                       -1 : The alpha isn't the gsm 7bit code
-*/
-int SmsPluginTextConvert::convertUCS2ToUTF8(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN  int srcTextLen)
-{
-       int remainedBuffer = maxLength;
-       int utf8Length;
-
-#ifdef CONVERT_DUMP
-       int srcLen = srcTextLen;
-       const unsigned char * pTempSrcText = pSrcText;
-#endif
-       unsigned char * pTempDestText = pDestText;
-
-       if (srcTextLen == 0 || pSrcText == NULL || pDestText ==  NULL || maxLength == 0)
-       {
-               MSG_DEBUG("UCS2 to UTF8 Failed as text length is 0\n");
-               return false;
-       }
-
-       GIConv cd;
-       int err=0;
-
-       cd = g_iconv_open( "UTF8", "UCS-2BE" );
-
-       if (cd > 0)
-       {
-               err = g_iconv(cd, (char**)&pSrcText, (gsize*)&srcTextLen, (char**)&pDestText, (gsize*)&remainedBuffer);
-       }
-
-       utf8Length = maxLength - remainedBuffer;
-       pTempDestText[utf8Length] = 0x00;
-
-#ifdef CONVERT_DUMP
-       MSG_DEBUG("\n########## Dump UCS2 -> UTF8\n");
-       convertDumpTextToHex((unsigned char*)pTempSrcText, srcLen);
-       convertDumpTextToHex((unsigned char*)pTempDestText, utf8Length);
-#endif
-
-       g_iconv_close(cd);
-
-       return utf8Length;
-}
-
-
-int SmsPluginTextConvert::convertEUCKRToUTF8(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN  int srcTextLen)
-{
-       int remainedBuffer = maxLength;
-       int utf8Length;
-
-#ifdef CONVERT_DUMP
-       int srcLen = srcTextLen;
-       const unsigned char * pTempSrcText = pSrcText;
-#endif
-       unsigned char * pTempDestText = pDestText;
-
-       if(srcTextLen == 0 || pSrcText == NULL || pDestText ==  NULL || maxLength == 0)
-       {
-               MSG_DEBUG("EUCKR to UTF8 Failed as text length is 0\n");
-               return false;
-       }
-
-       GIConv cd;
-       int err=0;
-
-       cd = g_iconv_open( "UTF8", "EUCKR" );
-
-       if (cd > 0)
-       {
-               err = g_iconv(cd, (char**)&pSrcText, (gsize*)&srcTextLen, (char**)&pDestText, (gsize*)&remainedBuffer);
-       }
-
-       utf8Length = maxLength - remainedBuffer;
-       pTempDestText[utf8Length] = 0x00;
-
-#ifdef CONVERT_DUMP
-       MSG_DEBUG("\n########## Dump EUCKR -> UTF8\n");
-       convertDumpTextToHex((unsigned char*)pTempSrcText, srcLen);
-       convertDumpTextToHex((unsigned char*)pTempDestText, utf8Length);
-#endif
-
-       g_iconv_close(cd);
-
-       return utf8Length;
-}
-
-
-/**
-
-args:
-               unsigned char *pDestText
-               int maxLength                           : max destination buffer size
-               const unsigned char *pSrcText
-               int srcTextLen                          : BYTE length of src text (UCS2)
-return:
-               bytelength of gsm7bit text
-               -1 : converting error
-*/
-int SmsPluginTextConvert::convertUCS2ToGSM7bit(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, OUT SMS_LANGUAGE_ID_T *pLangId)
-{
-       // for UNICODE
-       int outTextLen = 0;
-       unsigned char lowerByte, upperByte;
-
-       if (srcTextLen == 0 || pSrcText == NULL || pDestText ==  NULL || maxLength == 0)
-       {
-               MSG_DEBUG("UCS2 to GSM7bit Failed as text length is 0\n");
-               return -1;
-       }
-
-       std::map<unsigned short, unsigned char>::iterator itChar;
-       std::map<unsigned short, unsigned char>::iterator itExt;
-
-       SMS_CHAR_TYPE_T currType = SMS_CHAR_DEFAULT;
-       SMS_CHAR_TYPE_T newType = SMS_CHAR_DEFAULT;
-
-       unsigned short inText;
-
-       // Get Language Type by checking each character
-       for (int index = 0; index < srcTextLen; index++)
-       {
-               upperByte = pSrcText[index++];
-               lowerByte = pSrcText[index];
-
-               inText = (upperByte << 8) & 0xFF00;
-
-               inText = inText | lowerByte;
-
-//MSG_DEBUG("inText : [%04x]", inText);
-
-               itExt = extCharList.find(inText);
-
-               if (itExt != extCharList.end())
-               {
-                       newType = (SMS_CHAR_TYPE_T)itExt->second;
-
-                       if (newType >= currType)
-                       {
-                               currType = newType;
-                       }
-               }
-       }
-
-MSG_DEBUG("charType : [%d]", currType);
-
-       for (int index = 0; index < srcTextLen; index++)
-       {
-               upperByte = pSrcText[index++];
-               lowerByte = pSrcText[index];
-
-               inText = (upperByte << 8) & 0xFF00;
-               inText = inText | lowerByte;
-
-MSG_DEBUG("inText : [%04x]", inText);
-
-               // Check Default Char
-               itChar = ucs2toGSM7DefList.find(inText);
-
-               if (itChar != ucs2toGSM7DefList.end())
-               {
-MSG_DEBUG("default char");
-                       pDestText[outTextLen++] = (unsigned char)itChar->second;
-               }
-               else
-               {
-                       if (currType == SMS_CHAR_GSM7EXT)
-                       {
-                               itExt = ucs2toGSM7ExtList.find(inText);
-
-                               if (itExt != ucs2toGSM7ExtList.end())
-                               {
-                                       // prevent buffer overflow
-                                       if (maxLength <= outTextLen + 1)
-                                       {
-                                               MSG_DEBUG("Buffer Full");
-                                               break;
-                                       }
-
-                                       pDestText[outTextLen++] = 0x1B;
-                                       pDestText[outTextLen++] = (unsigned char)itExt->second;
-                               }
-                               else
-                               {
-                                       pDestText[outTextLen++] = 0x20;
-                               }
-                       }
-                       else if (currType == SMS_CHAR_TURKISH)
-                       {
-                               *pLangId = SMS_LANG_ID_TURKISH;
-
-                               itExt = ucs2toTurkishList.find(inText);
-
-                               if (itExt != ucs2toTurkishList.end())
-                               {
-                                       // prevent buffer overflow
-                                       if (maxLength <= outTextLen + 1)
-                                       {
-                                               MSG_DEBUG("Buffer Full");
-                                               break;
-                                       }
-
-                                       pDestText[outTextLen++] = 0x1B;
-                                       pDestText[outTextLen++] = (unsigned char)itExt->second;
-                               }
-                               else
-                               {
-                                       pDestText[outTextLen++] = 0x20;
-                               }
-                       }
-                       else if (currType == SMS_CHAR_SPANISH)
-                       {
-                               *pLangId = SMS_LANG_ID_SPANISH;
-
-                               itExt = ucs2toSpanishList.find(inText);
-
-                               if (itExt != ucs2toSpanishList.end())
-                               {
-                                       // prevent buffer overflow
-                                       if (maxLength <= outTextLen + 1)
-                                       {
-                                               MSG_DEBUG("Buffer Full");
-                                               break;
-                                       }
-
-                                       pDestText[outTextLen++] = 0x1B;
-                                       pDestText[outTextLen++] = (unsigned char)itExt->second;
-                               }
-                               else
-                               {
-                                       pDestText[outTextLen++] = 0x20;
-                               }
-                       }
-                       else if (currType == SMS_CHAR_PORTUGUESE)
-                       {
-                               *pLangId = SMS_LANG_ID_PORTUGUESE;
-
-                               itExt = ucs2toPortuList.find(inText);
-
-                               if (itExt != ucs2toPortuList.end())
-                               {
-                                       // prevent buffer overflow
-                                       if (maxLength <= outTextLen + 1)
-                                       {
-                                               MSG_DEBUG("Buffer Full");
-                                               break;
-                                       }
-
-MSG_DEBUG("ucs2toPortuList : [%02x]", (unsigned char)itExt->second);
-
-                                       pDestText[outTextLen++] = 0x1B;
-                                       pDestText[outTextLen++] = (unsigned char)itExt->second;
-                               }
-                               else
-                               {
-MSG_DEBUG("no char");
-                                       pDestText[outTextLen++] = 0x20;
-                               }
-                       }
-                       else
-                       {
-                               pDestText[outTextLen++] = 0x20;
-                       }
-               }
-
-               // prevent buffer overflow
-               if (maxLength <= outTextLen)
-               {
-                       MSG_DEBUG("Buffer full\n");
-                       break;
-               }
-       }
-
-#ifdef CONVERT_DUMP
-       MSG_DEBUG("\n########## Dump UCS2 -> GSM7bit\n");
-       convertDumpTextToHex((unsigned char*)pSrcText, srcTextLen);
-       convertDumpTextToHex((unsigned char*)pDestText, outTextLen);
-#endif
-
-       return outTextLen;
-}
-
-
-int SmsPluginTextConvert::convertUCS2ToGSM7bitAuto(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, OUT bool *pUnknown)
-{
-       // for UNICODE
-       int outTextLen = 0;
-       unsigned char lowerByte, upperByte;
-
-       if (srcTextLen == 0 || pSrcText == NULL || pDestText ==  NULL || maxLength == 0)
-       {
-               MSG_DEBUG("UCS2 to GSM7bit Failed as text length is 0\n");
-               return -1;
-       }
-
-       std::map<unsigned short, unsigned char>::iterator itChar;
-       std::map<unsigned short, unsigned char>::iterator itExt;
-
-       unsigned short inText;
-
-       for (int index = 0; index < srcTextLen; index++)
-       {
-               upperByte = pSrcText[index++];
-               lowerByte = pSrcText[index];
-
-               inText = (upperByte << 8) & 0xFF00;
-               inText = inText | lowerByte;
-
-//MSG_DEBUG("inText : [%04x]", inText);
-
-               // Check Default Char
-               itChar = ucs2toGSM7DefList.find(inText);
-
-               if (itChar != ucs2toGSM7DefList.end())
-               {
-//MSG_DEBUG("default char");
-                       pDestText[outTextLen++] = (unsigned char)itChar->second;
-               }
-               else
-               {
-                       itExt = ucs2toGSM7ExtList.find(inText);
-
-                       if (itExt != ucs2toGSM7ExtList.end())
-                       {
-                               // prevent buffer overflow
-                               if (maxLength <= outTextLen + 1)
-                               {
-                                       MSG_DEBUG("Buffer Full");
-                                       break;
-                               }
-
-                               pDestText[outTextLen++] = 0x1B;
-                               pDestText[outTextLen++] = (unsigned char)itExt->second;
-                       }
-                       else
-                       {
-                               *pUnknown = true;
-                               return 0;
-                       }
-               }
-
-               // prevent buffer overflow
-               if (maxLength <= outTextLen)
-               {
-                       MSG_DEBUG("Buffer full\n");
-                       break;
-               }
-       }
-
-#ifdef CONVERT_DUMP
-       MSG_DEBUG("\n########## Dump UCS2 -> GSM7bit\n");
-       convertDumpTextToHex((unsigned char*)pSrcText, srcTextLen);
-       convertDumpTextToHex((unsigned char*)pDestText, outTextLen);
-#endif
-
-       return outTextLen;
-}
-
-
-/**
- args :
-               unsigned char *pDestText                                : destination text (UCS2) - byte order depends on local byte order
-               const unsigned char *pSrcText           : source text (gsm7bit)
-               int maxLength                   : max destination buffer size
-               int srcTextLen                  : byte length of source text (gsm7bit)
- return :
-               byte length of converted UCS2 characters
-                       -1 : The alpha isn't the gsm 7bit code
-*/
-int SmsPluginTextConvert::convertGSM7bitToUCS2(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, IN SMS_LANG_INFO_S *pLangInfo)
-{
-       int outTextLen = 0;
-       unsigned char lowerByte = 0, upperByte = 0;
-
-       if (srcTextLen == 0 || pSrcText == NULL || pDestText ==  NULL || maxLength == 0)
-       {
-               MSG_DEBUG("UCS2 to GSM7bit Failed as text length is 0\n");
-               return -1;
-       }
-
-       for (int i = 0; i<srcTextLen; i++)
-       {
-               if (maxLength == 0)
-               {
-                       break;
-               }
-
-               if (pSrcText[i] >= 0x80)
-               {
-                       //error
-                       MSG_DEBUG(">>>>>>>a_pTextString[i]=%x, The alpha isn't the gsm 7bit code, Never Come here!!!\n", pSrcText[i]);
-                       return -1;
-               }
-
-               if (pLangInfo->bLockingShift == true) // National Language Locking Shift
-               {
-                       MSG_DEBUG("Locking Shift [%d]", pLangInfo->lockingLang);
-
-                       if (pLangInfo->lockingLang == SMS_LANG_ID_TURKISH)
-                       {
-                               // Check Escape
-                               if (g_TurkishLockingToUCS2[pSrcText[i]] == 0x001B)
-                               {
-                                       i++;
-
-                                       if (pLangInfo->bSingleShift == true) // National Language Single Shift
-                                       {
-                                               MSG_DEBUG("Single Shift [%d]", pLangInfo->singleLang);
-
-                                               if (pLangInfo->singleLang == SMS_LANG_ID_TURKISH)
-                                               {
-                                                       lowerByte = g_TurkishSingleToUCS2[pSrcText[i]] & 0x00FF;
-                                                       upperByte = (g_TurkishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                               }
-                                               else if (pLangInfo->singleLang == SMS_LANG_ID_SPANISH)
-                                               {
-                                                       lowerByte = g_SpanishSingleToUCS2[pSrcText[i]] & 0x00FF;
-                                                       upperByte = (g_SpanishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                               }
-                                               else if (pLangInfo->singleLang == SMS_LANG_ID_PORTUGUESE)
-                                               {
-                                                       lowerByte = g_PortuSingleToUCS2[pSrcText[i]] & 0x00FF;
-                                                       upperByte = (g_PortuSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                               }
-                                               else
-                                               {
-                                                       lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
-                                                       upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                               }
-                                       }
-                                       else // GSM 7 bit Default Alphabet Extension Table
-                                       {
-                                               lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
-                                               upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                       }
-                               }
-                               else // TURKISH - National Language Locking Shift
-                               {
-                                       lowerByte = g_TurkishLockingToUCS2[pSrcText[i]] & 0x00FF;
-                                       upperByte = (g_TurkishLockingToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                               }
-                       }
-                       else if (pLangInfo->lockingLang == SMS_LANG_ID_PORTUGUESE)
-                       {
-                               // Check Escape
-                               if (g_PortuLockingToUCS2[pSrcText[i]] == 0x001B)
-                               {
-                                       i++;
-
-                                       if (pLangInfo->bSingleShift == true) // National Language Single Shift
-                                       {
-                                               MSG_DEBUG("Single Shift [%d]", pLangInfo->singleLang);
-
-                                               if (pLangInfo->singleLang == SMS_LANG_ID_TURKISH)
-                                               {
-                                                       lowerByte = g_TurkishSingleToUCS2[pSrcText[i]] & 0x00FF;
-                                                       upperByte = (g_TurkishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                               }
-                                               else if (pLangInfo->singleLang == SMS_LANG_ID_SPANISH)
-                                               {
-                                                       lowerByte = g_SpanishSingleToUCS2[pSrcText[i]] & 0x00FF;
-                                                       upperByte = (g_SpanishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                               }
-                                               else if (pLangInfo->singleLang == SMS_LANG_ID_PORTUGUESE)
-                                               {
-                                                       lowerByte = g_PortuSingleToUCS2[pSrcText[i]] & 0x00FF;
-                                                       upperByte = (g_PortuSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                               }
-                                               else
-                                               {
-                                                       lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
-                                                       upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                               }
-                                       }
-                                       else // GSM 7 bit Default Alphabet Extension Table
-                                       {
-                                               lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
-                                               upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                       }
-                               }
-                               else // PORTUGUESE - National Language Locking Shift
-                               {
-                                       lowerByte = g_PortuLockingToUCS2[pSrcText[i]] & 0x00FF;
-                                       upperByte = (g_PortuLockingToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                               }
-                       }
-               }
-               else
-               {
-                       // Check Escape
-                       if (g_GSM7BitToUCS2[pSrcText[i]] == 0x001B)
-                       {
-                               i++;
-
-                               if (pLangInfo->bSingleShift == true) // National Language Single Shift
-                               {
-                                       MSG_DEBUG("Single Shift [%d]", pLangInfo->singleLang);
-
-                                       if (pLangInfo->singleLang == SMS_LANG_ID_TURKISH)
-                                       {
-                                               lowerByte = g_TurkishSingleToUCS2[pSrcText[i]] & 0x00FF;
-                                               upperByte = (g_TurkishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                       }
-                                       else if (pLangInfo->singleLang == SMS_LANG_ID_SPANISH)
-                                       {
-                                               lowerByte = g_SpanishSingleToUCS2[pSrcText[i]] & 0x00FF;
-                                               upperByte = (g_SpanishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                       }
-                                       else if (pLangInfo->singleLang == SMS_LANG_ID_PORTUGUESE)
-                                       {
-                                               lowerByte = g_PortuSingleToUCS2[pSrcText[i]] & 0x00FF;
-                                               upperByte = (g_PortuSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                       }
-                                       else
-                                       {
-                                               lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
-                                               upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                                       }
-                               }
-                               else // GSM 7 bit Default Alphabet Extension Table
-                               {
-                                       lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
-                                       upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                               }
-                       }
-                       else
-                       {
-                               lowerByte = g_GSM7BitToUCS2[pSrcText[i]] & 0x00FF;
-                               upperByte = (g_GSM7BitToUCS2[pSrcText[i]] & 0xFF00) >> 8;
-                       }
-               }
-
-               pDestText[outTextLen++] = upperByte;
-               pDestText[outTextLen++] = lowerByte;
-               maxLength -= 2;
-       }
-
-#ifdef CONVERT_DUMP
-       MSG_DEBUG("\n########## Dump GSM7bit -> UCS2\n");
-       convertDumpTextToHex((unsigned char*)pSrcText, srcTextLen);
-       convertDumpTextToHex((unsigned char*)pDestText, outTextLen);
-#endif
-
-       return outTextLen;
-}
-
-
-void SmsPluginTextConvert::convertDumpTextToHex(const unsigned char *pText, int length)
-{
-       printf("\n=======================================\n");
-       printf("   Dump Text To Hex - Length :%d\n", length);
-       printf("=======================================");
-
-       for (int i = 0; i < length; i++ )
-       {
-               if ( i % MAX_DUMP_COLUMN == 0 )
-               {
-                       printf("\n\t");
-               }
-               printf("%02x ", pText[i]);
-       }
-
-       printf("\n=======================================\n\n");
-}
-
-
-SmsPluginTextConvert::SmsPluginTextConvert()
-{
-       extCharList.clear();
-       ucs2toGSM7DefList.clear();
-       ucs2toGSM7ExtList.clear();
-       ucs2toTurkishList.clear();
-       ucs2toSpanishList.clear();
-       ucs2toPortuList.clear();
-
-       extCharList[0x000C] = SMS_CHAR_GSM7EXT;
-       extCharList[0x005B] = SMS_CHAR_GSM7EXT;
-       extCharList[0x005C] = SMS_CHAR_GSM7EXT;
-       extCharList[0x005D] = SMS_CHAR_GSM7EXT;
-       extCharList[0x005E] = SMS_CHAR_GSM7EXT;
-       extCharList[0x007B] = SMS_CHAR_GSM7EXT;
-       extCharList[0x007C] = SMS_CHAR_GSM7EXT;
-       extCharList[0x007D] = SMS_CHAR_GSM7EXT;
-       extCharList[0x007E] = SMS_CHAR_GSM7EXT;
-       extCharList[0x20AC] = SMS_CHAR_GSM7EXT; // ¢æ
-
-       extCharList[0x00E7] = SMS_CHAR_TURKISH;
-       extCharList[0x011E] = SMS_CHAR_TURKISH;
-       extCharList[0x011F] = SMS_CHAR_TURKISH;
-       extCharList[0x01E6] = SMS_CHAR_TURKISH;
-       extCharList[0x01E7] = SMS_CHAR_TURKISH;
-       extCharList[0x0130] = SMS_CHAR_TURKISH;
-       extCharList[0x0131] = SMS_CHAR_TURKISH;
-       extCharList[0x015E] = SMS_CHAR_TURKISH;
-       extCharList[0x015F] = SMS_CHAR_TURKISH;
-
-       extCharList[0x00C1] = SMS_CHAR_SPANISH;
-       extCharList[0x00E1] = SMS_CHAR_SPANISH;
-       extCharList[0x00CD] = SMS_CHAR_SPANISH;
-       extCharList[0x00ED] = SMS_CHAR_SPANISH;
-       extCharList[0x00D3] = SMS_CHAR_SPANISH;
-       extCharList[0x00F3] = SMS_CHAR_SPANISH;
-       extCharList[0x00DA] = SMS_CHAR_SPANISH;
-       extCharList[0x00FA] = SMS_CHAR_SPANISH;
-
-       extCharList[0x00D4] = SMS_CHAR_PORTUGUESE;
-       extCharList[0x00F4] = SMS_CHAR_PORTUGUESE;
-       extCharList[0x00CA] = SMS_CHAR_PORTUGUESE;
-       extCharList[0x00EA] = SMS_CHAR_PORTUGUESE;
-       extCharList[0x00C0] = SMS_CHAR_PORTUGUESE;
-       extCharList[0x00E7] = SMS_CHAR_PORTUGUESE;
-       extCharList[0x00C3] = SMS_CHAR_PORTUGUESE;
-       extCharList[0x00E3] = SMS_CHAR_PORTUGUESE;
-       extCharList[0x00D5] = SMS_CHAR_PORTUGUESE;
-       extCharList[0x00F5] = SMS_CHAR_PORTUGUESE;
-       extCharList[0x00C2] = SMS_CHAR_PORTUGUESE;
-       extCharList[0x00E2] = SMS_CHAR_PORTUGUESE;
-
-       for (unsigned char i = 0; i < 128; i++)
-       {
-               ucs2toGSM7DefList[g_GSM7BitToUCS2[i]] = i;
-       }
-
-       // GSM 7 bit Extension
-       ucs2toGSM7ExtList[0x005B] = 0x3C; // [
-       ucs2toGSM7ExtList[0x005D] = 0x3E; // ]
-       ucs2toGSM7ExtList[0x007B] = 0x28; // {
-       ucs2toGSM7ExtList[0x007D] = 0x29; // }
-       ucs2toGSM7ExtList[0x000C] = 0x0A; // Page Break
-       ucs2toGSM7ExtList[0x005C] = 0x2F; /* \ */
-       ucs2toGSM7ExtList[0x005E] = 0x14; // ^
-       ucs2toGSM7ExtList[0x007C] = 0x40; // |
-       ucs2toGSM7ExtList[0x007E] = 0x3D; // ~
-       ucs2toGSM7ExtList[0x20AC] = 0x65; // ¢æ
-
-       // Turkish
-       ucs2toTurkishList[0x005B] = 0x3C; // [
-       ucs2toTurkishList[0x005D] = 0x3E; // ]
-       ucs2toTurkishList[0x007B] = 0x28; // {
-       ucs2toTurkishList[0x007D] = 0x29; // }
-       ucs2toTurkishList[0x000C] = 0x0A; // Page Break
-       ucs2toTurkishList[0x005C] = 0x2F; /* \ */
-       ucs2toTurkishList[0x005E] = 0x14; // ^
-       ucs2toTurkishList[0x007C] = 0x40; // |
-       ucs2toTurkishList[0x007E] = 0x3D; // ~
-       ucs2toTurkishList[0x20AC] = 0x65; // ¢æ
-       ucs2toTurkishList[0x00E7] = 0x63; // c LATIN SMALL LETTER S WITH CEDILLA *
-       ucs2toTurkishList[0x011E] = 0x47; // G LATIN CAPITAL LETTER G WITH BREVE
-       ucs2toTurkishList[0x011F] = 0x67; // g LATIN SMALL LETTER G WITH BREVE
-       ucs2toTurkishList[0x01E6] = 0x47; // G LATIN CAPITAL LETTER G WITH CARON
-       ucs2toTurkishList[0x01E7] = 0x67; // g LATIN SMALL LETTER G WITH CARON
-       ucs2toTurkishList[0x0130] = 0x49; // I LATIN CAPITAL LETTER I WITH DOT ABOVE
-       ucs2toTurkishList[0x0131] = 0x69; // i LATIN SMALL LETTER DOTLESS
-       ucs2toTurkishList[0x015E] = 0x53; // S LATIN CAPITAL LETTER S WITH CEDILLA *
-       ucs2toTurkishList[0x015F] = 0x73; // s LATIN SMALL LETTER S WITH CEDILLA *
-
-       // Spanish
-       ucs2toSpanishList[0x005B] = 0x3C; // [
-       ucs2toSpanishList[0x005D] = 0x3E; // ]
-       ucs2toSpanishList[0x007B] = 0x28; // {
-       ucs2toSpanishList[0x007D] = 0x29; // }
-       ucs2toSpanishList[0x000C] = 0x0A; // Page Break
-       ucs2toSpanishList[0x005C] = 0x2F; /* \ */
-       ucs2toSpanishList[0x005E] = 0x14; // ^
-       ucs2toSpanishList[0x007C] = 0x40; // |
-       ucs2toSpanishList[0x007E] = 0x3D; // ~
-       ucs2toSpanishList[0x20AC] = 0x65; // ¢æ
-       ucs2toSpanishList[0x00C1] = 0x41; // A
-       ucs2toSpanishList[0x00E1] = 0x61; // a
-       ucs2toSpanishList[0x00CD] = 0x49; // I
-       ucs2toSpanishList[0x00ED] = 0x69; // i
-       ucs2toSpanishList[0x00D3] = 0x4F; // O
-       ucs2toSpanishList[0x00F3] = 0x6F; // o
-       ucs2toSpanishList[0x00DA] = 0x55; // U
-       ucs2toSpanishList[0x00FA] = 0x75; // u
-
-       // Portuguese
-       ucs2toPortuList[0x005B] = 0x3C; // [
-       ucs2toPortuList[0x005D] = 0x3E; // ]
-       ucs2toPortuList[0x007B] = 0x28; // {
-       ucs2toPortuList[0x007D] = 0x29; // }
-       ucs2toPortuList[0x000C] = 0x0A; // Page Break
-       ucs2toPortuList[0x005C] = 0x2F; /* \ */
-       ucs2toPortuList[0x005E] = 0x14; // ^
-       ucs2toPortuList[0x007C] = 0x40; // |
-       ucs2toPortuList[0x007E] = 0x3D; // ~
-       ucs2toPortuList[0x20AC] = 0x65; // ¢æ
-       ucs2toPortuList[0x00D4] = 0x0B; // O
-       ucs2toPortuList[0x00F4] = 0x0C; // o
-       ucs2toPortuList[0x00C1] = 0x0E; // A
-       ucs2toPortuList[0x00E1] = 0x0F; // a
-       ucs2toPortuList[0x00CA] = 0x1F; // E
-       ucs2toPortuList[0x00EA] = 0x05; // e
-       ucs2toPortuList[0x00C0] = 0x41; // A
-       ucs2toPortuList[0x00E7] = 0x09; // c
-       ucs2toPortuList[0x00CD] = 0x49; // I
-       ucs2toPortuList[0x00ED] = 0x69; // i
-       ucs2toPortuList[0x00D3] = 0x4F; // O
-       ucs2toPortuList[0x00F3] = 0x6F; // o
-       ucs2toPortuList[0x00DA] = 0x55; // U
-       ucs2toPortuList[0x00FA] = 0x75; // u
-       ucs2toPortuList[0x00C3] = 0x61; // A
-       ucs2toPortuList[0x00E3] = 0x7B; // a
-       ucs2toPortuList[0x00D5] = 0x5C; // O
-       ucs2toPortuList[0x00F5] = 0x7C; // o
-       ucs2toPortuList[0x00C2] = 0x61; // A
-       ucs2toPortuList[0x00E2] = 0x7F; // a
-       ucs2toPortuList[0x03A6] = 0x12; // ¥Õ
-       ucs2toPortuList[0x0393] = 0x13; // ¥Ã
-       ucs2toPortuList[0x03A9] = 0x15; // ¥Ø
-       ucs2toPortuList[0x03A0] = 0x16; // ¥Ð
-       ucs2toPortuList[0x03A8] = 0x17; // ¥×
-       ucs2toPortuList[0x03A3] = 0x18; // ¥Ò
-       ucs2toPortuList[0x0398] = 0x19; // ¥È
-}
-
-
-SmsPluginTextConvert::~SmsPluginTextConvert()
-{
-       extCharList.clear();
-       ucs2toGSM7DefList.clear();
-       ucs2toGSM7ExtList.clear();
-       ucs2toTurkishList.clear();
-       ucs2toSpanishList.clear();
-       ucs2toPortuList.clear();
-
-       if (pInstance)
-       {
-               delete pInstance;
-               pInstance = NULL;
-       }
-}
-
index 6849f7f..789f14b 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
@@ -21,7 +21,6 @@
 #include "MsgCppTypes.h"
 #include "MsgException.h"
 #include "MsgGconfWrapper.h"
-#include "MsgUtilFile.h"
 
 #include "SmsPluginTpduCodec.h"
 #include "SmsPluginParamCodec.h"
@@ -105,19 +104,19 @@ int SmsPluginTpduCodec::encodeSubmit(const SMS_SUBMIT_S *pSubmit, char *pTpdu)
        int offset = 0, length = 0, encodeSize = 0;
 
        char* address = NULL;
-       AutoPtr<char> addressBuf(&address);
+       unique_ptr<char*, void(*)(char**)> addressBuf(&address, unique_ptr_deleter);
 
        char* dcs = NULL;
-       AutoPtr<char> dcsBuf(&dcs);
+       unique_ptr<char*, void(*)(char**)> dcsBuf(&dcs, unique_ptr_deleter);
 
        char* vpTime = NULL;
-       AutoPtr<char> vpBuf(&vpTime);
+       unique_ptr<char*, void(*)(char**)> vpBuf(&vpTime, unique_ptr_deleter);
 
        //TP-MTI
        pTpdu[offset] = 0x01;
 
        //TP-RD
-       if(pSubmit->bRejectDup == false)
+       if(pSubmit->bRejectDup == true)
                pTpdu[offset] |= 0x04;
 
        //TP-VPF
@@ -196,6 +195,15 @@ MSG_DEBUG("encodeSize : %d", encodeSize);
 
        offset += encodeSize;
 
+#if 0
+       printf("\n\n[encodeSubmit] pTpdu data.\n");
+       for (int i = 0; i < offset; i++)
+       {
+               printf(" [%02x]", pTpdu[i]);
+       }
+       printf("\n\n");
+#endif
+
        return offset;
 }
 
@@ -205,13 +213,13 @@ int SmsPluginTpduCodec::encodeDeliver(const SMS_DELIVER_S *pDeliver, char *pTpdu
        int offset = 0, length = 0, encodeSize = 0;
 
        char* address = NULL;
-       AutoPtr<char> addressBuf(&address);
+       unique_ptr<char*, void(*)(char**)> addressBuf(&address, unique_ptr_deleter);
 
        char* dcs = NULL;
-       AutoPtr<char> dcsBuf(&dcs);
+       unique_ptr<char*, void(*)(char**)> dcsBuf(&dcs, unique_ptr_deleter);
 
        char* scts = NULL;
-       AutoPtr<char> timeBuf(&scts);
+       unique_ptr<char*, void(*)(char**)> timeBuf(&scts, unique_ptr_deleter);
 
        // TP-MTI : 00
        pTpdu[offset] = 0x00;
@@ -277,8 +285,10 @@ int SmsPluginTpduCodec::encodeDeliverReport(const SMS_DELIVER_REPORT_S *pDeliver
        offset++;
 
        // TP-FCS
-       if (pDeliverRep->reportType == SMS_REPORT_NEGATIVE)
+       if (pDeliverRep->reportType == SMS_REPORT_NEGATIVE) {
                pTpdu[offset++] = pDeliverRep->failCause;
+               MSG_DEBUG("Delivery report : fail cause = [%02x]", pDeliverRep->failCause);
+       }
 
        // TP-PI
        pTpdu[offset++] = pDeliverRep->paramInd;
@@ -293,7 +303,7 @@ int SmsPluginTpduCodec::encodeDeliverReport(const SMS_DELIVER_REPORT_S *pDeliver
                int length = 0;
 
                char* dcs = NULL;
-               AutoPtr<char> dcsBuf(&dcs);
+               unique_ptr<char*, void(*)(char**)> dcsBuf(&dcs, unique_ptr_deleter);
 
                length = SmsPluginParamCodec::encodeDCS(&pDeliverRep->dcs, &dcs);
                memcpy(&(pTpdu[offset]), dcs, length);
@@ -324,13 +334,13 @@ int SmsPluginTpduCodec::encodeStatusReport(const SMS_STATUS_REPORT_S *pStatusRep
        int offset = 0, length = 0;
 
        char* address = NULL;
-       AutoPtr<char> addressBuf(&address);
+       unique_ptr<char*, void(*)(char**)> addressBuf(&address, unique_ptr_deleter);
 
        char* scts = NULL;
-       AutoPtr<char> sctsBuf(&scts);
+       unique_ptr<char*, void(*)(char**)> sctsBuf(&scts, unique_ptr_deleter);
 
        char* dt = NULL;
-       AutoPtr<char> dtBuf(&dt);
+       unique_ptr<char*, void(*)(char**)> dtBuf(&dt, unique_ptr_deleter);
 
        // TP-MTI : 10
        pTpdu[offset] = 0x02;
@@ -383,7 +393,7 @@ int SmsPluginTpduCodec::encodeStatusReport(const SMS_STATUS_REPORT_S *pStatusRep
                int length = 0;
 
                char* dcs = NULL;
-               AutoPtr<char> dcsBuf(&dcs);
+               unique_ptr<char*, void(*)(char**)> dcsBuf(&dcs, unique_ptr_deleter);
 
                length = SmsPluginParamCodec::encodeDCS(&pStatusRep->dcs, &dcs);
                memcpy(&(pTpdu[offset]), dcs, length);
@@ -469,7 +479,17 @@ int SmsPluginTpduCodec::decodeSubmit(const unsigned char *pTpdu, int TpduLen, SM
 
 int SmsPluginTpduCodec::decodeDeliver(const unsigned char *pTpdu, int TpduLen, SMS_DELIVER_S *pDeliver)
 {
-       int offset = 0, udLen = 0;
+       int offset = 0, udLen = 0, tmpOffset = 0;
+
+
+       char tpduTmp[(TpduLen*2)+1];
+       memset(tpduTmp, 0x00, sizeof(tpduTmp));
+       for (int i = 0; i < TpduLen; i++) {
+               snprintf(tpduTmp+(i*2), sizeof(tpduTmp)-(i*2), "%02X", pTpdu[i]);
+       }
+       MSG_DEBUG("Deliver TPDU.");
+       MSG_INFO("[%s]", tpduTmp);
+
 
        // TP-MMS
        if (pTpdu[offset] & 0x04)
@@ -497,6 +517,8 @@ int SmsPluginTpduCodec::decodeDeliver(const unsigned char *pTpdu, int TpduLen, S
 
        offset++;
 
+       tmpOffset = offset;
+#if 1
        // TP-OA
        offset += SmsPluginParamCodec::decodeAddress(&pTpdu[offset], &(pDeliver->originAddress));
 
@@ -506,6 +528,65 @@ int SmsPluginTpduCodec::decodeDeliver(const unsigned char *pTpdu, int TpduLen, S
        // TP-DCS
        offset += SmsPluginParamCodec::decodeDCS(&pTpdu[offset], &(pDeliver->dcs));
 
+       // Support KSC5601 :: Coding group bits == 0x84
+       if (pTpdu[offset-1] == 0x84) {
+               pDeliver->dcs.codingScheme = SMS_CHARSET_EUCKR;
+       }
+
+#else
+       //For alphanumeric address test
+
+       offset += SmsPluginParamCodec::decodeAddress(&pTpdu[offset], &(pDeliver->originAddress));
+
+       char* address = new char[15];
+       address[0] = 0x04;
+       address[1] = 0xd0;
+       address[2] = 0x11;
+       address[3] = 0x00;
+       address[4] = 0x20;
+       address[5] = 0xF2;
+       address[6] = 0x01;
+       address[7] = 0x01;
+       address[8] = 0x11;
+       address[9] = 0x61;
+       address[10] = 0x40;
+       address[11] = 0x82;
+       address[12] = 0x2b;
+       address[13] = 0x01;
+       address[14] = 0x20;
+
+       SmsPluginParamCodec::decodeAddress((unsigned char*)address, &(pDeliver->originAddress));
+
+       pDeliver->pid = 0x20;
+       offset++;
+       offset += SmsPluginParamCodec::decodeDCS((unsigned char*)address, &(pDeliver->dcs));
+       // end test
+#endif
+
+       if (pDeliver->pid == 0x20 && pDeliver->originAddress.ton == SMS_TON_ALPHANUMERIC) {
+               int setType = -1;
+               int indType = -1;
+
+               bool bVmi = SmsPluginParamCodec::checkCphsVmiMsg(&pTpdu[tmpOffset], &setType, &indType);
+
+               MSG_DEBUG("bVmi = [%d], setType=[%d], indType=[%d]", bVmi, setType, indType);
+
+               if (bVmi) {
+                       pDeliver->dcs.bMWI = true;
+
+                       if (setType == 0) {
+                               pDeliver->dcs.bIndActive = false;
+                       } else {
+                               pDeliver->dcs.bIndActive = true;
+                       }
+
+                       if (indType == 0)
+                               pDeliver->dcs.indType = SMS_VOICE_INDICATOR;
+                       else if (indType == 1)
+                               pDeliver->dcs.indType = SMS_VOICE2_INDICATOR;
+               }
+       }
+
        // TP-SCTS
        offset += SmsPluginParamCodec::decodeTime(&pTpdu[offset], &(pDeliver->timeStamp));
 
@@ -518,16 +599,26 @@ int SmsPluginTpduCodec::decodeDeliver(const unsigned char *pTpdu, int TpduLen, S
 
 int SmsPluginTpduCodec::decodeStatusReport(const unsigned char *pTpdu, int TpduLen, SMS_STATUS_REPORT_S *pStatusRep)
 {
+#ifdef LOG_ENABLE
+       printf("\n\n[decodeStatusReport] pTpdu data - Length [%d]\n", TpduLen);
+
+       for (int i = 0; i < TpduLen; i++)
+       {
+               printf(" [%02x]", pTpdu[i]);
+       }
+       printf("\n\n");
+#endif
+
        int offset = 0, udLen = 0;
 
        char* address = NULL;
-       AutoPtr<char> addressBuf(&address);
+       unique_ptr<char*, void(*)(char**)> addressBuf(&address, unique_ptr_deleter);
 
        char* scts = NULL;
-       AutoPtr<char> sctsBuf(&scts);
+       unique_ptr<char*, void(*)(char**)> sctsBuf(&scts, unique_ptr_deleter);
 
        char* dt = NULL;
-       AutoPtr<char> dtBuf(&dt);
+       unique_ptr<char*, void(*)(char**)> dtBuf(&dt, unique_ptr_deleter);
 
        // TP-MMS
        if (pTpdu[offset] & 0x04)
index 133ff94..e81538e 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
 #include "MsgException.h"
 #include "MsgGconfWrapper.h"
 #include "MsgUtilFile.h"
-#include "SmsPluginTextConvert.h"
+#include "MsgNotificationWrapper.h"
+#include "MsgUtilStorage.h"
+
 #include "SmsPluginParamCodec.h"
 #include "SmsPluginTpduCodec.h"
 #include "SmsPluginEventHandler.h"
 #include "SmsPluginStorage.h"
 #include "SmsPluginCallback.h"
 #include "SmsPluginTransport.h"
+#include "SmsPluginDSHandler.h"
+#include "SmsPluginSetting.h"
 
 extern "C"
 {
        #include <ITapiNetText.h>
 }
 
-#define MSG_DEBUG_BY_FILE
 
-extern struct tapi_handle *pTapiHandle;
+extern bool isMemAvailable;
 
 /*==================================================================================================
                                      IMPLEMENTATION OF SmsPluginTransport - Member Functions
@@ -50,6 +53,8 @@ SmsPluginTransport::SmsPluginTransport()
        msgRef          = 0x00;
        msgRef8bit      = 0x00;
        msgRef16bit     = 0x0000;
+       curStatus       = 0x00;
+       memset(&curMoCtrlData, 0x00, sizeof(curMoCtrlData));
 }
 
 
@@ -72,56 +77,71 @@ void SmsPluginTransport::submitRequest(SMS_REQUEST_INFO_S *pReqInfo)
 {
        MSG_BEGIN();
 
-       SMS_TPDU_S tpdu;
+       SMS_TPDU_S tpdu = {0,};
 
        tpdu.tpduType = SMS_TPDU_SUBMIT;
 
-       // Set SMS Send Options - Setting
-       setSmsSendOptions(&(tpdu.data.submit));
+       // Get SMS Send Options - Setting
+       getSmsSendOption(pReqInfo->msgInfo.sim_idx, &(tpdu.data.submit));
 
        // Set SMS Send Options - Each Message
-       if (pReqInfo->sendOptInfo.bSetting == true)
-       {
-               tpdu.data.submit.bStatusReport = pReqInfo->sendOptInfo.bDeliverReq;
-               tpdu.data.submit.bReplyPath = pReqInfo->sendOptInfo.option.smsSendOptInfo.bReplyPath;
-       }
+       setSmsSendOption(pReqInfo, &tpdu);
 
-       // Set Coding Scheme for apps that use port number
-       if (pReqInfo->msgInfo.msgPort.valid == true)
-       {
-               tpdu.data.submit.dcs.codingScheme = (SMS_CODING_SCHEME_T)pReqInfo->msgInfo.encodeType;
+       // Set coding scheme
+       setSmsDcsOption(pReqInfo, &tpdu);
 
-               MSG_DEBUG("DCS is changed by application : [%d]", tpdu.data.submit.dcs.codingScheme);
-       }
+       // Set SMS report request
+       setSmsReportOption(pReqInfo, &tpdu);
 
        // Set SMSC Options
-       SMS_ADDRESS_S smsc;
-       setSmscOptions(&smsc);
-       int i = 0;
-       int j = 0;
+       SMS_ADDRESS_S smsc = {0,};
+       setSmscOptions(pReqInfo->msgInfo.sim_idx, &smsc);
 
+       // Get TAPI handle
+       struct tapi_handle *handle = SmsPluginDSHandler::instance()->getTelHandle(pReqInfo->msgInfo.sim_idx);
+
+       // Get address informations.
+       MsgDbHandler *dbHandle = getDbHandle();
+       MsgStoGetAddressByMsgId(dbHandle, pReqInfo->msgInfo.msgId, 0, &pReqInfo->msgInfo.nAddressCnt, &pReqInfo->msgInfo.addressList);
        MSG_DEBUG("pReqInfo->msgInfo.nAddressCnt [%d]", pReqInfo->msgInfo.nAddressCnt);
 
-       for (i = 0; i < pReqInfo->msgInfo.nAddressCnt; i++)
+       // Get MSISDN
+       char *msisdn = NULL;
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_MSISDN, pReqInfo->msgInfo.sim_idx);
+       msisdn = MsgSettingGetString(keyName);
+
+       for (int i = 0; i < pReqInfo->msgInfo.nAddressCnt; i++)
        {
                // Make SMS_SUBMIT_DATA_S from MSG_REQUEST_INFO_S
                SMS_SUBMIT_DATA_S submitData = {{0},};
                msgInfoToSubmitData(&(pReqInfo->msgInfo), &submitData, &(tpdu.data.submit.dcs.codingScheme), i);
 
+               // Insert message reference into db
+               if (tpdu.data.submit.bStatusReport == true) {
+                       SmsPluginStorage::instance()->insertMsgRef(&(pReqInfo->msgInfo), tpdu.data.submit.msgRef, i);
+               }
+
                // Encode SMSC Address
                unsigned char smscAddr[MAX_SMSC_LEN];
                memset(smscAddr, 0x00, sizeof(smscAddr));
 
                int smscLen = SmsPluginParamCodec::encodeSMSC(&smsc, smscAddr);
 
-               if (smscLen <= 0) return;
+               if (smscLen <= 0) {
+                       MSG_DEBUG("smscLen <= 0");
+                       goto _RETURN_FUNC;
+               }
 
-               for (j = 0; j < smscLen; j++)
-               {
-                       MSG_DEBUG("pSCAInfo [%02x]", smscAddr[j]);
+               char smscAddrTmp[(smscLen*2)+1];
+               memset(smscAddrTmp, 0x00, sizeof(smscAddrTmp));
+               for (int j = 0; j < smscLen; j++) {
+                       snprintf(smscAddrTmp+(j*2), sizeof(smscAddrTmp)-(j*2), "%02X", smscAddr[j]);
                }
+               MSG_DEBUG("pSCAInfo [%s]", smscAddrTmp);
 
-               int bufLen = 0, reqId = 0;
+               int bufLen = 0;
 
                char buf[MAX_TPDU_DATA_LEN];
 
@@ -134,103 +154,242 @@ void SmsPluginTransport::submitRequest(SMS_REQUEST_INFO_S *pReqInfo)
                        memcpy(tpdu.data.submit.destAddress.address, submitData.destAddress.address, addLen);
                        tpdu.data.submit.destAddress.address[addLen] = '\0';
                } else {
-                       memcpy(tpdu.data.submit.destAddress.address, submitData.destAddress.address, MAX_ADDRESS_LEN);
+                       if (submitData.destAddress.address[0] == '+')
+                               memcpy(tpdu.data.submit.destAddress.address, submitData.destAddress.address, MAX_ADDRESS_LEN);
+                       else
+                               memcpy(tpdu.data.submit.destAddress.address, submitData.destAddress.address, MAX_ADDRESS_LEN-1);
+
                        tpdu.data.submit.destAddress.address[MAX_ADDRESS_LEN] = '\0';
                }
 
+MSG_DEBUG("ton [%d]", tpdu.data.submit.destAddress.ton);
+MSG_DEBUG("npi [%d]", tpdu.data.submit.destAddress.npi);
+MSG_SEC_DEBUG("address [%s]", tpdu.data.submit.destAddress.address);
+
+               bool bStatusReport = false;
+
                for (unsigned int segCnt = 0; segCnt < submitData.segCount; segCnt++)
                {
-                       if (submitData.userData[segCnt].headerCnt > 0)
-                       {
+                       if (submitData.userData[segCnt].headerCnt > 0) {
                                tpdu.data.submit.bHeaderInd = true;
-                       }
-                       else
-                       {
+                       } else {
                                tpdu.data.submit.bHeaderInd = false;
                        }
 
+                       if (segCnt == 0 && submitData.segCount > 1) {
+                               bStatusReport = tpdu.data.submit.bStatusReport;
+                               tpdu.data.submit.bStatusReport = false;
+                       } else if ((segCnt+1 == submitData.segCount) && submitData.segCount > 1) {
+                               tpdu.data.submit.bStatusReport = bStatusReport;
+                       }
+
                        memset(&(tpdu.data.submit.userData), 0x00, sizeof(SMS_USERDATA_S));
                        memcpy(&(tpdu.data.submit.userData), &(submitData.userData[segCnt]), sizeof(SMS_USERDATA_S));
 
-                       // Encode SMS-SUBMIT TPDU
-                       memset(buf, 0x00, sizeof(buf));
-
-                       bufLen = SmsPluginTpduCodec::encodeTpdu(&tpdu, buf);
+                       SMS_NETWORK_STATUS_T retStatus = SMS_NETWORK_SENDING;
 
-                       // Make Telephony Structure
-                       TelSmsDatapackageInfo_t pkgInfo;
+                       bool bMoreMsg = false;
 
-                       // Set TPDU data
-                       memset((void*)pkgInfo.szData, 0x00, sizeof(pkgInfo.szData));
-                       memcpy((void*)pkgInfo.szData, buf, bufLen);
+                       int retMoCtrlStatus = TAPI_SAT_CALL_CTRL_R_ALLOWED_NO_MOD;
+                       bool bRetryByMoCtrl = false;
+                       bool bSatMoCtrl = false;
 
-                       pkgInfo.szData[bufLen] = 0;
-                       pkgInfo.MsgLength = bufLen;
 
-                       // Set SMSC data
-                       memset(pkgInfo.Sca, 0x00, sizeof(pkgInfo.Sca));
-                       memcpy((void*)pkgInfo.Sca, smscAddr, smscLen);
-                       pkgInfo.Sca[smscLen] = '\0';
+                       for (int cnt = 0; cnt < MAX_SMS_SEND_RETRY; ++cnt)
+                       {
+                               // Encode SMS-SUBMIT TPDU
+                               memset(buf, 0x00, sizeof(buf));
 
-                       SMS_SENT_INFO_S sentInfo = {};
+                               if (cnt > 0)
+                                       tpdu.data.submit.bRejectDup = true;
 
-                       bool bMoreMsg = FALSE;
+                               bufLen = SmsPluginTpduCodec::encodeTpdu(&tpdu, buf);
 
-                       memcpy(&(sentInfo.reqInfo), pReqInfo, sizeof(SMS_REQUEST_INFO_S));
+                               // Make Telephony Structure
+                               TelSmsDatapackageInfo_t pkgInfo;
 
-                       if ((segCnt+1) == submitData.segCount && (i+1)==pReqInfo->msgInfo.nAddressCnt)
-                       {
-                               sentInfo.bLast = true;
+                               // Set TPDU data
+                               memset((void*)pkgInfo.szData, 0x00, sizeof(pkgInfo.szData));
+                               memcpy((void*)pkgInfo.szData, buf, bufLen);
 
-                               bMoreMsg = FALSE;
-                       }
-                       else
-                       {
-                               sentInfo.bLast = false;
+                               pkgInfo.szData[bufLen] = 0;
+                               pkgInfo.MsgLength = bufLen;
+                               pkgInfo.format = TAPI_NETTEXT_NETTYPE_3GPP;
 
-                               bMoreMsg = TRUE;
-                       }
+                               // Set SMSC data
+                               memset(pkgInfo.Sca, 0x00, sizeof(pkgInfo.Sca));
+                               memcpy((void*)pkgInfo.Sca, smscAddr, smscLen);
+                               pkgInfo.Sca[smscLen] = '\0';
 
-                       SmsPluginEventHandler::instance()->SetSentInfo(&sentInfo);
 
-                       curStatus = MSG_NETWORK_SENDING;
+                               char pkgInfoTmp[(pkgInfo.MsgLength*2)+1];
+                               memset(pkgInfoTmp, 0x00, sizeof(pkgInfoTmp));
+                               for (int j = 0; j < pkgInfo.MsgLength; j++) {
+                                       snprintf(pkgInfoTmp+(j*2), sizeof(pkgInfoTmp)-(j*2), "%02X", pkgInfo.szData[j]);
+                               }
+                               MSG_INFO("Submit Request TPDU. try cnt : %d", cnt+1);
+                               MSG_INFO("[%s]", pkgInfoTmp);
 
-                       // Send SMS
-                       int tapiRet = TAPI_API_SUCCESS;
+                               SMS_SENT_INFO_S sentInfo;
+                               memset(&sentInfo, 0x00, sizeof(SMS_SENT_INFO_S));
 
-                       tapiRet = tel_send_sms(pTapiHandle, &pkgInfo, bMoreMsg, TapiEventSentStatus, NULL);
+                               bMoreMsg = FALSE;
 
-                       if (tapiRet == TAPI_API_SUCCESS)
-                       {
-                               MSG_DEBUG("########  TelTapiSmsSend Success !!! req Id : [%d] return : [%d] #######", reqId, tapiRet);
+                               memcpy(&(sentInfo.reqInfo), pReqInfo, sizeof(SMS_REQUEST_INFO_S));
+
+                               if ((segCnt+1) == submitData.segCount && (i+1)==pReqInfo->msgInfo.nAddressCnt)
+                               {
+                                       sentInfo.bLast = true;
+                                       bMoreMsg = FALSE;
+                               }
+                               else
+                               {
+                                       sentInfo.bLast = false;
+                                       bMoreMsg = TRUE;
+                               }
+
+                               SmsPluginEventHandler::instance()->SetSentInfo(&sentInfo);
+
+                               curStatus = SMS_NETWORK_SENDING;
+
+                               // Send SMS
+                               int tapiRet = TAPI_API_SUCCESS;
+
+                               tapiRet = tel_send_sms(handle, &pkgInfo, bMoreMsg, TapiEventSentStatus, (void *)&curMoCtrlData);
+
+                               if (tapiRet == TAPI_API_SUCCESS)
+                               {
+                                       MSG_DEBUG("########  tel_send_sms Success !!! return : [%d] #######", tapiRet);
+
+                                       memset(keyName, 0x00, sizeof(keyName));
+                                       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_MO_CONTROL, pReqInfo->msgInfo.sim_idx);
+                                       if (MsgSettingGetBool(keyName, &bSatMoCtrl) != MSG_SUCCESS)
+                                               MSG_DEBUG("MsgSettingGetBool [%s] failed", keyName);
+
+                                       if (bSatMoCtrl) {
+                                               // Get SAT MO SM control
+                                               retMoCtrlStatus = getMoCtrlStatus();
+                                               MSG_DEBUG("retMoCtrlStatus  = [%d]", retMoCtrlStatus);
+
+                                               if (retMoCtrlStatus == TAPI_SAT_CALL_CTRL_R_ALLOWED_WITH_MOD) {
+
+                                                       if (bRetryByMoCtrl == false) {
+                                                               bRetryByMoCtrl = true;
+
+                                                               // Modify Address with control data
+                                                               memset(smsc.address, 0x00, sizeof(smsc.address));
+                                                               memcpy(smsc.address, curMoCtrlData.rpDestAddr.string, sizeof(smsc.address)-1);
+
+                                                               memset(smscAddr, 0x00, sizeof(smscAddr));
+                                                               smscLen = SmsPluginParamCodec::encodeSMSC(&smsc, smscAddr);
+
+                                                               MSG_SEC_DEBUG("SMSC address=[%s], Encoded length=[%d]", smsc.address, smscLen);
+
+                                                               if (curMoCtrlData.tpDestAddr.stringLen < MAX_ADDRESS_LEN) {
+                                                                       memcpy(tpdu.data.submit.destAddress.address, curMoCtrlData.tpDestAddr.string, curMoCtrlData.tpDestAddr.stringLen);
+                                                                       tpdu.data.submit.destAddress.address[curMoCtrlData.tpDestAddr.stringLen] = '\0';
+                                                               } else {
+                                                                       memcpy(tpdu.data.submit.destAddress.address, submitData.destAddress.address, MAX_ADDRESS_LEN);
+                                                                       tpdu.data.submit.destAddress.address[MAX_ADDRESS_LEN] = '\0';
+                                                               }
+                                                       } else {
+                                                               curMoCtrlData.moSmsCtrlResult = TAPI_SAT_CALL_CTRL_R_NOT_ALLOWED;
+                                                       }
+                                               }
+                                       }
+                               }
+                               else
+                               {
+                                       SmsPluginEventHandler::instance()->handleSentStatus(MSG_NETWORK_SEND_FAIL);
+
+                                       if (msisdn) {
+                                               free(msisdn);
+                                               msisdn = NULL;
+                                       }
+                                       THROW(MsgException::SMS_PLG_ERROR, "########  tel_send_sms Fail !!! return : [%d] #######", tapiRet);
+                               }
+
+                               // Tizen Validation System
+                               MSG_SMS_VLD_INFO("%d, SMS Send Start, %s->%s, %s",  pReqInfo->msgInfo.msgId, \
+                                                                                                                                                       (msisdn == NULL)?"ME":msisdn, \
+                                                                                                                                                       pReqInfo->msgInfo.addressList[0].addressVal, \
+                                                                                                                                                       (tapiRet == TAPI_API_SUCCESS)?"Success":"Fail");
+
+                               MSG_SMS_VLD_TXT("%d, [%s]", pReqInfo->msgInfo.msgId, pReqInfo->msgInfo.msgText);
+
+                               retStatus = getNetStatus();
+
+                               if (retStatus != SMS_NETWORK_SEND_FAIL_TEMPORARY && retStatus != SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_WITH_MOD)
+                                       break;
                        }
-                       else
+
+#ifdef MSG_SMS_REPORT
+                       if (err == MSG_SUCCESS && tmpInfo.msgInfo.msgPort.valid == false)
                        {
-                               SmsPluginEventHandler::instance()->handleSentStatus(MSG_NETWORK_SEND_FAIL);
-                               THROW(MsgException::SMS_PLG_ERROR, "########  TelTapiSmsSend Fail !!! req Id : [%d] return : [%d] #######", reqId, tapiRet);
+                               if(pReqInfo->sendOptInfo.bDeliverReq == true)
+                               {
+                                       MSG_DEBUG("Update Delivery Report Status : [%d] Msg ID : [%d]", err, tmpInfo.msgInfo.msgId);
+
+                                       // Adding delivery report status info.
+                                       MsgStoAddDeliveryReportStatus( tmpInfo.msgInfo.msgId, (unsigned char)tmpInfo.msgInfo.referenceId);
+                               }
                        }
+#endif
 
-                       msg_network_status_t retStatus = getNetStatus();
+                       MSG_SMS_VLD_INFO("%d, SMS Send End, %s->%s, %s",  pReqInfo->msgInfo.msgId, \
+                                                                                                                                       (msisdn == NULL)?"ME":msisdn, \
+                                                                                                                                       pReqInfo->msgInfo.addressList[0].addressVal, \
+                                                                                                                                       (retStatus == SMS_NETWORK_SEND_SUCCESS)?"Success":"Fail");
 
-                       if (retStatus == MSG_NETWORK_SEND_SUCCESS)
+                       if (retStatus == SMS_NETWORK_SEND_SUCCESS)
                        {
-                               MSG_DEBUG("########  Msg Sent was Successful !!! req Id : [%d] return : [%d] #######", reqId, retStatus);
+                               bool bTTS = false;
+
+                               if (MsgSettingGetBool(VCONFKEY_SETAPPL_ACCESSIBILITY_TTS, &bTTS) != MSG_SUCCESS) {
+                                       MSG_DEBUG("MsgSettingGetBool is failed.");
+                               }
+
+                               if (bTTS) {
+                                       if (bMoreMsg == false) {
+                                               MsgInsertTicker("SMS is sent", SMS_MESSAGE_SENT, false, 0);
+                                       }
+                                       MSG_DEBUG("########  Msg Sent was Successful !!! #######");
+                               }
                        }
                        else
                        {
-                               SmsPluginEventHandler::instance()->handleSentStatus(MSG_NETWORK_SEND_FAIL);
-                               THROW(MsgException::SMS_PLG_ERROR, "########  Msg Sent was Failed !!! req Id : [%d] return : [%d] #######", reqId, retStatus);
+                               if (retStatus == SMS_NETWORK_SEND_FAIL_TIMEOUT || retStatus == SMS_NETWORK_SEND_FAIL_TEMPORARY || retStatus == SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_WITH_MOD)
+                                       SmsPluginEventHandler::instance()->handleSentStatus(MSG_NETWORK_SEND_FAIL);
+
+                               if (retStatus == SMS_NETWORK_SEND_FAIL_FDN_RESTRICED) {
+                                       MsgInsertTicker("Unable to send the message while Fixed dialling mode is enabled", SMS_FDN_RESTRICTED, true, 0);
+                               } else {
+                                       MsgInsertTicker("Sending SMS is failed", SMS_MESSAGE_SENDING_FAIL, true, pReqInfo->msgInfo.msgId);
+                               }
+
+                               if (msisdn) {
+                                       free(msisdn);
+                                       msisdn = NULL;
+                               }
+                               THROW(MsgException::SMS_PLG_ERROR, "########  Msg Sent was Failed !!! return : [%d] #######", retStatus);
                        }
 
                        if (tpdu.data.submit.userData.headerCnt > 0) tpdu.data.submit.userData.headerCnt--;
+
                }
        }
 
+_RETURN_FUNC :
+       if (msisdn) {
+               free(msisdn);
+               msisdn = NULL;
+       }
        MSG_END();
+       return;
 }
 
 
-void SmsPluginTransport::sendDeliverReport(msg_error_t err)
+void SmsPluginTransport::sendDeliverReport(struct tapi_handle *handle, msg_error_t err)
 {
        MSG_BEGIN();
 
@@ -240,56 +399,206 @@ void SmsPluginTransport::sendDeliverReport(msg_error_t err)
 
        TelSmsResponse_t response;
 
-       int tapiRet = TAPI_API_SUCCESS, reqId = 0;
+       int tapiRet = TAPI_API_SUCCESS;
+
+       int simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
 
        if (err == MSG_SUCCESS)
        {
                tpdu.data.deliverRep.reportType = SMS_REPORT_POSITIVE;
                response = TAPI_NETTEXT_SENDSMS_SUCCESS;
 
-               tapiRet = tel_set_sms_memory_status(pTapiHandle, TAPI_NETTEXT_PDA_MEMORY_STATUS_AVAILABLE, NULL, NULL);
+               if(isMemAvailable == false)
+               {
+                       tapiRet = tel_set_sms_memory_status(handle, TAPI_NETTEXT_PDA_MEMORY_STATUS_AVAILABLE, TapiEventMemoryStatus, NULL);
+
+                       if (tapiRet == TAPI_API_SUCCESS)
+                       {
+                               MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
+                       }
+                       else
+                       {
+                               MSG_DEBUG("########  tel_set_sms_memory_status() Failed !!! return : [%d] #######", tapiRet);
+                       }
+               }
+       }
+       else if (err == MSG_ERR_SIM_STORAGE_FULL)
+       {
+               tpdu.data.deliverRep.reportType = SMS_REPORT_NEGATIVE;
+               tpdu.data.deliverRep.failCause = SMS_FC_SIM_STORAGE_FULL;
+
+               response = TAPI_NETTEXT_SIM_FULL;
+               MsgInsertTicker("Sim memory full. Delete some items", SMS_MESSAGE_SIM_MESSAGE_FULL, true, 0);
+
+#if 0
+               tapiRet = tel_set_sms_memory_status(handle, TAPI_NETTEXT_PDA_MEMORY_STATUS_FULL, TapiEventMemoryStatus, NULL);
 
                if (tapiRet == TAPI_API_SUCCESS)
                {
-                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! req Id : [%d] #######", reqId);
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
                }
                else
                {
-                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! req Id : [%d] return : [%d] #######", reqId, tapiRet);
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Failed !!! return : [%d] #######", tapiRet);
                }
+#endif
        }
-       else if (err == MSG_ERR_SIM_STORAGE_FULL)
+       else if (err == MSG_ERR_MESSAGE_COUNT_FULL)
        {
                tpdu.data.deliverRep.reportType = SMS_REPORT_NEGATIVE;
                tpdu.data.deliverRep.failCause = SMS_FC_MSG_CAPA_EXCEEDED;
+               response = TAPI_NETTEXT_ME_FULL;
+               MsgInsertTicker("Not enough memory. Delete some items.", SMS_MESSAGE_MEMORY_FULL, true, 0);
+               tapiRet = tel_set_sms_memory_status(handle, TAPI_NETTEXT_PDA_MEMORY_STATUS_FULL, TapiEventMemoryStatus, NULL);
+
+               if (tapiRet == TAPI_API_SUCCESS)
+               {
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
+               }
+               else
+               {
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Failed !!! return : [%d] #######", tapiRet);
+               }
+       }
+       else
+       {
+               tpdu.data.deliverRep.reportType = SMS_REPORT_NEGATIVE;
+               tpdu.data.deliverRep.failCause = SMS_FC_UNSPEC_ERROR;
+               //response = TAPI_NETTEXT_PROTOCOL_ERROR;
+               // For gcf test [34.2.5.3 class2 message]
                response = TAPI_NETTEXT_SIM_FULL;
 
-               tapiRet = tel_set_sms_memory_status(pTapiHandle, TAPI_NETTEXT_PDA_MEMORY_STATUS_FULL, NULL, NULL);
+       }
+
+       MSG_DEBUG("err : [%d], response : [%02x]", err, response);
+
+       tpdu.data.deliverRep.bHeaderInd = false;
+       tpdu.data.deliverRep.paramInd = 0x00;
+
+       // Encode SMS-DELIVER-REPORT TPDU
+       int bufLen = 0;
+
+       char buf[MAX_TPDU_DATA_LEN];
+       memset(buf, 0x00, sizeof(buf));
+
+       bufLen = SmsPluginTpduCodec::encodeTpdu(&tpdu, buf);
+
+#ifdef MSG_FOR_DEBUG
+       /////// print DeliverReport tpdu
+       printf("\n\n######## DeliverReport tpdu #########\n");
+       for(int i=0; i < bufLen; i++)
+       {
+               printf("[%02x] ", buf[i]);
+       }
+       printf("\n#################################\n\n");
+       //////
+#endif
+
+       // Make Telephony Structure
+       TelSmsDatapackageInfo_t pkgInfo;
+
+       // Set TPDU data
+       memset((void*)pkgInfo.szData, 0x00, sizeof(pkgInfo.szData));
+       memcpy((void*)pkgInfo.szData, buf, bufLen);
+
+       pkgInfo.szData[bufLen] = 0;
+       pkgInfo.MsgLength = bufLen;
+       pkgInfo.format = TAPI_NETTEXT_NETTYPE_3GPP;
+
+       // Set SMSC Address
+       SMS_ADDRESS_S smsc;
+
+       // Set SMSC Options
+       setSmscOptions(simIndex, &smsc);
+
+       // Encode SMSC Address
+       unsigned char smscAddr[MAX_SMSC_LEN];
+       memset(smscAddr, 0x00, sizeof(smscAddr));
+
+       int smscLen = SmsPluginParamCodec::encodeSMSC(&smsc, smscAddr);
+
+       if (smscLen <= 0) return;
+
+       // Set SMSC data
+       memset(pkgInfo.Sca, 0x00, sizeof(pkgInfo.Sca));
+       memcpy((void*)pkgInfo.Sca, smscAddr, smscLen);
+       pkgInfo.Sca[smscLen] = '\0';
+
+       // Send Deliver Report
+       tapiRet = tel_send_sms_deliver_report(handle, &pkgInfo, response, TapiEventDeliveryReportCNF, NULL);
+
+       if (tapiRet == TAPI_API_SUCCESS)
+       {
+               MSG_DEBUG("########  tel_send_sms_deliver_report() Success !!! #######");
+       }
+       else
+       {
+               MSG_DEBUG("########  tel_send_sms_deliver_report() Fail !!! return : [%d] #######", tapiRet);
+       }
+
+       MSG_END();
+}
+
+void SmsPluginTransport::sendClass0DeliverReport(struct tapi_handle *handle, msg_error_t err)
+{
+       MSG_BEGIN();
+
+       SMS_TPDU_S tpdu;
+
+       tpdu.tpduType = SMS_TPDU_DELIVER_REP;
+
+       TelSmsResponse_t response;
+
+       int tapiRet = TAPI_API_SUCCESS;
+
+       int simIndex = SmsPluginDSHandler::instance()->getSimIndex(handle);
+
+       if (err == MSG_SUCCESS)
+       {
+               tpdu.data.deliverRep.reportType = SMS_REPORT_POSITIVE;
+               response = TAPI_NETTEXT_SENDSMS_SUCCESS;
+
+               tapiRet = tel_set_sms_memory_status(handle, TAPI_NETTEXT_PDA_MEMORY_STATUS_AVAILABLE, TapiEventMemoryStatus, NULL);
+
+               if (tapiRet == TAPI_API_SUCCESS)
+               {
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
+               }
+               else
+               {
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Failed !!! return : [%d] #######", tapiRet);
+               }
+       }
+       else if (err == MSG_ERR_SIM_STORAGE_FULL)
+       {
+               tpdu.data.deliverRep.reportType = SMS_REPORT_POSITIVE;
+               response = TAPI_NETTEXT_SENDSMS_SUCCESS;
+
+               tapiRet = tel_set_sms_memory_status(handle, TAPI_NETTEXT_PDA_MEMORY_STATUS_FULL, TapiEventMemoryStatus, NULL);
 
                if (tapiRet == TAPI_API_SUCCESS)
                {
-                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! req Id : [%d] #######", reqId);
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
                }
                else
                {
-                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! req Id : [%d] return : [%d] #######", reqId, tapiRet);
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Failed !!! return : [%d] #######", tapiRet);
                }
        }
        else if (err == MSG_ERR_MESSAGE_COUNT_FULL)
        {
-               tpdu.data.deliverRep.reportType = SMS_REPORT_NEGATIVE;
-               tpdu.data.deliverRep.failCause = SMS_FC_MSG_CAPA_EXCEEDED;
-               response = TAPI_NETTEXT_ME_FULL;
+               tpdu.data.deliverRep.reportType = SMS_REPORT_POSITIVE;
+               response = TAPI_NETTEXT_SENDSMS_SUCCESS;
 
-               tapiRet = tel_set_sms_memory_status(pTapiHandle, TAPI_NETTEXT_PDA_MEMORY_STATUS_FULL, NULL, NULL);
+               tapiRet = tel_set_sms_memory_status(handle, TAPI_NETTEXT_PDA_MEMORY_STATUS_FULL, TapiEventMemoryStatus, NULL);
 
                if (tapiRet == TAPI_API_SUCCESS)
                {
-                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! req Id : [%d] #######", reqId);
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! #######");
                }
                else
                {
-                       MSG_DEBUG("########  tel_set_sms_memory_status() Success !!! req Id : [%d] return : [%d] #######", reqId, tapiRet);
+                       MSG_DEBUG("########  tel_set_sms_memory_status() Failed !!! return : [%d] #######", tapiRet);
                }
        }
        else
@@ -324,12 +633,13 @@ void SmsPluginTransport::sendDeliverReport(msg_error_t err)
 
        pkgInfo.szData[bufLen] = 0;
        pkgInfo.MsgLength = bufLen;
+       pkgInfo.format = TAPI_NETTEXT_NETTYPE_3GPP;
 
        // Set SMSC Address
        SMS_ADDRESS_S smsc;
 
        // Set SMSC Options
-       setSmscOptions(&smsc);
+       setSmscOptions(simIndex, &smsc);
 
        // Encode SMSC Address
        unsigned char smscAddr[MAX_SMSC_LEN];
@@ -345,22 +655,22 @@ void SmsPluginTransport::sendDeliverReport(msg_error_t err)
        pkgInfo.Sca[smscLen] = '\0';
 
        // Send Deliver Report
-       tapiRet = tel_send_sms_deliver_report(pTapiHandle, &pkgInfo, response, TapiEventDeliveryReportCNF, NULL);
+       tapiRet = tel_send_sms_deliver_report(handle, &pkgInfo, response, TapiEventDeliveryReportCNF, NULL);
 
        if (tapiRet == TAPI_API_SUCCESS)
        {
-               MSG_DEBUG("########  tel_send_sms_deliver_report() Success !!! req Id : [%d] #######", reqId);
+               MSG_DEBUG("########  tel_send_sms_deliver_report() Success !!! #######");
        }
        else
        {
-               MSG_DEBUG("########  tel_send_sms_deliver_report() Fail !!! req Id : [%d] return : [%d] #######", reqId, tapiRet);
+               MSG_DEBUG("########  tel_send_sms_deliver_report() Fail !!! return : [%d] #######", tapiRet);
        }
 
        MSG_END();
 }
 
 
-void SmsPluginTransport::setSmsSendOptions(SMS_SUBMIT_S *pSubmit)
+void SmsPluginTransport::getSmsSendOption(int simIndex, SMS_SUBMIT_S *pSubmit)
 {
        // Set SMS Send Options
        pSubmit->bRejectDup = false;
@@ -379,78 +689,115 @@ void SmsPluginTransport::setSmsSendOptions(SMS_SUBMIT_S *pSubmit)
 
        MSG_DEBUG("DCS : %d", pSubmit->dcs.codingScheme);
 
-       int selectIdx = MsgSettingGetInt(SMSC_SELECTED);
+       MSG_SMSC_LIST_S smscList = {0,};
+       SmsPluginSetting::instance()->getSmscListInfo(simIndex, &smscList);
 
-       char keyName[128];
+       int selectIdx = smscList.selected;
+       int valPeriod = 0;
 
-       memset(keyName, 0x00, sizeof(keyName));
-       sprintf(keyName, "%s/%d", SMSC_PID, selectIdx);
-       MSG_SMS_PID_T pid = (MSG_SMS_PID_T)MsgSettingGetInt(keyName);
+       if (selectIdx < SMSC_LIST_MAX) {
+               MSG_SMS_PID_T pid = smscList.smscData[selectIdx].pid;
+               pSubmit->pid = convertPid(pid);
+
+               valPeriod = smscList.smscData[selectIdx].valPeriod;
+       } else {
+               MSG_WARN("Invalid case");
+               pSubmit->pid = SMS_PID_NORMAL;
+               valPeriod = 255;
+       }
 
-       pSubmit->pid = convertPid(pid);
        MSG_DEBUG("PID : %d", pSubmit->pid);
 
-       memset(keyName, 0x00, sizeof(keyName));
-       sprintf(keyName, "%s/%d", SMSC_VAL_PERIOD, selectIdx);
-       int valPeriod = MsgSettingGetInt(keyName);
+       pSubmit->vpf = SMS_VPF_NOT_PRESENT; // default value
 
        MSG_DEBUG("valPeriod : %d", valPeriod);
+       MSG_DEBUG("vpf : %d", pSubmit->vpf);
+}
 
-       if (valPeriod == 0)
-       {
-               pSubmit->vpf = SMS_VPF_NOT_PRESENT;
+
+void SmsPluginTransport::setSmsSendOption(SMS_REQUEST_INFO_S *pReqInfo, SMS_TPDU_S* pSmsTpdu)
+{
+       if (!pReqInfo || !pSmsTpdu) {
+               MSG_DEBUG("Input param is NULL");
+               return;
        }
-       else
+
+       if (pReqInfo->sendOptInfo.bSetting == true)
        {
-               pSubmit->vpf = SMS_VPF_RELATIVE;
-               pSubmit->validityPeriod.format = SMS_TIME_RELATIVE;
-               pSubmit->validityPeriod.time.relative.time = valPeriod;
+               pSmsTpdu->data.submit.bStatusReport = pReqInfo->sendOptInfo.bDeliverReq;
+               pSmsTpdu->data.submit.bReplyPath = pReqInfo->sendOptInfo.option.smsSendOptInfo.bReplyPath;
        }
 }
 
 
-void SmsPluginTransport::setSmscOptions(SMS_ADDRESS_S *pSmsc)
+void SmsPluginTransport::setSmsDcsOption(SMS_REQUEST_INFO_S *pReqInfo, SMS_TPDU_S* pSmsTpdu)
 {
-       // Set SMSC Options
-       int selectIdx = MsgSettingGetInt(SMSC_SELECTED);
-
-       char keyName[128];
+       if (!pReqInfo || !pSmsTpdu) {
+               MSG_DEBUG("Input param is NULL");
+               return;
+       }
 
-       memset(keyName, 0x00, sizeof(keyName));
-       sprintf(keyName, "%s/%d", SMSC_ADDRESS, selectIdx);
+       if (pReqInfo->msgInfo.msgPort.valid == true) {
+               // Set Coding Scheme for apps that use port number
+               pSmsTpdu->data.submit.dcs.codingScheme = (SMS_CODING_SCHEME_T)pReqInfo->msgInfo.encodeType;
+               MSG_DEBUG("DCS is changed by application : [%d]", pSmsTpdu->data.submit.dcs.codingScheme);
+       } else {
+               // Change coding scheme if it is set coding scheme by apps
+               if (pSmsTpdu->data.submit.dcs.codingScheme == SMS_CHARSET_7BIT && pReqInfo->msgInfo.encodeType != MSG_ENCODE_GSM7BIT) {
+                       pSmsTpdu->data.submit.dcs.codingScheme = (SMS_CODING_SCHEME_T)pReqInfo->msgInfo.encodeType;
+                       MSG_DEBUG("DCS is changed by application : [%d]", pSmsTpdu->data.submit.dcs.codingScheme);
+               }
+       }
+}
 
-       char* tmpValue = NULL;
 
-       tmpValue = MsgSettingGetString(keyName);
+void SmsPluginTransport::setSmsReportOption(SMS_REQUEST_INFO_S *pReqInfo, SMS_TPDU_S* pSmsTpdu)
+{
+       if (!pReqInfo || !pSmsTpdu) {
+               MSG_DEBUG("Input param is NULL");
+               return;
+       }
 
-       if (tmpValue != NULL)
+#ifdef MSG_SMS_REPORT
+       // Update Msg Ref into Report Table
+       if (pSmsTpdu->data.submit.bStatusReport == true)
        {
-               memset(pSmsc->address, 0x00, sizeof(pSmsc->address));
-               strncpy(pSmsc->address, tmpValue, MAX_ADDRESS_LEN);
+               MSG_DEBUG("Update Msg Ref [%d] in Report Table", pSmsTpdu->data.submit.msgRef);
 
-               MSG_DEBUG("address : %s", pSmsc->address);
+               SmsPluginStorage::instance()->updateMsgRef(pReqInfo->msgInfo.msgId, pSmsTpdu->data.submit.msgRef);
        }
-       else
-       {
-               strncpy(pSmsc->address, "+8210911111", MAX_ADDRESS_LEN);
+#endif
+
+       // Set Message Reference
+       if (pSmsTpdu->data.submit.bStatusReport == true) {
+               pSmsTpdu->data.submit.msgRef = (pReqInfo->msgInfo.msgId % 256);
        }
+}
 
-       memset(keyName, 0x00, sizeof(keyName));
-       sprintf(keyName, "%s/%d", SMSC_TON, selectIdx);
-       pSmsc->ton = (SMS_TON_T)MsgSettingGetInt(keyName);
 
-       MSG_DEBUG("ton : %d", pSmsc->ton);
+void SmsPluginTransport::setSmscOptions(int simIndex, SMS_ADDRESS_S *pSmsc)
+{
+       // Set SMSC Options
+       MSG_SMSC_LIST_S smscList = {0,};
+       SmsPluginSetting::instance()->getSmscListInfo(simIndex, &smscList);
+
+       int selectIdx = smscList.selected;
 
-       memset(keyName, 0x00, sizeof(keyName));
-       sprintf(keyName, "%s/%d", SMSC_NPI, selectIdx);
-       pSmsc->npi = (SMS_NPI_T)MsgSettingGetInt(keyName);
+       if (selectIdx < SMSC_LIST_MAX) {
+               if (smscList.smscData[selectIdx].smscAddr.address[0] != '\0') {
+                       memset(pSmsc->address, 0x00, sizeof(pSmsc->address));
+                       strncpy(pSmsc->address, smscList.smscData[selectIdx].smscAddr.address, MAX_ADDRESS_LEN);
 
-       MSG_DEBUG("npi : %d", pSmsc->npi);
+                       MSG_SEC_DEBUG("address : %s", pSmsc->address);
+               } else {
+                       memset(pSmsc->address, 0x00, MAX_ADDRESS_LEN);
+               }
 
-       if (tmpValue != NULL)
-       {
-               free(tmpValue);
-               tmpValue = NULL;
+               pSmsc->ton = (SMS_TON_T)smscList.smscData[selectIdx].smscAddr.ton;
+               MSG_DEBUG("ton : %d", pSmsc->ton);
+
+               pSmsc->npi = (SMS_NPI_T)smscList.smscData[selectIdx].smscAddr.npi;
+               MSG_DEBUG("npi : %d", pSmsc->npi);
        }
 }
 
@@ -466,23 +813,27 @@ void SmsPluginTransport::msgInfoToSubmitData(const MSG_MESSAGE_INFO_S *pMsgInfo,
 
        MSG_DEBUG("ton [%d]", pData->destAddress.ton);
        MSG_DEBUG("npi [%d]", pData->destAddress.npi);
-       MSG_DEBUG("address [%s]", pData->destAddress.address);
+       MSG_SEC_DEBUG("address [%s]", pData->destAddress.address);
 
        int decodeLen = 0, bufSize = (MAX_GSM_7BIT_DATA_LEN*MAX_SEGMENT_NUM) + 1;       // SMS_CHARSET_7BIT
 
        unsigned char decodeData[bufSize];
        memset(decodeData, 0x00, sizeof(decodeData));
 
+       MsgTextConvert *textCvt = MsgTextConvert::instance();
+
        msg_encode_type_t encodeType = MSG_ENCODE_GSM7BIT;
 
-       SMS_LANGUAGE_ID_T langId = SMS_LANG_ID_RESERVED;
+       MSG_LANGUAGE_ID_T langId = MSG_LANG_ID_RESERVED;
+
+       bool bAbnormal = false;
 
        // User Data
        if (pMsgInfo->bTextSms == true)
        {
                if (*pCharType == SMS_CHARSET_7BIT)
                {
-                       decodeLen = SmsPluginTextConvert::instance()->convertUTF8ToGSM7bit(decodeData, bufSize, (unsigned char*)pMsgInfo->msgText, pMsgInfo->dataSize, &langId);
+                       decodeLen = textCvt->convertUTF8ToGSM7bit(decodeData, bufSize, (unsigned char*)pMsgInfo->msgText, (int)pMsgInfo->dataSize, &langId, &bAbnormal);
                }
                else if (*pCharType == SMS_CHARSET_8BIT)
                {
@@ -491,11 +842,11 @@ void SmsPluginTransport::msgInfoToSubmitData(const MSG_MESSAGE_INFO_S *pMsgInfo,
                }
                else if (*pCharType == SMS_CHARSET_UCS2)
                {
-                       decodeLen = SmsPluginTextConvert::instance()->convertUTF8ToUCS2(decodeData, bufSize, (unsigned char*)pMsgInfo->msgText, pMsgInfo->dataSize);
+                       decodeLen = textCvt->convertUTF8ToUCS2(decodeData, bufSize, (unsigned char*)pMsgInfo->msgText, (int)pMsgInfo->dataSize);
                }
                else if (*pCharType == SMS_CHARSET_AUTO)
                {
-                       decodeLen = SmsPluginTextConvert::instance()->convertUTF8ToAuto(decodeData, bufSize, (unsigned char*)pMsgInfo->msgText, pMsgInfo->dataSize, &encodeType);
+                       decodeLen = textCvt->convertUTF8ToAuto(decodeData, bufSize, (unsigned char*)pMsgInfo->msgText, (int)pMsgInfo->dataSize, &langId, &encodeType);
                        *pCharType = encodeType;
                }
        }
@@ -504,17 +855,17 @@ void SmsPluginTransport::msgInfoToSubmitData(const MSG_MESSAGE_INFO_S *pMsgInfo,
                int fileSize = 0;
 
                char* pFileData = NULL;
-               AutoPtr<char> FileBuf(&pFileData);
+               unique_ptr<char*, void(*)(char**)> FileBuf(&pFileData, unique_ptr_deleter);
 
                // Read Message Data from File
                if (MsgOpenAndReadFile(pMsgInfo->msgData, &pFileData, &fileSize) == false)
-               THROW(MsgException::FILE_ERROR, "MsgOpenAndReadFile error");
+                       THROW(MsgException::FILE_ERROR, "MsgOpenAndReadFile error");
 
                MSG_DEBUG("file size : [%d] file data : [%s]", fileSize, pFileData);
 
                if (*pCharType == SMS_CHARSET_7BIT)
                {
-                       decodeLen = SmsPluginTextConvert::instance()->convertUTF8ToGSM7bit(decodeData, bufSize, (unsigned char*)pFileData, fileSize, &langId);
+                       decodeLen = textCvt->convertUTF8ToGSM7bit(decodeData, bufSize, (unsigned char*)pFileData, fileSize, &langId, &bAbnormal);
                }
                else if (*pCharType == SMS_CHARSET_8BIT)
                {
@@ -523,27 +874,28 @@ void SmsPluginTransport::msgInfoToSubmitData(const MSG_MESSAGE_INFO_S *pMsgInfo,
                }
                else if (*pCharType == SMS_CHARSET_UCS2)
                {
-                       decodeLen = SmsPluginTextConvert::instance()->convertUTF8ToUCS2(decodeData, bufSize, (unsigned char*)pFileData, fileSize);
+                       decodeLen = textCvt->convertUTF8ToUCS2(decodeData, bufSize, (unsigned char*)pFileData, fileSize);
                }
                else if (*pCharType == SMS_CHARSET_AUTO)
                {
-                       decodeLen = SmsPluginTextConvert::instance()->convertUTF8ToAuto(decodeData, bufSize, (unsigned char*)pFileData, fileSize, &encodeType);
+                       decodeLen = textCvt->convertUTF8ToAuto(decodeData, bufSize, (unsigned char*)pFileData, fileSize, &langId, &encodeType);
                        *pCharType = encodeType;
                }
 
                // Delete File
-               MsgDeleteFile(pMsgInfo->msgData);
+               if (pMsgInfo->nAddressCnt == (addrIndex + 1))
+                       MsgDeleteFile(pMsgInfo->msgData);
        }
 
 MSG_DEBUG("decode length : [%d]", decodeLen);
 MSG_DEBUG("character type : [%d]", *pCharType);
 MSG_DEBUG("Language Identifier : [%d]", langId);
-MSG_DEBUG("reply address : [%s]", pMsgInfo->replyAddress);
+MSG_SEC_DEBUG("reply address : [%s]", pMsgInfo->replyAddress);
 
        int addrLen = 0;
 
        char* encodedAddr = NULL;
-       AutoPtr<char> addressBuf(&encodedAddr);
+       unique_ptr<char*, void(*)(char**)> addressBuf(&encodedAddr, unique_ptr_deleter);
 
        if (strlen(pMsgInfo->replyAddress) > 0)
        {
@@ -564,12 +916,15 @@ MSG_DEBUG("reply address : [%s]", pMsgInfo->replyAddress);
 
        segSize = getSegmentSize(*pCharType, decodeLen, pMsgInfo->msgPort.valid, langId, addrLen);
 
+       if (segSize == 0)
+               THROW(MsgException::SMS_PLG_ERROR, "DIVIDE_BY_ZERO : %d", segSize);
+
        pData->segCount = ceil((double)decodeLen/(double)segSize);
 
 MSG_DEBUG("segment size : [%d], pData->segCount : [%d]", segSize, pData->segCount);
 
        if (pData->segCount > MAX_SEGMENT_NUM)
-               THROW(MsgException::SMS_PLG_ERROR, "Segment Count is over maximum : %d", pData->segCount);
+               THROW(MsgException::SMS_PLG_ERROR, "Segment Count is over maximum : %d", pData->segCount);
 
        int headerCnt = 0;
 
@@ -627,7 +982,7 @@ MSG_DEBUG("user data [%s]", pData->userData[i].data);
                }
 
                // Set User Data Header for National Language Single Shift
-               if (*pCharType == SMS_CHARSET_7BIT && langId != SMS_LANG_ID_RESERVED)
+               if (*pCharType == SMS_CHARSET_7BIT && langId != MSG_LANG_ID_RESERVED)
                {
                        pData->userData[i].header[headerCnt].udhType = SMS_UDH_SINGLE_SHIFT;
                        pData->userData[i].header[headerCnt].udh.singleShift.langId = langId;
@@ -642,7 +997,7 @@ MSG_DEBUG("user data [%s]", pData->userData[i].data);
 }
 
 
-int SmsPluginTransport::getSegmentSize(SMS_CODING_SCHEME_T CodingScheme, int DataLen, bool bPortNum, SMS_LANGUAGE_ID_T LangId, int ReplyAddrLen)
+int SmsPluginTransport::getSegmentSize(SMS_CODING_SCHEME_T CodingScheme, int DataLen, bool bPortNum, MSG_LANGUAGE_ID_T LangId, int ReplyAddrLen)
 {
        int headerLen = 1, concat = 5, port = 6, lang = 3, reply = 2;
        int headerSize = 0, segSize = 0, maxSize = 0;
@@ -664,7 +1019,7 @@ int SmsPluginTransport::getSegmentSize(SMS_CODING_SCHEME_T CodingScheme, int Dat
                headerSize += port;
        }
 
-       if (LangId != SMS_LANG_ID_RESERVED)
+       if (LangId != MSG_LANG_ID_RESERVED)
        {
                MSG_DEBUG("National Language Exists");
                headerSize += lang;
@@ -679,14 +1034,14 @@ int SmsPluginTransport::getSegmentSize(SMS_CODING_SCHEME_T CodingScheme, int Dat
 
        if (CodingScheme == SMS_CHARSET_7BIT)
        {
-               if (((DataLen+headerSize)/maxSize) >= 1)
+               if ((DataLen+headerSize) > maxSize)
                        segSize = ((140*8) - ((headerLen + concat + headerSize)*8)) / 7;
                else
                        segSize = DataLen;
        }
        else if (CodingScheme == SMS_CHARSET_8BIT || CodingScheme == SMS_CHARSET_UCS2)
        {
-               if (((DataLen+headerSize)/maxSize) >= 1)
+               if ((DataLen+headerSize) > maxSize)
                        segSize = 140 - (headerLen + concat + headerSize);
                else
                        segSize = DataLen;
@@ -721,36 +1076,71 @@ void SmsPluginTransport::setConcatHeader(SMS_UDH_S *pSrcHeader, SMS_UDH_S *pDstH
 }
 
 
-void SmsPluginTransport::setNetStatus(msg_network_status_t netStatus)
+void SmsPluginTransport::setNetStatus(SMS_NETWORK_STATUS_T sentStatus)
 {
        mx.lock();
-       curStatus = netStatus;
+       curStatus = sentStatus;
        cv.signal();
        mx.unlock();
 }
 
 
-msg_network_status_t SmsPluginTransport::getNetStatus()
+SMS_NETWORK_STATUS_T SmsPluginTransport::getNetStatus()
 {
        mx.lock();
 
        int ret = 0;
 
-       if (curStatus == MSG_NETWORK_SENDING)
-               ret = cv.timedwait(mx.pMutex(), 65);
+       if (curStatus == SMS_NETWORK_SENDING)
+               ret = cv.timedwait(mx.pMutex(), 125);
 
        mx.unlock();
 
        if (ret == ETIMEDOUT)
        {
                MSG_DEBUG("WARNING: SENT STATUS TIME-OUT");
-               curStatus = MSG_NETWORK_SEND_TIMEOUT;
+               curStatus = SMS_NETWORK_SEND_FAIL_TIMEOUT;
        }
 
        return curStatus;
 }
 
 
+void SmsPluginTransport::setMoCtrlStatus(TelSatMoSmCtrlIndData_t *moCtrlData)
+{
+       mx.lock();
+
+       if (moCtrlData) {
+               memset(&curMoCtrlData, 0x00, sizeof(TelSatMoSmCtrlIndData_t));
+               memcpy(&curMoCtrlData, moCtrlData, sizeof(TelSatMoSmCtrlIndData_t));
+               MSG_DEBUG("MO Control Data is set by Tapi Event Noti");
+       }
+
+       cv.signal();
+       mx.unlock();
+}
+
+
+int SmsPluginTransport::getMoCtrlStatus()
+{
+       mx.lock();
+
+       int ret = 0;
+
+       ret = cv.timedwait(mx.pMutex(), 10);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT)
+       {
+               MSG_DEBUG("WARNING: SENT STATUS TIME-OUT");
+               return -1;
+       }
+
+       return (curMoCtrlData.moSmsCtrlResult);
+}
+
+
 unsigned char SmsPluginTransport::getMsgRef()
 {
        return msgRef++;
index 0e97339..fb72329 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
@@ -55,11 +55,16 @@ void SmsPluginUAManager::run()
 {
        while (1)
        {
-               if (smsTranQ.empty())
-                       cv.wait(mx.pMutex());
-
+               lock();
+               while (smsTranQ.empty()) {
+                       wait();
+               }
                SMS_REQUEST_INFO_S request;
                smsTranQ.front(&request);
+               unlock();
+
+               request.msgInfo.addressList = NULL;
+               unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&request.msgInfo.addressList, unique_ptr_deleter);
 
                try
                {
@@ -69,25 +74,38 @@ void SmsPluginUAManager::run()
                {
                        MSG_FATAL("%s", e.what());
 
+                       lock();
                        smsTranQ.pop_front();
+                       unlock();
                        continue;
                }
                catch (exception& e)
                {
                        MSG_FATAL("%s", e.what());
-
+                       lock();
                        smsTranQ.pop_front();
+                       unlock();
                        continue;
                }
 
+               lock();
                smsTranQ.pop_front();
+               unlock();
        }
 }
 
 
-void SmsPluginUAManager::addReqEntity(SMS_REQUEST_INFO_S request)
+void SmsPluginUAManager::addReqEntity(SMS_REQUEST_INFO_S *request)
 {
-       smsTranQ.push_back(request);
+       SMS_REQUEST_INFO_S reqTmp = {0,};
+
+       memcpy(&reqTmp, request, sizeof(SMS_REQUEST_INFO_S));
+
+       lock();
+
+       smsTranQ.push_back(reqTmp);
        cv.signal();
+
+       unlock();
 }
 
index e953d95..d5b51e6 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
@@ -19,6 +19,7 @@
 #include "SmsPluginParamCodec.h"
 #include "SmsPluginUDCodec.h"
 
+using namespace std;
 
 /*==================================================================================================
                                      IMPLEMENTATION OF SmsPluginUDCodec - Member Functions
@@ -157,6 +158,15 @@ MSG_DEBUG("dataLen [%d]", pUserData->length);
 MSG_DEBUG("packSize [%d]", packSize);
 MSG_DEBUG("encodeLen [%d]", encodeLen);
 
+#if 0
+printf("\n\n[encodeGSMData] userData data.\n");
+for (int j = 0; j < encodeLen; j++)
+{
+       printf(" [%02x]", pEncodeData[j]);
+}
+printf("\n\n");
+#endif
+
        return encodeLen;
 }
 
@@ -239,6 +249,15 @@ MSG_DEBUG("dataLen [%d]", pUserData->length);
 
        encodeLen = offset + pUserData->length;
 
+#if 0
+printf("\n\n[encodeUCS2Data] userData data.\n");
+for (int j = 0; j < encodeLen; j++)
+{
+       printf(" [%02x]", pEncodeData[j]);
+}
+printf("\n\n");
+#endif
+
        return encodeLen;
 }
 
@@ -284,9 +303,8 @@ MSG_DEBUG("bHeaderInd = %d", bHeaderInd);
                {
                        headerLen = decodeHeader(&(pTpdu[offset]), &(pUserData->header[i]));
 
-                       if (headerLen <= 0)
-                       {
-                               MSG_DEBUG("Error to decode User Data Header");
+                       if (headerLen <= 0) {
+                               MSG_DEBUG("Error to decode User Data Header. headerLen [%d]", headerLen);
 
                                pUserData->length = 0;
                                memset(pUserData->data, 0x00, sizeof(pUserData->data));
@@ -296,6 +314,15 @@ MSG_DEBUG("bHeaderInd = %d", bHeaderInd);
 
                        offset += headerLen;
 
+                       if (offset > (udhl+2)) {
+                               MSG_DEBUG("Error to decode User Data Header. offset [%d] > (udhl [%d] + 2)", offset, udhl);
+
+                               pUserData->length = 0;
+                               memset(pUserData->data, 0x00, sizeof(pUserData->data));
+
+                               return 0;
+                       }
+
                        pUserData->headerCnt++;
                }
        }
@@ -318,6 +345,10 @@ MSG_DEBUG("offset = %d", offset);
 
        pUserData->length = unpack7bitChar(&(pTpdu[offset]), udl, fillBits, pUserData->data);
 
+       //MSG_DEBUG("data = [%s]", pUserData->data);
+       //MSG_DEBUG("length = [%d]", pUserData->length);
+
+
        return pUserData->length;
 }
 
@@ -361,9 +392,8 @@ MSG_DEBUG("bHeaderInd = %d", bHeaderInd);
                {
                        headerLen = decodeHeader(&(pTpdu[offset]), &(pUserData->header[i]));
 
-                       if (headerLen <= 0)
-                       {
-                               MSG_DEBUG("Error to decode User Data Header");
+                       if (headerLen <= 0) {
+                               MSG_DEBUG("Error to decode User Data Header. headerLen [%d]", headerLen);
 
                                pUserData->length = 0;
                                memset(pUserData->data, 0x00, sizeof(pUserData->data));
@@ -373,6 +403,15 @@ MSG_DEBUG("bHeaderInd = %d", bHeaderInd);
 
                        offset += headerLen;
 
+                       if (offset > (udhl+2)) {
+                               MSG_DEBUG("Error to decode User Data Header. offset [%d] > (udhl [%d] + 2)", offset, udhl);
+
+                               pUserData->length = 0;
+                               memset(pUserData->data, 0x00, sizeof(pUserData->data));
+
+                               return 0;
+                       }
+
                        pUserData->headerCnt++;
                }
        }
@@ -435,9 +474,8 @@ MSG_DEBUG("bHeaderInd = %d", bHeaderInd);
                {
                        headerLen = decodeHeader(&(pTpdu[offset]), &(pUserData->header[i]));
 
-                       if (headerLen <= 0)
-                       {
-                               MSG_DEBUG("Error to decode User Data Header");
+                       if (headerLen <= 0) {
+                               MSG_DEBUG("Error to decode User Data Header. headerLen [%d]", headerLen);
 
                                pUserData->length = 0;
                                memset(pUserData->data, 0x00, sizeof(pUserData->data));
@@ -447,6 +485,15 @@ MSG_DEBUG("bHeaderInd = %d", bHeaderInd);
 
                        offset += headerLen;
 
+                       if (offset > (udhl+2)) {
+                               MSG_DEBUG("Error to decode User Data Header. offset [%d] > (udhl [%d] + 2)", offset, udhl);
+
+                               pUserData->length = 0;
+                               memset(pUserData->data, 0x00, sizeof(pUserData->data));
+
+                               return 0;
+                       }
+
                        pUserData->headerCnt++;
                }
        }
@@ -473,7 +520,7 @@ int SmsPluginUDCodec::encodeHeader(const SMS_UDH_S header, char *pEncodeHeader)
        int offset = 0, addrLen = 0;
 
        char* encodedAddr = NULL;
-       AutoPtr<char> addressBuf(&encodedAddr);
+       unique_ptr<char*, void(*)(char**)> addressBuf(&encodedAddr, unique_ptr_deleter);
 
        switch (header.udhType)
        {
@@ -548,6 +595,11 @@ int SmsPluginUDCodec::encodeHeader(const SMS_UDH_S header, char *pEncodeHeader)
 
                        addrLen = SmsPluginParamCodec::encodeAddress(&(header.udh.alternateAddress), &encodedAddr);
 
+//MSG_DEBUG("addrLen : %d", addrLen);
+
+//for (int i = 0; i < addrLen; i++)
+//     MSG_DEBUG("header.udh.alternateAddress.address : [%02x]", encodedAddr[i]);
+
                        // IEDL
                        pEncodeHeader[offset++] = addrLen;
 
@@ -681,7 +733,7 @@ MSG_DEBUG("Decoding special sms udh.");
 
                        offset += SmsPluginParamCodec::decodeAddress(&pTpdu[offset], &(pHeader->udh.alternateAddress));
 
-MSG_DEBUG("alternate reply address [%s]", pHeader->udh.alternateAddress.address);
+                       MSG_SEC_DEBUG("alternate reply address [%s]", pHeader->udh.alternateAddress.address);
                }
                break;
 
@@ -712,7 +764,11 @@ MSG_DEBUG("lockingShift.langId [%02x]", pHeader->udh.lockingShift.langId);
                default :
                {
                        MSG_DEBUG("Not Supported Header Type [%02x]", pHeader->udhType);
-                       return 0;
+
+                       IEDL = pTpdu[offset++];
+
+                       MSG_DEBUG("IEDL [%d]", IEDL);
+                       return (offset + IEDL);
                }
                break;
        }
@@ -725,6 +781,8 @@ int SmsPluginUDCodec::pack7bitChar(const unsigned char *pUserData, int dataLen,
 {
        int srcIdx = 0, dstIdx = 0, shift = fillBits;
 
+//MSG_DEBUG("dataLen = %d", dataLen);
+
        if (shift > 0)
                dstIdx = 1;
 
@@ -732,36 +790,51 @@ int SmsPluginUDCodec::pack7bitChar(const unsigned char *pUserData, int dataLen,
        {
                if (shift == 0)
                {
+//                     if (srcIdx > 0) srcIdx++;
 
-                       pPackData[dstIdx] = pUserData[srcIdx];
+//MSG_DEBUG("pUserData [%02x]", pUserData[srcIdx]);
+//MSG_DEBUG("shift = %d", shift);
 
-                       if (srcIdx >= dataLen) break;
+                       pPackData[dstIdx] = pUserData[srcIdx];
 
+//MSG_DEBUG("pPackData [%02x]", pPackData[dstIdx]);
                        shift = 7;
                        srcIdx++;
                        dstIdx++;
+
+                       if (srcIdx >= dataLen) break;
                }
 
                if (shift > 1)
                {
+//MSG_DEBUG("pUserData [%02x]", pUserData[srcIdx]);
+
+//MSG_DEBUG("shift = %d", shift);
 
                        pPackData[dstIdx-1] |= pUserData[srcIdx] << shift;
                        pPackData[dstIdx] = pUserData[srcIdx] >> (8-shift);
                        shift--;
+//MSG_DEBUG("pPackData [%02x]", pPackData[dstIdx]);
 
                        srcIdx++;
                        dstIdx++;
                }
                else if (shift == 1)
                {
+//MSG_DEBUG("pUserData [%02x]", pUserData[srcIdx]);
+//MSG_DEBUG("shift = %d", shift);
                        pPackData[dstIdx-1] |= pUserData[srcIdx] << shift;
 
+//MSG_DEBUG("pPackData [%02x]", pPackData[dstIdx-1]);
+
                        srcIdx++;
 
                        shift--;
                }
        }
 
+//MSG_DEBUG("dstIdx = %d", dstIdx);
+
        return dstIdx;
 }
 
@@ -779,8 +852,11 @@ MSG_DEBUG("dataLen = %d", dataLen);
        {
                if (shift == 0)
                {
+//MSG_DEBUG("shift = %d", shift);
+
                        pUnpackData[dstIdx] = pTpdu[srcIdx] & 0x7F;
 
+//MSG_DEBUG("UserData[%d] = %02x", dstIdx, pUnpackData[dstIdx]);
                        shift = 7;
                        srcIdx++;
                        dstIdx++;
@@ -790,10 +866,14 @@ MSG_DEBUG("dataLen = %d", dataLen);
 
                if (shift > 0)
                {
+//MSG_DEBUG("shift = %d", shift);
+
                        pUnpackData[dstIdx] = (pTpdu[srcIdx-1] >> shift) + (pTpdu[srcIdx] << (8 - shift));
 
                        pUnpackData[dstIdx] &= 0x7F;
 
+//MSG_DEBUG("UserData[%d] = %02x", dstIdx, pUnpackData[dstIdx]);
+
                        shift--;
 
                        if (shift > 0) srcIdx++;
@@ -802,3 +882,4 @@ MSG_DEBUG("dataLen = %d", dataLen);
 
        return dstIdx;
 }
+
index 015a750..98de445 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
 #include "SmsPluginEventHandler.h"
 #include "SmsPluginWapPushHandler.h"
 
+#include <glib.h>
+#include <gio/gio.h>
+#if MSG_DRM_SUPPORT
 #include <drm_client.h>
+#endif
 
 static unsigned short wapPushPortList [] = {0x0b84, 0x0b85, 0x23F0, 0x23F1, 0x23F2, 0x23F3, 0xC34F};
 
+#if 0
 const SMS_PUSH_APP_INFO_S pushDefaultApplication [] =
 {
        {(char*)"text/vnd.wap.si", (char*)"X-Wap-Application-Id: x-wap-application:wml.ua\r\n", SMS_WAP_APPLICATION_PUSH_SI},
@@ -60,13 +65,20 @@ const SMS_PUSH_APP_INFO_S pushDefaultApplication [] =
        {(char*)"application/vnd.oma.drm.roap-trigger+xml", (char*)"X-Wap-Application-Id: x-wap-application:drm.ua\r\n", SMS_WAP_APPLICATION_DRM_V2_ROAP_TRIGGER_XML},
        {(char*)"application/vnd.oma.drm.roap-trigger+wbxml", (char*)"X-Wap-Application-Id: x-wap-application:drm.ua\r\n", SMS_WAP_APPLICATION_DRM_V2_ROAP_TRIGGER_WBXML},
 
+       {(char*)"text/vnd.wap.connectivity-xml", (char*)"X-Wap-Application-Id: x-wap-samsung:provisioning.ua\r\n", SMS_WAP_APPLICATION_PUSH_PROVISIONING_XML},
+       {(char*)"application/vnd.wap.connectivity-wbxml", (char*)"X-Wap-Application-Id: x-wap-samsung:provisioning.ua\r\n", SMS_WAP_APPLICATION_PUSH_PROVISIONING_WBXML},
+
+       {(char*)"application/x-wap-prov.browser-settings", (char*)"X-Wap-Application-Id: x-wap-samsung:provisioning.ua\r\n", SMS_WAP_APPLICATION_PUSH_BROWSER_SETTINGS},
+       {(char*)"application/x-wap-prov.browser-bookmarks", (char*)"X-Wap-Application-Id: x-wap-samsung:provisioning.ua\r\n", SMS_WAP_APPLICATION_PUSH_BROWSER_BOOKMARKS},
+       {(char*)"application/x-wap-prov.syncset+xml", (char*)"X-Wap-Application-Id: x-wap-samsung:provisioning.ua\r\n", SMS_WAP_APPLICATION_PUSH_SYNCSET_WBXML},
+       {(char*)"application/x-wap-prov.syncset+wbxml", (char*)"X-Wap-Application-Id: x-wap-samsung:provisioning.ua\r\n", SMS_WAP_APPLICATION_PUSH_SYNCSET_XML},
        {(char*)"text/vnd.wap.emn+xml", (char*)"X-Wap-Application-Id: x-wap-application:emn.ua\r\n", SMS_WAP_APPLICATION_PUSH_EMAIL_XML},
        {(char*)"application/vnd.wap.emn+wbxml", (char*)"X-Wap-Application-Id: x-wap-application:emn.ua\r\n", SMS_WAP_APPLICATION_PUSH_EMAIL_WBXML},
        {(char*)"application/vnd.wv.csp.cir", (char*)"X-Wap-Application-Id: x-wap-application:wv.ua\r\n", SMS_WAP_APPLICATION_PUSH_IMPS_CIR},
        {(char*)"application/vnd.omaloc-supl-init", (char*)"X-Wap-Application-Id: x-oma-application:ulp.ua\r\n", SMS_WAP_APPLICATION_LBS},
        {NULL, NULL}
 };
-
+#endif
 
 char gWapCodeBufferLeft[WSP_CODE_BUFFER_LEFT_LEN_MAX];
 char gWapCodeBufferRight[WSP_CODE_BUFFER_RIGHT_LEN_MAX];
@@ -602,7 +614,22 @@ const SMS_WSP_HEADER_PARAMETER_S wspHeaderApplId[] =
        { (char*)"x-wap-application:loc.ua",  0x06 },
        { (char*)"x-wap-application:syncml.dm", 0x07 },
        { (char*)"x-wap-application:drm.ua", 0x08 },
-       { (char*)"x-wap-application:emn.ua", 0x09 }
+       { (char*)"x-wap-application:emn.ua", 0x09 },
+       { (char*)"x-oma-application:ulp.ua ", 0x10 },
+       { (char*)"x-oma-docomo:open.ctl", 0x9055 },
+       { (char*)"x-oma-docomo:xmd.mail.ua", 0x905C },
+       { (char*)"x-oma-docomo:xmd.storage.ua", 0x905F },
+       { (char*)"x-oma-docomo:xmd.lcsapp.ua", 0x9060 },
+       { (char*)"x-oma-docomo:xmd.info.ua", 0x9061 },
+       { (char*)"x-oma-docomo:xmd.agent.ua", 0x9062 },
+       { (char*)"x-oma-docomo:xmd.sab.ua", 0x9063 },
+       { (char*)"x-oma-docomo:xmd.am.ua", 0x9064 },
+       { (char*)"x-oma-docomo:xmd.emdm.ua", 0x906B },
+       { (char*)"x-oma-docomo:xmd.lac.ua", 0x906C },
+       { (char*)"x-oma-docomo:xmd.osv.ua", 0x906D },
+       { (char*)"x-oma-docomo:xmd.dcs.ua", 0x906E },
+       { (char*)"x-oma-docomo:xmd.wipe.ua", 0x906F },
+       { (char*)"x-oma-docomo:xmd.vdapp.ua ", 0x9070 },
 };
 
 
@@ -693,6 +720,7 @@ SmsPluginWapPushHandler* SmsPluginWapPushHandler::pInstance = NULL;
 SmsPluginWapPushHandler::SmsPluginWapPushHandler()
 {
        memset(&tmpAddress, 0x00, sizeof(tmpAddress));
+       memset(&tmpTimeStamp, 0x00, sizeof(tmpTimeStamp));
 }
 
 
@@ -743,7 +771,7 @@ bool SmsPluginWapPushHandler::IsWapPushMsg(SMS_USERDATA_S *pUserData)
        return false;
 }
 
-
+#if 0
 SMS_WAP_APP_CODE_T SmsPluginWapPushHandler::getAppCode(const char *pPushHeader)
 {
        int appCount = sizeof(pushDefaultApplication)/sizeof(pushDefaultApplication[0]) - 1;
@@ -771,6 +799,7 @@ SMS_WAP_APP_CODE_T SmsPluginWapPushHandler::getAppCode(const char *pPushHeader)
 
        return appCode;
 }
+#endif
 
 
 void SmsPluginWapPushHandler::copyDeliverData(SMS_DELIVER_S *pDeliver)
@@ -780,7 +809,7 @@ void SmsPluginWapPushHandler::copyDeliverData(SMS_DELIVER_S *pDeliver)
 
        strncpy(tmpAddress.address, pDeliver->originAddress.address, MAX_ADDRESS_LEN);
 
-       MSG_DEBUG("Address [%s]", tmpAddress.address);
+       MSG_SEC_DEBUG("Address [%s]", tmpAddress.address);
 
        tmpTimeStamp.format = pDeliver->timeStamp.format;
 
@@ -796,29 +825,40 @@ void SmsPluginWapPushHandler::copyDeliverData(SMS_DELIVER_S *pDeliver)
 }
 
 
-void SmsPluginWapPushHandler::handleWapPushMsg(const char *pUserData, int DataSize)
+void SmsPluginWapPushHandler::handleWapPushMsg(const char *pUserData, int DataSize, int simIndex)
 {
        MSG_BEGIN();
 
+#ifdef MSG_FW_FOR_DEBUG
+       MSG_DEBUG("DataSize [%d]", DataSize);
+
+       MSG_DEBUG("[pUserData]");
+       for (int i = 0; i < DataSize; i++)
+       {
+               printf("[%02x]", pUserData[i]);
+       }
+       printf("\n\n");
+#endif
+
        unsigned char* pPDUTypeData = (unsigned char*)pUserData;
        unsigned long PDUTypeDataLen = DataSize;
 
        char* pPushHeader = NULL;
-       AutoPtr<char> pushHeaderBuf(&pPushHeader);
+       unique_ptr<char*, void(*)(char**)> pushHeaderBuf(&pPushHeader, unique_ptr_deleter);
        unsigned long pushHeaderLen = 0;
 
        char* pPushBody = NULL;
-       AutoPtr<char> PushBodyBuf(&pPushBody);
+       unique_ptr<char*, void(*)(char**)> PushBodyBuf(&pPushBody, unique_ptr_deleter);
        unsigned long pushBodyLen = 0;
 
        unsigned long iPDU = 1;
 
        char* pWspHeader = NULL;
-       AutoPtr<char> WspHeaderBuf(&pWspHeader);
+       unique_ptr<char*, void(*)(char**)> WspHeaderBuf(&pWspHeader, unique_ptr_deleter);
        unsigned long   wspHeaderLen = 0;
 
        char* pWspBody = NULL;
-       AutoPtr<char> WspBodyBuf(&pWspBody);
+       unique_ptr<char*, void(*)(char**)> WspBodyBuf(&pWspBody, unique_ptr_deleter);
        unsigned long wspBodyLen = 0;
 
        /** pass PDU type */
@@ -846,6 +886,17 @@ void SmsPluginWapPushHandler::handleWapPushMsg(const char *pUserData, int DataSi
                }
        }
 
+#ifdef MSG_FW_FOR_DEBUG
+       MSG_DEBUG("wspHeaderLen [%d]", wspHeaderLen);
+
+       MSG_DEBUG("[pWspHeader]");
+       for (int i = 0; i < wspHeaderLen; i++)
+       {
+               printf("[%02x]", pWspHeader[i]);
+       }
+       printf("\n\n");
+#endif
+
        /** return if it is below case error */
        if (PDUTypeDataLen < wspHeaderLen) {
                MSG_DEBUG("PDUTypeDataLen < wspHeaderLen !!!");
@@ -889,12 +940,12 @@ void SmsPluginWapPushHandler::handleWapPushMsg(const char *pUserData, int DataSi
                return;
        }
 
-       handleWapPushCallback((char *)pPushHeader, (char *)pPushBody, (int)pushBodyLen, (char *)pWspHeader, (int)wspHeaderLen, (char *)pWspBody, (int)wspBodyLen);
+       handleWapPushCallback((char *)pPushHeader, (char *)pPushBody, (int)pushBodyLen, (char *)pWspHeader, (int)wspHeaderLen, (char *)pWspBody, (int)wspBodyLen, simIndex);
 
        MSG_END();
 }
 
-
+#if 0
 void SmsPluginWapPushHandler::handleWapPushCallback(char* pPushHeader, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen, char* pWspBody, int WspBodyLen)
 {
        MSG_BEGIN();
@@ -1040,29 +1091,356 @@ void SmsPluginWapPushHandler::handleWapPushCallback(char* pPushHeader, char* pPu
 
        MSG_END();
 }
+#else
+
+static void launchProcessByAppcode(int appcode)
+{
+       MSG_BEGIN();
+       GError *error = NULL;
+       GDBusConnection *connection_agent = NULL;
+       GDBusProxy *dbus_proxy_agent = NULL;
+       GDBusConnection *connection_service = NULL;
+       GDBusProxy *dbus_proxy_service = NULL;
+       GVariant *result_agent = NULL;
+       GVariant *result_service = NULL;
+
+       switch(appcode){
+               case SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP:
+               case SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP_XML:
+               case SMS_WAP_APPLICATION_PUSH_PROVISIONING_XML:
+               case SMS_WAP_APPLICATION_PUSH_PROVISIONING_WBXML:
+               case SMS_WAP_APPLICATION_PUSH_BROWSER_SETTINGS:
+               case SMS_WAP_APPLICATION_PUSH_BROWSER_BOOKMARKS:
+               case SMS_WAP_APPLICATION_SYNCML_DM_NOTIFICATION:
+                       {
+                               connection_agent = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to system bus failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               dbus_proxy_agent = g_dbus_proxy_new_sync(connection_agent, G_DBUS_PROXY_FLAGS_NONE,
+                                                                                       NULL, "org.tizen.omadmagent", "/org/tizen/omadmagent",
+                                                                                       "org.tizen.omadmagent", NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to agent proxy failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               result_agent = g_dbus_proxy_call_sync(dbus_proxy_agent, "Hello_Agent", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("invoking agent proxy call failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               connection_service = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to system bus failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               dbus_proxy_service =g_dbus_proxy_new_sync(connection_service, G_DBUS_PROXY_FLAGS_NONE, NULL,
+                                                                                       "org.tizen.omadmservice", "/org/tizen/omadmservice",
+                                                                                       "org.tizen.omadmservice", NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to service proxy failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               result_service = g_dbus_proxy_call_sync(dbus_proxy_service, "wakeup", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("invoking service proxy call failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               Mutex mx;
+                               CndVar cv;
+                               mx.lock();
+                               cv.timedwait(mx.pMutex(), 2);
+                               mx.unlock();
+
+                               MSG_END();
+                       }
+                       break;
+               case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION:
+               case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION_WBXML:
+                       {
+                               connection_agent = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to system bus failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               dbus_proxy_agent = g_dbus_proxy_new_sync(connection_agent, G_DBUS_PROXY_FLAGS_NONE, NULL,
+                                                                                       "org.tizen.omadsagent", "/org/tizen/omadsagent",
+                                                                                       "org.tizen.omadsagent", NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("Connecting to agent proxy failed: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+
+                               result_agent = g_dbus_proxy_call_sync(dbus_proxy_agent, "Hello_Agent", NULL,
+                                                                               G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error);
+                               if (error) {
+                                       MSG_DEBUG("invoking service error: %s\n", error->message);
+                                       goto _DBUS_ERROR;
+                               }
+                       }
+                       break;
+               default:
+                       break;
+       }
+
+_DBUS_ERROR:
+       if (error) {
+               g_error_free(error);
+               error = NULL;
+       }
+
+       if (connection_agent) {
+               g_object_unref(connection_agent);
+               connection_agent = NULL;
+       }
+
+       if (dbus_proxy_agent) {
+               g_object_unref(dbus_proxy_agent);
+               dbus_proxy_agent = NULL;
+       }
+
+       if (result_agent) {
+               g_object_unref(result_service);
+               result_service = NULL;
+       }
+
+       if (connection_service) {
+               g_object_unref(connection_service);
+               connection_service = NULL;
+       }
+
+       if (dbus_proxy_service) {
+               g_object_unref(dbus_proxy_service);
+               dbus_proxy_service = NULL;
+       }
+
+       if (result_service) {
+               g_object_unref(result_service);
+               result_service = NULL;
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginWapPushHandler::handleWapPushCallback(char* pPushHeader, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen, char* pWspBody, int WspBodyLen, int simIndex)
+{
+       MSG_BEGIN();
+
+       if (pPushBody == NULL) {
+               MSG_DEBUG("pPushBody is NULL");
+               return;
+       }
+
+       msg_error_t err = MSG_SUCCESS;
+       int pushEvt_cnt = 0;
+       char app_id[MAX_WAPPUSH_ID_LEN] = {0,};
+       char content_type[MAX_WAPPUSH_CONTENT_TYPE_LEN] = {0,};
+       SmsPluginStorage *storageHandler = SmsPluginStorage::instance();
+
+       err = storageHandler->getRegisteredPushEvent(pPushHeader, &pushEvt_cnt, app_id, sizeof(app_id), content_type, sizeof(content_type));
+       MSG_DEBUG("pushEvt_cnt: %d", pushEvt_cnt);
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to get registered push event");
+               return;
+       }
+
+       for(int i = 0; i < pushEvt_cnt; ++i)    {
+
+               /**  check Push message receive setting */
+               bool bPushRecv = false;
+               int appcode = 0;
+               MsgSettingGetBool(PUSH_RECV_OPTION, &bPushRecv);
+
+               storageHandler->getnthPushEvent(i, &appcode);
+               MSG_DEBUG("pushEvt_cnt: %d, appcode: %d", pushEvt_cnt, appcode);
+               if ((bPushRecv == false) && (appcode != SMS_WAP_APPLICATION_MMS_UA)) {
+                       MSG_DEBUG("Push Message Receive option is OFF. Drop Push Message.");
+                       return;
+               }
+
+#ifdef FEATURE_MMS_DISABLE
+               if (appcode == SMS_WAP_APPLICATION_MMS_UA){
+                       MSG_DEBUG("Drop MMS Notification for DOCOMO");
+                       return;
+               }
+
+#endif
+               launchProcessByAppcode(appcode);
+
+               switch (appcode) {
+               case SMS_WAP_APPLICATION_MMS_UA:
+                       MSG_DEBUG("Received MMS Notification");
+                       handleMMSNotification(pPushBody, PushBodyLen, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_SI:
+                       MSG_DEBUG("Received WAP Push (Service Indication Textual form)");
+                       handleSIMessage(pPushBody, PushBodyLen, true, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_SIC:
+                       MSG_DEBUG("Received WAP Push (Service Indication Tokenised form)");
+                       handleSIMessage(pPushBody, PushBodyLen, false, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_SL:
+                       MSG_DEBUG("Received WAP Push (Service Loading Textual form)");
+                       handleSLMessage(pPushBody, PushBodyLen, true, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_SLC:
+                       MSG_DEBUG("Received WAP Push (Service Loading Tokenised form)");
+                       handleSLMessage(pPushBody, PushBodyLen, false, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_CO:
+                       MSG_DEBUG("Received WAP Push (Cache Operation Textual form)");
+                       handleCOMessage(pPushBody, PushBodyLen, true, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_COC:
+                       MSG_DEBUG("Received WAP Push (Cache Operation Tokenised form)");
+                       handleCOMessage(pPushBody, PushBodyLen, false, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP:
+                       MSG_DEBUG("Received DM BOOTSTRAP");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DM_WBXML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP_XML:
+                       MSG_DEBUG("Received DM BOOTSTRAP");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DM_XML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_PROVISIONING_XML:
+                       MSG_DEBUG("Received Provisioning");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(CP_XML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_PROVISIONING_WBXML:
+                       MSG_DEBUG("Received Provisioning");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(CP_WBXML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_BROWSER_SETTINGS:
+               case SMS_WAP_APPLICATION_PUSH_BROWSER_BOOKMARKS:
+                       MSG_DEBUG("Received Provisioning");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(OTHERS, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_SYNCML_DM_NOTIFICATION:
+                       MSG_DEBUG("Received DM Notification");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DM_NOTIFICATION, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION:
+                       MSG_DEBUG("Received DS Notification");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DS_NOTIFICATION, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION_WBXML:
+                       MSG_DEBUG("Received DS Notification");
+                       SmsPluginEventHandler::instance()->handleSyncMLMsgIncoming(DS_WBXML, pPushBody, PushBodyLen, pWspHeader, WspHeaderLen, simIndex);
+                       break;
+
+               case SMS_WAP_APPLICATION_DRM_UA_RIGHTS_XML:
+               case SMS_WAP_APPLICATION_DRM_UA_RIGHTS_WBXML:
+                       MSG_DEBUG("Received DRM UA");
+
+                       if (pPushBody != NULL)
+                               handleDrmVer1(pPushBody, PushBodyLen);
+
+                       break;
+
+               case SMS_WAP_APPLICATION_DRM_V2_RO_XML:
+               case SMS_WAP_APPLICATION_DRM_V2_ROAP_PDU_XML:
+               case SMS_WAP_APPLICATION_DRM_V2_ROAP_TRIGGER_XML:
+               case SMS_WAP_APPLICATION_DRM_V2_ROAP_TRIGGER_WBXML:
+                       MSG_DEBUG("Received DRM V2");
+                       // TODO: DRM V2
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_EMAIL:
+               case SMS_WAP_APPLICATION_PUSH_EMAIL_XML:
+               case SMS_WAP_APPLICATION_PUSH_EMAIL_WBXML:
+                       MSG_DEBUG("Received Email");
+                       // TODO: Email
+                       break;
 
 
-void SmsPluginWapPushHandler::handleMMSNotification(const char *pPushBody, int PushBodyLen)
+               case SMS_WAP_APPLICATION_PUSH_IMPS_CIR:
+                       MSG_DEBUG("Received IMPS CIR");
+                       // TODO: IMPS CIR
+                       break;
+
+               case SMS_WAP_APPLICATION_LBS :
+                       MSG_DEBUG("Received LBS related message");
+                       SmsPluginEventHandler::instance()->handleLBSMsgIncoming(pPushHeader, pPushBody, PushBodyLen);
+                       // TODO: LBS
+                       break;
+
+               case SMS_WAP_APPLICATION_PUSH_SIA :
+                       MSG_DEBUG("Received SIA");
+                       // TODO: SIA
+                       break;
+
+               default:
+                       SmsPluginEventHandler::instance()->handlePushMsgIncoming(pPushHeader, pPushBody, PushBodyLen, app_id, content_type);
+                       break;
+               }
+       }
+       storageHandler->releasePushEvent();
+
+       MSG_END();
+}
+#endif
+
+void SmsPluginWapPushHandler::handleMMSNotification(const char *pPushBody, int PushBodyLen, int simIndex)
 {
        MSG_BEGIN();
 
+#ifdef MSG_FW_FOR_DEBUG
+       printf("\n\n[handleMMSNotification] Push Body.\n");
+
+       for (int i = 0; i < PushBodyLen; i++)
+       {
+               printf(" [%02x]", pPushBody[i]);
+       }
+       printf("\n\n");
+#endif
+
        /** Make MSG_MESSAGE_INFO_S */
        MSG_MESSAGE_INFO_S msgInfo;
        memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
 
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
        createMsgInfo(&msgInfo);
 
        /** Convert Type values */
        msgInfo.msgType.mainType = MSG_MMS_TYPE;
        msgInfo.msgType.subType = MSG_NOTIFICATIONIND_MMS;
-
+       msgInfo.msgType.classType = MSG_CLASS_NONE;
+       msgInfo.storageId = MSG_STORAGE_PHONE;
        msgInfo.dataSize = PushBodyLen;
+       msgInfo.sim_idx = simIndex;
 
        if (msgInfo.dataSize > MAX_MSG_TEXT_LEN) {
                msgInfo.bTextSms = false;
 
                /** Save Message Data into File */
-               char fileName[MAX_COMMON_INFO_SIZE+1];
+               char fileName[MSG_FILENAME_LEN_MAX+1];
                memset(fileName, 0x00, sizeof(fileName));
 
                if (MsgCreateFileName(fileName) == false)
@@ -1082,7 +1460,7 @@ void SmsPluginWapPushHandler::handleMMSNotification(const char *pPushBody, int P
        msg_error_t err = MSG_SUCCESS;
 
        /** Add MMS Noti Msg into DB */
-       err = SmsPluginStorage::instance()->addMessage(&msgInfo);
+       err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
 
        if (err == MSG_SUCCESS) {
                /**  Callback */
@@ -1092,13 +1470,13 @@ void SmsPluginWapPushHandler::handleMMSNotification(const char *pPushBody, int P
                        MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
                }
        } else {
-               MSG_DEBUG("addMessage() Error !! [%d]", err);
+               MSG_DEBUG("checkMessage() Error !! [%d]", err);
        }
 
        MSG_END();
 }
 
-void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen, bool isText)
+void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen, bool isText, int simIndex)
 {
        MSG_BEGIN();
 
@@ -1124,8 +1502,8 @@ void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen,
 
        topNode = xmlDocGetRootElement(xmlDoc);
 
-       if (xmlDoc == NULL) {
-               MSG_DEBUG("Empty Document");
+       if (topNode == NULL) {
+               MSG_DEBUG("topNode is NULL");
                xmlFreeDoc(xmlDoc);
                return;
        }
@@ -1134,7 +1512,7 @@ void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen,
 
        while (indNode != NULL) {
                if (!xmlStrcmp(indNode->name, (const xmlChar*) "indication")) {
-                       MSG_DEBUG("indNode->name = %s\n", indNode->name);
+                       MSG_SEC_DEBUG("indNode->name = %s\n", indNode->name);
                        break;
                }
 
@@ -1163,7 +1541,7 @@ void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen,
        }
 
        if (tmpXmlChar != NULL)
-               strncpy(pushMsg.href, (char*)tmpXmlChar, MAX_WAPPUSH_HREF_LEN-1);
+               strncpy(pushMsg.href, (char*)tmpXmlChar, MAX_WAPPUSH_HREF_LEN-1);
 
        tmpXmlChar = xmlGetProp(indNode, (xmlChar*)SMS_PUSH_XML_SI_ID_TAG);
 
@@ -1197,7 +1575,7 @@ void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen,
        strncpy(pushMsg.contents, (char*)tmpXmlChar, MAX_WAPPUSH_CONTENTS_LEN-1);
 
        /** Write push Msg to file */
-       char fileName[MAX_COMMON_INFO_SIZE+1];
+       char fileName[MSG_FILENAME_LEN_MAX+1];
        memset(fileName, 0x00, sizeof(fileName));
 
        if (MsgCreateFileName(fileName) == false) {
@@ -1214,6 +1592,10 @@ void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen,
 
        /**  Pack Message Info Structure */
        MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
 
        createMsgInfo(&msgInfo);
 
@@ -1224,6 +1606,8 @@ void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen,
        msgInfo.msgType.subType = MSG_WAP_SI_SMS;
 
        msgInfo.dataSize = sizeof(pushMsg);
+       msgInfo.sim_idx = simIndex;
+       getDisplayName(msgInfo.msgType.subType, msgInfo.addressList[0].addressVal);
 
        xmlFree(xmlDoc);
        xmlFree(tmpXmlChar);
@@ -1231,7 +1615,7 @@ void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen,
        msg_error_t err = MSG_SUCCESS;
 
        /** Add WAP Push Msg into DB */
-       err = SmsPluginStorage::instance()->addMessage(&msgInfo);
+       err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
 
        if (err == MSG_SUCCESS) {
                /** Callback */
@@ -1241,7 +1625,7 @@ void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen,
                        MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
                }
        } else {
-               MSG_DEBUG("addMessage() Error !! [%d]", err);
+               MSG_DEBUG("checkMessage() Error !! [%d]", err);
        }
 
        MSG_END();
@@ -1250,7 +1634,7 @@ void SmsPluginWapPushHandler::handleSIMessage(char* pPushBody, int PushBodyLen,
 }
 
 
-void SmsPluginWapPushHandler::handleSLMessage(char* pPushBody, int PushBodyLen, bool isText)
+void SmsPluginWapPushHandler::handleSLMessage(char* pPushBody, int PushBodyLen, bool isText, int simIndex)
 {
        MSG_BEGIN();
 
@@ -1262,6 +1646,8 @@ void SmsPluginWapPushHandler::handleSLMessage(char* pPushBody, int PushBodyLen,
 
        xmlChar*                tmpXmlChar = NULL;
 
+       msg_error_t err = MSG_SUCCESS;
+
        if (pPushBody == NULL) {
                MSG_DEBUG("pPushBody is NULL \n" );
                return;
@@ -1281,14 +1667,14 @@ void SmsPluginWapPushHandler::handleSLMessage(char* pPushBody, int PushBodyLen,
                xmlFreeDoc(xmlDoc);
                return;
        } else {
-               MSG_DEBUG("Not an empty Document and topNode->name = %s \n",topNode->name );
+               MSG_SEC_DEBUG("Not an empty Document and topNode->name = %s \n",topNode->name );
        }
 
        indNode = topNode;
 
        while (indNode != NULL) {
                if (!xmlStrcmp(indNode->name, (const xmlChar*) "sl")) {
-                       MSG_DEBUG("indNode->name = %s\n",indNode->name);
+                       MSG_SEC_DEBUG("indNode->name = %s\n",indNode->name);
                        break;
                }
 
@@ -1323,12 +1709,12 @@ void SmsPluginWapPushHandler::handleSLMessage(char* pPushBody, int PushBodyLen,
        MSG_DEBUG("pushMsg.received : [%d]", pushMsg.received);
        MSG_DEBUG("pushMsg.created : [%d]", pushMsg.created);
        MSG_DEBUG("pushMsg.expires : [%d]", pushMsg.expires);
-       MSG_DEBUG("pushMsg.id : [%s]", pushMsg.id);
+       MSG_SEC_DEBUG("pushMsg.id : [%s]", pushMsg.id);
        MSG_DEBUG("pushMsg.href : [%s]", pushMsg.href);
        MSG_DEBUG("pushMsg.contents : [%s]", pushMsg.contents);
 
        /** Write push Msg to file */
-       char fileName[MAX_COMMON_INFO_SIZE+1];
+       char fileName[MSG_FILENAME_LEN_MAX+1];
        memset(fileName, 0x00, sizeof(fileName));
 
        if (MsgCreateFileName(fileName) == false)
@@ -1339,6 +1725,10 @@ void SmsPluginWapPushHandler::handleSLMessage(char* pPushBody, int PushBodyLen,
 
        /** Pack Message Info Structure */
        MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
 
        createMsgInfo(&msgInfo);
 
@@ -1352,11 +1742,23 @@ void SmsPluginWapPushHandler::handleSLMessage(char* pPushBody, int PushBodyLen,
        strncpy(msgInfo.msgText, pushMsg.href, MAX_MSG_TEXT_LEN);
 
        msgInfo.dataSize = sizeof(pushMsg);
+       msgInfo.sim_idx = simIndex;
+       getDisplayName(msgInfo.msgType.subType, msgInfo.addressList[0].addressVal);
 
        MSG_DEBUG("dataSize : %d", msgInfo.dataSize);
 
-       /** Callback to MSG FW */
-       SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+       /** Add WAP Push Msg into DB */
+       err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
+
+       if (err == MSG_SUCCESS) {
+               /** Callback to MSG FW */
+               err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+
+               if (err != MSG_SUCCESS)
+                       MSG_DEBUG("callbackMsgIncoming is failed, err=[%d]", err);
+       } else {
+               MSG_DEBUG("checkMessage() Error !! [%d]", err);
+       }
 
        xmlFree(xmlDoc);
        xmlFree(tmpXmlChar);
@@ -1366,7 +1768,7 @@ void SmsPluginWapPushHandler::handleSLMessage(char* pPushBody, int PushBodyLen,
        return;
 }
 
-void SmsPluginWapPushHandler::handleCOMessage(char* pPushBody, int PushBodyLen, bool isText)
+void SmsPluginWapPushHandler::handleCOMessage(char* pPushBody, int PushBodyLen, bool isText, int simIndex)
 {
        MSG_PUSH_CACHEOP_S cacheOp;
 
@@ -1404,7 +1806,7 @@ void SmsPluginWapPushHandler::handleCOMessage(char* pPushBody, int PushBodyLen,
 
                xmlChar* tmpUrl = NULL;
                if (!xmlStrcmp(indNode->name, (const xmlChar*) SMS_PUSH_XML_INVAL_OBJ)) {
-                       MSG_DEBUG("indNode->name = %s\n", indNode->name);
+                       MSG_SEC_DEBUG("indNode->name = %s\n", indNode->name);
 
                        tmpUrl = xmlGetProp(indNode, (xmlChar*) SMS_PUSH_XML_CO_URI);
 
@@ -1416,7 +1818,7 @@ void SmsPluginWapPushHandler::handleCOMessage(char* pPushBody, int PushBodyLen,
                                MSG_DEBUG("NO href value from the xmlDoc\n");
                        }
                } else if (!xmlStrcmp(indNode->name, (const xmlChar*) SMS_PUSH_XML_INVAL_SVC)) {
-                       MSG_DEBUG("indNode->name = %s\n",indNode->name);
+                       MSG_SEC_DEBUG("indNode->name = %s\n",indNode->name);
                        tmpUrl = xmlGetProp(indNode, (xmlChar*)SMS_PUSH_XML_CO_URI);
 
                        if (tmpUrl != NULL) {
@@ -1434,7 +1836,7 @@ void SmsPluginWapPushHandler::handleCOMessage(char* pPushBody, int PushBodyLen,
        }
 
        /**  Write push Msg to file */
-       char fileName[MAX_COMMON_INFO_SIZE+1];
+       char fileName[MSG_FILENAME_LEN_MAX+1];
        memset(fileName, 0x00, sizeof(fileName));
 
        if (MsgCreateFileName(fileName) == false) {
@@ -1449,6 +1851,10 @@ void SmsPluginWapPushHandler::handleCOMessage(char* pPushBody, int PushBodyLen,
 
        /**  Pack Message Info Structure */
        MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
 
        createMsgInfo(&msgInfo);
 
@@ -1459,11 +1865,12 @@ void SmsPluginWapPushHandler::handleCOMessage(char* pPushBody, int PushBodyLen,
        msgInfo.msgType.subType = MSG_WAP_CO_SMS;
 
        msgInfo.dataSize = sizeof(cacheOp);
+       msgInfo.sim_idx = simIndex;
 
        msg_error_t err = MSG_SUCCESS;
 
        /** Add WAP Push Msg into DB */
-       err = SmsPluginStorage::instance()->addMessage(&msgInfo);
+       err = SmsPluginStorage::instance()->checkMessage(&msgInfo);
 
        if (err == MSG_SUCCESS) {
                /** Callback */
@@ -1473,7 +1880,7 @@ void SmsPluginWapPushHandler::handleCOMessage(char* pPushBody, int PushBodyLen,
                        MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
                }
        } else {
-               MSG_DEBUG("addMessage() Error !! [%d]", err);
+               MSG_DEBUG("checkMessage() Error !! [%d]", err);
        }
 
        xmlFree(xmlDoc);
@@ -1484,9 +1891,10 @@ void SmsPluginWapPushHandler::handleCOMessage(char* pPushBody, int PushBodyLen,
 
 void SmsPluginWapPushHandler::handleDrmVer1(char* pPushBody, int PushBodyLen)
 {
+#if MSG_DRM_SUPPORT
        int drmRt = DRM_RETURN_SUCCESS;
        char* cid = NULL;
-       AutoPtr<char> buf(&cid);
+       unique_ptr<char*, void(*)(char**)> buf(&cid, unique_ptr_deleter);
 
        MSG_DEBUG("Received DRM RIGHTS OBJECT Type WAP Push Message.");
        drm_request_type_e request_type = DRM_REQUEST_TYPE_REGISTER_LICENSE;
@@ -1509,7 +1917,7 @@ void SmsPluginWapPushHandler::handleDrmVer1(char* pPushBody, int PushBodyLen)
        } else {
                MSG_DEBUG("Fail to regist DRM to drm-service.");
        }
-
+#endif
        return;
 }
 
@@ -1528,20 +1936,76 @@ void SmsPluginWapPushHandler::createMsgInfo(MSG_MESSAGE_INFO_S* pMsgInfo)
        pMsgInfo->priority = MSG_MESSAGE_PRIORITY_NORMAL;
        pMsgInfo->direction = MSG_DIRECTION_TYPE_MT;
 
-
        time_t rawtime = time(NULL);
 
+/*** Comment below lines to save local UTC time..... (it could be used later.)
+
+       if (tmpTimeStamp.format == SMS_TIME_ABSOLUTE) {
+
+               MSG_DEBUG("year : %d", tmpTimeStamp.time.absolute.year);
+               MSG_DEBUG("month : %d", tmpTimeStamp.time.absolute.month);
+               MSG_DEBUG("day : %d", tmpTimeStamp.time.absolute.day);
+               MSG_DEBUG("hour : %d", tmpTimeStamp.time.absolute.hour);
+               MSG_DEBUG("minute : %d", tmpTimeStamp.time.absolute.minute);
+               MSG_DEBUG("second : %d", tmpTimeStamp.time.absolute.second);
+               MSG_DEBUG("timezone : %d", tmpTimeStamp.time.absolute.timeZone);
+
+               char displayTime[32];
+               struct tm * timeTM;
+
+               struct tm timeinfo;
+               memset(&timeinfo, 0x00, sizeof(tm));
+
+               timeinfo.tm_year = (tmpTimeStamp.time.absolute.year + 100);
+               timeinfo.tm_mon = (tmpTimeStamp.time.absolute.month - 1);
+               timeinfo.tm_mday = tmpTimeStamp.time.absolute.day;
+               timeinfo.tm_hour = tmpTimeStamp.time.absolute.hour;
+               timeinfo.tm_min = tmpTimeStamp.time.absolute.minute;
+               timeinfo.tm_sec = tmpTimeStamp.time.absolute.second;
+               timeinfo.tm_isdst = 0;
+
+               rawtime = mktime(&timeinfo);
+
+               MSG_DEBUG("tzname[0] [%s]", tzname[0]);
+               MSG_DEBUG("tzname[1] [%s]", tzname[1]);
+               MSG_DEBUG("timezone [%d]", timezone);
+               MSG_DEBUG("daylight [%d]", daylight);
+
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", &timeinfo);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= (tmpTimeStamp.time.absolute.timeZone * (3600/4));
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+
+               rawtime -= timezone;
+
+               timeTM = localtime(&rawtime);
+               memset(displayTime, 0x00, sizeof(displayTime));
+               strftime(displayTime, 32, "%Y-%02m-%02d %T %z", timeTM);
+               MSG_DEBUG("displayTime [%s]", displayTime);
+       }
+
+***/
+
        pMsgInfo->displayTime = rawtime;
 
        /**  Convert Address values */
        pMsgInfo->nAddressCnt = 1;
+
+       pMsgInfo->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S)];
+       memset(pMsgInfo->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
        pMsgInfo->addressList[0].addressType = MSG_ADDRESS_TYPE_PLMN;
        strncpy(pMsgInfo->addressList[0].addressVal, tmpAddress.address, MAX_ADDRESS_VAL_LEN);
 
        pMsgInfo->msgPort.valid = false;
        pMsgInfo->msgPort.dstPort = 0;
        pMsgInfo->msgPort.srcPort = 0;
-
 }
 
 void SmsPluginWapPushHandler::getXmlDoc(const char* pPushBody, const int PushBodyLen, xmlDocPtr *pXmlDoc, const bool isText)
@@ -1553,7 +2017,7 @@ void SmsPluginWapPushHandler::getXmlDoc(const char* pPushBody, const int PushBod
 
 
        if (isText) {
-               *pXmlDoc = xmlParseMemory(pPushBody, strlen(pPushBody));
+               *pXmlDoc = xmlParseMemory(pPushBody, AcStrlen(pPushBody));
        } else {
                WB_UTINY*       xmldata = NULL;
                WBXMLConvWBXML2XML *conv = NULL;
@@ -1574,7 +2038,7 @@ void SmsPluginWapPushHandler::getXmlDoc(const char* pPushBody, const int PushBod
 
                MSG_DEBUG("xmldata : \n%s\n", xmldata);
 
-               *pXmlDoc = xmlParseMemory((char*)xmldata, strlen((char*)xmldata));
+               *pXmlDoc = xmlParseMemory((char*)xmldata, AcStrlen((char*)xmldata));
        }
 
 }
@@ -1587,10 +2051,10 @@ unsigned long SmsPluginWapPushHandler::convertXmlCharToSec(char* pDate)
        int                     i = 0, index = 0;
 
        memset(tmpBuf, 0x00, sizeof(tmpBuf));
-       memset(&timeStruct, 0x00, sizeof(&timeStruct));
+       memset(&timeStruct, 0x00, sizeof(struct tm));
 
        /** check pDate */
-       if (strlen(pDate)<20)
+       if (AcStrlen(pDate)<20)
                return 0;
 
        MSG_DEBUG("pDate [%s]", pDate);
@@ -1658,27 +2122,27 @@ msg_push_action_t SmsPluginWapPushHandler::convertSIActionStrToEnum(char* pActio
        }
 
        /** compare  with signal-none. */
-       comp = strcmp( "signal-none", pAction );
+       comp = g_strcmp0( "signal-none", pAction );
        if (comp == 0)
                return MSG_PUSH_SI_ACTION_SIGNAL_NONE;
 
        /** compare  with signal-low. */
-       comp = strcmp( "signal-low", pAction );
+       comp = g_strcmp0( "signal-low", pAction );
        if (comp == 0)
                return MSG_PUSH_SI_ACTION_SIGNAL_LOW;
 
        /**  compare  with signal-medium. */
-       comp = strcmp( "signal-medium", pAction );
+       comp = g_strcmp0( "signal-medium", pAction );
        if (comp == 0)
                return MSG_PUSH_SI_ACTION_SIGNAL_MEDIUM;
 
        /**  compare  with signal-high. */
-       comp = strcmp( "signal-high", pAction );
+       comp = g_strcmp0( "signal-high", pAction );
        if (comp == 0)
                return MSG_PUSH_SI_ACTION_SIGNAL_HIGH;
 
        /**  compare  with delete. */
-       comp = strcmp( "delete", pAction );
+       comp = g_strcmp0( "delete", pAction );
        if (comp == 0)
                return MSG_PUSH_SI_ACTION_DELETE;
 
@@ -1697,17 +2161,17 @@ msg_push_action_t SmsPluginWapPushHandler::convertSLActionStrToEnum(char* pActio
        }
 
        /**  compare pSrcStr with execute-low. */
-       comp = strcmp( "execute-low", pAction );
+       comp = g_strcmp0( "execute-low", pAction );
        if (comp == 0)
                return MSG_PUSH_SL_ACTION_EXECUTE_LOW;
 
        /**  compare pSrcStr with execute-high. */
-       comp = strcmp( "execute-high", pAction );
+       comp = g_strcmp0( "execute-high", pAction );
        if (comp == 0)
                return MSG_PUSH_SL_ACTION_EXECUTE_HIGH;
 
        /** compare pSrcStr with cache. */
-       comp = strcmp( "cache", pAction );
+       comp = g_strcmp0( "cache", pAction );
        if (comp == 0)
                return MSG_PUSH_SL_ACTION_CACHE;
 
@@ -1752,12 +2216,12 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
        unsigned long currentLength;
 
        char* encodedHeader = NULL;
-       AutoPtr<char> encodedHeaderbuf(&encodedHeader);
+       unique_ptr<char*, void(*)(char**)> encodedHeaderbuf(&encodedHeader, unique_ptr_deleter);
 
        char* outTemper = NULL;
 
        char* temper = NULL;
-       AutoPtr<char> temperbuf(&temper);
+       unique_ptr<char*, void(*)(char**)> temperbuf(&temper, unique_ptr_deleter);
 
        unsigned char track;
        unsigned long iEncodedHeader = 0;
@@ -1822,13 +2286,17 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
        /* Is it reacehd end of header? */
        while (iEncodedHeader < encodedHeaderLen) {
                /* Get memory for single header */
-               temper = new char[ WSP_STANDARD_STR_LEN_MAX * 5 ];
                if (temper == NULL) {
-                       MSG_DEBUG("temper Memory allocation is failed.\n" );
-                       return;
-               }
+                       temper = new char[ WSP_STANDARD_STR_LEN_MAX * 5 ];
 
-               memset(temper, 0x00, (WSP_STANDARD_STR_LEN_MAX * 5));
+                       if (temper == NULL) {
+                               MSG_DEBUG("temper Memory allocation is failed.\n" );
+                               return;
+                       }
+                       memset(temper, 0x00, (WSP_STANDARD_STR_LEN_MAX * 5));
+               } else {
+                       memset(temper, 0x00, (WSP_STANDARD_STR_LEN_MAX * 5));
+               }
 
                /* this section presents header code page shifting procedure
                   This part can be implemented by future request.
@@ -1986,7 +2454,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                                        /* If parameter exist */
                                                                        if (iField < fieldValueLen) {
                                                                                char* param = NULL;
-                                                                               AutoPtr<char> parambuf(&param);
+                                                                               unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
                                                                                wspHeaderDecodeQValue( fieldValueLen - iField, fieldValue + iField, &param);
                                                                                strncat( (char*)temper, (char*)param, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
                                                                        }
@@ -2027,6 +2495,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                                unsigned long  i = 0;
                                                                /* encoded content type length body */
                                                                unsigned long  tempLen;
+                                                               MSG_DEBUG("fieldValueLen: %d", fieldValueLen);
 
                                                                /* Like HTTP result state 304, it's for processing without Content type. This part doesn't defined. */
                                                                if (0 == fieldValueLen) {
@@ -2039,8 +2508,8 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                                        MSG_DEBUG("WspLDecodeHeader:For mmO2 problem\r\n" );
                                                                }
 
-                                                               if ((fieldValue[0] < 0x20 ) || (fieldValue[0] > 0x80 )) {
-                                                                       if (fieldValue[0] > 0x80) {
+                                                               if ((fieldValue[0] < 0x20 ) || (fieldValue[0] >= 0x80 )) {
+                                                                       if (fieldValue[0] >= 0x80) {
                                                                                tempLen = 1;
                                                                        } else if (fieldValueLen == 2 && fieldValue[0] == 0x03 && fieldValue[1] == 0x0A) { /** 06 05 02 03 0A AF 89 */
                                                                                fieldValue[3] = fieldValue[2];
@@ -2074,7 +2543,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                                        } else {
                                                                                contentsTypeCode = wspHeaderDecodeInteger(fieldValue);
 
-                                                                               while ((wspUnregisterContentsType[i].contentsTypeCode != contentsTypeCode) && (i < wspUnregisteredContentsTypeCount)) i++;
+                                                                               while ((i < wspUnregisteredContentsTypeCount) && (wspUnregisterContentsType[i].contentsTypeCode != contentsTypeCode)) i++;
 
                                                                                /** If there is a Content-Type assigned, */
                                                                                if (i < wspUnregisteredContentsTypeCount)
@@ -2092,7 +2561,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                                /* If there is a parameter */
                                                                if (tempLen < fieldValueLen) {
                                                                        char* param = NULL;
-                                                                       AutoPtr<char> parambuf(&param);
+                                                                       unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
                                                                        wspHeaderDecodeParameter( fieldValue + tempLen, fieldValueLen - tempLen, &param);
                                                                        if (param != NULL) {
                                                                                strncat( (char*)temper, "; ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1);
@@ -2138,7 +2607,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
 
                                                                if (tempLen < fieldValueLen) {
                                                                        char* param = NULL;
-                                                                       AutoPtr<char> parambuf(&param);
+                                                                       unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
                                                                        wspHeaderDecodeQValue(  fieldValueLen - tempLen, fieldValue + tempLen, &param );
                                                                        strncat( (char*)temper, (char*)param, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
                                                                }
@@ -2182,19 +2651,22 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
 
                                                                integerValue = wspHeaderDecodeIntegerByLength(fieldValue, fieldValueLen);
 
-                                                               if (integerValue > 0x0A) {
-                                                                       MSG_DEBUG("WspLDecodeHeader: integerValue is over limit(0x0A).\n");
-                                                                       break;
+                                                               int count = sizeof(wspHeaderApplId)/sizeof(SMS_WSP_HEADER_PARAMETER_S);
+                                                               for(int i = 0; i < count ; ++i)
+                                                               {
+                                                                       if ((unsigned int)integerValue == wspHeaderApplId[i].parameterCode)
+                                                                       {
+                                                                               snprintf((char*)temp, 64, "%s", wspHeaderApplId[i].parameterToken);
+                                                                               strncat((char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1);
+                                                                               break;
+                                                                       }
                                                                }
-
-                                                               snprintf((char*)temp, 64, "%s", wspHeaderApplId[integerValue].parameterToken);
-                                                               strncat((char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(temper)-1);
                                                        }
                                                        break;
                                                /* Accept-Application */
                                                case 0x32 :
                                                        if (0x80 == fieldValue[0]) {
-                                                               strncat( (char*)temper, "*", (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(temper)-1 );
+                                                               strncat( (char*)temper, "*", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1 );
                                                        } else {
 
                                                                unsigned char temp[16];
@@ -2204,7 +2676,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                 else
                                                                */
                                                                sprintf( (char*)temp, "%u", (unsigned int)wspHeaderDecodeIntegerByLength( fieldValue, fieldValueLen ));
-                                                               strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(temper)-1);
+                                                               strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1);
                                                        }
                                                        break;
 
@@ -2224,23 +2696,23 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                case 0x12 :
                                                        {
                                                                char* decodedString = NULL;
-                                                               AutoPtr<char> decodedStringbuf(&decodedString);
+                                                               unique_ptr<char*, void(*)(char**)> decodedStringbuf(&decodedString, unique_ptr_deleter);
                                                                wspHeaderDecodeDateValue( fieldValueLen, fieldValue, &decodedString);
-                                                               strncat( (char*)temper, (char*)decodedString, (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(temper)-1 );
+                                                               strncat( (char*)temper, (char*)decodedString, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1 );
                                                        }
                                                        break;
 
                                                /* connection */
                                                case 0x09 :
                                                        if (fieldValue[0] == 0x80 )
-                                                               strncat( (char*)temper, "Close", (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(temper)-1 );
+                                                               strncat( (char*)temper, "Close", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1 );
                                                        break;
                                                /* accept-ranges */
                                                case 0x04 :
                                                        if (fieldValue[0] == 0x80 )
-                                                               strncat( (char*)temper, "None", (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(temper)-1 );
+                                                               strncat( (char*)temper, "None", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1 );
                                                        if (fieldValue[0] == 0x81 )
-                                                               strncat( (char*)temper, "Bytes", (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(temper)-1 );
+                                                               strncat( (char*)temper, "Bytes", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen(temper)-1 );
                                                        break;
                                                /* content-md5 */
                                                case 0x0f :
@@ -2258,7 +2730,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                case 0x21 :
                                                        if (fieldValue[0] == 0x80) {
                                                                char* addString = NULL;
-                                                               AutoPtr<char> addStringbuf(&addString);
+                                                               unique_ptr<char*, void(*)(char**)> addStringbuf(&addString, unique_ptr_deleter);
                                                                wspHeaderDecodeAuth(fieldValueLen, fieldValue, &addString );
                                                                strncat( (char*)temper, addString, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
                                                        } else {
@@ -2267,7 +2739,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                                strncat( (char*)temper, (char*)fieldValue, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
                                                                if (iField < fieldValueLen) {
                                                                        char* param = NULL;
-                                                                       AutoPtr<char> parambuf(&param);
+                                                                       unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
                                                                        wspHeaderDecodeParameter( fieldValue + 1, fieldValueLen - 1, &param );
                                                                        if (param != NULL) {
                                                                                strncat( (char*)temper, ", ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
@@ -2287,7 +2759,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                                break;
                                                        if (fieldValue[0] == 0x80) {
                                                                char* addString = NULL;
-                                                               AutoPtr<char> addStringbuf(&addString);
+                                                               unique_ptr<char*, void(*)(char**)> addStringbuf(&addString, unique_ptr_deleter);
                                                                wspHeaderDecodeChallenge(fieldValueLen, fieldValue, &addString );
                                                                strncat( (char*)temper, addString, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
                                                        } else {
@@ -2299,12 +2771,12 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                                iField = AcStrlen( (char*)authScheme ) + 1;
                                                                strncpy( (char*)realmValue, (char*)(fieldValue + iField ), WSP_STANDARD_STR_LEN_MAX-1);
                                                                iField = iField + AcStrlen( (char*)realmValue ) + 1;
-                                                               sprintf( (char*)addedString, "%s %s", authScheme, realmValue );
+                                                               snprintf( (char*)addedString, sizeof(addedString), "%s %s", authScheme, realmValue );
                                                                wspHeaderCopyDecodedString( addedString, &currentLength, &temper );
 
                                                                if (iField < fieldValueLen) {
                                                                        char* param = NULL;
-                                                                       AutoPtr<char> parambuf(&param);
+                                                                       unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
                                                                        wspHeaderDecodeParameter( fieldValue + iField, fieldValueLen - iField, &param );
                                                                        if (param != NULL) {
                                                                                strncat( (char*)temper, ", ", (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
@@ -2339,7 +2811,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                case 0x08 :
                                                        {
                                                                char* cacheString = NULL;
-                                                               AutoPtr<char> cacheStringbuf(&cacheString);
+                                                               unique_ptr<char*, void(*)(char**)> cacheStringbuf(&cacheString, unique_ptr_deleter);
 
                                                                wspHeaderDecodeCacheControl( fieldValue, fieldValueLen, &cacheString );
                                                                strncat( (char*)temper, (char*)cacheString, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
@@ -2353,7 +2825,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                        } else {
                                                                if (1 < fieldValueLen) {
                                                                        char* param = NULL;
-                                                                       AutoPtr<char> parambuf(&param);
+                                                                       unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
                                                                        wspHeaderDecodeParameter( fieldValue, fieldValueLen, &param );
 
                                                                        if (param != NULL) {
@@ -2402,7 +2874,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                case 0x25 :
                                                        if (fieldValue[0] == 0x80) {
                                                                char* temp = NULL;
-                                                               AutoPtr<char> tempbuf(&temp);
+                                                               unique_ptr<char*, void(*)(char**)> tempbuf(&temp, unique_ptr_deleter);
 
                                                                wspHeaderDecodeDateValue( fieldValueLen - 1, fieldValue + 1, &temp );
                                                                strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
@@ -2411,7 +2883,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                        if (fieldValue[0] == 0x81) {
                                                                unsigned char temp[16];
 
-                                                               sprintf( (char*)temp, "%u", (unsigned int)wspHeaderDecodeIntegerByLength( fieldValue,fieldValueLen ));
+                                                               snprintf( (char*)temp, sizeof((char*)temp), "%u", (unsigned int)wspHeaderDecodeIntegerByLength( fieldValue,fieldValueLen ));
                                                                strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
                                                        }
                                                        break;
@@ -2436,14 +2908,14 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                /* warning */
                                                case 0x2c :
                                                        {
-
                                                                unsigned char temp[WSP_STANDARD_STR_LEN_MAX];
 
                                                                if (fieldValue[0] < 0x20 )
                                                                        iField = fieldValue[0];
                                                                else
                                                                        iField = 1;
-                                                               sprintf( (char*)temp, "%u", (unsigned int)wspHeaderDecodeIntegerByLength( fieldValue, iField ));
+
+                                                               snprintf( (char*)temp, sizeof(temp), "%u", (unsigned int)wspHeaderDecodeIntegerByLength( fieldValue, iField ));
                                                                strncat( (char*)temper, (char*)temp, (WSP_STANDARD_STR_LEN_MAX * 5)-AcStrlen((char*)temper)-1 );
                                                                if (iField < fieldValueLen) {
                                                                        unsigned char agent[WSP_STANDARD_STR_LEN_MAX];
@@ -2451,8 +2923,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                                        strncpy( (char*)agent, (char*)(fieldValue + iField ),WSP_STANDARD_STR_LEN_MAX-1);
                                                                        iField = iField + AcStrlen((char*)agent ) + 1;
                                                                        strncpy((char*)text, (char*)(fieldValue + iField ),WSP_STANDARD_STR_LEN_MAX-1);
-
-                                                                       sprintf( (char*)temp, " %s %s", agent, text );
+                                                                       snprintf( (char*)temp, sizeof(temp), " %s %s", agent, text );
                                                                        wspHeaderCopyDecodedString( temp, &currentLength, &temper );
                                                                }
                                                        }
@@ -2467,7 +2938,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
 
                                                        if (1 < fieldValueLen) {
                                                                char* param = NULL;
-                                                               AutoPtr<char> parambuf(&param);
+                                                               unique_ptr<char*, void(*)(char**)> parambuf(&param, unique_ptr_deleter);
                                                                wspHeaderDecodeParameter( fieldValue + 1, fieldValueLen - 1, &param );
 
                                                                if (param != NULL) {
@@ -2486,7 +2957,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                        {
                                                                unsigned char temp[WSP_STANDARD_STR_LEN_MAX];
 
-                                                               sprintf( (char*)temp, "%lX", wspHeaderDecodeInteger(fieldValue ));
+                                                               snprintf( (char*)temp, sizeof(temp), "%lX", wspHeaderDecodeInteger(fieldValue ));
                                                                temp[2] = temp[1];
                                                                temp[1] = (unsigned char)0x30;
                                                                temp[3] = '\0';
@@ -2496,7 +2967,7 @@ void SmsPluginWapPushHandler::wspDecodeHeader( unsigned char* sEncodedHeader, un
                                                                        if (fieldValueLen > ( AcStrlen( (char*)(fieldValue + 1)) + 1 )) {
                                                                                /* copy warn-date */
                                                                                char* decodedString = NULL;
-                                                                               AutoPtr<char> decodedStringbuf(&decodedString);
+                                                                               unique_ptr<char*, void(*)(char**)> decodedStringbuf(&decodedString, unique_ptr_deleter);
                                                                                wspHeaderDecodeDateValue( fieldValueLen - ( AcStrlen( (char*)(fieldValue + 1)) + 2 ), fieldValue + AcStrlen( (char*)(fieldValue + 1)) + 1, &decodedString );
                                                                                strncat( (char*)temp, (char*)decodedString, WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)temp)-1 );
                                                                        }
@@ -2588,7 +3059,7 @@ void SmsPluginWapPushHandler::wspHeaderDecodeQValue( unsigned long length, unsig
        if (qValue > 100) {
                qValue = qValue - 100;
                qValue = qValue / 1000;
-               sprintf( (char*)*pDecodedString, "; q=%.3f", qValue );
+               snprintf( (char*)*pDecodedString, sizeof(char)*WSP_STANDARD_STR_LEN_MAX, "; q=%.3f", qValue );
        } else {
                /* qValue variable is divided by 100. And it's multiplied by 100.
                   It's to resolve problem of changed 0.01 of qValue. */
@@ -2597,9 +3068,9 @@ void SmsPluginWapPushHandler::wspHeaderDecodeQValue( unsigned long length, unsig
                qValue = qValue / 100;
                qValueTemp = (unsigned long)(qValue * 100);
                if (0 == (qValueTemp % 10 ))
-                       sprintf( (char*)*pDecodedString, "; q=%.1f", qValue );
+                       snprintf( (char*)*pDecodedString, sizeof(char)*WSP_STANDARD_STR_LEN_MAX, "; q=%.1f", qValue );
                else
-                       sprintf( (char*)*pDecodedString, "; q=%.2f", qValue );
+                       snprintf( (char*)*pDecodedString, sizeof(char)*WSP_STANDARD_STR_LEN_MAX, "; q=%.2f", qValue );
        }
        return;
 }
@@ -2668,7 +3139,7 @@ void SmsPluginWapPushHandler::wspHeaderDecodeParameter( unsigned char* data, uns
                }
 
                strncat( (char*)param, "=", WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)param)-1 );
-               strncat( (char*)param, (char*)(data + AcStrlen( (char*)param )), WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)param)-1);
+               strncat( (char*)param, (char*)(data + strlen( (char*)param )), WSP_STANDARD_STR_LEN_MAX-strlen((char*)param)-1);
 
                *pParam = param;
 
@@ -2694,7 +3165,7 @@ void SmsPluginWapPushHandler::wspHeaderDecodeParameter( unsigned char* data, uns
                                MSG_DEBUG("WspLHeaderDecodeParameter: 0x03 MemAlloc failed\n");
                                return;
                        } else {
-                               sprintf( (char*)param, "Type=%i", (int)wspHeaderDecodeInteger( data + 1 ));
+                               snprintf((char*)param, sizeof(char)*WSP_STANDARD_STR_LEN_MAX, "Type=%i", (int)wspHeaderDecodeInteger( data + 1 ));
                        }
                        break;
                case 0x08 :
@@ -2704,7 +3175,7 @@ void SmsPluginWapPushHandler::wspHeaderDecodeParameter( unsigned char* data, uns
                                MSG_DEBUG("WspLHeaderDecodeParameter:0x08 MemAlloc failed\n");
                                return;
                        } else {
-                               sprintf( (char*)param, "Padding=%i", (int)wspHeaderDecodeInteger( data + 1 ));
+                               snprintf((char*)param, sizeof(char)*WSP_STANDARD_STR_LEN_MAX, "Padding=%i", (int)wspHeaderDecodeInteger( data + 1 ));
                        }
                        break;
                case 0x05 :
@@ -2771,31 +3242,41 @@ void SmsPluginWapPushHandler::wspHeaderDecodeParameter( unsigned char* data, uns
 void SmsPluginWapPushHandler::wspHeaderDecodeCharset( unsigned long length, unsigned char* data, char**pDecodedString)
 {
 
-       *pDecodedString = new char[WSP_STANDARD_STR_LEN_MAX];
+       char* param = NULL;
 
-       if (*pDecodedString == NULL) {
+       param = new char[WSP_STANDARD_STR_LEN_MAX];
+
+       if (param == NULL) {
                MSG_DEBUG("WspLHeaderDecodeCharset:MemAlloc failed\n");
+               *pDecodedString = NULL;
                return;
        }
 
-       strncpy( (char*)*pDecodedString, "charset=", WSP_STANDARD_STR_LEN_MAX-1);
+       strncpy( (char*)param, "charset=", WSP_STANDARD_STR_LEN_MAX-1);
 
        if (data[0] > 0x80) {
                unsigned long code = wspHeaderDecodeInteger(data );
                unsigned long i = 0;
                while (wspCharset[i].charsetCode !=  code) {
                        if (wspCharset[i].charsetCode == 0xffff) {
+                               *pDecodedString = param;
                                return;
                        }
                        i++;
                }
-               strncat( (char*)*pDecodedString, (char*)wspCharset[i].charsetName, WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)*pDecodedString)-1 );
+               strncat( (char*)param, (char*)wspCharset[i].charsetName, WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)param)-1 );
        } else {
-               unsigned long  lastLen = AcStrlen((char*)*pDecodedString);
-               memcpy( (char*)(*pDecodedString + lastLen), data, (size_t)length );
-               *pDecodedString[length + lastLen] = '\0';
+               unsigned long lastLen = AcStrlen((char*)param);
+               if (length + lastLen < WSP_STANDARD_STR_LEN_MAX - 1) {
+                       memcpy( (char*)(param + lastLen), data, (size_t)length );
+                       param[length + lastLen] = '\0';
+               } else {
+                       memcpy( (char*)(param + lastLen), data, WSP_STANDARD_STR_LEN_MAX - lastLen - 1 );
+                       param[WSP_STANDARD_STR_LEN_MAX-1] = '\0';
+               }
        }
 
+       *pDecodedString = param;
        return;
 }
 
@@ -2817,7 +3298,7 @@ void SmsPluginWapPushHandler::wspHeaderDecodeVersion( unsigned long length, unsi
                /* typed version */
                unsigned char majorVer  = ((data[0] & 0x7f ) >> 4 );
                unsigned char minorVer = data[0] & 0x0f;
-               sprintf( (char*)*pDecodedString, "level=%u.%u", majorVer, minorVer );
+               snprintf( (char*)*pDecodedString, sizeof(char)*WSP_STANDARD_STR_LEN_MAX, "level=%u.%u", majorVer, minorVer );
        }
 
        return;
@@ -2827,7 +3308,7 @@ void SmsPluginWapPushHandler::wspHeaderDecodeVersion( unsigned long length, unsi
 void SmsPluginWapPushHandler::wspHeaderDecodeDateValue( unsigned long length, unsigned char* data, char** pDecodedString )
 {
        time_t  lTime;
-       struct  tm* pTMData;
+       struct  tm pTMData;
 
        MSG_DEBUG("WspLHeaderDecodeDateValue:   \n" );
 
@@ -2840,27 +3321,49 @@ void SmsPluginWapPushHandler::wspHeaderDecodeDateValue( unsigned long length, un
 
        lTime = wspHeaderDecodeIntegerByLength(data, length);
 
-       pTMData = (struct tm*)gmtime((const time_t* )&lTime);
+       (struct tm*)gmtime_r((const time_t* )&lTime, &pTMData);
 
-       if (pTMData == NULL) {
-               MSG_DEBUG( "WspLHeaderDecodeDateValue: Date decode fail \n" );
-               strncpy( (char*)*pDecodedString, "Decoding Failed", WSP_STANDARD_STR_LEN_MAX-1);
-               return;
-       }
+//     if (pTMData == NULL) {
+//             MSG_DEBUG( "WspLHeaderDecodeDateValue: Date decode fail \n" );
+//             strncpy( (char*)*pDecodedString, "Decoding Failed", WSP_STANDARD_STR_LEN_MAX-1);
+//             return;
+//     }
 
        /* check date value validity */
        {
-               if (( pTMData->tm_wday > 6 ) || (pTMData->tm_mon > 12 ) || (pTMData->tm_mday >  31 ))
+               if (( pTMData.tm_wday > 6 ) || (pTMData.tm_mon > 11 ) || (pTMData.tm_mday >  31 ))
                {
-                       MSG_DEBUG( "WspLHeaderDecodeDateValue: Date decode fail %d, %d, %d \n", pTMData->tm_wday, pTMData->tm_mon, pTMData->tm_mday );
+                       MSG_DEBUG( "WspLHeaderDecodeDateValue: Date decode fail %d, %d, %d \n", pTMData.tm_wday, pTMData.tm_mon, pTMData.tm_mday );
                        strncpy( (char*)*pDecodedString, "Decoding Failed", WSP_STANDARD_STR_LEN_MAX-1);
                        return;
                }
        }
 
+#ifdef MSG_FW_FOR_DEBUG
+       /** Date type selection */
+       switch ( wspMachineStatus.dateType )
+       {
+                       /* UNIX asciitime function */
+               case UNIX_DATE_TYPE :
+                       snprintf( (char*)decodedString, sizeof(decodedString), "%s %s %-2u %u:%u:%u %u GMT", wspWeek[pTMData.tm_wday], wspMonth[pTMData.tm_mon],
+                                          pTMData.tm_mday, pTMData.tm_hour, pTMData.tm_min, pTMData.tm_sec, pTMData.tm_year + 1900 );
+                       break;
+               case RFC1123_DATE_TYPE :
+                       snprintf( (char*)decodedString, sizeof(decodedString), "%s, %u %s %u %u:%u:%u GMT", wspWeek[pTMData.tm_wday], pTMData.tm_mday,
+                                          wspMonth[pTMData.tm_mon], pTMData.tm_year + 1900, pTMData.tm_hour, pTMData.tm_min, pTMData.tm_sec );
+                       break;
+               case RFC850_DATE_TYPE :
+                       /* Have some Y2K Problems */
+                       /* In RFC 850, date is represented like 11-May-99. So Y2K problem always can be occured. So remainer (year divided by 100) is used.                     */
+                       snprintf( (char*)decodedString, sizeof(decodedString), "%s, %2u-%s-%2u %u:%u:%u GMT", wspWeekDay[pTMData.tm_wday], pTMData.tm_mday,
+                                          wspMonth[pTMData.tm_mon], pTMData.tm_year % CENTURY, pTMData.tm_hour, pTMData.tm_min, pTMData.tm_sec );
+
+                       break;
+       }
+#endif
        /**UNIX_DATE_TYPE : */
-       sprintf( (char*)*pDecodedString, "%s %s %-2u %u:%u:%u %u GMT", wspWeek[pTMData->tm_wday], wspMonth[pTMData->tm_mon],
-                                                                                       pTMData->tm_mday, pTMData->tm_hour, pTMData->tm_min, pTMData->tm_sec, pTMData->tm_year + 1900 );
+       snprintf( (char*)*pDecodedString, (sizeof(char)*WSP_STANDARD_STR_LEN_MAX), "%s %s %-2u %u:%u:%u %u GMT", wspWeek[pTMData.tm_wday], wspMonth[pTMData.tm_mon],
+                                                                                       pTMData.tm_mday, pTMData.tm_hour, pTMData.tm_min, pTMData.tm_sec, pTMData.tm_year + 1900 );
 
        return;
 
@@ -2897,6 +3400,7 @@ void SmsPluginWapPushHandler::wspHeaderDecodeAuth(unsigned long fieldValueLen, u
        unsigned char  userId[WSP_STANDARD_STR_LEN_MAX];
        unsigned char  passWd[WSP_STANDARD_STR_LEN_MAX];
        unsigned long iField = 0;
+       char authStr[256];
 
        *pDecodedString = new char[WSP_STANDARD_STR_LEN_MAX * 2];
 
@@ -2907,11 +3411,15 @@ void SmsPluginWapPushHandler::wspHeaderDecodeAuth(unsigned long fieldValueLen, u
 
        /* skip 'basic' code */
        iField++;
-       sscanf((char*)(fieldValue + iField), "%s", userId );
+       memset(authStr, 0x00, sizeof(authStr));
+       snprintf(authStr, sizeof(authStr), "%%%ds", sizeof(userId));
+       sscanf((char*)(fieldValue + iField), authStr, userId );
        iField = iField + AcStrlen( (char*)userId ) + 1;
-       sscanf( (char*)(fieldValue + iField), "%s", passWd );
+       memset(authStr, 0x00, sizeof(authStr));
+       snprintf(authStr, sizeof(authStr), "%%%ds", sizeof(passWd));
+       sscanf( (char*)(fieldValue + iField), authStr, passWd );
        iField = iField + AcStrlen( (char*)userId ) + 1;
-       sprintf( (char*)*pDecodedString, "basic %s/%s", userId, passWd );
+       snprintf( (char*)*pDecodedString, (sizeof(char)*WSP_STANDARD_STR_LEN_MAX*2), "basic %s/%s", userId, passWd );
 
        return;
 }
@@ -2921,6 +3429,7 @@ void SmsPluginWapPushHandler::wspHeaderDecodeChallenge(unsigned long fieldValueL
 {
        unsigned char userId[WSP_STANDARD_STR_LEN_MAX];
        unsigned long iField = 0;
+       char authStr[256];
 
        *pDecodedString = new char[WSP_STANDARD_STR_LEN_MAX];
 
@@ -2931,10 +3440,12 @@ void SmsPluginWapPushHandler::wspHeaderDecodeChallenge(unsigned long fieldValueL
 
        /* skip 'basic' code */
        iField++;
-       sscanf( (char*)(fieldValue + iField), "%s", userId );
+       memset(authStr, 0x00, sizeof(authStr));
+       snprintf(authStr, sizeof(authStr), "%%%ds", sizeof(userId));
+       sscanf( (char*)(fieldValue + iField), authStr, userId );
        iField = iField + AcStrlen( (char*)userId ) + 1;
 
-       sprintf( (char*)*pDecodedString, "basic realm=\"%s\"", userId );
+       snprintf( (char*)*pDecodedString, (sizeof(char)*WSP_STANDARD_STR_LEN_MAX), "basic realm=\"%s\"", userId );
 
        return;
 }
@@ -2986,14 +3497,14 @@ void SmsPluginWapPushHandler::wspHeaderDecodeCacheControl(unsigned char* fieldVa
                        case 0x03 :
                                /* min-fresh */
                        case 0x04 :
-                               sprintf( (char*)paramString, "%u", (unsigned int)wspHeaderDecodeInteger( fieldValue + 1));
+                               snprintf( (char*)paramString, sizeof(paramString), "%u", (unsigned int)wspHeaderDecodeInteger( fieldValue + 1));
                                break;
 
                        default :
                                break;
 
                }
-               sprintf((char*)*pCacheString, "%s=%s", (char*)wspCacheControl[cacheCode], (char*)paramString );
+               snprintf((char*)*pCacheString, (sizeof(char)*WSP_STANDARD_STR_LEN_MAX), "%s=%s", (char*)wspCacheControl[cacheCode], (char*)paramString );
        } else {
                /* cache extentions */
                /* In case of come directive of doesn't specified string style */
@@ -3008,7 +3519,7 @@ void SmsPluginWapPushHandler::wspHeaderDecodeCacheControl(unsigned char* fieldVa
                        if (fieldValue[stringLen+ 1] > 0x7f) {
                                int untyped = (int)wspHeaderDecodeIntegerByLength( fieldValue + stringLen + 1, fieldValueLen - (stringLen + 1 ));
 
-                               sprintf( szString, "%d", untyped );
+                               snprintf( szString, sizeof(szString), "%d", untyped );
                                strncat( (char*)*pCacheString, (char*)"=", WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)*pCacheString)-1 );
                                strncat( (char*)*pCacheString, (char*)szString, WSP_STANDARD_STR_LEN_MAX-AcStrlen((char*)*pCacheString)-1 );
                        } else {
@@ -3022,3 +3533,10 @@ void SmsPluginWapPushHandler::wspHeaderDecodeCacheControl(unsigned char* fieldVa
 
        return;
 }
+
+void SmsPluginWapPushHandler::getDisplayName(MSG_SUB_TYPE_T subType,char* displayName)
+{
+       if(subType == MSG_WAP_SL_SMS || subType == MSG_WAP_SI_SMS)
+               snprintf(displayName, MAX_ADDRESS_VAL_LEN + 1, "Push message");
+       return;
+}
index 90a07ba..1634292 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_CALLBACK_H
@@ -28,39 +28,68 @@ extern "C"
 {
        #include <tapi_common.h>
        #include <TelSms.h>
+       #include <TelSim.h>
        #include <TapiUtility.h>
        #include <ITapiNetText.h>
+       #include <ITapiNetwork.h>
 }
 
 /*==================================================================================================
                                      FUNCTION PROTOTYPES
 ==================================================================================================*/
-void TapiEventDeviceReady(TapiHandle *handle, int result, void *data, void *user_data);
+void TapiEventDeviceReady(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
 
 void TapiEventSentStatus(TapiHandle *handle, int result, void *data, void *user_data);
+void TapiEventSatSmsSentStatus(TapiHandle *handle, int result, void *data, void *user_data);
 void TapiEventMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
 void TapiEventCbMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
+void TapiEventEtwsMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
 void TapiEventDeliveryReportCNF(TapiHandle *handle, int result, void *data, void *user_data);
 
 void TapiEventGetSimMsgCnt(TapiHandle *handle, int result, void *data, void *user_data);
 void TapiEventGetSimMsg(TapiHandle *handle, int result, void *data, void *user_data);
 void TapiEventSaveSimMsg(TapiHandle *handle, int result, void *data, void *user_data);
+void TapiEventSaveClass2Msg(TapiHandle *handle, int result, void *data, void *user_data);
 void TapiEventDeleteSimMsg(TapiHandle *handle, int result, void *data, void *user_data);
 
 void TapiEventSetConfigData(TapiHandle *handle, int result, void *data, void *user_data);
 
+void TapiEventSetSmscInfo(TapiHandle *handle, int result, void *data, void *user_data);
+
 void TapiEventGetCBConfig(TapiHandle *handle, int result, void *data, void *user_data);
 
+void TapiEventSetMailboxInfo(TapiHandle *handle, int result, void *data, void *user_data);
+void TapiEventGetMailboxInfo(TapiHandle *handle, int result, void *data, void *user_data);
+
+void TapiEventSetMwiInfo(TapiHandle *handle, int result, void *data, void *user_data);
+void TapiEventGetMwiInfo(TapiHandle *handle, int result, void *data, void *user_data);
+
+void TapiEventGetMsisdnInfo(TapiHandle *handle, int result, void *data, void *user_data);
+
+void TapiEventGetSimServiceTable(TapiHandle *handle, int result, void *data, void *user_data);
+
 void TapiEventGetParamCnt(TapiHandle *handle, int result, void *data, void *user_data);
 void TapiEventGetParam(TapiHandle *handle, int result, void *data, void *user_data);
 
 void TapiEventSatSmsRefresh(TapiHandle *handle, int result, void *data, void *user_data);
-void TapiEventSatSendSms(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
+void TapiEventSatSendSms(TapiHandle *handle, int result, void *data, void *user_data);
 void TapiEventSatMoSmsCtrl(TapiHandle *handle, int result, void *data, void *user_data);
 
 void TapiEventSimFileInfo(TapiHandle *handle, int result, void *data, void *user_data);
 void TapiEventSimReadFile(TapiHandle *handle, int result, void *data, void *user_data);
+void TapiEventMemoryStatus(TapiHandle *handle, int result, void *data, void *user_data);
+
+void TapiEventSetMsgStatus(TapiHandle *handle, int result, void *data, void *user_data);
+
+void TapiEventGetMeImei(TapiHandle *handle, int result, void *data, void *user_data);
+
+void TapiEventSimStatusChange(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
+
+void TapiEventNetworkStatusChange(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
+
+void TapiEventSimRefreshed(TapiHandle *handle, const char *noti_id, void *data, void *user_data);
 
+SMS_NETWORK_STATUS_T convertTapiRespToSmsPlugin(int result);
 
 /*==================================================================================================
                                      CLASS DEFINITIONS
index 9e46c77..c351889 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_CBMSG_HANDLER_H
@@ -26,6 +26,7 @@
 
 using namespace std;
 
+#include "MsgTextConvert.h"
 #include "SmsPluginTypes.h"
 
 extern "C"
@@ -39,7 +40,7 @@ extern "C"
 /*==================================================================================================
                                          VARIABLES
 ==================================================================================================*/
-typedef map<unsigned char, string> cbPageMap;
+typedef map<unsigned char, SMS_CBMSG_PAGE_S> cbPageMap;
 
 
 typedef struct _CB_PAGE_INFO_S
@@ -64,7 +65,8 @@ class SmsPluginCbMsgHandler
 public:
        static SmsPluginCbMsgHandler* instance();
 
-       void handleCbMsg(TelSmsCbMsg_t *pCbMsg);
+       void handleCbMsg(TapiHandle *handle, TelSmsCbMsg_t *pCbMsg);
+       void handleEtwsMsg(TapiHandle *handle, TelSmsEtwsMsg_t *pEtwsMsg);
 
 private:
        SmsPluginCbMsgHandler();
@@ -74,20 +76,26 @@ private:
 
        void Decode2gCbMsg(TelSmsCbMsg_t *pCbMsg, SMS_CBMSG_PAGE_S *pCbPage);
        void Decode3gCbMsg(TelSmsCbMsg_t *pCbMsg, SMS_CBMSG_PAGE_S *pCbPage);
-
-       bool checkCbOpt(SMS_CBMSG_PAGE_S CbPage, bool *pJavaMsg);
-       unsigned char checkCbPage(SMS_CBMSG_PAGE_S CbPage);
-       void MakeCbMsg(SMS_CBMSG_PAGE_S CbPage, SMS_CBMSG_S *pCbMsg);
-       void convertCbMsgToMsginfo(SMS_CBMSG_S cbMsg, MSG_MESSAGE_INFO_S *pMsgInfo);
-       void addToPageLiat(SMS_CBMSG_PAGE_S CbPage);
-       void removeFromPageList(SMS_CBMSG_PAGE_S CbPage);
+       void DecodeEtwsMsg(TelSmsEtwsMsg_t *pEtwsMsg, SMS_ETWS_PRIMARY_S *pEtwsPn);
+       unsigned short encodeCbSerialNum ( SMS_CBMSG_SERIAL_NUM_S snFields );
+       int CMAS_class(unsigned short message_id);
+
+       bool checkCbOpt(SMS_CBMSG_PAGE_S *CbPage, bool *pJavaMsg, msg_sim_slot_id_t simIndex);
+       unsigned char checkCbPage(SMS_CBMSG_PAGE_S *CbPage);
+       void MakeCbMsg(SMS_CBMSG_PAGE_S *CbPage, SMS_CBMSG_S *pCbMsg);
+       void convertCbMsgToMsginfo(SMS_CBMSG_S *pCbMsg, MSG_MESSAGE_INFO_S *pMsgInfo, msg_sim_slot_id_t simIndex);
+       void convertEtwsMsgToMsginfo(SMS_CBMSG_PAGE_S *EtwsMsg, MSG_MESSAGE_INFO_S *pMsgInfo, msg_sim_slot_id_t simIndex);
+       int convertTextToUtf8 (unsigned char* outBuf, int outBufSize, SMS_CBMSG_S* pCbMsg);
+       void addToPageList(SMS_CBMSG_PAGE_S *CbPage);
+       void removeFromPageList(SMS_CBMSG_PAGE_S *CbPage);
 
        void decodeCbMsgDCS(unsigned char dcsData, const unsigned char *pMsgData, SMS_CBMSG_DCS_S* pDcs);
        void convertLangType(SMS_CBMSG_LANG_TYPE_T InType , MSG_CB_LANGUAGE_TYPE_T *pOutType);
        unsigned long getRecvTime();
-       void getDisplayName(unsigned short      MsgId, char *pDisplayName);
+       void getDisplayName(unsigned short      MsgId, char *pDisplayName, msg_sim_slot_id_t simIndex);
 
        vector<CB_PAGE_INFO_S> pageList;
+
 };
 
 #endif //SMS_PLUGIN_CBMSG_HANDLER_H
index 1920a62..fa3552a 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_CONCAT_HANDLER_H
@@ -27,6 +27,7 @@
 
 using namespace std;
 
+#include "MsgTextConvert.h"
 #include "SmsPluginTypes.h"
 
 
@@ -53,6 +54,8 @@ typedef struct _SMS_CONCAT_MSG_S
        SMS_ADDRESS_S   originAddress;
        SMS_DCS_S               dcs;
        bool                            bRead;
+       int                             simId;
+       int                     simIndex;
 } SMS_CONCAT_MSG_S;
 
 typedef struct _SMS_CONCAT_INFO_S
@@ -68,6 +71,9 @@ typedef struct _SMS_CONCAT_INFO_S
 
        unsigned int            totalSize;
        concatDataMap   data;
+       int     simIdList[MAX_SIM_SMS_NUM];
+       unsigned int    display_time;
+       int                             simIndex;
 } SMS_CONCAT_INFO_S;
 
 typedef struct _SMS_SIM_ID_S
@@ -86,8 +92,11 @@ public:
        static SmsPluginConcatHandler* instance();
 
        bool IsConcatMsg(SMS_USERDATA_S *pUserData);
-       void handleConcatMsg(SMS_TPDU_S *pTpdu);
+       void handleConcatMsg(struct tapi_handle *handle, SMS_TPDU_S *pTpdu);
+       void handleSimConcatMsg(struct tapi_handle *handle, SMS_TPDU_S *pTpdu, int msgId, int bRead, int *simIdList);
+//     void handleConcatMsg(SMS_TPDU_S *pTpdu, msg_sim_id_t SimMsgId, bool bRead);
 
+//     void handleBrokenMsg();
 
 private:
        SmsPluginConcatHandler();
@@ -96,13 +105,20 @@ private:
        static SmsPluginConcatHandler* pInstance;
 
        unsigned char checkConcatMsg(SMS_CONCAT_MSG_S *pConcatMsg, SMS_USERDATA_S *pUserData);
-       int makeConcatUserData(unsigned short MsgRef, char **ppTotalData);
+       int makeConcatUserData(unsigned short MsgRef, int simIndex, char **ppTotalData);
 
        void convertConcatToMsginfo(const SMS_DELIVER_S *pTpdu, const char *pUserData, int DataSize, MSG_MESSAGE_INFO_S *pMsgInfo);
+       void convertConcatToMsginfo(const SMS_SUBMIT_S *pTpdu, const char *pUserData, int DataSize, MSG_MESSAGE_INFO_S *pMsgInfo);
+//     void convertSimMsgToMsginfo(const SMS_CONCAT_MSG_S *pConcatMsg, const char *pUserData, int DataSize, MSG_MESSAGE_INFO_S *pMsgInfo);
 
-       void removeFromConcatList(unsigned short MsgRef);
+       void removeFromConcatList(unsigned short MsgRef, int simIndex);
+
+//     void addToSimIdList(unsigned short MsgRef, msg_sim_id_t SimMsgId);
+//     void removeFromSimIdList(unsigned short MsgRef);
 
        vector<SMS_CONCAT_INFO_S> concatList;
+//     vector<SMS_SIM_ID_S> simIdList;
+
 };
 
 #endif //SMS_PLUGIN_CONCAT_HANDLER_H
diff --git a/plugin/sms_plugin/include/SmsPluginDSHandler.h b/plugin/sms_plugin/include/SmsPluginDSHandler.h
new file mode 100755 (executable)
index 0000000..60b21b6
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef SMS_PLUGIN_DS_HANDLER_H
+#define SMS_PLUGIN_DS_HANDLER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "SmsPluginTypes.h"
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginDSHandler
+{
+public:
+       static SmsPluginDSHandler* instance();
+       int initTelHandle();
+       void deinitTelHandle();
+       struct tapi_handle *getTelHandle(int sim_idx);
+       int getTelHandleCount();
+       int getActiveSimCount();
+       int getSimIndex(struct tapi_handle *handle);
+       void getDefaultNetworkSimId(int *simId);
+
+private:
+       static SmsPluginDSHandler* pInstance;
+       SmsPluginDSHandler();
+       virtual ~SmsPluginDSHandler();
+       char **cp_list;
+       SMS_TELEPHONY_HANDLE_LIST_S handle_list;
+};
+
+#endif //SMS_PLUGIN_DS_HANDLER_H
+
index 0165eb2..12a0cdb 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_EVENT_HANDLER_H
@@ -22,6 +22,7 @@
                                          INCLUDE FILES
 ==================================================================================================*/
 #include "MsgMutex.h"
+#include "MsgTextConvert.h"
 #include "MsgPluginInterface.h"
 #include "SmsPluginTypes.h"
 
@@ -36,21 +37,29 @@ public:
 
        void registerListener(MSG_PLUGIN_LISTENER_S *pListener);
        void handleSentStatus(msg_network_status_t NetStatus);
-       void handleMsgIncoming(SMS_TPDU_S *pTpdu);
-       void handleSyncMLMsgIncoming(msg_syncml_message_type_t msgType, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen);
+       void handleMsgIncoming(struct tapi_handle *handle, SMS_TPDU_S *pTpdu);
+       void handleSyncMLMsgIncoming(msg_syncml_message_type_t msgType, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen, int simIndex);
        void handleLBSMsgIncoming(char* pPushHeader, char* pPushBody, int pushBodyLen);
+       void handlePushMsgIncoming(char* pPushHeader, char* pPushBody, int pushBodyLen, char *app_id, char *content_type);
+       void handleResendMessage(void);
 
        msg_error_t callbackMsgIncoming(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t callbackCBMsgIncoming(MSG_CB_MSG_S *pCbMsg, MSG_MESSAGE_INFO_S *pMsgInfo);
        msg_error_t callbackInitSimBySat();
        msg_error_t callbackStorageChange(msg_storage_change_type_t storageChangeType, MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t handleSimMsg(MSG_MESSAGE_INFO_S *pMsgInfo, int *simIdList, msg_message_id_t *retMsgId, int listSize);
+       msg_error_t updateIMSI(int sim_idx);
+       void handleSimMemoryFull(int simIndex);
 
        void SetSentInfo(SMS_SENT_INFO_S *pSentInfo);
 
-       void setDeviceStatus();
-       bool getDeviceStatus();
+       void setDeviceStatus(struct tapi_handle *handle);
+       bool getDeviceStatus(struct tapi_handle *handle);
 
        void convertTpduToMsginfo(SMS_TPDU_S *pTpdu, MSG_MESSAGE_INFO_S *msgInfo); // temp
 
+       MSG_SUB_TYPE_T convertMsgSubType(SMS_PID_T pid);
+
 private:
        SmsPluginEventHandler();
        virtual ~SmsPluginEventHandler();
@@ -58,7 +67,6 @@ private:
        void convertSubmitTpduToMsginfo(const SMS_SUBMIT_S *pTpdu, MSG_MESSAGE_INFO_S *msgInfo);
        void convertDeliverTpduToMsginfo(const SMS_DELIVER_S *pTpdu, MSG_MESSAGE_INFO_S *msgInfo);
        void convertStatusRepTpduToMsginfo(const SMS_STATUS_REPORT_S *pTpdu, MSG_MESSAGE_INFO_S *msgInfo);
-       MSG_SUB_TYPE_T convertMsgSubType(SMS_PID_T pid);
 
        static SmsPluginEventHandler* pInstance;
 
@@ -67,9 +75,12 @@ private:
        SMS_SENT_INFO_S sentInfo;
 
        bool devStatus;
+       bool bUdhMwiMethod;
+       int udhMwiCnt;
 
        Mutex mx;
        CndVar cv;
+       struct tapi_handle *devHandle;
 };
 
 #endif //SMS_PLUGIN_EVENT_HANDLER_H
index e8c55ca..bedffb8 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_MAIN_H
@@ -40,32 +40,28 @@ msg_error_t SmsPlgFinalize();
 
 msg_error_t SmsPlgRegisterListener(MSG_PLUGIN_LISTENER_S *pListener);
 
-msg_error_t SmsPlgCheckSimStatus(MSG_SIM_STATUS_T *pStatus);
-
-msg_error_t SmsPlgCheckDeviceStatus();
-
 msg_error_t SmsPlgSubmitRequest(MSG_REQUEST_INFO_S *pReqInfo);
 
-msg_error_t SmsPlgInitSimMessage();
-
 msg_error_t SmsPlgSaveSimMessage(const MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList);
 
-msg_error_t SmsPlgDeleteSimMessage(msg_sim_id_t SimMsgId);
+msg_error_t SmsPlgDeleteSimMessage(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId);
 
 msg_error_t SmsPlgGetSimMessage(msg_sim_id_t SimMsgId);
 
 msg_error_t SmsPlgGetSimMessageCount();
 
-msg_error_t SmsPlgSetReadStatus(msg_sim_id_t SimMsgId);
+msg_error_t SmsPlgSetReadStatus(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId);
 
-msg_error_t SmsPlgSetMemoryStatus(msg_error_t Error);
-
-msg_error_t SmsPlgInitConfigData(MSG_SIM_STATUS_T SimStatus);
+msg_error_t SmsPlgSetMemoryStatus(msg_sim_slot_id_t simIndex, msg_error_t Error);
 
 msg_error_t SmsPlgSetConfigData(const MSG_SETTING_S *pSetting);
 
 msg_error_t SmsPlgGetConfigData(MSG_SETTING_S *pSetting);
 
+msg_error_t SmsPlgAddMessage(MSG_MESSAGE_INFO_S *pMsgInfo,  MSG_SENDINGOPT_INFO_S* pSendOptInfo, char* pFileData);
+
+msg_error_t SmsPlgGetDefaultNetworkSimId(int *simId);
+
 #ifdef __cplusplus
 }
 #endif
index 8591935..0795823 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_PARAMCODEC_H
@@ -44,6 +44,8 @@ public:
        static int decodeDCS(const unsigned char *pTpdu, SMS_DCS_S *pDCS);
        static void decodeSMSC(unsigned char* pAddress, int AddrLen, MSG_SMS_TON_T ton, char *pDecodeAddr);
 
+       static bool checkCphsVmiMsg(const unsigned char *pTpdu, int *setType, int *indType);
+
 private:
        static int convertDigitToBcd(char *pDigit, int DigitLen, unsigned char *pBcd);
        static int convertBcdToDigit(const unsigned char *pBcd, int BcdLen, char *pDigit);
index 0cbf0bb..e6a640f 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_SAT_HANDLER_H
                                          INCLUDE FILES
 ==================================================================================================*/
 #include "SmsPluginTypes.h"
+#include "MsgMutex.h"
+
+extern "C"
+{
+       #include <TelSat.h>
+}
 
 /*==================================================================================================
                                      CLASS DEFINITIONS
@@ -31,10 +37,10 @@ class SmsPluginSatHandler
 public:
        static SmsPluginSatHandler* instance();
 
-       void refreshSms(void *pData);
-       void sendSms(void *pData);
-       void ctrlSms(void *pData);
-       void ctrlSms(msg_network_status_t netStatus);
+       void refreshSms(struct tapi_handle *handle, void *pData);
+       void sendSms(struct tapi_handle *handle, void *pData);
+       void ctrlSms(struct tapi_handle *handle, void *pData);
+       void ctrlSms(struct tapi_handle *handle, SMS_NETWORK_STATUS_T netStatus);
 
        void finishSimMsgInit(msg_error_t Err);
 
@@ -49,16 +55,18 @@ private:
 
        int handleSatTpdu(unsigned char *pTpdu, unsigned char TpduLen, int bIsPackingRequired);
 
-       void sendResult(SMS_SAT_CMD_TYPE_T CmdType, int ResultType);
+       void sendResult(struct tapi_handle *handle, SMS_SAT_CMD_TYPE_T CmdType, int ResultType);
 
        static SmsPluginSatHandler* pInstance;
 
        int commandId;
 
-       bool bSendSms;
        bool bInitSim;
        bool bSMSPChanged;
        bool bCBMIChanged;
+
+       Mutex mx;
+       CndVar cv;
 };
 
 #endif //SMS_PLUGIN_SAT_HANDLER_H
index d649e48..05e39d1 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_SETTING_H
 ==================================================================================================*/
 #include "MsgMutex.h"
 #include "MsgSettingTypes.h"
+#include <list>
 
+extern "C"
+{
+       #include <tapi_common.h>
+}
 
 /*==================================================================================================
                                      CLASS DEFINITIONS
@@ -33,49 +38,88 @@ class SmsPluginSetting
 public:
        static SmsPluginSetting* instance();
 
-       void initConfigData(MSG_SIM_STATUS_T SimStatus);
-
        void setConfigData(const MSG_SETTING_S *pSetting);
        void getConfigData(MSG_SETTING_S *pSetting);
+       void getMeImei(char *pImei);
 
        void setParamCntEvent(int ParamCnt);
-       void setParamEvent(const MSG_SMSC_DATA_S *pSmscData, int RecordIdx, bool bSuccess);
-       void setCbConfigEvent(const MSG_CBMSG_OPT_S *pCbOpt, bool bSuccess);
+       void setParamEvent(struct tapi_handle *handle, const MSG_SMSC_DATA_S *pSmscData, int RecordIdx, bool bSuccess);
+       void setCbConfigEvent(struct tapi_handle *handle, const MSG_CBMSG_OPT_S *pCbOpt, bool bSuccess);
+       void setMailboxInfoEvent(struct tapi_handle *handle, SMS_SIM_MAILBOX_LIST_S *pVoiceOpt, bool bSuccess, bool bMbdn);
+       void setMwiInfo(int simIndex, MSG_SUB_TYPE_T type, int count);
+       void setMwiInfoEvent(struct tapi_handle *handle, SMS_SIM_MWI_INFO_S *pMwiInfo, bool bSuccess);
        void setResultFromSim(bool bResult);
+       void setResultImei(bool bResult, char *pImei);
+
+       void setSmscInfo(const MSG_SMSC_LIST_S *pSmscList);
+
+       void setSimChangeStatus(struct tapi_handle *handle, bool bInitializing);
+       void getSmscListInfo(int simIndex, MSG_SMSC_LIST_S *pSmscList);
+       void SimRefreshCb(struct tapi_handle *handle);
 
 private:
        SmsPluginSetting();
        ~SmsPluginSetting();
 
-       msg_error_t addSMSCList(MSG_SMSC_LIST_S *pSmscList);
+       void updateSimStatus(struct tapi_handle *handle);
+
+       void initConfigData(struct tapi_handle *handle);
+       static void* init_config_data(void *data);
+       static void* initSimInfo(void *data);
+       void* processInitSimInfo(void *data);
+
+       void addSMSCList(MSG_SMSC_LIST_S *pSmscList);
 
        msg_error_t addCbOpt(MSG_CBMSG_OPT_S *pCbOpt);
-       void getCbOpt(MSG_SETTING_S *pSetting);
+       void getCbOpt(MSG_SETTING_S *pSetting, int simIndex);
 
        void setParamList(const MSG_SMSC_LIST_S *pSMSCList);
        void getParamList(MSG_SMSC_LIST_S *pSMSCList);
 
-       int getParamCount();
-       bool getParam(int Index, MSG_SMSC_DATA_S *pSmscData);
+       int getParamCount(struct tapi_handle *handle);
+       bool getParam(struct tapi_handle *handle, int Index, MSG_SMSC_DATA_S *pSmscData);
 
        bool setCbConfig(const MSG_CBMSG_OPT_S *pCbOpt);
        bool getCbConfig(MSG_CBMSG_OPT_S *pCbOpt);
 
+       void setVoiceMailInfo(const MSG_VOICEMAIL_OPT_S *pVoiceOpt);
+       bool getVoiceMailInfo(struct tapi_handle *handle);
+
+       bool getMwiInfo(struct tapi_handle *handle);
+       bool getMsisdnInfo(struct tapi_handle *handle);
+       bool getSimServiceTable(struct tapi_handle *handle);
+       bool getResultImei(char *pImei);
+
        int getParamCntEvent();
-       bool getParamEvent(MSG_SMSC_DATA_S *pSmscData);
+       bool getParamEvent(struct tapi_handle *handle, MSG_SMSC_DATA_S *pSmscData);
        bool getCbConfigEvent(MSG_CBMSG_OPT_S *pCbOpt);
+
+       bool getMailboxInfoEvent();
+
        bool getResultFromSim();
 
        SMS_PID_T convertPid(MSG_SMS_PID_T pid);
+       void deliverVoiceMsgNoti(int simIndex, int mwiCnt);
 
        static SmsPluginSetting* pInstance;
-
-       MSG_SMSC_DATA_S         smscData;
-       MSG_CBMSG_OPT_S         cbOpt;
-
-       bool            bTapiResult;
+       std::list<TapiHandle *> tel_handle_list;
+
+       /* Setting values for keeping in setting instance */
+       MSG_SMSC_LIST_S         smscList[MAX_TELEPHONY_HANDLE_CNT+1];
+       MSG_SIM_STATUS_T        simStatus[MAX_TELEPHONY_HANDLE_CNT+1];
+       MSG_SMSC_DATA_S         smscData[MAX_TELEPHONY_HANDLE_CNT+1];
+       SMS_SIM_MAILBOX_LIST_S  simMailboxList[MAX_TELEPHONY_HANDLE_CNT+1];
+       SMS_SIM_MWI_INFO_S      simMwiInfo[MAX_TELEPHONY_HANDLE_CNT+1];
+       MSG_CBMSG_OPT_S cbOpt[MAX_TELEPHONY_HANDLE_CNT+1];
+
+       /* Local values for getting from SIM(TAPI) */
+       bool    bTapiResult;
        int             paramCnt;
        int             selectedParam;
+       int     selectedSimIndex;
+       char    meImei[MAX_ME_IMEI_LEN + 1];
+
+       bool    bMbdnEnable[MAX_TELEPHONY_HANDLE_CNT];
 
        Mutex mx;
        CndVar cv;
index c83bd6e..fed6a1a 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_SIMMSG_H
@@ -43,45 +43,59 @@ class SmsPluginSimMsg
 public:
        static SmsPluginSimMsg* instance();
 
-       void initSimMessage();
+       void initSimMessage(struct tapi_handle *handle);
        msg_error_t saveSimMessage(const MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList);
        msg_error_t saveClass2Message(const MSG_MESSAGE_INFO_S *pMsgInfo);
-       void deleteSimMessage(msg_sim_id_t SimMsgId);
+       void deleteSimMessage(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId);
        void getSimMessageList(MSG_SIM_MSG_INFO_LIST_S **ppSimMsgList);
-       void setReadStatus(msg_sim_id_t SimMsgId);
-       bool checkSimMsgFull(unsigned int SegCnt);
+       void setReadStatus(msg_sim_slot_id_t sim_idx, msg_sim_id_t SimMsgId);
+       bool checkSimMsgFull(msg_sim_slot_id_t sim_idx, unsigned int SegCnt);
 
-       void setSimMsgCntEvent(const MSG_SIM_COUNT_S *pSimMsgCnt);
-       void setSimMsgEvent(const MSG_MESSAGE_INFO_S *pMsgInfo, bool bSuccess);
+       void setSimMsgCntEvent(struct tapi_handle *handle, const MSG_SIM_COUNT_S *pSimMsgCnt);
+       void setSimMsgEvent(struct tapi_handle *handle, const MSG_MESSAGE_INFO_S *pMsgInfo, bool bSuccess);
+       void setSaveSimMsgEvent(struct tapi_handle *handle, int simId, int result);
+       void setSaveClass2MsgEvent(struct tapi_handle *handle, int simId, int result, MSG_MESSAGE_INFO_S *data);
        void setSimEvent(msg_sim_id_t SimId, bool bResult);
+       void setUpdateSimEvent(int SimId, bool bResult);
+       void setDelSimEvent(int SimId, bool bResult);
+
+       void setSmsData(const char *sca, const char *szData, int msgLength);
+       void setSmsTpduTotalSegCount(int totalSeg);
 
 private:
        SmsPluginSimMsg();
        ~SmsPluginSimMsg();
 
-       void getSimMsgCount(MSG_SIM_COUNT_S *pSimMsgCnt);
-       bool getSimMsg(msg_sim_id_t SimMsgId, MSG_MESSAGE_INFO_S* pMsgInfo);
+       void getSimMsgCount(struct tapi_handle *handle, MSG_SIM_COUNT_S *pSimMsgCnt);
+       bool getSimMsg(struct tapi_handle *handle, msg_sim_id_t SimMsgId, MSG_MESSAGE_INFO_S* pMsgInfo, int *simIdList);
 
-       void setSmsOptions(SMS_DELIVER_S *pDeliver);
+       void setSmsOptions(const MSG_MESSAGE_INFO_S* pMsgInfo, SMS_DELIVER_S *pDeliver);
        void convertTimeStamp(const MSG_MESSAGE_INFO_S* pMsgInfo, SMS_DELIVER_S *pDeliver);
 
-       bool getSimMsgCntEvent(MSG_SIM_COUNT_S *pSimMsgCnt);
-       bool getSimMsgEvent(MSG_MESSAGE_INFO_S *pMsgInfo);
+       bool getSimMsgCntEvent(struct tapi_handle *handle, MSG_SIM_COUNT_S *pSimMsgCnt);
+       bool getSimMsgEvent(struct tapi_handle *handle, MSG_MESSAGE_INFO_S *pMsgInfo);
        bool getSimEvent(msg_sim_id_t *pSimId);
+       bool getUpdateSimEvent();
+       bool getDelSimEvent(int *pSimId);
+
 
        static SmsPluginSimMsg* pInstance;
 
-       msg_sim_id_t                    simMsgId;
+       msg_sim_id_t                            simMsgId;
+       int                             delSimMsgId;
+       int             simIdList[MAX_SIM_SMS_NUM];             /** send total simIds to handleSimMsg **/
 
        MSG_SIM_COUNT_S                 simMsgCnt;
 
        MSG_MESSAGE_INFO_S              simMsgInfo;
+       MSG_ADDRESS_INFO_S              simAddrInfo;
 
-       unsigned int                            usedCnt;
-       unsigned int                            totalCnt;
+       int                                     usedCnt;
+       int                                     totalCnt;
 
        bool                                            bTapiResult;
-       bool                                            bClass2Msg;
+
+       SMS_DATA_INFO_S                 simMsgDataInfo;
 
        Mutex mx;
        CndVar cv;
index fae7306..0506e8f 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_STORAGE_H
@@ -27,6 +27,7 @@
 #include "SmsPluginTypes.h"
 #include "MsgInternalTypes.h"
 #include "MsgSqliteWrapper.h"
+#include <list>
 
 extern "C"
 {
@@ -44,34 +45,46 @@ class SmsPluginStorage
 public:
        static SmsPluginStorage* instance();
 
+       msg_error_t insertMsgRef(MSG_MESSAGE_INFO_S *pMsg, unsigned char msgRef, int index);
+       msg_error_t updateMsgDeliverStatus(MSG_MESSAGE_INFO_S *pMsgInfo, unsigned char msgRef);
+
        msg_error_t updateSentMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_network_status_t Status);
+//     msg_error_t updateMsgRef(msg_message_id_t MsgId, unsigned char MsgRef);
+//     msg_error_t updateStatusReport(unsigned char MsgRef, msg_delivery_report_status_t Status, time_t DeliveryTime);
 
-       msg_error_t addSimMessage(MSG_MESSAGE_INFO_S *pSimMsgInfo);
+       msg_error_t addSimMessage(MSG_MESSAGE_INFO_S *pSimMsgInfo, int *simIdList);
+       msg_error_t insertSimMessage(int simId, int msgId);
+       msg_error_t deleteSimMessage(int sim_idx, int simId);
 
-       msg_error_t addMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t checkMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
        msg_error_t addSmsMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t deleteSmsMessage(msg_message_id_t msgId);
+#if 0
+       msg_error_t isReceivedCBMessage(SMS_CBMSG_PAGE_S CbPage);
+       msg_error_t insertReceivedCBMessage(SMS_CBMSG_PAGE_S CbPage);
+#endif
+       msg_error_t addSmsSendOption(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo);
 
-       msg_error_t deleteSmsMessage(msg_message_id_t MsgId);
+       msg_error_t getReplaceSimMsg(const MSG_MESSAGE_INFO_S *pMsg, int *pMsgId, int *pSimId);
 
+       msg_error_t checkStorageStatus(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t getRegisteredPushEvent(char* pPushHeader, int *count, char *app_id, int app_id_len, char *content_type, int content_type_len);
+       msg_error_t getnthPushEvent(int index, int *appcode);
+       msg_error_t releasePushEvent();
 private:
        SmsPluginStorage();
        ~SmsPluginStorage();
 
-       msg_error_t updateSmsMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
-
-       msg_error_t addCbMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
-       msg_error_t addReplaceTypeMsg(MSG_MESSAGE_INFO_S *pMsgInfo);
-       msg_error_t addWAPMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
-       msg_error_t handleCOWAPMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
-       msg_error_t checkPushMsgValidation(MSG_PUSH_MESSAGE_S *pPushMsg, bool *pbProceed);
-
-       msg_error_t checkStorageStatus(MSG_MESSAGE_INFO_S *pMsgInfo);
-       msg_error_t updateAllAddress();
+       msg_error_t addClass2Message(MSG_MESSAGE_INFO_S *pMsgInfo);
 
        static SmsPluginStorage* pInstance;
+       static void* class2_thread(void *data);
 
-       MsgDbHandler dbHandle;
+       MSG_MESSAGE_INFO_S msgInfo;
+       MSG_ADDRESS_INFO_S addrInfo;
 
+       std::list<PUSH_APPLICATION_INFO_S> pushAppInfoList;
+//     unsigned char tmpMsgRef;
 };
 
 #endif //SMS_PLUGIN_STORAGE_H
index 43a79e1..597a91d 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_TPDU_CODEC_H
index e86f463..59f177c 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_TRANSPORT_H
                                          INCLUDE FILES
 ==================================================================================================*/
 #include "MsgMutex.h"
+#include "MsgTextConvert.h"
 #include "MsgTransportTypes.h"
 #include "MsgSettingTypes.h"
 #include "SmsPluginTypes.h"
 #include "MsgInternalTypes.h"
 
+extern "C"
+{
+       #include <TelSat.h>
+}
+
 /*==================================================================================================
                                      CLASS DEFINITIONS
 ==================================================================================================*/
@@ -36,16 +42,19 @@ public:
        static SmsPluginTransport* instance();
 
        void submitRequest(SMS_REQUEST_INFO_S *pReqInfo);
-       void sendDeliverReport(msg_error_t err);
+       void sendDeliverReport(struct tapi_handle *handle, msg_error_t err);
+       void sendClass0DeliverReport(struct tapi_handle *handle, msg_error_t err);
 
-       void setSmsSendOptions(SMS_SUBMIT_S *pSubmit);
-       void setSmscOptions(SMS_ADDRESS_S *pSmsc);
+       void setSmscOptions(int simIndex, SMS_ADDRESS_S *pSmsc);
 
        void msgInfoToSubmitData(const MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SUBMIT_DATA_S *pData, SMS_CODING_SCHEME_T *pCharType, int addrIndex);
        void setConcatHeader(SMS_UDH_S *pSrcHeader, SMS_UDH_S *pDstHeader);
 
-       void setNetStatus(msg_network_status_t netStatus);
-       msg_network_status_t getNetStatus();
+       void setNetStatus(SMS_NETWORK_STATUS_T sentStatus);
+       SMS_NETWORK_STATUS_T getNetStatus();
+
+       void setMoCtrlStatus(TelSatMoSmCtrlIndData_t *moCtrlData);
+       int getMoCtrlStatus();
 
        unsigned char getMsgRef();
 
@@ -53,7 +62,12 @@ private:
        SmsPluginTransport();
        ~SmsPluginTransport();
 
-       int getSegmentSize(SMS_CODING_SCHEME_T CodingScheme, int DataLen, bool bPortNum, SMS_LANGUAGE_ID_T LangId, int ReplyAddrLen);
+       void getSmsSendOption(int simIndex, SMS_SUBMIT_S *pSubmit);
+       void setSmsSendOption(SMS_REQUEST_INFO_S *pReqInfo, SMS_TPDU_S* pSmsTpdu);
+       void setSmsDcsOption(SMS_REQUEST_INFO_S *pReqInfo, SMS_TPDU_S* pSmsTpdu);
+       void setSmsReportOption(SMS_REQUEST_INFO_S *pReqInfo, SMS_TPDU_S* pSmsTpdu);
+
+       int getSegmentSize(SMS_CODING_SCHEME_T CodingScheme, int DataLen, bool bPortNum, MSG_LANGUAGE_ID_T LangId, int ReplyAddrLen);
        SMS_PID_T convertPid(MSG_SMS_PID_T pid);
 
        static SmsPluginTransport* pInstance;
@@ -63,7 +77,8 @@ private:
        unsigned char           msgRef8bit;
        unsigned short  msgRef16bit;
 
-       msg_network_status_t curStatus;
+       SMS_NETWORK_STATUS_T curStatus;
+       TelSatMoSmCtrlIndData_t curMoCtrlData;
 
        Mutex mx;
        CndVar cv;
index eb07acc..d705686 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_TYPES_H
@@ -21,6 +21,7 @@
 /*==================================================================================================
                                          INCLUDE FILES
 ==================================================================================================*/
+#include "MsgTextConvert.h"
 #include "MsgInternalTypes.h"
 #include "MsgStorageTypes.h"
 #include "MsgSettingTypes.h"
 #define MAX_USER_DATA_LEN                      160
 #define MAX_GSM_7BIT_DATA_LEN          160
 #define MAX_UCS2_DATA_LEN                      140
-#define MAX_TPDU_DATA_LEN                      165
+//#define MAX_TPDU_DATA_LEN                    165
+//CID 321400: Making MAX_TPDU_DATA_LEN same as TAPI_NETTEXT_SMDATA_SIZE_MAX of TelSms.h to prevent any buffer overflow
+#define MAX_TPDU_DATA_LEN                      255
+#define MAX_SMS_SEND_RETRY                     4
 #define MAX_SMSC_LEN                           20
 #define MAX_ADD_PARAM_LEN                      12
 #define MAX_ABS_TIME_PARAM_LEN         7
 #define MAX_REL_TIME_PARAM_LEN         1
 #define MAX_UD_HEADER_NUM                      7
 #define MAX_SAT_TPDU_LEN                       175
-#define MAX_CBMSG_PAGE_SIZE            93
+#define MAX_CBMSG_PAGE_SIZE            1252
+#define MAX_ETWS_SIZE                  56
 #define MAX_CBMSG_PAGE_NUM             15
-#define MAX_SIM_SMS_NUM                        90
+#define MAX_SIM_SMS_NUM                        255
+#define MAX_SIM_IMSI_NUM               20
+#define MAX_SIM_MSP_CNT                        2
+#define MAX_TELEPHONY_HANDLE_CNT       3
 
 #define SMS_PUSH_XML_HREF_TAG          "href"
 #define SMS_PUSH_XML_SI_ID_TAG         "si-id"
                                          TYPES
 ==================================================================================================*/
 
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_TPDU_TYPE_T;
+typedef unsigned char SMS_TPDU_TYPE_T;         /* _SMS_TPDU_TYPE_E */
 
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_VPF_T;
+typedef unsigned char SMS_VPF_T;               /* _SMS_VPF_E */
 
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_TON_T;
+typedef unsigned char SMS_TON_T;               /* _SMS_TON_E */
 
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_NPI_T;
+typedef unsigned char SMS_NPI_T;               /* _SMS_NPI_E */
 
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_PID_T;
+typedef unsigned char SMS_PID_T;               /* _SMS_PID_E */
 
+typedef unsigned char SMS_MSG_CLASS_T;         /* _SMS_MSG_CLASS_E */
 
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_MSG_CLASS_T;
+typedef unsigned char SMS_CODING_SCHEME_T;     /* _SMS_CODING_SCHEME_E */
 
+typedef unsigned char SMS_CODING_GROUP_T;      /* _SMS_CODING_GROUP_E */
 
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_CODING_SCHEME_T;
-
-
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_CODING_GROUP_T;
-
+typedef unsigned char SMS_INDICATOR_TYPE_T;    /* _SMS_INDICATOR_TYPE_E */
 
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_INDICATOR_TYPE_T;
-
-
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_TIME_FORMAT_T;
-
-
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_FAIL_CAUSE_T;
-
-
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_STATUS_T;
-
-
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_REF_NUMBER_T;
-
-
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_REPORT_TYPE_T;
-
-
-/**
-\brief Represents TPDU Type.
-*/
-typedef unsigned char SMS_UDH_TYPE_T;
-
-
-/**
-\brief Represents WAP Push App Code.
-*/
-typedef unsigned char SMS_WAP_APP_CODE_T;
+typedef unsigned char SMS_TIME_FORMAT_T;       /* _SMS_TIME_FORMAT_E */
 
+typedef unsigned char SMS_FAIL_CAUSE_T;                /* _SMS_FAIL_CAUSE_E */
 
-typedef unsigned char SMS_CB_NETWORK_TYPE_T;
+typedef unsigned char SMS_STATUS_T;            /* _SMS_STATUS_E */
 
+typedef unsigned char SMS_REF_NUMBER_T;                /* _SMS_REF_NUMBER_E */
 
-typedef unsigned char SMS_CBMSG_TYPE_T;
+typedef unsigned char SMS_REPORT_TYPE_T;       /* _SMS_REPORT_TYPE_E */
 
+typedef unsigned char SMS_UDH_TYPE_T;          /* _SMS_UDH_TYPE_E */
 
-typedef unsigned char SMS_CBMSG_LANG_TYPE_T;
+typedef unsigned char SMS_WAP_APP_CODE_T;      /* _SMS_WAP_APP_CODE_E */
 
+typedef unsigned char SMS_CB_NETWORK_TYPE_T;   /* _SMS_CB_NETWORK_TYPE_E */
 
-typedef unsigned char SMS_CBMSG_CODING_GROUP_T;
+typedef unsigned char SMS_CBMSG_TYPE_T;                /* _SMS_CBMSG_TYPE_E */
 
+typedef unsigned char SMS_CBMSG_LANG_TYPE_T;   /* _SMS_CBMSG_LANG_TYPE_E */
 
-typedef unsigned char SMS_SAT_CMD_TYPE_T;
+typedef unsigned char SMS_CBMSG_CODING_GROUP_T;        /* _SMS_CBMSG_CODING_GROUP_E */
 
+typedef unsigned char SMS_SAT_CMD_TYPE_T;      /* _SMS_SAT_CMD_TYPE_E */
 
-typedef unsigned short SMS_SIM_EFILE_NAME_T;
+typedef unsigned short SMS_SIM_EFILE_NAME_T;   /* _SMS_SIM_EFILE_NAME_E */
 
+typedef unsigned char SMS_SIM_MAILBOX_TYPE_T;  /* _SMS_SIM_MAILBOX_TYPE_E */
 
-typedef unsigned char SMS_LANGUAGE_ID_T;
-
+typedef unsigned char SMS_NETWORK_STATUS_T;    /* _SMS_NETWORK_STATUS_E */
 
 /*==================================================================================================
                                     ENUMS
@@ -286,6 +229,7 @@ enum _SMS_CODING_GROUP_E
 enum _SMS_INDICATOR_TYPE_E
 {
        SMS_VOICE_INDICATOR = 0,
+       SMS_VOICE2_INDICATOR, // Only for CPSH
        SMS_FAX_INDICATOR,
        SMS_EMAIL_INDICATOR,
        SMS_OTHER_INDICATOR,
@@ -329,6 +273,7 @@ enum _SMS_STATUS_E
        SMS_STATUS_TRY_NO_RESPONSE = 0x22,
        SMS_STATUS_TRY_SERVICE_REJECTED = 0x23,
        SMS_STATUS_TRY_QOS_NOT_AVAILABLE = 0x24,
+       SMS_STATUS_TRY_REQUEST_PENDING = 0x30,
 
        SMS_STATUS_PERM_REMOTE_ERROR = 0x40,
        SMS_STATUS_PERM_IMCOMPATIBLE_DEST = 0x41,
@@ -375,6 +320,8 @@ enum _SMS_UDH_TYPE_E
        SMS_UDH_SRC_IND = 0x07,
        SMS_UDH_CONCAT_16BIT = 0x08,
        SMS_UDH_WCMP = 0x09,
+       SMS_UDH_EMS_FIRST = 0x0a,
+       SMS_UDH_EMS_LAST = 0x1f,
        SMS_UDH_ALTERNATE_REPLY_ADDRESS = 0x22,
        SMS_UDH_SINGLE_SHIFT = 0x24,
        SMS_UDH_LOCKING_SHIFT = 0x25,
@@ -462,6 +409,7 @@ enum _SMS_CBMSG_TYPE_E
        SMS_CBMSG_TYPE_SCHEDULE,                /**< Schedule */
        SMS_CBMSG_TYPE_CBS41,                   /**< CBS41 */
        SMS_CBMSG_TYPE_JAVACBS,         /**< JAVA-CB Message*/
+       SMS_CBMSG_TYPE_ETWS,
 };
 
 
@@ -538,22 +486,28 @@ enum _SMS_SIM_EFILE_NAME_E
 };
 
 
-enum _SMS_LANGUAGE_ID_E
-{
-       SMS_LANG_ID_RESERVED = 0,
-       SMS_LANG_ID_TURKISH,
-       SMS_LANG_ID_SPANISH,
-       SMS_LANG_ID_PORTUGUESE,
-       SMS_LANG_ID_BENGALI,
-       SMS_LANG_ID_GUJARATI,
-       SMS_LANG_ID_HINDI,
-       SMS_LANG_ID_KANNADA,
-       SMS_LANG_ID_MALAYALAM,
-       SMS_LANG_ID_ORIYA,
-       SMS_LANG_ID_PUNJABI,
-       SMS_LANG_ID_TAMIL,
-       SMS_LANG_ID_TELUGU,
-       SMS_LANG_ID_URDU,
+enum _SMS_SIM_MAILBOX_TYPE_E {
+       SMS_SIM_MAILBOX_VOICE = 0x01,
+       SMS_SIM_MAILBOX_VOICE2 = 0x02,
+       SMS_SIM_MAILBOX_FAX = 0x03,
+       SMS_SIM_MAILBOX_DATA = 0x04,
+       SMS_SIM_MAILBOX_EMAIL = 0x05,
+       SMS_SIM_MAILBOX_OTHER = 0x06,
+};
+
+
+enum _SMS_NETWORK_STATUS_E {
+       SMS_NETWORK_SEND_SUCCESS = 0x00,
+       SMS_NETWORK_SENDING,
+       SMS_NETWORK_SEND_FAIL,
+       SMS_NETWORK_SEND_FAIL_TIMEOUT,
+       SMS_NETWORK_SEND_FAIL_MANDATORY_INFO_MISSING,
+       SMS_NETWORK_SEND_FAIL_TEMPORARY,
+       SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_WITH_MOD,
+       SMS_NETWORK_SEND_FAIL_BY_MO_CONTROL_NOT_ALLOWED,
+       SMS_NETWORK_SEND_FAIL_FDN_RESTRICED,
+       SMS_NETWORK_SEND_FAIL_NO_ROUTING,
+       SMS_NETWORK_SEND_PENDING,
 };
 
 
@@ -648,18 +602,6 @@ typedef struct _SMS_SPECIAL_INDICATION_S
 } SMS_SPECIAL_INDICATION_S;
 
 
-typedef struct _SMS_SINGLE_SHIFT_S
-{
-       SMS_LANGUAGE_ID_T       langId;
-} SMS_SINGLE_SHIFT_S;
-
-
-typedef struct _SMS_LOCKING_SHIFT_S
-{
-       SMS_LANGUAGE_ID_T       langId;
-} SMS_LOCKING_SHIFT_S;
-
-
 typedef struct _SMS_UDH_S
 {
        SMS_UDH_TYPE_T udhType;
@@ -671,8 +613,8 @@ typedef struct _SMS_UDH_S
                SMS_APP_PORT_8BIT_S             appPort8bit;
                SMS_APP_PORT_16BIT_S            appPort16bit;
                SMS_SPECIAL_INDICATION_S        specialInd;
-               SMS_SINGLE_SHIFT_S                      singleShift;
-               SMS_LOCKING_SHIFT_S                     lockingShift;
+               MSG_SINGLE_SHIFT_S                      singleShift;
+               MSG_LOCKING_SHIFT_S                     lockingShift;
                SMS_ADDRESS_S                           alternateAddress;
        } udh;
 } SMS_UDH_S;
@@ -837,7 +779,7 @@ typedef struct _SMS_CBMSG_PAGE_S
        SMS_CBMSG_TYPE_T                        cbMsgType;                                                      /*CBS Msg or SCHEDULE Msg or CBS41 Msg */
        SMS_CBMSG_HEADER_S                      pageHeader;                                                     /**< CB Message Header */
        int                                                     pageLength;                                                     /**< message string length */
-       char                                                    pageData[MAX_CBMSG_PAGE_SIZE+1];                /**< user data */
+       char                                                    pageData[MAX_CBMSG_PAGE_SIZE*8/7+1];            /**< user data */
 } SMS_CBMSG_PAGE_S;
 
 
@@ -849,18 +791,17 @@ typedef struct _SMS_CBMSG_S
        SMS_CODING_SCHEME_T             codingScheme;                                           /**< How to encode a message. */
        time_t                                          recvTime;                                                       /**< Msg Recv Time */
        int                                                     msgLength;                                                      /**< message string length */
-       char                                                    msgData[MAX_CBMSG_PAGE_SIZE*MAX_CBMSG_PAGE_NUM+1];              /**< user data */
+       char                                                    msgData[MAX_CBMSG_PAGE_SIZE*8/7*MAX_CBMSG_PAGE_NUM+1];          /**< user data */
 } SMS_CBMSG_S;
 
-
-typedef struct _SMS_LANG_INFO_S
+typedef struct _SMS_ETWS_PRIMARY_S
 {
-       bool                                                    bSingleShift;
-       bool                                                    bLockingShift;
-
-       SMS_LANGUAGE_ID_T                       singleLang;
-       SMS_LANGUAGE_ID_T                       lockingLang;
-} SMS_LANG_INFO_S;
+       time_t                                          recvTime;
+       SMS_CBMSG_SERIAL_NUM_S          serialNum;
+       unsigned short                          msgId;
+       unsigned short                          warningType;
+       unsigned char                           warningSecurityInfo[MAX_ETWS_SIZE-6];
+}SMS_ETWS_PRIMARY_S;
 
 
 typedef struct _SMS_WSP_CONTENTS_TYPE_S
@@ -894,7 +835,7 @@ typedef struct _SMS_WSP_LANGUAGE_S
 typedef struct _SMS_WSP_HEADER_PARAMETER_S
 {
        char*         parameterToken;
-       unsigned char parameterCode;
+       unsigned int parameterCode;
 } SMS_WSP_HEADER_PARAMETER_S;
 
 
@@ -933,5 +874,104 @@ typedef struct
        char                            msgData[(MAX_MSG_DATA_LEN*MAX_SEGMENT_NUM)+1];          /**< user data */
 } SMS_CONCAT_SIM_MSG_S;
 
-#endif //SMS_PLUGIN_TYPES_H
 
+/**
+ *     @brief  Represents Sim Mailbox information
+ */
+typedef struct {
+       int                     b_cphs;
+       int                     rec_index;                                                              /**< index which stands for the location where record is saved in SIM*/
+       int                     profile_num;                                                    /**< SIM profile index*/
+       SMS_SIM_MAILBOX_TYPE_T  mb_type;
+       int                     alpha_id_max_len;                                               /**< alpha max length in SIM - READ ONLY*/
+       char                    alpha_id[MAX_SIM_XDN_ALPHA_ID_LEN + 1]; /**< Alpha Identifier */
+       MSG_SMS_TON_T   ton;                                                                    /**< Type Of Number */
+       MSG_SMS_NPI_T   npi;                                                                    /**< Number Plan Identity */
+       char                    num[MAX_PHONE_NUMBER_LEN + 1];                  /**< Dialing Number/SSC String */
+       unsigned char   cc_id;                                                                  /**< Capability/Configuration Identifier */
+       unsigned char   ext1_id;                                                                /**< Extensiion1 Record Identifier */
+       int                             num_len;                                                                        /**< Length of the original number read from SIM*/
+} SMS_SIM_MAILBOX_INFO_S;
+
+
+/**
+ *     @brief  Represents Sim Mailbox list
+ */
+typedef struct {
+       int count;
+       SMS_SIM_MAILBOX_INFO_S list[MAX_SIM_MSP_CNT*5]; //max is 10
+} SMS_SIM_MAILBOX_LIST_S;
+
+
+/**
+ *     @brief  Represents Message Waiting Indication
+ */
+typedef struct {
+       int                     rec_index;
+       unsigned char   indicator_status;       /**< Indicator Type*/
+       int                     voice_count;            /**< VoiceMail Count*/
+       int                     fax_count;                      /**< FAX Count*/
+       int                     email_count;            /**< Email Count*/
+       int                             other_count;            /**< Other Count*/
+       int                     video_count;            /**< VideoMail Count*/
+} SMS_SIM_MWI_NORMAL_INFO_S;
+
+
+/**
+ *     @brief  Represents Message Waiting Indication list
+ */
+typedef struct {
+       int profile_count;
+       SMS_SIM_MWI_NORMAL_INFO_S mw_info[MAX_SIM_MSP_CNT];
+} SMS_SIM_MWI_LIST_S;
+
+
+/**
+ *     @brief  Represents Message Waiting Indication for CPHS
+ */
+typedef struct {
+       int     b_voice1;       /**< VoiceMsgLine1 message waiting flag */
+       int     b_voice2;       /**< VoiceMsgLine2 message waiting flag */
+       int     b_fax;          /**< FAX message waiting flag */
+       int     b_data;         /**< Data message waiting flag */
+} SMS_SIM_MWI_CPHS_INFO_S;
+
+
+/**
+ *     @brief  Represents Message Waiting Indication Information
+ */
+typedef struct {
+       int b_cphs;
+       SMS_SIM_MWI_LIST_S mwi_list;
+       SMS_SIM_MWI_CPHS_INFO_S cphs_mwi;
+} SMS_SIM_MWI_INFO_S;
+
+/**
+ *     @brief  Represents SIM MSISDN Information
+ */
+typedef struct {
+       char    simMsisdn[MAX_SIM_MSISDN_LEN + 1];
+       int     sim_index;
+} SMS_SIM_MSISDN_INFO_S;
+
+
+/**
+ *     @brief  Represents Message Data Information from Telephony.
+ */
+typedef struct {
+       unsigned char sca[MAX_ADDRESS_LEN]; /**< Service Center address */
+       int msgLength; /**< Size of array szData (which is actual TPDU message) */
+       unsigned char szData[MAX_TPDU_DATA_LEN + 1]; /**< SMS TPDU message */
+       int totalSegment;       /** total segment count of TPDU message */
+} SMS_DATA_INFO_S;
+
+
+/**
+ *     @brief  Represents Telephony Handle from Telephony.
+ */
+typedef struct {
+       int count;
+       struct tapi_handle *handle[MAX_TELEPHONY_HANDLE_CNT]; //max is 3
+} SMS_TELEPHONY_HANDLE_LIST_S;
+
+#endif //SMS_PLUGIN_TYPES_H
index 02d0ccb..8a50cab 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_UA_MANAGER_H
@@ -37,19 +37,21 @@ public:
 
        //virtual void start();
 
-       void addReqEntity(SMS_REQUEST_INFO_S request);
+       void addReqEntity(SMS_REQUEST_INFO_S *request);
 
 private:
        SmsPluginUAManager();
        ~SmsPluginUAManager();
+       void lock()     { mx.lock(); };
+       void unlock()   { mx.unlock(); };
+       void wait()     { cv.wait(mx.pMutex()); };
+       void signal()   { cv.signal(); };
 
        virtual void run();
 
        static SmsPluginUAManager* pInstance;
 
-       bool bRunning;
-
-       MsgThdSafeQ <SMS_REQUEST_INFO_S> smsTranQ;
+       MsgSimpleQ <SMS_REQUEST_INFO_S> smsTranQ;
 
        Mutex mx;
        CndVar cv;
index 6db9d06..c109210 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_UDCODEC_H
index e89199a..f47b46e 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #ifndef SMS_PLUGIN_WAPPUSH_HANDLER_H
@@ -38,7 +38,6 @@
 #define WSP_CODE_BUFFER_LEFT_LEN_MAX   1024
 #define WSP_CODE_BUFFER_RIGHT_LEN_MAX  2048
 
-#define  MemFree(x)  {if(x != NULL) free(x);x=NULL;}
 #define  AcStrlen(x) ((x==NULL)?0:strlen(x))
 #define MIN(a,b)  (((a)  <  (b)) ? (a)  :  (b))
 
@@ -55,8 +54,8 @@ public:
        bool IsWapPushMsg(SMS_USERDATA_S *pUserData);
 
        void copyDeliverData(SMS_DELIVER_S *pDeliver);
-       void handleWapPushMsg(const char *pUserData, int DataSize);
-       void handleWapPushCallback(char* pPushHeader, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen, char* pWspBody, int WspBodyLen);
+       void handleWapPushMsg(const char *pUserData, int DataSize, int simIndex);
+       void handleWapPushCallback(char* pPushHeader, char* pPushBody, int PushBodyLen, char* pWspHeader, int WspHeaderLen, char* pWspBody, int WspBodyLen, int simIndex);
 
 private:
        SmsPluginWapPushHandler();
@@ -66,13 +65,14 @@ private:
 
        SMS_WAP_APP_CODE_T getAppCode(const char *pPushHeader);
 
-       void handleMMSNotification(const char *pPushBody, int PushBodyLen);
-       void handleSIMessage(char* pPushBody, int PushBodyLen, bool isText);
-       void handleSLMessage(char* pPushBody, int PushBodyLen, bool isText);
-       void handleCOMessage(char* pPushBody, int PushBodyLen, bool isText);
+       void handleMMSNotification(const char *pPushBody, int PushBodyLen, int simIndex);
+       void handleSIMessage(char* pPushBody, int PushBodyLen, bool isText, int simIndex);
+       void handleSLMessage(char* pPushBody, int PushBodyLen, bool isText, int simIndex);
+       void handleCOMessage(char* pPushBody, int PushBodyLen, bool isText, int simIndex);
        void handleDrmVer1(char* pPushBody, int PushBodyLen);
        void getXmlDoc(const char* pPushBody, const int PushBodyLen, xmlDocPtr *pXmlDoc, const bool isText);
        void createMsgInfo(MSG_MESSAGE_INFO_S* pMsgInfo);
+       void getDisplayName(MSG_SUB_TYPE_T subType, char* displayName);
        unsigned long convertXmlCharToSec(char* pDate);
        msg_push_action_t convertSIActionStrToEnum(char* pAction);
        msg_push_action_t convertSLActionStrToEnum(char* pAction);
index e0b7c59..d2ca1d3 100755 (executable)
@@ -8,7 +8,7 @@ IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
 ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
 MESSAGE("Build type: ${CMAKE_BUILD_TYPE}")
 
-SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
+SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
 
 ##########################################################
 # Define Transaction Proxy
@@ -26,26 +26,25 @@ SET(TRANS-PROXY-SRCS
 INCLUDE_DIRECTORIES(
     ${CMAKE_SOURCE_DIR}/include/mapi
        ${CMAKE_SOURCE_DIR}/include/common
-       ${CMAKE_SOURCE_DIR}/include/framework
        ${CMAKE_SOURCE_DIR}/include/utils
        ${CMAKE_SOURCE_DIR}/include/proxy
 )
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(trans_proxy_pkgs REQUIRED glib-2.0 dlog vconf security-server)
+pkg_check_modules(trans_proxy_pkgs REQUIRED glib-2.0 dlog vconf db-util)
 
 FOREACH(flag ${trans_proxy_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
 ENDFOREACH(flag)
 
-SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
 
 ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
 
 SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
 
 ADD_LIBRARY(${TRANS-PROXY-LIB} SHARED ${TRANS-PROXY-SRCS})
-TARGET_LINK_LIBRARIES(${TRANS-PROXY-LIB} ${trans_proxy_pkgs_LDFLAGS} ${UTILS-LIB} ${FW-HANDLER-LIB})
+TARGET_LINK_LIBRARIES(${TRANS-PROXY-LIB} ${trans_proxy_pkgs_LDFLAGS} ${UTILS-LIB})
 
 INSTALL(TARGETS ${TRANS-PROXY-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
 
index 31af9c9..3102631 100755 (executable)
@@ -1,31 +1,31 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
 #include <stdlib.h>
 
-#include <security-server.h>
-
 #include "MsgDebug.h"
 #include "MsgCppTypes.h"
 #include "MsgException.h"
+#include "MsgContact.h"
 #include "MsgUtilFile.h"
 #include "MsgGconfWrapper.h"
 #include "MsgProxyListener.h"
 #include "MsgHandle.h"
+#include "MsgSqliteWrapper.h"
 
 /*==================================================================================================
                                      IMPLEMENTATION OF MsgHandle - Control Member Functions
@@ -33,6 +33,7 @@
 MsgHandle::MsgHandle() : mCounter(0), mClientSock()
 {
        memset(mConnectionId, 0x00, sizeof(mConnectionId));
+       memset(mCookie, 0x00, sizeof(mCookie));
 }
 
 
@@ -44,8 +45,8 @@ MsgHandle::~MsgHandle()
 
 void MsgHandle::openHandle()
 {
-       int ret = 0;
-       size_t cookieSize;
+//     int ret = 0;
+//     size_t cookieSize;
 
        bool bReady = false;
 
@@ -55,22 +56,9 @@ void MsgHandle::openHandle()
        if (bReady == false) {
                THROW(MsgException::SERVER_READY_ERROR, "Msg Server is not ready !!!!!");
        } else {
-               MSG_DEBUG("Msg Server is ready !!!!!");
+               MSG_INFO("Msg Server is ready !!!!!");
        }
 
-       // Get Cookie Size
-       cookieSize = security_server_get_cookie_size();
-
-       MSG_DEBUG("cookie size : [%d]", cookieSize);
-
-       // Request Cookie
-       ret = security_server_request_cookie(mCookie, cookieSize);
-
-       if (ret < 0) {
-
-               MSG_DEBUG("security_server_request_cookie() error!! [%d]", ret);
-               return;
-       }
 
        // Open Socket IPC
        connectSocket();
@@ -90,6 +78,12 @@ void MsgHandle::closeHandle(MsgHandle* pHandle)
        // Close Socket IPC
        disconnectSocket();
 
+       // Close Contact Service
+       if (MsgCloseContactSvc() != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to close contact service.");
+       }
+       removeDbHandle(); /* unregister db handler */
+
        MSG_END();
 }
 
@@ -112,28 +106,43 @@ void MsgHandle::write(const char *pCmdData, int cmdSize, char **ppEvent)
                THROW(MsgException::INVALID_PARAM, "Param is NULL");
        }
 
+       int ret = 0;
+
        // Send Command to MSG FW
-       mClientSock.write(pCmdData, cmdSize);
+       ret = mClientSock.write(pCmdData, cmdSize);
+       if (ret < 0)
+               THROW(MsgException::IPC_ERROR, "IPC write error");
+
+       char *tmpEvent = NULL;
 
-       // Receive Result from MSG FW
-       read(ppEvent);
+       while(1)
+       {
+               // Receive Result from MSG FW
+               read(&tmpEvent);
 
-       if (ppEvent == NULL) {
-               THROW(MsgException::INVALID_RESULT, "event is NULL");
+               if(tmpEvent == NULL) {
+                       MSG_DEBUG("Event Data is NULL!!");
+                       break;
+               }
+
+               if(!CheckEventData(tmpEvent)) {
+                       delete [] tmpEvent;
+               } else {
+                       *ppEvent = tmpEvent;
+                       break;
+               }
        }
 }
 
 
 void MsgHandle::read(char **ppEvent)
 {
-       int dataSize = 0;
+       unsigned int dataSize = 0;
 
-       dataSize = mClientSock.read(ppEvent, &dataSize);
+       int ret = mClientSock.read(ppEvent, &dataSize);
 
-       if (dataSize == 0) {
+       if (ret == CLOSE_CONNECTION_BY_SIGNAL) {
                THROW(MsgException::IPC_ERROR, "Server closed connection");
-       } else if(dataSize < 0) {
-               THROW(MsgException::IPC_ERROR, "negative length??? %d", dataSize);
        }
 }
 
@@ -150,17 +159,16 @@ void MsgHandle::convertMsgStruct(const MSG_MESSAGE_HIDDEN_S *pSrc, MSG_MESSAGE_I
        pDest->msgType.classType= pSrc->classType;
        pDest->storageId = pSrc->storageId;
 
-       msg_struct_list_s *addr_info_s = pSrc->addr_list;
-
-       if (addr_info_s) {
+       if (g_list_length(pSrc->addressList) > 0) {
                msg_struct_s *addr_info = NULL;
                MSG_ADDRESS_INFO_S *address = NULL;
 
-               pDest->nAddressCnt = addr_info_s->nCount;
+               pDest->nAddressCnt = g_list_length(pSrc->addressList);
+               pDest->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S) * pDest->nAddressCnt];
+               memset(pDest->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S) * pDest->nAddressCnt);
 
-               for (int i = 0; i < addr_info_s->nCount; i++)
-               {
-                       addr_info = (msg_struct_s *)addr_info_s->msg_struct_info[i];
+               for (int i = 0; i < pDest->nAddressCnt; i++) {
+                       addr_info = (msg_struct_s *)g_list_nth_data(pSrc->addressList,(guint)i);
                        address = (MSG_ADDRESS_INFO_S *)addr_info->data;
 
                        pDest->addressList[i].addressType = address->addressType;
@@ -168,7 +176,31 @@ void MsgHandle::convertMsgStruct(const MSG_MESSAGE_HIDDEN_S *pSrc, MSG_MESSAGE_I
                        pDest->addressList[i].contactId = address->contactId;
                        strncpy(pDest->addressList[i].addressVal, address->addressVal, MAX_ADDRESS_VAL_LEN);
                        strncpy(pDest->addressList[i].displayName, address->displayName, MAX_DISPLAY_NAME_LEN);
-                       pDest->addressList[i].displayName[MAX_DISPLAY_NAME_LEN] = '\0';
+               }
+       } else {
+
+               msg_struct_list_s *addr_info_s = pSrc->addr_list;
+
+               if (addr_info_s && (addr_info_s->nCount > 0)) {
+                       msg_struct_s *addr_info = NULL;
+                       MSG_ADDRESS_INFO_S *address = NULL;
+
+                       pDest->nAddressCnt = addr_info_s->nCount;
+
+                       pDest->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S) * addr_info_s->nCount];
+                       memset(pDest->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S) * addr_info_s->nCount);
+
+                       for (int i = 0; i < addr_info_s->nCount; i++) {
+                               addr_info = (msg_struct_s *)addr_info_s->msg_struct_info[i];
+
+                               address = (MSG_ADDRESS_INFO_S *)addr_info->data;
+
+                               pDest->addressList[i].addressType = address->addressType;
+                               pDest->addressList[i].recipientType = address->recipientType;
+                               pDest->addressList[i].contactId = address->contactId;
+                               strncpy(pDest->addressList[i].addressVal, address->addressVal, MAX_ADDRESS_VAL_LEN);
+                               strncpy(pDest->addressList[i].displayName, address->displayName, MAX_DISPLAY_NAME_LEN);
+                       }
                }
        }
 
@@ -195,38 +227,45 @@ void MsgHandle::convertMsgStruct(const MSG_MESSAGE_HIDDEN_S *pSrc, MSG_MESSAGE_I
        MSG_DEBUG("nSize = %d",  pSrc->dataSize);
 
        if (pSrc->mainType == MSG_SMS_TYPE){
-               pDest->bTextSms = true;
-               pDest->dataSize = pSrc->dataSize;
+               if (pSrc->pData != NULL) {
+                       pDest->bTextSms = true;
+                       pDest->dataSize = pSrc->dataSize;
 
-               memset(pDest->msgText, 0x00, sizeof(pDest->msgText));
+                       memset(pDest->msgText, 0x00, sizeof(pDest->msgText));
 
-               if (pSrc->dataSize > MAX_MSG_TEXT_LEN) {
-                       // Save Message Data into File
-                       char fileName[MAX_COMMON_INFO_SIZE+1];
-                       memset(fileName, 0x00, sizeof(fileName));
+                       if (pSrc->dataSize > MAX_MSG_TEXT_LEN) {
+                               // Save Message Data into File
+                               char fileName[MSG_FILENAME_LEN_MAX+1];
+                               memset(fileName, 0x00, sizeof(fileName));
 
-                       if(MsgCreateFileName(fileName) == false)
-                               THROW(MsgException::FILE_ERROR, "MsgCreateFileName error");
+                               if(MsgCreateFileName(fileName) == false)
+                                       THROW(MsgException::FILE_ERROR, "MsgCreateFileName error");
 
-                       MSG_DEBUG("Save pSrc->pData into file : size[%d] name[%s]", pDest->dataSize, fileName);
+                               MSG_SEC_DEBUG("Save pSrc->pData into file : size[%d] name[%s]", pDest->dataSize, fileName);
 
-                       if (MsgWriteIpcFile(fileName, (char*)pSrc->pData, pSrc->dataSize) == false)
-                               THROW(MsgException::FILE_ERROR, "MsgWriteIpcFile error");
+                               if (MsgWriteIpcFile(fileName, (char*)pSrc->pData, pSrc->dataSize) == false)
+                                       THROW(MsgException::FILE_ERROR, "MsgWriteIpcFile error");
 
-                       memset(pDest->msgData, 0x00, sizeof(pDest->msgData));
-                       strncpy(pDest->msgData, fileName, MAX_MSG_DATA_LEN);
+                               memset(pDest->msgData, 0x00, sizeof(pDest->msgData));
+                               strncpy(pDest->msgData, fileName, MAX_MSG_DATA_LEN);
+
+                               pDest->bTextSms = false;
 
-                       pDest->bTextSms = false;
+                       } else {
+                               if (pDest->encodeType == MSG_ENCODE_8BIT)
+                                       memcpy(pDest->msgText, pSrc->pData, pSrc->dataSize);
+                               else
+                                       strncpy(pDest->msgText, (char*)pSrc->pData, pSrc->dataSize);
+                       }
 
+                       MSG_DEBUG("pData = %s", pSrc->pData);
                } else {
-                       if (pDest->encodeType == MSG_ENCODE_8BIT)
-                               memcpy(pDest->msgText, pSrc->pData, pSrc->dataSize);
-                       else
-                               strncpy(pDest->msgText, (char*)pSrc->pData, pSrc->dataSize);
+                       MSG_DEBUG("pSrc->pData is NULL.");
+                       pDest->bTextSms = true;
+                       pDest->dataSize = 0;
                }
 
-               MSG_DEBUG("pData = %s",  pSrc->pData);
-               MSG_DEBUG("msgText = %s",  pDest->msgText);
+               MSG_SEC_DEBUG("msgText = %s", pDest->msgText);
        } else if (pSrc->mainType == MSG_MMS_TYPE) {
 
                pDest->bTextSms = false;
@@ -234,10 +273,15 @@ void MsgHandle::convertMsgStruct(const MSG_MESSAGE_HIDDEN_S *pSrc, MSG_MESSAGE_I
 
                if(pSrc->subType == MSG_READREPLY_MMS) {
                        memset(pDest->msgData, 0x00, sizeof(pDest->msgData));
-                       memcpy(pDest->msgData, pSrc->pMmsData, pSrc->dataSize);
+
+                       if (pSrc->mmsDataSize < MAX_MSG_DATA_LEN)
+                               memcpy(pDest->msgData, pSrc->pMmsData, pSrc->mmsDataSize);
+                       else
+                               memcpy(pDest->msgData, pSrc->pMmsData, MAX_MSG_DATA_LEN);
+
                } else {
                        // Save Message Data into File
-                       char fileName[MAX_COMMON_INFO_SIZE+1];
+                       char fileName[MSG_FILENAME_LEN_MAX+1];
                        memset(fileName, 0x00, sizeof(fileName));
 
                        if(MsgCreateFileName(fileName) == false)
@@ -245,24 +289,31 @@ void MsgHandle::convertMsgStruct(const MSG_MESSAGE_HIDDEN_S *pSrc, MSG_MESSAGE_I
 
                        // change file extension in case of java MMS msg
                        if (pSrc->subType == MSG_SENDREQ_JAVA_MMS) {
-                               char* pFileNameExt;
+                               char* pFileNameExt = NULL;
                                pFileNameExt = strstr(fileName,"DATA");
-                               strncpy(pFileNameExt,"JAVA", MAX_COMMON_INFO_SIZE);
+                               if (pFileNameExt)
+                                       snprintf(pFileNameExt, strlen("JAVA")+1, "JAVA");
                        }
 
-                       MSG_DEBUG("Save Message Data into file : size[%d] name[%s]", pDest->dataSize, fileName);
-
-                       if (MsgWriteIpcFile(fileName, (char*)pSrc->pMmsData, pSrc->dataSize) == false)
+                       MSG_SEC_DEBUG("Save Message Data into file : size[%d] name[%s]", pSrc->mmsDataSize, fileName);
+                       if (MsgWriteIpcFile(fileName, (char*)pSrc->pMmsData, pSrc->mmsDataSize) == false)
                                THROW(MsgException::FILE_ERROR, "MsgWriteIpcFile error");
 
                        memset(pDest->msgData, 0x00, sizeof(pDest->msgData));
                        strncpy(pDest->msgData, fileName, MAX_MSG_DATA_LEN);
                        if (pSrc->pData) {
-                               strncpy(pDest->msgText, (char*)pSrc->pData, sizeof(pDest->msgText));
+                               strncpy(pDest->msgText, (char*)pSrc->pData, MAX_MSG_TEXT_LEN);
+                       }
+
+                       if (strlen(pSrc->thumbPath) > 0) {
+                               memset(pDest->thumbPath, 0x00, sizeof(pDest->thumbPath));
+                               memcpy(pDest->thumbPath, pSrc->thumbPath, sizeof(pDest->thumbPath));
                        }
                }
        }
 
+       pDest->sim_idx = pSrc->simIndex;
+
        MSG_END();
 }
 
@@ -289,6 +340,7 @@ void MsgHandle::convertMsgStruct(const MSG_MESSAGE_INFO_S *pSrc, MSG_MESSAGE_HID
        pDest->bBackup = pSrc->bBackup;
        pDest->priority = pSrc->priority;
        pDest->direction = pSrc->direction;
+       pDest->simIndex = pSrc->sim_idx;
 
        // Set Port Info.
        pDest->bPortValid = pSrc->msgPort.valid;
@@ -301,13 +353,14 @@ void MsgHandle::convertMsgStruct(const MSG_MESSAGE_INFO_S *pSrc, MSG_MESSAGE_HID
        if(pSrc->thumbPath[0] != '\0')
                strncpy(pDest->thumbPath, pSrc->thumbPath, MSG_FILEPATH_LEN_MAX);
 
-       pDest->addr_list->nCount = pSrc->nAddressCnt;
+       int maxCnt = (pSrc->nAddressCnt > 10)? MAX_TO_ADDRESS_CNT: pSrc->nAddressCnt;
+
+       pDest->addr_list->nCount = maxCnt;
 
        msg_struct_s *addr_info_s = NULL;
        MSG_ADDRESS_INFO_S *addr_info = NULL;
 
-       for (int i = 0; i < pDest->addr_list->nCount; i++)
-       {
+       for (int i = 0; i < maxCnt; i++) {
                addr_info_s = (msg_struct_s *)pDest->addr_list->msg_struct_info[i];
                addr_info = (MSG_ADDRESS_INFO_S *)addr_info_s->data;
 
@@ -319,47 +372,67 @@ void MsgHandle::convertMsgStruct(const MSG_MESSAGE_INFO_S *pSrc, MSG_MESSAGE_HID
                addr_info->displayName[MAX_DISPLAY_NAME_LEN] = '\0';
        }
 
+       for (int i = 0; i < pSrc->nAddressCnt; i++) {
+               addr_info_s = new msg_struct_s;
+               memset(addr_info_s, 0x00, sizeof(msg_struct_s));
+
+               addr_info_s->type = MSG_STRUCT_ADDRESS_INFO;
+               addr_info_s->data = new MSG_ADDRESS_INFO_S;
+               memset(addr_info_s->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+               addr_info = (MSG_ADDRESS_INFO_S *)addr_info_s->data;
+
+               addr_info->addressType = pSrc->addressList[i].addressType;
+               addr_info->recipientType = pSrc->addressList[i].recipientType;
+               addr_info->contactId = pSrc->addressList[i].contactId;
+               strncpy(addr_info->addressVal, pSrc->addressList[i].addressVal, MAX_ADDRESS_VAL_LEN);
+               strncpy(addr_info->displayName, pSrc->addressList[i].displayName, MAX_DISPLAY_NAME_LEN);
+               addr_info->displayName[MAX_DISPLAY_NAME_LEN] = '\0';
+
+               pDest->addressList = g_list_append(pDest->addressList, addr_info_s);
+       }
+
 
        if (pSrc->bTextSms == false) {
                int fileSize = 0;
 
                char* pFileData = NULL;
-               AutoPtr<char> buf(&pFileData);
+               unique_ptr<char*, void(*)(char**)> buf(&pFileData, unique_ptr_deleter);
 
                pDest->dataSize = pSrc->dataSize;
 
                // Get Message Data from File
-               if (pSrc->networkStatus != MSG_NETWORK_RETRIEVE_FAIL) {
-                       MSG_DEBUG("Get Message Data from file : size[%d] name[%s]\n", pDest->dataSize, pSrc->msgData);
-                       if (MsgOpenAndReadFile(pSrc->msgData, &pFileData, &fileSize) == false)
-                               THROW(MsgException::FILE_ERROR, "MsgOpenAndReadFile error");
-
-                       if (pSrc->msgType.mainType == MSG_SMS_TYPE) {
-                               if (pDest->encodeType == MSG_ENCODE_8BIT) {
-                                       pDest->pData = (void*)new char[fileSize];
-                                       memset(pDest->pData, 0x00, fileSize);
-                                       memcpy(pDest->pData, pFileData, fileSize);
-                               } else {
-                                       pDest->pData = (void*)new char[fileSize+1];
-                                       memset(pDest->pData, 0x00, fileSize+1);
-                                       strncpy((char*)pDest->pData, pFileData, fileSize);
-                               }
+               if (MsgOpenAndReadFile(pSrc->msgData, &pFileData, &fileSize) == false)
+                       THROW(MsgException::FILE_ERROR, "MsgOpenAndReadFile error");
+
+               if (pSrc->msgType.mainType == MSG_SMS_TYPE) {
+                       if (pDest->encodeType == MSG_ENCODE_8BIT) {
+                               pDest->pData = (void*)new char[fileSize];
+                               memset(pDest->pData, 0x00, fileSize);
+                               memcpy(pDest->pData, pFileData, fileSize);
                        } else {
-                               if (pSrc->msgText[0] != '\0') {
-                                       pDest->pData = (void*)new char[strlen(pSrc->msgText)+1];
-                                       memset(pDest->pData, 0x00, strlen(pSrc->msgText)+1);
-                                       strncpy((char*)pDest->pData, pSrc->msgText, strlen(pSrc->msgText));
-                               }
-                               pDest->pMmsData = (void*)new char[fileSize];
-                               memset(pDest->pMmsData, 0x00, fileSize);
-                               memcpy(pDest->pMmsData, pFileData, fileSize);
+                               pDest->pData = (void*)new char[fileSize+1];
+                               memset(pDest->pData, 0x00, fileSize+1);
+                               strncpy((char*)pDest->pData, pFileData, fileSize);
                        }
+               } else {
+                       if (pSrc->msgText[0] != '\0') {
+                               pDest->pData = (void*)new char[strlen(pSrc->msgText)+1];
+                               memset(pDest->pData, 0x00, strlen(pSrc->msgText)+1);
+                               strncpy((char*)pDest->pData, pSrc->msgText, strlen(pSrc->msgText));
+                       }
+                       pDest->mmsDataSize = fileSize;
+                       pDest->pMmsData = (void*)new char[fileSize];
+                       memset(pDest->pMmsData, 0x00, fileSize);
+                       memcpy(pDest->pMmsData, pFileData, fileSize);
+                       MSG_SEC_DEBUG("Get Message Data from file : size[%d] name[%s]", pDest->mmsDataSize, pSrc->msgData);
                }
+
        } else {
                pDest->dataSize = pSrc->dataSize;
 
                if (pSrc->msgType.mainType == MSG_SMS_TYPE) {
-                       if (pDest->encodeType == MSG_ENCODE_8BIT) {
+                       if (pDest->encodeType == MSG_ENCODE_8BIT || pSrc->msgType.subType == MSG_ETWS_SMS) {
                                pDest->pData = (void*)new char[pDest->dataSize];
                                memset(pDest->pData, 0x00, pDest->dataSize);
                                memcpy(pDest->pData, pSrc->msgText, pDest->dataSize);
@@ -375,6 +448,7 @@ void MsgHandle::convertMsgStruct(const MSG_MESSAGE_INFO_S *pSrc, MSG_MESSAGE_HID
                                strncpy((char*)pDest->pData, pSrc->msgText, strlen(pSrc->msgText));
                        }
 
+                       pDest->mmsDataSize = pDest->dataSize;
                        pDest->pMmsData = (void*)new char[pDest->dataSize];
                        memset(pDest->pMmsData, 0x00, pDest->dataSize);
                        memcpy(pDest->pMmsData, pSrc->msgData, pDest->dataSize);
@@ -391,7 +465,7 @@ void MsgHandle::convertSendOptStruct(const MSG_SENDINGOPT_S* pSrc, MSG_SENDINGOP
 
        pDest->bSetting = pSrc->bSetting;
 
-       if (pDest->bSetting == false) {
+       if (pSrc->bSetting == false) {
                MSG_DEBUG("No Sending Option");
                return;
        }
@@ -405,34 +479,46 @@ void MsgHandle::convertSendOptStruct(const MSG_SENDINGOPT_S* pSrc, MSG_SENDINGOP
 
        if (msgType.mainType == MSG_SMS_TYPE) {
                msg_struct_s *pStruct = (msg_struct_s *)pSrc->smsSendOpt;
-               SMS_SENDINGOPT_S *pSms = (SMS_SENDINGOPT_S *)pStruct->data;
-               pDest->option.smsSendOptInfo.bReplyPath = pSms->bReplyPath;
+               if(pStruct)
+               {
+                       SMS_SENDINGOPT_S *pSms = (SMS_SENDINGOPT_S *)pStruct->data;
+                       if(pSms)
+                       {
+                               pDest->option.smsSendOptInfo.bReplyPath = pSms->bReplyPath;
+                       }
+               }
        } else if (msgType.mainType == MSG_MMS_TYPE) {
                msg_struct_s *pStruct = (msg_struct_s *)pSrc->mmsSendOpt;
-               MMS_SENDINGOPT_S *pMms = (MMS_SENDINGOPT_S *)pStruct->data;
-               pDest->option.mmsSendOptInfo.priority = pMms->priority;
-               pDest->option.mmsSendOptInfo.bReadReq = pMms->bReadReq;
-
-               MSG_DEBUG("pDest->option.mmsSendOpt.priority = %d", pMms->priority);
-               MSG_DEBUG("pDest->option.mmsSendOpt.bReadReq = %d", pMms->bReadReq);
+               if(pStruct)
+               {
+                       MMS_SENDINGOPT_S *pMms = (MMS_SENDINGOPT_S *)pStruct->data;
+                       if(pMms)
+                       {
+                               pDest->option.mmsSendOptInfo.priority = pMms->priority;
+                               pDest->option.mmsSendOptInfo.bReadReq = pMms->bReadReq;
+
+                               MSG_DEBUG("pDest->option.mmsSendOpt.priority = %d", pMms->priority);
+                               MSG_DEBUG("pDest->option.mmsSendOpt.bReadReq = %d", pMms->bReadReq);
+
+                               if (pMms->expiryTime == 0) {
+                                       pDest->option.mmsSendOptInfo.expiryTime.type = MMS_TIMETYPE_NONE;
+                                       pDest->option.mmsSendOptInfo.expiryTime.time = pMms->expiryTime;
+                               } else {
+                                       pDest->option.mmsSendOptInfo.expiryTime.type = MMS_TIMETYPE_RELATIVE;
+                                       pDest->option.mmsSendOptInfo.expiryTime.time = pMms->expiryTime;
+                               }
 
-               if (pMms->expiryTime == 0) {
-                       pDest->option.mmsSendOptInfo.expiryTime.type = MMS_TIMETYPE_NONE;
-                       pDest->option.mmsSendOptInfo.expiryTime.time = pMms->expiryTime;
-               } else {
-                       pDest->option.mmsSendOptInfo.expiryTime.type = MMS_TIMETYPE_RELATIVE;
-                       pDest->option.mmsSendOptInfo.expiryTime.time = pMms->expiryTime;
-               }
+                               if (pMms->bUseDeliveryCustomTime == true) {
+                                       pDest->option.mmsSendOptInfo.bUseDeliveryCustomTime = true;
+                               } else {
+                                       pDest->option.mmsSendOptInfo.bUseDeliveryCustomTime = false;
+                               }
+                               pDest->option.mmsSendOptInfo.deliveryTime.type = MMS_TIMETYPE_RELATIVE;
+                               pDest->option.mmsSendOptInfo.deliveryTime.time = pMms->deliveryTime;
 
-               if (pMms->bUseDeliveryCustomTime == true) {
-                       pDest->option.mmsSendOptInfo.bUseDeliveryCustomTime = true;
-               } else {
-                       pDest->option.mmsSendOptInfo.bUseDeliveryCustomTime = false;
+                               MSG_DEBUG("pDest->option.mmsSendOpt.expiryTime = %d", pDest->option.mmsSendOptInfo.expiryTime.time);
+                       }
                }
-               pDest->option.mmsSendOptInfo.deliveryTime.type = MMS_TIMETYPE_RELATIVE;
-               pDest->option.mmsSendOptInfo.deliveryTime.time = pMms->deliveryTime;
-
-               MSG_DEBUG("pDest->option.mmsSendOpt.expiryTime = %d", pDest->option.mmsSendOptInfo.expiryTime.time);
        }
 
        MSG_END();
@@ -510,3 +596,29 @@ int MsgHandle::getSettingCmdSize(MSG_OPTION_TYPE_T optionType)
 
        return cmdSize;
 }
+
+
+bool MsgHandle::CheckEventData(char *pEventData)
+{
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       switch (pEvent->eventType)
+       {
+       case MSG_EVENT_PLG_SENT_STATUS_CNF :
+       case MSG_EVENT_PLG_INCOMING_MSG_IND :
+       case MSG_EVENT_PLG_INCOMING_MMS_CONF :
+       case MSG_EVENT_PLG_INCOMING_SYNCML_MSG_IND :
+       case MSG_EVENT_PLG_INCOMING_LBS_MSG_IND :
+       case MSG_EVENT_PLG_STORAGE_CHANGE_IND :
+       case MSG_EVENT_PLG_INCOMING_CB_MSG_IND :
+       case MSG_EVENT_PLG_INCOMING_PUSH_MSG_IND :
+       case MSG_EVENT_PLG_REPORT_MSG_INCOMING_IND :
+               return false;
+               break;
+       default :
+               return true;
+               break;
+       }
+
+       return true;
+}
index 2799f47..04917b6 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
@@ -44,7 +44,7 @@ msg_error_t MsgHandle::addFilter(const MSG_FILTER_S *pFilter)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -80,7 +80,7 @@ msg_error_t MsgHandle::updateFilter(const MSG_FILTER_S *pFilter)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -116,7 +116,7 @@ msg_error_t MsgHandle::deleteFilter(msg_filter_id_t FilterId)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -149,7 +149,7 @@ msg_error_t MsgHandle::getFilterList(msg_struct_list_s *pFilterList)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -192,7 +192,7 @@ msg_error_t MsgHandle::setFilterOperation(bool bSetFlag)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -229,7 +229,7 @@ msg_error_t MsgHandle::getFilterOperation(bool *pSetFlag)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -253,3 +253,38 @@ msg_error_t MsgHandle::getFilterOperation(bool *pSetFlag)
        return ret;
 }
 
+msg_error_t MsgHandle::setFilterActivation(msg_filter_id_t filter_id, bool active)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_filter_id_t) + sizeof(bool);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SET_FILTER_ACTIVATION;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy(pCmd->cmdData, &filter_id, sizeof(msg_filter_id_t));
+       memcpy(pCmd->cmdData+sizeof(msg_filter_id_t), &active, sizeof(bool));
+
+       // Send Command to Messaging FW
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_SET_FILTER_ACTIVATION)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
index 716cdf8..c7e12b8 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
@@ -42,7 +42,7 @@ msg_error_t MsgHandle::getSMSCOption(msg_struct_t msg_struct)
        MSG_NULL_CHECK(smsc_opt->data);
 
        // Allocate Memory to Command Data
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T) + sizeof(msg_sim_slot_id_t);
 
        char cmdBuf[cmdSize];
        bzero(cmdBuf, cmdSize);
@@ -60,9 +60,15 @@ msg_error_t MsgHandle::getSMSCOption(msg_struct_t msg_struct)
        // Copy Command Data
        memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &opt_type, sizeof(MSG_OPTION_TYPE_T));
 
+       msg_sim_slot_id_t simIndex = ((MSG_SMSC_LIST_HIDDEN_S *)smsc_opt->data)->simIndex;
+       if (simIndex <= 0) {
+               THROW(MsgException::INVALID_PARAM, "Invalid SIM Index");
+       }
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_OPTION_TYPE_T)), &simIndex, sizeof(msg_sim_slot_id_t));
+
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -83,7 +89,10 @@ msg_error_t MsgHandle::getSMSCOption(msg_struct_t msg_struct)
 
                MSG_SMSC_LIST_HIDDEN_S *pTmp = (MSG_SMSC_LIST_HIDDEN_S *)smsc_opt->data;
 
+               pTmp->selected = smsc_list_tmp.selected;
                pTmp->smsc_list->nCount = smsc_list_tmp.totalCnt;
+               pTmp->index = smsc_list_tmp.selected;
+               pTmp->simIndex = smsc_list_tmp.simIndex;
 
                msg_struct_s *pStructTmp = NULL;
 
@@ -119,6 +128,15 @@ msg_error_t MsgHandle::setSMSCOption(msg_struct_t msg_struct)
 
        smsc_list_tmp.totalCnt = pTmpList->smsc_list->nCount;
        smsc_list_tmp.selected = pTmpList->selected;
+       smsc_list_tmp.index = pTmpList->index;
+       smsc_list_tmp.simIndex = pTmpList->simIndex;
+
+       if (smsc_list_tmp.totalCnt > SMSC_LIST_MAX) {
+               MSG_ERR("SMSC count is invaild value[Max:%d, Input:%d]", SMSC_LIST_MAX, smsc_list_tmp.totalCnt);
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MSG_DEBUG("SMSC totalcnt:%d selected:%d, index:%d ", smsc_list_tmp.totalCnt, smsc_list_tmp.selected, smsc_list_tmp.index);
 
        msg_struct_s *pStructTmp = NULL;
 
@@ -137,14 +155,14 @@ msg_error_t MsgHandle::setSMSCOption(msg_struct_t msg_struct)
        MSG_SETTING_S pSetting = {0,};
 
        pSetting.type = optionType;
-       memcpy(&(pSetting.option), &smsc_list_tmp, sizeof(MSG_SMSC_LIST_S));
+       memcpy(&(pSetting.option.smscList), &smsc_list_tmp, sizeof(MSG_SMSC_LIST_S));
 
     // Copy Command Data
     memcpy(pCmd->cmdData, &pSetting, cmdSize-sizeof(MSG_CMD_S));
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -166,7 +184,7 @@ msg_error_t MsgHandle::getCBOption(msg_struct_t msg_struct)
        MSG_NULL_CHECK(cb_opt->data);
 
        // Allocate Memory to Command Data
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T) + sizeof(msg_sim_slot_id_t);
 
        char cmdBuf[cmdSize];
        bzero(cmdBuf, cmdSize);
@@ -184,9 +202,12 @@ msg_error_t MsgHandle::getCBOption(msg_struct_t msg_struct)
        // Copy Command Data
        memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &opt_type, sizeof(MSG_OPTION_TYPE_T));
 
+       msg_sim_slot_id_t simIndex = ((MSG_CBMSG_OPT_HIDDEN_S*)cb_opt->data)->simIndex;
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_OPTION_TYPE_T)), &simIndex, sizeof(msg_sim_slot_id_t));
+
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -206,6 +227,7 @@ msg_error_t MsgHandle::getCBOption(msg_struct_t msg_struct)
                MSG_CBMSG_OPT_HIDDEN_S *pTmp = (MSG_CBMSG_OPT_HIDDEN_S *)cb_opt->data;
                pTmp->bReceive = cb_opt_tmp.bReceive;
                pTmp->maxSimCnt = cb_opt_tmp.maxSimCnt;
+               pTmp->simIndex = cb_opt_tmp.simIndex;
 
                for (i = 0; i < CB_LANG_TYPE_MAX; i++)
                        pTmp->bLanguage[i] = cb_opt_tmp.bLanguage[i];
@@ -251,6 +273,7 @@ msg_error_t MsgHandle::setCBOption(msg_struct_t msg_struct)
 
        cb_opt_tmp.bReceive = cb_msg_opt->bReceive;
        cb_opt_tmp.maxSimCnt = cb_msg_opt->maxSimCnt;
+       cb_opt_tmp.simIndex = cb_msg_opt->simIndex;
        for (int i = 0; i < CB_LANG_TYPE_MAX; i++)
                cb_opt_tmp.bLanguage[i] = cb_msg_opt->bLanguage[i];
 
@@ -274,7 +297,7 @@ msg_error_t MsgHandle::setCBOption(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -316,7 +339,7 @@ msg_error_t MsgHandle::getSmsSendOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -366,7 +389,7 @@ msg_error_t MsgHandle::setSmsSendOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -408,7 +431,7 @@ msg_error_t MsgHandle::getMmsSendOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -458,7 +481,7 @@ msg_error_t MsgHandle::setMmsSendOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -500,7 +523,7 @@ msg_error_t MsgHandle::getMmsRecvOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -550,7 +573,7 @@ msg_error_t MsgHandle::setMmsRecvOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -592,7 +615,7 @@ msg_error_t MsgHandle::getPushMsgOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -642,7 +665,7 @@ msg_error_t MsgHandle::setPushMsgOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -664,7 +687,7 @@ msg_error_t MsgHandle::getVoiceMsgOpt(msg_struct_t msg_struct)
        MSG_NULL_CHECK(voice_opt->data);
 
        // Allocate Memory to Command Data
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T) + sizeof(msg_sim_slot_id_t);
 
        char cmdBuf[cmdSize];
        bzero(cmdBuf, cmdSize);
@@ -682,9 +705,15 @@ msg_error_t MsgHandle::getVoiceMsgOpt(msg_struct_t msg_struct)
        // Copy Command Data
        memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &opt_type, sizeof(MSG_OPTION_TYPE_T));
 
+       msg_sim_slot_id_t simIndex = ((MSG_VOICEMAIL_OPT_S *)voice_opt->data)->simIndex;
+       if (simIndex <= 0) {
+               THROW(MsgException::INVALID_PARAM, "Invalid SIM Index : [index=%d]", simIndex);
+       }
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_OPTION_TYPE_T)), &simIndex, sizeof(msg_sim_slot_id_t));
+
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -734,7 +763,7 @@ msg_error_t MsgHandle::setVoiceMsgOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -776,7 +805,7 @@ msg_error_t MsgHandle::getGeneralOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -826,7 +855,7 @@ msg_error_t MsgHandle::setGeneralOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -868,7 +897,7 @@ msg_error_t MsgHandle::getMsgSizeOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -918,7 +947,7 @@ msg_error_t MsgHandle::setMsgSizeOpt(msg_struct_t msg_struct)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
index 5f72126..a72badd 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
 #include "MsgProxyListener.h"
 #include "MsgHandle.h"
 
-#include "MsgStorageHandler.h"
-
-
+#include "MsgVMessage.h"
 /*==================================================================================================
                                      IMPLEMENTATION OF MsgHandle - Storage Member Functions
 ==================================================================================================*/
 int MsgHandle::addMessage(MSG_MESSAGE_HIDDEN_S *pMsg, const MSG_SENDINGOPT_S *pSendOpt)
 {
-       MSG_MESSAGE_INFO_S msgInfo = {0};
-       MSG_SENDINGOPT_INFO_S sendOptInfo;
+       MSG_MESSAGE_INFO_S msgInfo = {0,};
+       MSG_SENDINGOPT_INFO_S sendOptInfo = {0,};
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
 
        // Covert MSG_MESSAGE_S to MSG_MESSAGE_INFO_S
        convertMsgStruct(pMsg, &msgInfo);
@@ -46,7 +47,11 @@ int MsgHandle::addMessage(MSG_MESSAGE_HIDDEN_S *pMsg, const MSG_SENDINGOPT_S *pS
        convertSendOptStruct(pSendOpt, &sendOptInfo, msgType);
 
        // Allocate Memory to Command Data
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_MESSAGE_INFO_S) + sizeof(MSG_SENDINGOPT_INFO_S);
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+       int dataSize = MsgEncodeMsgInfo(&msgInfo, &sendOptInfo, &encodedData);
+
+       int cmdSize = sizeof(MSG_CMD_S) + dataSize;
 
        char cmdBuf[cmdSize];
        bzero(cmdBuf, cmdSize);
@@ -59,24 +64,27 @@ int MsgHandle::addMessage(MSG_MESSAGE_HIDDEN_S *pMsg, const MSG_SENDINGOPT_S *pS
        memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
 
        // Copy Command Data
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &msgInfo, sizeof(MSG_MESSAGE_INFO_S));
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_MESSAGE_INFO_S)), &sendOptInfo, sizeof(MSG_SENDINGOPT_INFO_S));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), encodedData, dataSize);
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_ADD_MSG)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if (pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        msg_message_id_t msgId = 0;
 
@@ -90,13 +98,21 @@ int MsgHandle::addMessage(MSG_MESSAGE_HIDDEN_S *pMsg, const MSG_SENDINGOPT_S *pS
 msg_error_t MsgHandle::addSyncMLMessage(const MSG_SYNCML_MESSAGE_S *pSyncMLMsg)
 {
        MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
 
        // Covert MSG_MESSAGE_S to MSG_MESSAGE_INFO_S
        msg_struct_s *msg = (msg_struct_s *)pSyncMLMsg->msg;
        convertMsgStruct((MSG_MESSAGE_HIDDEN_S *)msg->data, &msgInfo);
 
        // Allocate Memory to Command Data
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(int) + sizeof(int) + sizeof(MSG_MESSAGE_INFO_S);
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+       int dataSize = MsgEncodeMsgInfo(&msgInfo, &encodedData);
+
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(int) + sizeof(int) + dataSize;
 
        char cmdBuf[cmdSize];
        bzero(cmdBuf, cmdSize);
@@ -111,11 +127,11 @@ msg_error_t MsgHandle::addSyncMLMessage(const MSG_SYNCML_MESSAGE_S *pSyncMLMsg)
        // Copy Command Data
        memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &pSyncMLMsg->extId, sizeof(int));
        memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(int)), &pSyncMLMsg->pinCode, sizeof(int));
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(int)+sizeof(int)), &msgInfo, sizeof(MSG_MESSAGE_INFO_S));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(int)+sizeof(int)), encodedData, dataSize);
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
 
        write((char*)pCmd, cmdSize, &pEventData);
@@ -123,24 +139,37 @@ msg_error_t MsgHandle::addSyncMLMessage(const MSG_SYNCML_MESSAGE_S *pSyncMLMsg)
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_ADD_SYNCML_MSG)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
+       msg_message_id_t msgId = 0;
+
+       // Decode Return Data
+       MsgDecodeMsgId(pEvent->data, &msgId);
+
+       ((MSG_MESSAGE_HIDDEN_S *)msg->data)->msgId = msgId;
+
        return pEvent->result;
 }
 
 
 msg_error_t MsgHandle::updateMessage(const MSG_MESSAGE_HIDDEN_S *pMsg, const MSG_SENDINGOPT_S *pSendOpt)
 {
-       MSG_MESSAGE_INFO_S msgInfo;
-       MSG_SENDINGOPT_INFO_S sendOptInfo;
+       MSG_MESSAGE_INFO_S msgInfo = {0, };
+       MSG_SENDINGOPT_INFO_S sendOptInfo = {0, };
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
 
        // Covert MSG_MESSAGE_S to MSG_MESSAGE_INFO_S
        convertMsgStruct(pMsg, &msgInfo);
 
-       if(pSendOpt != NULL) {
+       if (pSendOpt != NULL) {
                MSG_MESSAGE_TYPE_S msgType = {0,};
 
                msgType.mainType = pMsg->mainType;
@@ -151,7 +180,11 @@ msg_error_t MsgHandle::updateMessage(const MSG_MESSAGE_HIDDEN_S *pMsg, const MSG
        }
 
        // Allocate Memory to Command Data
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_MESSAGE_INFO_S) + sizeof(MSG_SENDINGOPT_INFO_S);
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+       int dataSize = MsgEncodeMsgInfo(&msgInfo, &sendOptInfo, &encodedData);
+
+       int cmdSize = sizeof(MSG_CMD_S) + dataSize;
 
        char cmdBuf[cmdSize];
        bzero(cmdBuf, cmdSize);
@@ -164,19 +197,20 @@ msg_error_t MsgHandle::updateMessage(const MSG_MESSAGE_HIDDEN_S *pMsg, const MSG
        memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
 
        // Copy Command Data
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &msgInfo, sizeof(MSG_MESSAGE_INFO_S));
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_MESSAGE_INFO_S)), &sendOptInfo, sizeof(MSG_SENDINGOPT_INFO_S));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), encodedData, dataSize);
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_UPDATE_MSG)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
@@ -207,14 +241,16 @@ msg_error_t MsgHandle::updateReadStatus(msg_message_id_t MsgId, bool bRead)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_UPDATE_READ)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
@@ -224,6 +260,45 @@ msg_error_t MsgHandle::updateReadStatus(msg_message_id_t MsgId, bool bRead)
 }
 
 
+msg_error_t MsgHandle::setConversationToRead(msg_thread_id_t ThreadId)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_thread_id_t);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_UPDATE_THREAD_READ;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &ThreadId, sizeof(msg_thread_id_t));
+
+       // Send Command to Messaging FW
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
+       if (pEvent->eventType != MSG_EVENT_UPDATE_THREAD_READ)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
 msg_error_t MsgHandle::updateProtectedStatus(msg_message_id_t MsgId, bool bProtected)
 {
        // Allocate Memory to Command Data
@@ -245,14 +320,16 @@ msg_error_t MsgHandle::updateProtectedStatus(msg_message_id_t MsgId, bool bProte
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_UPDATE_PROTECTED)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
@@ -282,14 +359,16 @@ msg_error_t MsgHandle::deleteMessage(msg_message_id_t MsgId)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_DELETE_MSG)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
@@ -320,14 +399,16 @@ msg_error_t MsgHandle::deleteAllMessagesInFolder(msg_folder_id_t FolderId, bool
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_DELALL_MSGINFOLDER)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
@@ -337,6 +418,47 @@ msg_error_t MsgHandle::deleteAllMessagesInFolder(msg_folder_id_t FolderId, bool
 }
 
 
+msg_error_t MsgHandle::deleteMessagesByList(msg_id_list_s *pMsgIdList)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(int) + (sizeof(int)*pMsgIdList->nCount);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_DELETE_MESSAGE_BY_LIST;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &(pMsgIdList->nCount), sizeof(int));
+       for (int i=0; i<pMsgIdList->nCount; i++) {
+               memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(int)+(sizeof(int)*i)), &(pMsgIdList->msgIdList[i]), sizeof(int));
+       }
+
+       // Send Command to Messaging FW
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
+       if (pEvent->eventType != MSG_EVENT_DELETE_MESSAGE_BY_LIST) {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
 msg_error_t MsgHandle::moveMessageToFolder(msg_message_id_t MsgId, msg_folder_id_t DestFolderId)
 {
        // Allocate Memory to Command Data
@@ -358,14 +480,16 @@ msg_error_t MsgHandle::moveMessageToFolder(msg_message_id_t MsgId, msg_folder_id
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_MOVE_MSGTOFOLDER)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
@@ -396,14 +520,16 @@ msg_error_t MsgHandle::moveMessageToStorage(msg_message_id_t MsgId, msg_storage_
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_MOVE_MSGTOSTORAGE)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
@@ -433,20 +559,23 @@ msg_error_t MsgHandle::countMessage(msg_folder_id_t FolderId, MSG_COUNT_INFO_S *
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_COUNT_MSG)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        // Decode Return Data
        MsgDecodeCountInfo(pEvent->data, pCountInfo);
@@ -475,19 +604,23 @@ msg_error_t MsgHandle::countMsgByType(const MSG_MESSAGE_TYPE_S *pMsgType, int *p
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_COUNT_BY_MSGTYPE)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        // Decode Return Data
        memcpy(pMsgCount, (void*)((char*)pEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)), sizeof(int));
@@ -518,19 +651,23 @@ msg_error_t MsgHandle::countMsgByContact(const MSG_THREAD_LIST_INDEX_INFO_S *pAd
        memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN + sizeof(msg_contact_id_t)), pAddr->data, sizeof(MSG_ADDRESS_INFO_S));
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_GET_CONTACT_COUNT)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        // Decode Return Data
        MsgDecodeContactCount(pEvent->data, pMsgThreadCountList);
@@ -559,7 +696,7 @@ msg_error_t MsgHandle::getMessage(msg_message_id_t MsgId, MSG_MESSAGE_HIDDEN_S *
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
 
        write((char*)pCmd, cmdSize, &pEventData);
@@ -567,23 +704,29 @@ msg_error_t MsgHandle::getMessage(msg_message_id_t MsgId, MSG_MESSAGE_HIDDEN_S *
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
-       if (pEvent->eventType != MSG_EVENT_GET_MSG)
-       {
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
+       if (pEvent->eventType != MSG_EVENT_GET_MSG) {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS)
+       if (pEvent->result != MSG_SUCCESS)
                return pEvent->result;
 
        // Decode Return Data
        MSG_MESSAGE_INFO_S msgInfo;
        MSG_SENDINGOPT_INFO_S sendOptInfo;
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
        MsgDecodeMsgInfo(pEvent->data, &msgInfo, &sendOptInfo);
 
        // Covert MSG_MESSAGE_INFO_S to MSG_MESSAGE_HIDDEN_S
        convertMsgStruct(&msgInfo, pMsg);
 
-       if(pSendOpt != NULL) {
+       if (pSendOpt != NULL) {
                MSG_MESSAGE_TYPE_S msgType = {0,};
 
                msgType.mainType = pMsg->mainType;
@@ -608,13 +751,13 @@ msg_error_t MsgHandle::getFolderViewList(msg_folder_id_t FolderId, const MSG_SOR
 {
        msg_error_t err = MSG_SUCCESS;
 
-       err = MsgStoConnectDB();
-
-       if (err != MSG_SUCCESS)
-       {
-               MSG_DEBUG("MsgStoConnectDB() Error!!");
-               return err;
-       }
+//     err = MsgStoConnectDB();
+//
+//     if (err != MSG_SUCCESS)
+//     {
+//             MSG_DEBUG("MsgStoConnectDB() Error!!");
+//             return err;
+//     }
 
        err = MsgStoGetFolderViewList(FolderId, (MSG_SORT_RULE_S *)pSortRule, pMsgFolderViewList);
 
@@ -624,7 +767,7 @@ msg_error_t MsgHandle::getFolderViewList(msg_folder_id_t FolderId, const MSG_SOR
                return err;
        }
 
-       MsgStoDisconnectDB();
+//     MsgStoDisconnectDB();
 
        return err;
 }
@@ -650,14 +793,16 @@ msg_error_t MsgHandle::addFolder(const MSG_FOLDER_INFO_S *pFolderInfo)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_ADD_FOLDER)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
@@ -687,20 +832,22 @@ msg_error_t MsgHandle::updateFolder(const MSG_FOLDER_INFO_S *pFolderInfo)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_UPDATE_FOLDER)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       return pEvent->result;;
+       return pEvent->result;
 }
 
 
@@ -724,14 +871,16 @@ msg_error_t MsgHandle::deleteFolder(msg_folder_id_t FolderId)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_DELETE_FOLDER)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
@@ -758,19 +907,23 @@ msg_error_t MsgHandle::getFolderList(msg_struct_list_s *pFolderList)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_GET_FOLDERLIST)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        // Decode Return Data
        MsgDecodeFolderList(pEvent->data, pFolderList);
@@ -783,13 +936,13 @@ msg_error_t MsgHandle::getThreadViewList(const MSG_SORT_RULE_S *pSortRule, msg_s
 {
        msg_error_t err =  MSG_SUCCESS;
 
-       err = MsgStoConnectDB();
-
-       if (err != MSG_SUCCESS)
-       {
-               MSG_DEBUG("MsgStoConnectDB() Error!!");
-               return err;
-       }
+//     err = MsgStoConnectDB();
+//
+//     if (err != MSG_SUCCESS)
+//     {
+//             MSG_DEBUG("MsgStoConnectDB() Error!!");
+//             return err;
+//     }
 
        err = MsgStoGetThreadViewList(pSortRule, pThreadViewList);
 
@@ -799,69 +952,85 @@ msg_error_t MsgHandle::getThreadViewList(const MSG_SORT_RULE_S *pSortRule, msg_s
                return err;
        }
 
-       MsgStoDisconnectDB();
-
-       return err;
-}
-
-
-msg_error_t MsgHandle::getConversationViewList(msg_thread_id_t ThreadId, msg_struct_list_s *pConvViewList)
-{
-       MSG_BEGIN();
-
-       msg_error_t err =  MSG_SUCCESS;
-
-       MsgStoConnectDB();
-       err = MsgStoGetConversationViewList(ThreadId, pConvViewList);
-       MsgStoDisconnectDB();
-
-       if(err != MSG_SUCCESS)
-               return err;
+//     MsgStoDisconnectDB();
 
-
-// Update Read Status for the Thead ID
-#if 1
+#if 0
        // Allocate Memory to Command Data
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_thread_id_t);
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_SORT_RULE_S);
 
        char cmdBuf[cmdSize];
        bzero(cmdBuf, cmdSize);
        MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
 
        // Set Command Parameters
-       pCmd->cmdType = MSG_CMD_UPDATE_THREAD_READ;
-
-       // Copy Cookie
-       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+       pCmd->cmdType = MSG_CMD_GET_THREADVIEWLIST;
 
        // Copy Command Data
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &ThreadId, sizeof(msg_thread_id_t));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)), pSortRule, sizeof(MSG_SORT_RULE_S));
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
-       if (pEvent->eventType != MSG_EVENT_UPDATE_THREAD_READ)
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
+       if (pEvent->eventType != MSG_EVENT_GET_THREADVIEWLIST)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
+
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
+
+       // Decode Return Data
+       MsgDecodeThreadViewList(pEvent->data, pMsgThreadViewList);
 #endif
 
+       return err;
+}
+
+msg_error_t MsgHandle::getConversationViewItem(msg_message_id_t MsgId, MSG_CONVERSATION_VIEW_S *pConv)
+{
+       MSG_BEGIN();
+
+       msg_error_t err =  MSG_SUCCESS;
+
+//     MsgStoConnectDB();
+       err = MsgStoGetConversationViewItem(MsgId, pConv);
+//     MsgStoDisconnectDB();
+
+       return err;
+}
+
+msg_error_t MsgHandle::getConversationViewList(msg_thread_id_t ThreadId, msg_struct_list_s *pConvViewList)
+{
+       MSG_BEGIN();
+
+       msg_error_t err =  MSG_SUCCESS;
+
+//     MsgStoConnectDB();
+       err = MsgStoGetConversationViewList(ThreadId, pConvViewList);
+//     MsgStoDisconnectDB();
+
+       if (err != MSG_SUCCESS)
+               return err;
+
        MSG_END();
 
        return err;
 }
 
 
-msg_error_t MsgHandle::deleteThreadMessageList(msg_thread_id_t ThreadId)
+msg_error_t MsgHandle::deleteThreadMessageList(msg_thread_id_t ThreadId, bool include_protected_msg)
 {
        // Allocate Memory to Command Data
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_THREAD_LIST_INDEX_S);
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_thread_id_t) + sizeof(bool);
 
        char cmdBuf[cmdSize];
        bzero(cmdBuf, cmdSize);
@@ -875,23 +1044,27 @@ msg_error_t MsgHandle::deleteThreadMessageList(msg_thread_id_t ThreadId)
 
        // Copy Command Data
        memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &ThreadId, sizeof(msg_thread_id_t));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_thread_id_t)), &include_protected_msg, sizeof(bool));
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_DELETE_THREADMESSAGELIST)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        return MSG_SUCCESS;
 }
@@ -917,24 +1090,33 @@ msg_error_t MsgHandle::getQuickPanelData(msg_quickpanel_type_t Type, MSG_MESSAGE
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_GET_QUICKPANEL_DATA)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        // Decode Return Data
        MSG_MESSAGE_INFO_S msgInfo;
 
-       memcpy(&msgInfo, (void*)((char*)pEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)), sizeof(MSG_MESSAGE_INFO_S));
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       MsgDecodeMsgInfo((char *)pEvent->data, &msgInfo);
 
        // Covert MSG_MESSAGE_INFO_S to MSG_MESSAGE_S
        convertMsgStruct(&msgInfo, pMsg);
@@ -967,13 +1149,16 @@ msg_error_t MsgHandle::resetDatabase()
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_RESET_DB)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
@@ -1000,20 +1185,23 @@ msg_error_t MsgHandle::getMemSize(unsigned int* memsize)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_GET_MEMSIZE)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        // Decode Return Data
        MsgDecodeMemSize(pEvent->data, memsize);
@@ -1021,11 +1209,31 @@ msg_error_t MsgHandle::getMemSize(unsigned int* memsize)
        return MSG_SUCCESS;
 }
 
-
-msg_error_t MsgHandle::backupMessage()
+msg_error_t MsgHandle::backupMessage(msg_message_backup_type_t type, const char *backup_filepath)
 {
+       if (backup_filepath == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       //Create an empty file for writing.
+       //If a file with the same name already exists its content is erased
+       //and the file is treated as a new empty file.
+       if (MsgAccessFile(backup_filepath, F_OK)) {
+               if (remove(backup_filepath) != 0)
+                       MSG_SEC_DEBUG("Fail to delete file [%s]", backup_filepath);
+       }
+
+       FILE *pFile = MsgOpenFile(backup_filepath, "w");
+       if (pFile == NULL) {
+               MSG_DEBUG("File Open error");
+               return MSG_ERR_STORAGE_ERROR;
+       }
+       MsgCloseFile(pFile);
+
+       char path[MSG_FILEPATH_LEN_MAX+1] = {0,};
+       strncpy(path, backup_filepath, MSG_FILEPATH_LEN_MAX);
+
        // Allocate Memory to Command Data
-       int cmdSize = sizeof(MSG_CMD_S);
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_message_backup_type_t) + sizeof(path);
 
        char cmdBuf[cmdSize];
        bzero(cmdBuf, cmdSize);
@@ -1036,32 +1244,47 @@ msg_error_t MsgHandle::backupMessage()
 
        // Copy Cookie
        memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &type, sizeof(msg_message_backup_type_t));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_message_backup_type_t)), (char *)path, sizeof(path));
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_BACKUP_MESSAGE)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        return MSG_SUCCESS;
 }
 
-
-msg_error_t MsgHandle::restoreMessage()
+msg_error_t MsgHandle::restoreMessage(const char *backup_filepath)
 {
+       if (backup_filepath == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       if (MsgAccessFile(backup_filepath, R_OK) == false) {
+               MSG_DEBUG("File access error");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       char path[MSG_FILEPATH_LEN_MAX+1] = {0,};
+       strncpy(path, backup_filepath, MSG_FILEPATH_LEN_MAX);
+
        // Allocate Memory to Command Data
-       int cmdSize = sizeof(MSG_CMD_S);
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(path);
 
        char cmdBuf[cmdSize];
        bzero(cmdBuf, cmdSize);
@@ -1072,23 +1295,27 @@ msg_error_t MsgHandle::restoreMessage()
 
        // Copy Cookie
        memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), (char *)path, sizeof(path));
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_RESTORE_MESSAGE)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        return MSG_SUCCESS;
 }
@@ -1098,13 +1325,13 @@ msg_error_t MsgHandle::searchMessage(const char *pSearchString, msg_struct_list_
 {
        msg_error_t err =  MSG_SUCCESS;
 
-       err = MsgStoConnectDB();
-
-       if (err != MSG_SUCCESS)
-       {
-               MSG_DEBUG("MsgStoConnectDB() Error!!");
-               return err;
-       }
+//     err = MsgStoConnectDB();
+//
+//     if (err != MSG_SUCCESS)
+//     {
+//             MSG_DEBUG("MsgStoConnectDB() Error!!");
+//             return err;
+//     }
 
        err = MsgStoSearchMessage(pSearchString, pThreadViewList);
 
@@ -1114,31 +1341,7 @@ msg_error_t MsgHandle::searchMessage(const char *pSearchString, msg_struct_list_
                return err;
        }
 
-       MsgStoDisconnectDB();
-
-       return err;
-}
-
-
-msg_error_t MsgHandle::searchMessage(const MSG_SEARCH_CONDITION_S *pSearchCon, int offset, int limit, msg_struct_list_s *pMsgList)
-{
-       msg_error_t err =  MSG_SUCCESS;
-
-       err = MsgStoConnectDB();
-
-       if (err != MSG_SUCCESS) {
-               MSG_DEBUG("MsgStoConnectDB() Error!!");
-               return err;
-       }
-
-       err = MsgStoSearchMessage(pSearchCon, offset, limit, pMsgList);
-
-       if (err != MSG_SUCCESS) {
-               MSG_DEBUG("MsgStoSearchMessage() Error!!");
-               return err;
-       }
-
-       MsgStoDisconnectDB();
+//     MsgStoDisconnectDB();
 
        return err;
 }
@@ -1148,13 +1351,13 @@ msg_error_t MsgHandle::getRejectMsgList(const char *pNumber, msg_struct_list_s *
 {
        msg_error_t err =  MSG_SUCCESS;
 
-       err = MsgStoConnectDB();
-
-       if (err != MSG_SUCCESS)
-       {
-               MSG_DEBUG("MsgStoConnectDB() Error!!");
-               return err;
-       }
+//     err = MsgStoConnectDB();
+//
+//     if (err != MSG_SUCCESS)
+//     {
+//             MSG_DEBUG("MsgStoConnectDB() Error!!");
+//             return err;
+//     }
 
        err = MsgStoGetRejectMsgList(pNumber, pRejectMsgList);
 
@@ -1164,7 +1367,7 @@ msg_error_t MsgHandle::getRejectMsgList(const char *pNumber, msg_struct_list_s *
                return err;
        }
 
-       MsgStoDisconnectDB();
+//     MsgStoDisconnectDB();
 
        return err;
 }
@@ -1177,10 +1380,15 @@ msg_error_t MsgHandle::regStorageChangeCallback(msg_storage_change_cb onStorageC
 
        MsgProxyListener* eventListener = MsgProxyListener::instance();
 
-       eventListener->start();
+       eventListener->start(this);
 
-       if (eventListener->regStorageChangeEventCB(this, onStorageChange, pUserParam) == false) // callback was already registered, just return SUCCESS
-               return MSG_SUCCESS;
+       int remoteFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+
+       if (remoteFd == -1 )
+               return MSG_ERR_INVALID_MSGHANDLE;
+
+       if (eventListener->regStorageChangeEventCB(this, onStorageChange, pUserParam) == false)
+               return MSG_ERR_INVALID_PARAMETER;
 
        // Allocate Memory to Command Data
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(int); // cmd type, listenerFd
@@ -1194,23 +1402,24 @@ msg_error_t MsgHandle::regStorageChangeCallback(msg_storage_change_cb onStorageC
        // Copy Cookie
        memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
 
-       int listenerFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+       MSG_DEBUG("remote fd %d", remoteFd);
 
-       MSG_DEBUG("remote fd %d", listenerFd);
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &remoteFd, sizeof(remoteFd));
 
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &listenerFd, sizeof(listenerFd));
-
-       MSG_DEBUG("reg status [%d : %s], %d", pCmd->cmdType, MsgDbgCmdStr(pCmd->cmdType), listenerFd);
+       MSG_DEBUG("reg status [%d : %s], %d", pCmd->cmdType, MsgDbgCmdStr(pCmd->cmdType), remoteFd);
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_REG_STORAGE_CHANGE_CB)
        {
                THROW(MsgException::INVALID_PARAM, "Event Data Error");
@@ -1219,8 +1428,7 @@ msg_error_t MsgHandle::regStorageChangeCallback(msg_storage_change_cb onStorageC
        return pEvent->result;
 }
 
-
-msg_error_t MsgHandle::getReportStatus(msg_message_id_t msg_id, MSG_REPORT_STATUS_INFO_S *pReport_status)
+msg_error_t MsgHandle::getReportStatus(msg_message_id_t msg_id, msg_struct_list_s *report_list)
 {
        // Allocate Memory to Command Data
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_message_id_t);
@@ -1229,6 +1437,9 @@ msg_error_t MsgHandle::getReportStatus(msg_message_id_t msg_id, MSG_REPORT_STATU
        bzero(cmdBuf, cmdSize);
        MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
 
+       report_list->nCount = 0;
+       report_list->msg_struct_info = NULL;
+
        // Set Command Parameters
        pCmd->cmdType = MSG_CMD_GET_REPORT_STATUS;
 
@@ -1240,23 +1451,26 @@ msg_error_t MsgHandle::getReportStatus(msg_message_id_t msg_id, MSG_REPORT_STATU
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_GET_REPORT_STATUS)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        // Decode Return Data
-       MsgDecodeReportStatus(pEvent->data, pReport_status);
+       MsgDecodeReportStatus(pEvent->data, report_list);
 
        return MSG_SUCCESS;
 }
@@ -1266,13 +1480,13 @@ msg_error_t MsgHandle::getAddressList(const msg_thread_id_t threadId, msg_struct
 {
        msg_error_t err =  MSG_SUCCESS;
 
-       err = MsgStoConnectDB();
-
-       if (err != MSG_SUCCESS)
-       {
-               MSG_DEBUG("MsgStoConnectDB() Error!!");
-               return err;
-       }
+//     err = MsgStoConnectDB();
+//
+//     if (err != MSG_SUCCESS)
+//     {
+//             MSG_DEBUG("MsgStoConnectDB() Error!!");
+//             return err;
+//     }
 
        err = MsgStoGetAddressList(threadId, (msg_struct_list_s *)pAddrList);
 
@@ -1282,7 +1496,7 @@ msg_error_t MsgHandle::getAddressList(const msg_thread_id_t threadId, msg_struct
                return err;
        }
 
-       MsgStoDisconnectDB();
+//     MsgStoDisconnectDB();
 
        return err;
 }
@@ -1312,20 +1526,74 @@ msg_error_t MsgHandle::getThreadIdByAddress(msg_struct_list_s *pAddrList, msg_th
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
+       if (pEvent->eventType != MSG_EVENT_GET_THREAD_ID_BY_ADDRESS)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
+
+       // Decode Return Data
+       MsgDecodeThreadId(pEvent->data, pThreadId);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgHandle::getThreadIdByAddress(msg_list_handle_t msg_address_list, msg_thread_id_t *pThreadId)
+{
+       int addrCnt = (int)g_list_length((GList *)msg_address_list);
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(int) + (sizeof(MSG_ADDRESS_INFO_S)*addrCnt);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_THREAD_ID_BY_ADDRESS;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &addrCnt, sizeof(int));
+       int addSize = sizeof(MSG_ADDRESS_INFO_S);
+       for(int i=0; i<addrCnt; i++) {
+               memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+sizeof(addrCnt)+(addSize*i)+MAX_COOKIE_LEN), ((msg_struct_s *)(g_list_nth_data((GList *)msg_address_list,(guint)i)))->data, sizeof(MSG_ADDRESS_INFO_S));
+       }
+
+       // Send Command to Messaging FW
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_GET_THREAD_ID_BY_ADDRESS)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
        }
 
-       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
 
        // Decode Return Data
        MsgDecodeThreadId(pEvent->data, pThreadId);
@@ -1354,13 +1622,16 @@ msg_error_t MsgHandle::getThread(msg_thread_id_t threadId, MSG_THREAD_VIEW_S* pT
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
        // Get Return Data
        MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
 
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
        if (pEvent->eventType != MSG_EVENT_GET_THREAD_INFO)
        {
                THROW(MsgException::INVALID_RESULT, "Event Data Error");
@@ -1373,25 +1644,224 @@ msg_error_t MsgHandle::getThread(msg_thread_id_t threadId, MSG_THREAD_VIEW_S* pT
 }
 
 
-msg_error_t MsgHandle::getMessageList(msg_folder_id_t folderId, msg_thread_id_t threadId, msg_message_type_t msgType, msg_storage_id_t storageId, msg_struct_list_s *pMsgList)
+msg_error_t MsgHandle::getMessageList(const MSG_LIST_CONDITION_S *pListCond, msg_struct_list_s *pMsgList)
 {
        msg_error_t err =  MSG_SUCCESS;
 
-       err = MsgStoConnectDB();
+//     err = MsgStoConnectDB();
+//
+//     if (err != MSG_SUCCESS) {
+//             MSG_DEBUG("MsgStoConnectDB() Error!!");
+//             return err;
+//     }
+
+       err = MsgStoGetMessageList(pListCond, pMsgList);
 
        if (err != MSG_SUCCESS) {
-               MSG_DEBUG("MsgStoConnectDB() Error!!");
+               MSG_DEBUG("MsgStoGetMessageList() Error!!");
                return err;
        }
 
-       err = MsgStoGetMessageList(folderId, threadId, msgType, storageId, pMsgList);
+//     MsgStoDisconnectDB();
+
+       return err;
+}
+
+
+msg_error_t MsgHandle::getMediaList(const msg_thread_id_t thread_id, msg_list_handle_t *pMediaList)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       err = MsgStoGetMediaList(thread_id, pMediaList);
 
        if (err != MSG_SUCCESS) {
-               MSG_DEBUG("MsgStoSearchMessage() Error!!");
+               MSG_DEBUG("MsgStoGetFmMediaList() Error!!");
                return err;
        }
 
-       MsgStoDisconnectDB();
-
        return err;
 }
+
+
+int MsgHandle::addPushEvent(MSG_PUSH_EVENT_INFO_S *pPushEvent)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_PUSH_EVENT_INFO_S);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_ADD_PUSH_EVENT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pPushEvent, sizeof(MSG_PUSH_EVENT_INFO_S));
+
+       // Send Command to Messaging FW
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
+       if (pEvent->eventType != MSG_EVENT_ADD_PUSH_EVENT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+int MsgHandle::deletePushEvent(MSG_PUSH_EVENT_INFO_S *pPushEvent)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_PUSH_EVENT_INFO_S);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_DELETE_PUSH_EVENT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pPushEvent, sizeof(MSG_PUSH_EVENT_INFO_S));
+
+       // Send Command to Messaging FW
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
+       if (pEvent->eventType != MSG_EVENT_DELETE_PUSH_EVENT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+int MsgHandle::updatePushEvent(MSG_PUSH_EVENT_INFO_S *pSrc, MSG_PUSH_EVENT_INFO_S *pDst)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) +  2 * sizeof(MSG_PUSH_EVENT_INFO_S);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_UPDATE_PUSH_EVENT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pSrc, sizeof(MSG_PUSH_EVENT_INFO_S));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_PUSH_EVENT_INFO_S)), pDst, sizeof(MSG_PUSH_EVENT_INFO_S));
+
+       // Send Command to Messaging FW
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
+       if (pEvent->eventType != MSG_EVENT_UPDATE_PUSH_EVENT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::getVobject(msg_message_id_t MsgId, void** encodedData)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_message_id_t);
+       char *encode_data = NULL;
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_MSG;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &MsgId, sizeof(msg_message_id_t));
+
+       // Send Command to Messaging FW
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent == NULL)
+               THROW(MsgException::INVALID_RESULT, "Event is NULL");
+
+       if (pEvent->eventType != MSG_EVENT_GET_MSG)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result != MSG_SUCCESS)
+               return pEvent->result;
+
+       // Decode Return Data
+       MSG_MESSAGE_INFO_S msgInfo = {0,};
+       MSG_SENDINGOPT_INFO_S sendOptInfo = {0,};
+
+       msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+       MsgDecodeMsgInfo(pEvent->data, &msgInfo, &sendOptInfo);
+
+       //Convert MSG_MESSAGE_INFO_S to
+       encode_data = MsgVMessageEncode(&msgInfo);
+       if (encode_data) {
+               *encodedData = (void*)encode_data;
+       } else {
+               MSG_DEBUG("Error Encode data");
+               *encodedData = NULL;
+       }
+
+       // Delete Temp File
+       if (msgInfo.bTextSms == false)
+       {
+               // Delete Temp File
+               MsgDeleteFile(msgInfo.msgData); //ipc
+       }
+
+       return MSG_SUCCESS;
+}
index e3ade18..6a7a4ee 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <time.h>
@@ -20,6 +20,7 @@
 #include "MsgDebug.h"
 #include "MsgCppTypes.h"
 #include "MsgException.h"
+#include "MsgUtilFunction.h"
 #include "MsgProxyListener.h"
 #include "MsgHandle.h"
 
@@ -34,18 +35,35 @@ msg_error_t MsgHandle::submitReq(MSG_REQUEST_S* pReq)
        if (pReq == NULL)
                THROW(MsgException::INVALID_PARAM, "pReq is NULL");
 
+#ifdef CHECK_SENT_STATUS_CALLBACK
+       if (MsgProxyListener::instance()->getSentStatusCbCnt() <= 0)
+               THROW(MsgException::SENT_STATUS_ERROR,"Register sent status callback");
+#endif
+
        MSG_REQUEST_INFO_S reqInfo = {0};
        char trId[MMS_TR_ID_LEN+1] = {0};
 
+       reqInfo.msgInfo.addressList = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&reqInfo.msgInfo.addressList, unique_ptr_deleter);
+
        msg_struct_s *msg_s = (msg_struct_s *)pReq->msg;
 
        MSG_MESSAGE_HIDDEN_S *reqmsg = (MSG_MESSAGE_HIDDEN_S*)msg_s->data;
 
+       if (reqmsg->simIndex <= 0) {
+               MSG_DEBUG("Wrong SIM Index [%d]", reqmsg->simIndex);
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
        if (reqmsg->subType != MSG_SENDREQ_JAVA_MMS) {
                // In case MMS read report, get address value later.
                if(reqmsg->subType != MSG_READREPLY_MMS) {
-                       if ((reqmsg->addr_list->nCount == 0) || (reqmsg->addr_list->nCount > MAX_TO_ADDRESS_CNT)) {
-                               MSG_DEBUG("Recipient address count error [%d]", reqmsg->addr_list->nCount );
+                       if (reqmsg->addr_list && (reqmsg->addr_list->nCount > 0) && (reqmsg->addr_list->nCount <= MAX_TO_ADDRESS_CNT)) {
+                               MSG_DEBUG("Recipient address count [%d]", reqmsg->addr_list->nCount );
+                       } else if (g_list_length(reqmsg->addressList) > 0) {
+                               MSG_DEBUG("Recipient address count [%d]", g_list_length(reqmsg->addressList) );
+                       } else {
+                               MSG_DEBUG("Address count is invalid.");
                                return MSG_ERR_INVALID_MESSAGE;
                        }
                }
@@ -60,7 +78,7 @@ msg_error_t MsgHandle::submitReq(MSG_REQUEST_S* pReq)
                }
 
                reqmsg->bRead = false;
-               reqmsg->bProtected = false;
+               //reqmsg->bProtected = false;
                reqmsg->priority = MSG_MESSAGE_PRIORITY_NORMAL;
                reqmsg->direction = MSG_DIRECTION_TYPE_MO;
                reqmsg->storageId = MSG_STORAGE_PHONE;
@@ -68,7 +86,7 @@ msg_error_t MsgHandle::submitReq(MSG_REQUEST_S* pReq)
                time_t curTime = time(NULL);
 
                if (curTime < 0)
-                       THROW(MsgException::INVALID_RESULT, "time error : %s", strerror(errno));
+                       THROW(MsgException::INVALID_RESULT, "time error : %s", g_strerror(errno));
 
                reqmsg->displayTime = curTime;
                /* End : Setting default values for submit request */
@@ -76,7 +94,7 @@ msg_error_t MsgHandle::submitReq(MSG_REQUEST_S* pReq)
                //in case of JAVA MMS msg, parse mms transaction id from pMmsData
                reqmsg->networkStatus = MSG_NETWORK_SENDING;
                strncpy(trId, (char*)reqmsg->pMmsData+3,MMS_TR_ID_LEN);
-               MSG_DEBUG("JavaMMS transaction Id:%s ",trId);
+               MSG_SEC_DEBUG("JavaMMS transaction Id:%s ",trId);
        }
 
        // Convert MSG_MESSAGE_S to MSG_MESSAGE_INFO_S
@@ -88,7 +106,10 @@ msg_error_t MsgHandle::submitReq(MSG_REQUEST_S* pReq)
        msgType.subType = reqmsg->subType;
        msgType.classType = reqmsg->classType;
 
-       convertSendOptStruct((const MSG_SENDINGOPT_S *)pReq->sendOpt, &(reqInfo.sendOptInfo), msgType);
+       msg_struct_s *send_opt_s = (msg_struct_s *)pReq->sendOpt;
+       MSG_SENDINGOPT_S *send_opt = (MSG_SENDINGOPT_S *)send_opt_s->data;
+
+       convertSendOptStruct((const MSG_SENDINGOPT_S *)send_opt, &(reqInfo.sendOptInfo), msgType);
 
        reqInfo.reqId = 0;
 
@@ -100,7 +121,11 @@ msg_error_t MsgHandle::submitReq(MSG_REQUEST_S* pReq)
        chInfo.handleAddr = (unsigned int) this;
 
        /* Allocate Memory to Command Data */
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_REQUEST_INFO_S) + sizeof(MSG_PROXY_INFO_S);
+       char* encodedData = NULL;
+       unique_ptr<char*, void(*)(char**)> buf(&encodedData, unique_ptr_deleter);
+       int dataSize = MsgEncodeMsgInfo(&reqInfo.msgInfo, &reqInfo.sendOptInfo, &encodedData);
+
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_request_id_t) + dataSize + sizeof(MSG_PROXY_INFO_S);
 
        // In case of JAVA MMS msg, add trId
        if (reqmsg->subType == MSG_SENDREQ_JAVA_MMS)
@@ -118,16 +143,17 @@ msg_error_t MsgHandle::submitReq(MSG_REQUEST_S* pReq)
        memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
 
        // Copy Command Data
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &reqInfo, sizeof(MSG_REQUEST_INFO_S));
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_REQUEST_INFO_S)), &chInfo, sizeof(MSG_PROXY_INFO_S));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &reqInfo.reqId, sizeof(msg_request_id_t));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_request_id_t)), &chInfo, sizeof(MSG_PROXY_INFO_S));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_request_id_t)+sizeof(MSG_PROXY_INFO_S)), encodedData, dataSize);
 
        // In case of JAVA MMS msg, add trId
        if (reqmsg->subType == MSG_SENDREQ_JAVA_MMS)
-               memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_REQUEST_INFO_S)+sizeof(MSG_PROXY_INFO_S)), &trId, sizeof(trId));
+               memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_request_id_t)+sizeof(MSG_PROXY_INFO_S)+dataSize), &trId, sizeof(trId));
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -140,7 +166,7 @@ msg_error_t MsgHandle::submitReq(MSG_REQUEST_S* pReq)
 
        if (pEvent->eventType != MSG_EVENT_SUBMIT_REQ)
        {
-               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+               THROW(MsgException::INVALID_RESULT, "Event Data Error:%d", pEvent->eventType);
        }
 
        MSG_END();
@@ -149,44 +175,6 @@ msg_error_t MsgHandle::submitReq(MSG_REQUEST_S* pReq)
 }
 
 
-msg_error_t MsgHandle::cancelReq(msg_request_id_t reqId)
-{
-       // Allocate Memory to Command Data
-       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_request_id_t);
-
-       char cmdBuf[cmdSize];
-       bzero(cmdBuf, cmdSize);
-
-       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
-
-       // Set Command Parameters
-       pCmd->cmdType = MSG_CMD_CANCEL_REQ;
-
-       // Copy Cookie
-       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
-
-       // Copy Command Data
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &reqId, sizeof(msg_request_id_t));
-
-       // Send Command to Messaging FW
-       char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
-
-
-       write((char*)pCmd, cmdSize, &pEventData);
-
-       // Get Return Data
-       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
-
-       if (pEvent->eventType != MSG_EVENT_CANCEL_REQ)
-       {
-               THROW(MsgException::INVALID_RESULT, "Event Data Error");
-       }
-
-       return pEvent->result;
-}
-
-
 msg_error_t MsgHandle::regSentStatusCallback(msg_sent_status_cb onStatusChanged, void *pUserParam)
 {
        if (!onStatusChanged)
@@ -194,10 +182,15 @@ msg_error_t MsgHandle::regSentStatusCallback(msg_sent_status_cb onStatusChanged,
 
        MsgProxyListener* eventListener = MsgProxyListener::instance();
 
-       eventListener->start();
+       eventListener->start(this);
 
-       if (eventListener->regSentStatusEventCB(this, onStatusChanged, pUserParam) == false) // callback was already registered, just return SUCCESS
-               return MSG_SUCCESS;
+       int remoteFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+
+       if(remoteFd == -1 )
+               return MSG_ERR_INVALID_MSGHANDLE;
+
+       if (eventListener->regSentStatusEventCB(this, onStatusChanged, pUserParam) == false)
+               return MSG_ERR_INVALID_PARAMETER;
 
        // Allocate Memory to Command Data
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(int); // cmd type, listenerFd
@@ -211,17 +204,15 @@ msg_error_t MsgHandle::regSentStatusCallback(msg_sent_status_cb onStatusChanged,
        // Copy Cookie
        memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
 
-       int listenerFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
-
-       MSG_DEBUG("remote fd %d", listenerFd);
+       MSG_DEBUG("remote fd %d", remoteFd);
 
-       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &listenerFd, sizeof(listenerFd));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &remoteFd, sizeof(remoteFd));
 
-       MSG_DEBUG("reg status [%d : %s], %d", pCmd->cmdType, MsgDbgCmdStr(pCmd->cmdType), listenerFd);
+       MSG_DEBUG("reg status [%d : %s], %d", pCmd->cmdType, MsgDbgCmdStr(pCmd->cmdType), remoteFd);
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -244,10 +235,15 @@ msg_error_t MsgHandle::regSmsMessageCallback(msg_sms_incoming_cb onMsgIncoming,
 
        MsgProxyListener* eventListener = MsgProxyListener::instance();
 
-       eventListener->start();
+       eventListener->start(this);
 
-       if (eventListener->regMessageIncomingEventCB(this, onMsgIncoming, port, pUserParam) == false) // callback was already registered, just return SUCCESS
-               return MSG_SUCCESS;
+       int remoteFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+
+       if(remoteFd == -1 )
+               return MSG_ERR_INVALID_MSGHANDLE;
+
+       if (eventListener->regMessageIncomingEventCB(this, onMsgIncoming, port, pUserParam) == false)
+               return MSG_ERR_INVALID_PARAMETER;
 
        // Allocate Memory to Command Data
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_CMD_REG_INCOMING_MSG_CB_S); //sizeof(int) + sizeof; // cmd type, listener fd
@@ -265,7 +261,7 @@ msg_error_t MsgHandle::regSmsMessageCallback(msg_sms_incoming_cb onMsgIncoming,
 
        MSG_CMD_REG_INCOMING_MSG_CB_S cmdParam = {0};
 
-       cmdParam.listenerFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+       cmdParam.listenerFd = remoteFd;
        cmdParam.msgType = MSG_SMS_TYPE;
        cmdParam.port = port;
 
@@ -275,7 +271,7 @@ msg_error_t MsgHandle::regSmsMessageCallback(msg_sms_incoming_cb onMsgIncoming,
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
 
        write((char*)pCmd, cmdSize, &pEventData);
@@ -299,10 +295,15 @@ msg_error_t MsgHandle::regMmsConfMessageCallback(msg_mms_conf_msg_incoming_cb on
 
        MsgProxyListener* eventListener = MsgProxyListener::instance();
 
-       eventListener->start();
+       eventListener->start(this);
 
-       if (eventListener->regMMSConfMessageIncomingEventCB(this, onMMSConfMsgIncoming, pAppId, pUserParam) == false) // callback was already registered, just return SUCCESS
-               return MSG_SUCCESS;
+       int remoteFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+
+       if(remoteFd == -1 )
+               return MSG_ERR_INVALID_MSGHANDLE;
+
+       if (eventListener->regMMSConfMessageIncomingEventCB(this, onMMSConfMsgIncoming, pAppId, pUserParam) == false)
+               return MSG_ERR_INVALID_PARAMETER;
 
        // Allocate Memory to Command Data
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB_S);
@@ -320,7 +321,7 @@ msg_error_t MsgHandle::regMmsConfMessageCallback(msg_mms_conf_msg_incoming_cb on
 
        MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB_S cmdParam = {0};
 
-       cmdParam.listenerFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+       cmdParam.listenerFd = remoteFd;
        cmdParam.msgType = MSG_MMS_TYPE;
 
        if (pAppId)
@@ -332,7 +333,7 @@ msg_error_t MsgHandle::regMmsConfMessageCallback(msg_mms_conf_msg_incoming_cb on
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
 
        write((char*)pCmd, cmdSize, &pEventData);
@@ -356,10 +357,15 @@ msg_error_t MsgHandle::regSyncMLMessageCallback(msg_syncml_msg_incoming_cb onSyn
 
        MsgProxyListener* eventListener = MsgProxyListener::instance();
 
-       eventListener->start();
+       eventListener->start(this);
 
-       if (eventListener->regSyncMLMessageIncomingEventCB(this, onSyncMLMsgIncoming, pUserParam) == false) // callback was already registered, just return SUCCESS
-               return MSG_SUCCESS;
+       int remoteFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+
+       if(remoteFd == -1 )
+               return MSG_ERR_INVALID_MSGHANDLE;
+
+       if (eventListener->regSyncMLMessageIncomingEventCB(this, onSyncMLMsgIncoming, pUserParam) == false)
+               return MSG_ERR_INVALID_PARAMETER;
 
        // Allocate Memory to Command Data
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_CMD_REG_INCOMING_SYNCML_MSG_CB_S); //sizeof(int) + sizeof; // cmd type, listener fd
@@ -377,7 +383,7 @@ msg_error_t MsgHandle::regSyncMLMessageCallback(msg_syncml_msg_incoming_cb onSyn
 
        MSG_CMD_REG_INCOMING_SYNCML_MSG_CB_S cmdParam = {0};
 
-       cmdParam.listenerFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+       cmdParam.listenerFd = remoteFd;
        cmdParam.msgType = MSG_SMS_TYPE;
 
        memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &cmdParam, sizeof(cmdParam));
@@ -386,7 +392,7 @@ msg_error_t MsgHandle::regSyncMLMessageCallback(msg_syncml_msg_incoming_cb onSyn
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
        write((char*)pCmd, cmdSize, &pEventData);
 
@@ -409,10 +415,15 @@ msg_error_t MsgHandle::regLBSMessageCallback(msg_lbs_msg_incoming_cb onLBSMsgInc
 
        MsgProxyListener* eventListener = MsgProxyListener::instance();
 
-       eventListener->start();
+       eventListener->start(this);
 
-       if (eventListener->regLBSMessageIncomingEventCB(this, onLBSMsgIncoming, pUserParam) == false) // callback was already registered, just return SUCCESS
-               return MSG_SUCCESS;
+       int remoteFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+
+       if(remoteFd == -1 )
+               return MSG_ERR_INVALID_MSGHANDLE;
+
+       if (eventListener->regLBSMessageIncomingEventCB(this, onLBSMsgIncoming, pUserParam) == false)
+               return MSG_ERR_INVALID_PARAMETER;
 
        // Allocate Memory to Command Data
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_CMD_REG_INCOMING_LBS_MSG_CB_S); //sizeof(int) + sizeof; // cmd type, listener fd
@@ -428,7 +439,7 @@ msg_error_t MsgHandle::regLBSMessageCallback(msg_lbs_msg_incoming_cb onLBSMsgInc
 
        MSG_CMD_REG_INCOMING_LBS_MSG_CB_S cmdParam = {0};
 
-       cmdParam.listenerFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+       cmdParam.listenerFd = remoteFd;
        cmdParam.msgType = MSG_SMS_TYPE;
 
        memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &cmdParam, sizeof(cmdParam));
@@ -437,7 +448,7 @@ msg_error_t MsgHandle::regLBSMessageCallback(msg_lbs_msg_incoming_cb onLBSMsgInc
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
 
        write((char*)pCmd, cmdSize, &pEventData);
@@ -461,10 +472,15 @@ msg_error_t MsgHandle::regSyncMLMessageOperationCallback(msg_syncml_msg_operatio
 
        MsgProxyListener* eventListener = MsgProxyListener::instance();
 
-       eventListener->start();
+       eventListener->start(this);
 
-       if (eventListener->regSyncMLMessageOperationEventCB(this, onSyncMLMsgOperation, pUserParam) == false) // callback was already registered, just return SUCCESS
-               return MSG_SUCCESS;
+       int remoteFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+
+       if(remoteFd == -1 )
+               return MSG_ERR_INVALID_MSGHANDLE;
+
+       if (eventListener->regSyncMLMessageOperationEventCB(this, onSyncMLMsgOperation, pUserParam) == false)
+               return MSG_ERR_INVALID_PARAMETER;
 
        // Allocate Memory to Command Data
        int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_CMD_REG_SYNCML_MSG_OPERATION_CB_S); //sizeof(int) + sizeof; // cmd type, listener fd
@@ -482,7 +498,7 @@ msg_error_t MsgHandle::regSyncMLMessageOperationCallback(msg_syncml_msg_operatio
 
        MSG_CMD_REG_SYNCML_MSG_OPERATION_CB_S cmdParam = {0};
 
-       cmdParam.listenerFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+       cmdParam.listenerFd = remoteFd;
        cmdParam.msgType = MSG_SMS_TYPE;
 
        memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &cmdParam, sizeof(cmdParam));
@@ -491,7 +507,7 @@ msg_error_t MsgHandle::regSyncMLMessageOperationCallback(msg_syncml_msg_operatio
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
 
        write((char*)pCmd, cmdSize, &pEventData);
@@ -507,6 +523,179 @@ msg_error_t MsgHandle::regSyncMLMessageOperationCallback(msg_syncml_msg_operatio
        return pEvent->result;
 }
 
+msg_error_t MsgHandle::regPushMessageCallback(msg_push_msg_incoming_cb onPushMsgIncoming, const char *pAppId, void *pUserParam)
+{
+       if( (!onPushMsgIncoming) )
+               THROW(MsgException::INVALID_PARAM, "Param %p", onPushMsgIncoming);
+
+       MsgProxyListener* eventListener = MsgProxyListener::instance();
+
+       eventListener->start(this);
+
+       int remoteFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+
+       if(remoteFd == -1 )
+               return MSG_ERR_INVALID_MSGHANDLE;
+
+       if (eventListener->regPushMessageIncomingEventCB(this, onPushMsgIncoming, pAppId, pUserParam) == false)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_CMD_REG_INCOMING_PUSH_MSG_CB_S);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_REG_INCOMING_PUSH_MSG_CB;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       MSG_CMD_REG_INCOMING_PUSH_MSG_CB_S cmdParam = {0};
+
+       cmdParam.listenerFd = remoteFd;
+       cmdParam.msgType = MSG_SMS_TYPE;
+
+       if (pAppId)
+               strncpy(cmdParam.appId, pAppId, MAX_WAPPUSH_ID_LEN);
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &cmdParam, sizeof(cmdParam));
+
+       MSG_DEBUG("reg new msg [%s], fd:%d, appId:%s", MsgDbgCmdStr(pCmd->cmdType), cmdParam.listenerFd,  (pAppId)? cmdParam.appId:"NULL" );
+
+       // Send Command to Messaging FW
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_REG_INCOMING_PUSH_MSG_CB)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::regCBMessageCallback(msg_cb_incoming_cb onCBIncoming, bool bSave, void *pUserParam)
+{
+       if( (!onCBIncoming) )
+               THROW(MsgException::INVALID_PARAM, "Param %p", onCBIncoming);
+
+       MsgProxyListener* eventListener = MsgProxyListener::instance();
+
+       eventListener->start(this);
+
+       int remoteFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+
+       if(remoteFd == -1 )
+               return MSG_ERR_INVALID_MSGHANDLE;
+
+       if (eventListener->regCBMessageIncomingEventCB(this, onCBIncoming, bSave, pUserParam) == false)
+               return MSG_SUCCESS;
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_CMD_REG_INCOMING_CB_MSG_CB_S); //sizeof(int) + sizeof; // cmd type, listener fd
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_REG_INCOMING_CB_MSG_CB;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       MSG_CMD_REG_CB_INCOMING_MSG_CB_S cmdParam = {0};
+
+       cmdParam.listenerFd = remoteFd;
+       cmdParam.msgType = MSG_SMS_TYPE;
+       cmdParam.bsave = bSave;
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &cmdParam, sizeof(cmdParam));
+
+       MSG_DEBUG("reg new msg [%s], fd: %d, bSave: %d", MsgDbgCmdStr(pCmd->cmdType), cmdParam.listenerFd, cmdParam.bsave);
+
+       // Send Command to Messaging FW
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_REG_INCOMING_CB_MSG_CB)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::regReportMessageCallback(msg_report_msg_incoming_cb onReportMsgCB, void *pUserParam)
+{
+       if (!onReportMsgCB)
+               THROW(MsgException::INVALID_PARAM, "onReportMsgCB is null");
+
+       MsgProxyListener* eventListener = MsgProxyListener::instance();
+
+       eventListener->start(this);
+
+       int remoteFd = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+
+       if(remoteFd == -1 )
+               return MSG_ERR_INVALID_MSGHANDLE;
+
+       if (eventListener->regReportMsgIncomingCB(this, onReportMsgCB, pUserParam) == false)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(int); // cmd type, listenerFd
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_REG_REPORT_MSG_INCOMING_CB;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       MSG_DEBUG("remote fd %d", remoteFd);
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &remoteFd, sizeof(remoteFd));
+
+       MSG_DEBUG("reg status [%d : %s], %d", pCmd->cmdType, MsgDbgCmdStr(pCmd->cmdType), remoteFd);
+
+       // Send Command to Messaging FW
+       char* pEventData = NULL;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_REG_REPORT_MSG_INCOMING_CB)
+       {
+               THROW(MsgException::INVALID_PARAM, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
 
 msg_error_t MsgHandle::operateSyncMLMessage(msg_message_id_t msgId)
 {
@@ -531,7 +720,7 @@ msg_error_t MsgHandle::operateSyncMLMessage(msg_message_id_t msgId)
 
        // Send Command to Messaging FW
        char* pEventData = NULL;
-       AutoPtr<char> eventBuf(&pEventData);
+       unique_ptr<char*, void(*)(char**)> eventBuf(&pEventData, unique_ptr_deleter);
 
 
        write((char*)pCmd, cmdSize, &pEventData);
index 1bf4a38..168663b 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <errno.h>
 #include "MsgDebug.h"
 #include "MsgCppTypes.h"
 #include "MsgException.h"
+#include "MsgUtilFunction.h"
 #include "MsgUtilFile.h"
 #include "MsgProxyListener.h"
+#include "MsgGconfWrapper.h"
 
+void MsgServerRestartCb(keynode_t *key, void* data)
+{
+       bool bReady = false;
+       MSG_DEBUG("Message Service Running State Changed");
+       // server is currently booting and service is not available until the end of booting
+       MsgSettingGetBool(VCONFKEY_MSG_SERVER_READY, &bReady);
+       MSG_INFO("Message Service Running State Changed bReady:(%d)", bReady);
+
+       //bReady false indicates that server has restarted. Hence the proxylistener needs to be reset
+       if (bReady == false) {
+               MSG_DEBUG("Message Service Is Restarted. Resetting ProxyListener");
+               MsgProxyListener::instance()->resetProxyListener();
+       }
+}
 
 gboolean readSocket(GIOChannel *source, GIOCondition condition, gpointer data)
 {
        MSG_BEGIN();
+#if 0
+       if ((G_IO_ERR & condition) || (G_IO_HUP & condition) || (G_IO_NVAL & condition))
+       {
+               MSG_DEBUG("IO condition Error!!! [%d]", condition);
 
+               MsgProxyListener::instance()->stop();
+               return FALSE;
+       }
+#endif
        if (G_IO_ERR & condition)
        {
-               MSG_DEBUG("IO Error!!! [%d]", condition);
+               MSG_ERR("IO Error!!! [%d]", condition);
 
                MsgProxyListener::instance()->stop();
                return FALSE;
@@ -37,7 +61,7 @@ gboolean readSocket(GIOChannel *source, GIOCondition condition, gpointer data)
 
        if (G_IO_HUP & condition)
        {
-               MSG_DEBUG("socket fd Error!!! [%d]", condition);
+               MSG_ERR("socket fd Error!!! [%d]", condition);
 
                MsgProxyListener::instance()->stop();
                return FALSE;
@@ -45,14 +69,15 @@ gboolean readSocket(GIOChannel *source, GIOCondition condition, gpointer data)
 
        if (G_IO_NVAL & condition)
        {
-               MSG_DEBUG("Invaild socket Error!!! [%d]", condition);
+               MSG_ERR("Invaild socket Error!!! [%d]", condition);
 
                MsgProxyListener::instance()->stop();
                return FALSE;
        }
 
        char* buf = NULL;
-       int len;
+       unique_ptr<char*, void(*)(char**)> eventBuf(&buf, unique_ptr_deleter);
+       unsigned int len = 0;
 
        int n = MsgProxyListener::instance()->readFromSocket(&buf, &len);
 
@@ -63,7 +88,7 @@ gboolean readSocket(GIOChannel *source, GIOCondition condition, gpointer data)
        }
        else if (n == 0)
        {
-               MSG_DEBUG("Server closed connection");
+               MSG_WARN("Server closed connection");
                MsgProxyListener::instance()->stop();
                return FALSE;
        }
@@ -72,12 +97,6 @@ gboolean readSocket(GIOChannel *source, GIOCondition condition, gpointer data)
                MSG_DEBUG("Data is not for Listener");
        }
 
-       if (buf)
-       {
-               delete [] buf;
-               buf = NULL;
-       }
-
        MSG_END();
 
        return TRUE;
@@ -97,6 +116,11 @@ MsgProxyListener::MsgProxyListener() : running(0)
        newMMSConfMessageCBList.clear();
        newSyncMLMessageCBList.clear();
        newLBSMessageCBList.clear();
+       openHandleSet.clear();
+       MsgSettingRegVconfCBCommon(VCONFKEY_MSG_SERVER_READY, MsgServerRestartCb);
+
+       channel = NULL;
+       eventSourceId = 0;
 }
 
 
@@ -107,6 +131,8 @@ MsgProxyListener::~MsgProxyListener()
        newMMSConfMessageCBList.clear();
        newSyncMLMessageCBList.clear();
        newLBSMessageCBList.clear();
+       openHandleSet.clear();
+       MsgSettingRemoveVconfCBCommon(VCONFKEY_MSG_SERVER_READY, MsgServerRestartCb);
 }
 
 
@@ -115,21 +141,25 @@ MsgProxyListener* MsgProxyListener::instance()
        static Mutex mm;
        MutexLocker lock(mm);
 
-       if (!pInstance)
+       if (!pInstance) {
                pInstance = new MsgProxyListener();
+       }
 
        return pInstance;
 }
 
 
-void MsgProxyListener::start()
+void MsgProxyListener::start(MsgHandle* pMsgHandle)
 {
+       MutexLocker lock(mx);
+
+       handle_set::iterator it = openHandleSet.find(pMsgHandle);
+       if (it == openHandleSet.end())
+               openHandleSet.insert(pMsgHandle);
        if (running == 0)
        {
-               mx.lock();
                cliSock.connect(MSG_SOCKET_PATH);
                cv.signal(); // wake up the waiting thread
-               mx.unlock();
 
                int fd = cliSock.fd();
 
@@ -158,8 +188,6 @@ void MsgProxyListener::stop()
        }
        else if (running == 1)
        {
-               MutexLocker lock(mx);
-
                running--;
 
                g_io_channel_unref(channel); // decrements ref_count = 1
@@ -183,12 +211,8 @@ bool MsgProxyListener::regSentStatusEventCB(MsgHandle* pMsgHandle, msg_sent_stat
 
        for (; it != sentStatusCBList.end(); it++)
        {
-               if (it->hAddr == pMsgHandle && it->pfSentStatusCB == pfSentStatus)
-               {
+               if (it->hAddr == pMsgHandle && it->pfSentStatusCB == pfSentStatus) {
                        MSG_DEBUG("msg_sent_status_cb() callback : [%p] is already registered!!!", pfSentStatus);
-
-                       it->userParam = pUserParam;
-
                        return false;
                }
        }
@@ -209,12 +233,8 @@ bool MsgProxyListener::regMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_sms_
 
        for (; it != newMessageCBList.end(); it++)
        {
-               if (it->port == port && it->pfIncomingCB == pfNewMessage)
-               {
+               if (it->hAddr == pMsgHandle && it->port == port && it->pfIncomingCB == pfNewMessage) {
                        MSG_DEBUG("msg_sms_incoming_cb() callback : Port Number [%d] is already registered!!!", port);
-
-                       it->userParam = pUserParam;
-
                        return false;
                }
        }
@@ -235,21 +255,13 @@ bool MsgProxyListener::regMMSConfMessageIncomingEventCB(MsgHandle* pMsgHandle, m
 
        for (; it != newMMSConfMessageCBList.end(); it++)
        {
-               if (it->pfMMSConfIncomingCB == pfNewMMSConfMessage)
-               {
+               if (it->hAddr == pMsgHandle && it->pfMMSConfIncomingCB == pfNewMMSConfMessage) {
 
-                       if(pAppId == NULL)
-                       {
+                       if(pAppId == NULL) {
                                MSG_DEBUG("msg_mms_conf_msg_incoming_cb() callback is already registered!!!");
-
                                return false;
-                       }
-                       else if(!strncmp(it->appId, pAppId, MAX_MMS_JAVA_APPID_LEN))
-                       {
+                       } else if(!strncmp(it->appId, pAppId, MAX_MMS_JAVA_APPID_LEN)) {
                                MSG_DEBUG("msg_mms_conf_msg_incoming_cb() callback : AppId [%s] is already registered!!!", pAppId);
-
-                               it->userParam = pUserParam;
-
                                return false;
                        }
                }
@@ -266,6 +278,83 @@ bool MsgProxyListener::regMMSConfMessageIncomingEventCB(MsgHandle* pMsgHandle, m
 }
 
 
+bool MsgProxyListener::regPushMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_push_msg_incoming_cb pfNewPushMessage, const char *pAppId, void *pUserParam)
+{
+       MutexLocker lock(mx);
+
+       std::list<MSG_PUSH_INCOMING_CB_ITEM_S>::iterator it = newPushMessageCBList.begin();
+
+       for (; it != newPushMessageCBList.end(); it++)
+       {
+               if (it->hAddr == pMsgHandle && it->pfPushIncomingCB == pfNewPushMessage) {
+
+                       if(pAppId == NULL) {
+                               MSG_DEBUG("msg_push_msg_incoming_cb() callback is already registered!!!");
+                               return false;
+                       } else if(!strncmp(it->appId, pAppId, MAX_WAPPUSH_ID_LEN)) {
+                               MSG_DEBUG("msg_push_msg_incoming_cb() callback : AppId [%s] is already registered!!!", pAppId);
+                               return false;
+                       }
+               }
+       }
+
+       MSG_PUSH_INCOMING_CB_ITEM_S incomingPushCB = {pMsgHandle, pfNewPushMessage, {0}, pUserParam};
+
+       if (pAppId != NULL)
+               strncpy(incomingPushCB.appId, pAppId, MAX_WAPPUSH_ID_LEN);
+
+       newPushMessageCBList.push_back(incomingPushCB);
+
+       return true;
+}
+
+bool MsgProxyListener::regCBMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_cb_incoming_cb pfNewCBMessage, bool bSave, void *pUserParam)
+{
+       MutexLocker lock(mx);
+
+       std::list<MSG_CB_INCOMING_CB_ITEM_S>::iterator it = newCBMessageCBList.begin();
+
+       for (; it != newCBMessageCBList.end(); it++)
+       {
+               if (it->hAddr == pMsgHandle && it->pfCBIncomingCB == pfNewCBMessage) {
+                       MSG_DEBUG("msg_CB_incoming_cb() callback : [%p] is already registered!!!", pfNewCBMessage);
+                        it->bsave = bSave;
+                        it->userParam = pUserParam;
+                       return false;
+               }
+       }
+
+       MSG_CB_INCOMING_CB_ITEM_S incomingCB = {pMsgHandle, pfNewCBMessage, bSave, pUserParam};
+
+       newCBMessageCBList.push_back(incomingCB);
+
+       return true;
+}
+
+
+bool MsgProxyListener::regReportMsgIncomingCB(MsgHandle* pMsgHandle, msg_report_msg_incoming_cb pfReportMessage, void *pUserParam)
+{
+       MutexLocker lock(mx);
+
+       std::list<MSG_REPORT_INCOMING_CB_ITEM_S>::iterator it = reportMessageCBList.begin();
+
+       for (; it != reportMessageCBList.end(); it++)
+       {
+               if (it->hAddr == pMsgHandle && it->pfReportMsgIncomingCB == pfReportMessage) {
+                       MSG_DEBUG("msg_report_msg_incoming_cb() callback : [%p] is already registered!!!", pfReportMessage);
+                        it->userParam = pUserParam;
+                       return false;
+               }
+       }
+
+       MSG_REPORT_INCOMING_CB_ITEM_S incomingCB = {pMsgHandle, pfReportMessage, pUserParam};
+
+       reportMessageCBList.push_back(incomingCB);
+
+       return true;
+}
+
+
 bool MsgProxyListener::regSyncMLMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_syncml_msg_incoming_cb pfNewSyncMLMessage, void *pUserParam)
 {
        MutexLocker lock(mx);
@@ -274,12 +363,8 @@ bool MsgProxyListener::regSyncMLMessageIncomingEventCB(MsgHandle* pMsgHandle, ms
 
        for (; it != newSyncMLMessageCBList.end(); it++)
        {
-               if (it->pfSyncMLIncomingCB == pfNewSyncMLMessage)
-               {
+               if (it->hAddr == pMsgHandle && it->pfSyncMLIncomingCB == pfNewSyncMLMessage) {
                        MSG_DEBUG("msg_syncml_msg_incoming_cb() callback : [%p] is already registered!!!", pfNewSyncMLMessage);
-
-                       it->userParam = pUserParam;
-
                        return false;
                }
        }
@@ -300,12 +385,8 @@ bool MsgProxyListener::regLBSMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_l
 
        for (; it != newLBSMessageCBList.end(); it++)
        {
-               if (it->pfLBSMsgIncoming == pfNewLBSMsgIncoming)
-               {
+               if (it->hAddr == pMsgHandle && it->pfLBSMsgIncoming == pfNewLBSMsgIncoming) {
                        MSG_DEBUG("msg_lbs_msg_incoming_cb() callback : [%p] is already registered!!!", pfNewLBSMsgIncoming);
-
-                       it->userParam = pUserParam;
-
                        return false;
                }
        }
@@ -326,12 +407,8 @@ bool MsgProxyListener::regSyncMLMessageOperationEventCB(MsgHandle* pMsgHandle, m
 
        for (; it != operationSyncMLMessageCBList.end(); it++)
        {
-               if (it->pfSyncMLOperationCB == pfSyncMLMessageOperation)
-               {
+               if (it->hAddr == pMsgHandle && it->pfSyncMLOperationCB == pfSyncMLMessageOperation) {
                        MSG_DEBUG("msg_syncml_msg_incoming_cb() callback : [%p] is already registered!!!", pfSyncMLMessageOperation);
-
-                       it->userParam = pUserParam;
-
                        return false;
                }
        }
@@ -352,12 +429,8 @@ bool MsgProxyListener::regStorageChangeEventCB(MsgHandle* pMsgHandle, msg_storag
 
        for (; it != storageChangeCBList.end(); it++)
        {
-               if (it->pfStorageChangeCB == pfStorageChangeOperation)
-               {
+               if (it->hAddr == pMsgHandle && it->pfStorageChangeCB == pfStorageChangeOperation) {
                        MSG_DEBUG("msg_storage_change_cb() callback : [%p] is already registered!!!", pfStorageChangeOperation);
-
-                       it->userParam = pUserParam;
-
                        return false;
                }
        }
@@ -374,96 +447,158 @@ void MsgProxyListener::clearListOfClosedHandle(MsgHandle* pMsgHandle)
 {
        MSG_BEGIN();
 
+       MutexLocker lock(mx);
+
        // sent status CB list
        std::list<MSG_SENT_STATUS_CB_ITEM_S>::iterator it = sentStatusCBList.begin();
 
-       for (; it != sentStatusCBList.end(); it++)
+       for (; it != sentStatusCBList.end(); )
        {
                if (it->hAddr == pMsgHandle)
                {
-                       sentStatusCBList.erase(it);
-                       it = sentStatusCBList.begin();
+                       sentStatusCBList.erase(it++);
 
                        //Stop client Listener
                        stop();
                }
+               else
+                       ++it;
        }
 
        // new message CB list
        std::list<MSG_INCOMING_CB_ITEM_S>::iterator it2 = newMessageCBList.begin();
 
-       for (; it2 != newMessageCBList.end(); it2++)
+       for (; it2 != newMessageCBList.end(); )
        {
                if (it2->hAddr == pMsgHandle)
                {
-                       newMessageCBList.erase(it2);
-                       it2 = newMessageCBList.begin();
+                       newMessageCBList.erase(it2++);
 
                        //Stop client Listener
                        stop();
                }
+               else
+                       ++it2;
        }
 
        // MMS conf Message CB list
        std::list<MSG_MMS_CONF_INCOMING_CB_ITEM_S>::iterator it3 = newMMSConfMessageCBList.begin();
 
-       for (; it3 != newMMSConfMessageCBList.end(); it3++)
+       for (; it3 != newMMSConfMessageCBList.end(); )
        {
                if (it3->hAddr == pMsgHandle)
                {
-                       newMMSConfMessageCBList.erase(it3);
-                       it3 = newMMSConfMessageCBList.begin();
+                       newMMSConfMessageCBList.erase(it3++);
 
                        //Stop client Listener
                        stop();
                }
+               else
+                       ++it3;
        }
 
        // SyncML Message CB list
        std::list<MSG_SYNCML_INCOMING_CB_ITEM_S>::iterator it4 = newSyncMLMessageCBList.begin();
 
-       for (; it4 != newSyncMLMessageCBList.end(); it4++)
+       for (; it4 != newSyncMLMessageCBList.end(); )
        {
                if (it4->hAddr == pMsgHandle)
                {
-                       newSyncMLMessageCBList.erase(it4);
-                       it4 = newSyncMLMessageCBList.begin();
+                       newSyncMLMessageCBList.erase(it4++);
 
                        //Stop client Listener
                        stop();
                }
+               else
+                       ++it4;
        }
 
        // LBS Message CB list
        std::list<MSG_LBS_INCOMING_CB_ITEM_S>::iterator it5 = newLBSMessageCBList.begin();
 
-       for (; it5 != newLBSMessageCBList.end(); it5++)
+       for (; it5 != newLBSMessageCBList.end(); )
        {
                if (it5->hAddr == pMsgHandle)
                {
-                       newLBSMessageCBList.erase(it5);
-                       it5 = newLBSMessageCBList.begin();
+                       newLBSMessageCBList.erase(it5++);
 
                        //Stop client Listener
                        stop();
                }
+               else
+                       ++it5;
        }
 
-       // Storage change Message CB list
-       std::list<MSG_STORAGE_CHANGE_CB_ITEM_S>::iterator it6 = storageChangeCBList.begin();
+       // Push Message CB list
+       std::list<MSG_PUSH_INCOMING_CB_ITEM_S>::iterator it6 = newPushMessageCBList.begin();
 
-       for (; it6 != storageChangeCBList.end(); it6++)
+       for (; it6 != newPushMessageCBList.end(); )
        {
                if (it6->hAddr == pMsgHandle)
                {
-                       storageChangeCBList.erase(it6);
-                       it6 = storageChangeCBList.begin();
+                       newPushMessageCBList.erase(it6++);
+
+                       //Stop client Listener
+                       stop();
+               }
+               else
+                       ++it6;
+
+       }
+
+       // CB Message CB list
+       std::list<MSG_CB_INCOMING_CB_ITEM_S>::iterator it7 = newCBMessageCBList.begin();
+
+       for (; it7 != newCBMessageCBList.end(); )
+       {
+
+               if (it7->hAddr == pMsgHandle)
+               {
+
+                       newCBMessageCBList.erase(it7++);
+
+                       //Stop client Listener
+                       stop();
+               }
+               else
+               {
+                       ++it7;
+               }
+       }
+
+       // Storage change Message CB list
+       std::list<MSG_STORAGE_CHANGE_CB_ITEM_S>::iterator it8 = storageChangeCBList.begin();
+
+       for (; it8 != storageChangeCBList.end(); )
+       {
+               if (it8->hAddr == pMsgHandle)
+               {
+                       storageChangeCBList.erase(it8++);
 
                        //Stop client Listener
                        stop();
                }
+               else
+                       ++it8;
        }
 
+
+       // Report message incoming CB list
+       std::list<MSG_REPORT_INCOMING_CB_ITEM_S>::iterator it9 = reportMessageCBList.begin();
+       for (; it9 != reportMessageCBList.end(); )
+       {
+               if (it9->hAddr == pMsgHandle)
+               {
+                       reportMessageCBList.erase(it9++);
+
+                       //Stop client Listener
+                       stop();
+               }
+               else
+                       ++it9;
+       }
+
+
        MSG_END();
 }
 
@@ -505,8 +640,15 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
        }
        else if ( pMsgEvent->eventType == MSG_EVENT_PLG_INCOMING_MSG_IND )
        {
-               MSG_MESSAGE_INFO_S *pMsgInfo = (MSG_MESSAGE_INFO_S *)pMsgEvent->data;
-               int portKey = (pMsgInfo->msgPort.valid)? pMsgInfo->msgPort.dstPort: 0;
+               MSG_MESSAGE_INFO_S msgInfo;
+               memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+               msgInfo.addressList = NULL;
+               unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+               MsgDecodeMsgInfo((char *)pMsgEvent->data, &msgInfo);
+
+               int portKey = (msgInfo.msgPort.valid)? msgInfo.msgPort.dstPort: 0;
 
                mx.lock();
 
@@ -529,7 +671,6 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
                {
                        MsgHandle* pHandle = it->hAddr;
 
-                       MSG_MESSAGE_INFO_S *pMsgInfo = (MSG_MESSAGE_INFO_S *)pMsgEvent->data;
                        MSG_MESSAGE_HIDDEN_S msgHidden = {0,};
 
                        msgHidden.pData = NULL;
@@ -539,12 +680,12 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
                        msg_struct_list_s *addr_list = (msg_struct_list_s *)new msg_struct_list_s;
 
                        addr_list->nCount = 0;
-                       addr_list->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_ADDRESS_INFO_S *)*MAX_TO_ADDRESS_CNT];
+                       addr_list->msg_struct_info = (msg_struct_t *)calloc(MAX_TO_ADDRESS_CNT, sizeof(MSG_ADDRESS_INFO_S *));
 
                        msg_struct_s *pTmp = NULL;
 
                        for (int i = 0; i < MAX_TO_ADDRESS_CNT; i++) {
-                               addr_list->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];
+                               addr_list->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
                                pTmp = (msg_struct_s *)addr_list->msg_struct_info[i];
                                pTmp->type = MSG_STRUCT_ADDRESS_INFO;
                                pTmp->data = new MSG_ADDRESS_INFO_S;
@@ -555,7 +696,12 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
 
                        msgHidden.addr_list = addr_list;
 
-                       pHandle->convertMsgStruct(pMsgInfo, &msgHidden);
+                       try {
+                               pHandle->convertMsgStruct(&msgInfo, &msgHidden);
+                       }
+                       catch (MsgException& e) {
+                               MSG_FATAL("%s", e.what());
+                       }
 
                        msg_struct_s msg = {0,};
                        msg.type = MSG_STRUCT_MESSAGE_INFO;
@@ -582,7 +728,7 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
                                        msgHidden.addr_list->msg_struct_info[i] = NULL;
                                }
 
-                               delete [] msgHidden.addr_list->msg_struct_info;
+                               g_free(msgHidden.addr_list->msg_struct_info);
 
                                delete msgHidden.addr_list;
                                msgHidden.addr_list = NULL;
@@ -593,8 +739,16 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
        }
        else if ( pMsgEvent->eventType == MSG_EVENT_PLG_INCOMING_MMS_CONF )
        {
-               MSG_MESSAGE_INFO_S *pMsgInfo = (MSG_MESSAGE_INFO_S *)pMsgEvent->data;
-               MMS_RECV_DATA_S* pMmsRecvData = ( MMS_RECV_DATA_S*)pMsgInfo->msgData;
+               MSG_MESSAGE_INFO_S msgInfo;
+               memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+               msgInfo.addressList = NULL;
+               unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> addressListBuf(&msgInfo.addressList, unique_ptr_deleter);
+
+               MsgDecodeMsgInfo((char *)pMsgEvent->data, &msgInfo);
+
+
+               MMS_RECV_DATA_S* pMmsRecvData = ( MMS_RECV_DATA_S*)msgInfo.msgData;
 
                char* appIdKey = (pMmsRecvData->msgAppId.valid)? pMmsRecvData->msgAppId.appId: NULL;
 
@@ -625,8 +779,8 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
 
                strncpy(tempFileName, pMmsRecvData->retrievedFilePath, MSG_FILENAME_LEN_MAX);
 
-               memset(pMsgInfo->msgData, 0, MAX_MSG_DATA_LEN+1);
-               memcpy(pMsgInfo->msgData, tempFileName + strlen(MSG_DATA_PATH), strlen(tempFileName));
+               memset(msgInfo.msgData, 0, MAX_MSG_DATA_LEN+1);
+               memcpy(msgInfo.msgData, tempFileName + strlen(MSG_DATA_PATH), MAX_MSG_DATA_LEN);
 
                it = matchList.begin();
 
@@ -634,7 +788,6 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
                {
                        MsgHandle* pHandle = it->hAddr;
 
-                       MSG_MESSAGE_INFO_S *pMsgInfo = (MSG_MESSAGE_INFO_S *)pMsgEvent->data;
                        MSG_MESSAGE_HIDDEN_S msgHidden = {0,};
 
                        msgHidden.pData = NULL;
@@ -644,12 +797,12 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
                        msg_struct_list_s *addr_list = (msg_struct_list_s *)new msg_struct_list_s;
 
                        addr_list->nCount = 0;
-                       addr_list->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_ADDRESS_INFO_S *)*MAX_TO_ADDRESS_CNT];
+                       addr_list->msg_struct_info = (msg_struct_t *)calloc(MAX_TO_ADDRESS_CNT, sizeof(MSG_ADDRESS_INFO_S *));
 
                        msg_struct_s *pTmp = NULL;
 
                        for (int i = 0; i < MAX_TO_ADDRESS_CNT; i++) {
-                               addr_list->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];
+                               addr_list->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
                                pTmp = (msg_struct_s *)addr_list->msg_struct_info[i];
                                pTmp->type = MSG_STRUCT_ADDRESS_INFO;
                                pTmp->data = new MSG_ADDRESS_INFO_S;
@@ -660,7 +813,12 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
 
                        msgHidden.addr_list = addr_list;
 
-                       pHandle->convertMsgStruct(pMsgInfo, &msgHidden);
+                       try {
+                               pHandle->convertMsgStruct(&msgInfo, &msgHidden);
+                       }
+                       catch (MsgException& e) {
+                               MSG_FATAL("%s", e.what());
+                       }
 
                        msg_struct_s msg = {0,};
                        msg.type = MSG_STRUCT_MESSAGE_INFO;
@@ -686,7 +844,7 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
                                        msgHidden.addr_list->msg_struct_info[i] = NULL;
                                }
 
-                               delete [] msgHidden.addr_list->msg_struct_info;
+                               g_free(msgHidden.addr_list->msg_struct_info);
 
                                delete msgHidden.addr_list;
                                msgHidden.addr_list = NULL;
@@ -697,7 +855,7 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
                        if(appIdKey)
                        {
                                MSG_DEBUG("delete received JAVA MMS message:%s from native storage",tempFileName);
-                               pHandle->deleteMessage(pMsgInfo->msgId);
+                               pHandle->deleteMessage(msgInfo.msgId);
                        }
                }
        }
@@ -719,7 +877,7 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
 
                        void* param = it->userParam;
 
-                       pfunc((msg_handle_t)pHandle, pSyncMLData->syncmlType, pSyncMLData->pushBody, pSyncMLData->pushBodyLen, pSyncMLData->wspHeader, pSyncMLData->wspHeaderLen, param);
+                       pfunc((msg_handle_t)pHandle, pSyncMLData->syncmlType, pSyncMLData->pushBody, pSyncMLData->pushBodyLen, pSyncMLData->wspHeader, pSyncMLData->wspHeaderLen, pSyncMLData->simIndex, param);
                }
 
                mx.unlock();
@@ -808,28 +966,156 @@ void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
                mx.unlock();
        }
 
+       else if (pMsgEvent->eventType == MSG_EVENT_PLG_INCOMING_CB_MSG_IND)
+       {
+               MSG_CB_MSG_S *pCbMsg = (MSG_CB_MSG_S *)pMsgEvent->data;
+
+               mx.lock();
+
+               MsgNewCBMessageCBList::iterator it = newCBMessageCBList.begin();
+
+               for( ; it != newCBMessageCBList.end() ; it++)
+               {
+                       MsgHandle* pHandle = it->hAddr;
+                       msg_struct_s msg = {0,};
+
+                       msg.type = MSG_STRUCT_CB_MSG;
+                       msg.data = pCbMsg;
+
+                       msg_cb_incoming_cb pfunc = it->pfCBIncomingCB;
+
+                       void* param = it->userParam;
+
+                       pfunc((msg_handle_t)pHandle, (msg_struct_t) &msg, param);
+               }
+
+               mx.unlock();
+       }
+
+       else if ( pMsgEvent->eventType == MSG_EVENT_PLG_INCOMING_PUSH_MSG_IND )
+       {
+               MSG_PUSH_MESSAGE_DATA_S* pPushData = (MSG_PUSH_MESSAGE_DATA_S *)pMsgEvent->data;
+
+               mx.lock();
+
+               MsgNewPushMessageCBList::iterator it = newPushMessageCBList.begin();
+
+               for( ; it != newPushMessageCBList.end() ; it++)
+               {
+                       MsgHandle* pHandle = it->hAddr;
+
+                       msg_push_msg_incoming_cb pfunc = it->pfPushIncomingCB;
+
+                       void* param = it->userParam;
+
+                       if(!strncmp(it->appId, pPushData->pushAppId, MAX_WAPPUSH_ID_LEN))
+                               pfunc((msg_handle_t)pHandle, pPushData->pushHeader, pPushData->pushBody, pPushData->pushBodyLen, param);
+               }
+
+               mx.unlock();
+       }
+
+       else if (pMsgEvent->eventType == MSG_EVENT_PLG_REPORT_MSG_INCOMING_IND)
+       {
+               msg_report_type_t reportType;
+               msg_message_id_t msgId;
+               int addr_len;
+               char *addr_val;
+
+               // Decode event data
+               memcpy(&reportType, (void*)((char*)pMsgEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)), sizeof(msg_report_type_t));
+               memcpy(&msgId, (void*)((char*)pMsgEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)+sizeof(msg_report_type_t)), sizeof(msg_message_id_t));
+               memcpy(&addr_len, (void*)((char*)pMsgEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)+sizeof(msg_report_type_t)+sizeof(msg_message_id_t)), sizeof(int));
+               addr_val = (char*)((char*)pMsgEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)+sizeof(msg_report_type_t)+sizeof(msg_message_id_t)+sizeof(int));
+               addr_val[addr_len] = '\0';
+
+               MSG_SEC_DEBUG("reportType [%d], msgId [%d], Address Length [%d], Address Value [%s]", reportType, msgId, addr_len, addr_val);
+
+               mx.lock();
+
+               MsgReportMessageCBList::iterator it = reportMessageCBList.begin();
+
+               for( ; it != reportMessageCBList.end() ; it++)
+               {
+                       MsgHandle* pHandle = it->hAddr;
+
+                       msg_report_msg_incoming_cb pfunc = it->pfReportMsgIncomingCB;
+
+                       void* param = it->userParam;
+
+                       pfunc((msg_handle_t)pHandle, reportType, msgId, addr_len, addr_val, param);
+               }
+
+               mx.unlock();
+       }
+
        MSG_END();
 }
 
 
 int  MsgProxyListener::getRemoteFd()
 {
-       MutexLocker lock(mx);
+       MSG_BEGIN();
+       //MutexLocker lock(mx);
+
+       int tmpFd = -1;
+       int ret = mx.timedlock();
+
+       if (ret != 0) {
+               MSG_DEBUG("mx.timedlock fail [%d]", ret);
+               return tmpFd;
+       }
 
-       int tmpFd = cliSock.getRemoteFd();
+       tmpFd = cliSock.getRemoteFd();
 
        MSG_DEBUG("listener fd [%d]", tmpFd);
 
-       if( tmpFd == -1 )
-       {
-               cv.wait(mx.pMutex());
+       if( tmpFd == -1 ) {
+               ret = cv.timedwait(mx.pMutex(),1);
        }
 
-       return cliSock.getRemoteFd();
+       if (ret == ETIMEDOUT) {
+               MSG_DEBUG("get listener fd TIME-OUT");
+               mx.unlock();
+               return tmpFd;
+       }
+
+       tmpFd = cliSock.getRemoteFd();
+       mx.unlock();
+
+       MSG_END();
+
+       return tmpFd;
 }
 
 
-int MsgProxyListener::readFromSocket(char** buf, int* len)
+int MsgProxyListener::readFromSocket(char** buf, unsigned int* len)
 {
        return cliSock.read(buf, len);
 }
+
+void MsgProxyListener::resetProxyListener()
+{
+       MSG_BEGIN();
+       MutexLocker lock(mx);
+       handle_set::iterator it = openHandleSet.begin();
+       for (; it != openHandleSet.end(); it++) {
+               MsgHandle *handle = (MsgHandle *)*it;
+               clearListOfClosedHandle(handle);
+       }
+       openHandleSet.clear();
+       MSG_END();
+}
+
+#ifdef CHECK_SENT_STATUS_CALLBACK
+int MsgProxyListener::getSentStatusCbCnt()
+{
+       int cbCnt = 0;
+
+       cbCnt = sentStatusCBList.size();
+
+       MSG_DEBUG("registered sent status callback count : [%d]", cbCnt);
+
+       return cbCnt;
+}
+#endif
diff --git a/sms-plugin.manifest b/sms-plugin.manifest
new file mode 100755 (executable)
index 0000000..2a0cec5
--- /dev/null
@@ -0,0 +1,5 @@
+<manifest>
+  <request>
+    <domain name="_"/>
+  </request>
+</manifest>
index ab89733..9e503d3 100755 (executable)
@@ -8,7 +8,7 @@ IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
 ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
 MESSAGE("Build type: ${CMAKE_BUILD_TYPE}")
 
-SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
+SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
 
 ##########################################################
 # Define Framework Utils
@@ -18,38 +18,41 @@ SET(UTILS-SRCS
        ${CMAKE_SOURCE_DIR}/utils/MsgDebug.cpp
        ${CMAKE_SOURCE_DIR}/utils/MsgException.cpp
        ${CMAKE_SOURCE_DIR}/utils/MsgUtilFunction.cpp
+       ${CMAKE_SOURCE_DIR}/utils/MsgTextConvert.cpp
        ${CMAKE_SOURCE_DIR}/utils/MsgIpcSocket.cpp
        ${CMAKE_SOURCE_DIR}/utils/MsgUtilFile.cpp
        ${CMAKE_SOURCE_DIR}/utils/MsgSqliteWrapper.cpp
-       ${CMAKE_SOURCE_DIR}/utils/MsgSoundPlayer.cpp
        ${CMAKE_SOURCE_DIR}/utils/MsgUtilStorage.cpp
        ${CMAKE_SOURCE_DIR}/utils/MsgGconfWrapper.cpp
        ${CMAKE_SOURCE_DIR}/utils/MsgContact.cpp
-       ${CMAKE_SOURCE_DIR}/utils/MsgNotificationWrapper.cpp
+       ${CMAKE_SOURCE_DIR}/utils/MsgVMessage.cpp
        ${CMAKE_SOURCE_DIR}/utils/MsgMemory.cpp
        ${CMAKE_SOURCE_DIR}/utils/MsgMmsMessage.cpp
-       ${CMAKE_SOURCE_DIR}/utils/MsgSpamFilter.cpp
        ${CMAKE_SOURCE_DIR}/utils/MsgDrmWrapper.cpp
+       ${CMAKE_SOURCE_DIR}/utils/MsgJsonParser.cpp
+       ${CMAKE_SOURCE_DIR}/utils/MsgSerialize.cpp
+       ${CMAKE_SOURCE_DIR}/utils/MsgSmil.cpp
 )
 
 INCLUDE_DIRECTORIES(
-    ${CMAKE_SOURCE_DIR}/include/mapi
+       ${CMAKE_SOURCE_DIR}/include/mapi
        ${CMAKE_SOURCE_DIR}/include/common
        ${CMAKE_SOURCE_DIR}/include/framework
-       ${CMAKE_SOURCE_DIR}/include/msg_helper
        ${CMAKE_SOURCE_DIR}/include/utils
+       ${CMAKE_SOURCE_DIR}/vobject-engine/include
 )
 
 INCLUDE(FindPkgConfig)
-pkg_check_modules(utils_pkgs REQUIRED glib-2.0 vconf db-util contacts-service dlog pmapi mm-session alarm-service notification drm-client)
+pkg_check_modules(utils_pkgs REQUIRED glib-2.0 vconf db-util contacts-service2 dlog libxml-2.0 storage json-glib-1.0 capi-system-info)
 
 FOREACH(flag ${utils_pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
 ENDFOREACH(flag)
 
 ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
+ADD_DEFINITIONS("-DFEATURE_JAVA_MMS")
 
-SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
 
 SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
 
index 6aecb5e..00ec0c6 100755 (executable)
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
-extern "C"
-{
-       #include <contacts-svc.h>
-}
+#include <ctype.h>
 
 #include "MsgDebug.h"
 #include "MsgUtilStorage.h"
+#include "MsgUtilFile.h"
 #include "MsgGconfWrapper.h"
 #include "MsgContact.h"
 
+extern "C"
+{
+       #include <contacts.h>
+}
 
 /*==================================================================================================
                                      VARIABLES
 ==================================================================================================*/
-static bool isContactSvcOpened = false;
+__thread bool isContactSvcConnected = false;
 
 MsgDbHandler ContactDbHandle;
 
 MsgContactChangeCB cbFunction = NULL;
+
+#define CONTACT_CALLBACK_USER_DATA                             "contact"
+#define ADDRESSBOOK_CALLBACK_USER_DATA "addressbook"
+
+// phonenumber minimum match digit.
+#define PHONENUMBER_MIN_MATCH_DIGIT VCONFKEY_CONTACTS_SVC_PHONENUMBER_MIN_MATCH_DIGIT
+#define DEFAULT_MIN_MATCH_DIGIT 8
+
+static int phonenumberMinMatchDigit = -1;
+
 /*==================================================================================================
-                                     FUNCTION IMPLEMENTATION
+                                     INTERNAL FUNCTION IMPLEMENTATION
 ==================================================================================================*/
-static void MsgContactSvcCallback(void *pData)
+int countryCodeLength(const char *src)
 {
-       MSG_DEBUG("Contact Data is Changed!!!");
+       int ret = 0;
+       switch (src[ret++]-'0')
+       {
+       case 1:
+       case 7:
+               break;
+       case 2:
+               switch (src[ret++]-'0')
+               {
+               case 0:
+               case 7:
+                       break;
+               case 1:
+               case 2:
+               case 3:
+               case 4:
+               case 5:
+               case 6:
+               case 8:
+               case 9:
+                       ret += 1;
+                       break;
+               default:
+                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+               }
+               break;
+       case 3:
+               switch (src[ret++]-'0')
+               {
+               case 0:
+               case 1:
+               case 2:
+               case 3:
+               case 4:
+               case 6:
+               case 9:
+                       break;
+               case 5:
+               case 7:
+               case 8:
+                       ret += 1;
+                       break;
+               default:
+                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+               }
+               break;
+       case 4:
+               switch (src[ret++]-'0')
+               {
+               case 0:
+               case 1:
+               case 3:
+               case 4:
+               case 5:
+               case 6:
+               case 7:
+               case 8:
+               case 9:
+                       break;
+               case 2:
+                       ret += 1;
+                       break;
+               default:
+                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+               }
+               break;
+       case 5:
+               switch (src[ret++]-'0')
+               {
+               case 1:
+               case 2:
+               case 3:
+               case 4:
+               case 5:
+               case 6:
+               case 7:
+               case 8:
+                       break;
+               case 0:
+               case 9:
+                       ret += 1;
+                       break;
+               default:
+                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+               }
+               break;
+       case 6:
+               switch (src[ret++]-'0')
+               {
+               case 0:
+               case 1:
+               case 2:
+               case 3:
+               case 4:
+               case 5:
+               case 6:
+                       break;
+               case 7:
+               case 8:
+               case 9:
+                       ret += 1;
+                       break;
+               default:
+                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+               }
+               break;
+       case 8:
+               switch (src[ret++]-'0')
+               {
+               case 1:
+               case 2:
+               case 4:
+               case 6:
+                       break;
+               case 0:
+               case 3:
+               case 5:
+               case 7:
+               case 8:
+               case 9:
+                       ret += 1;
+                       break;
+               default:
+                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+               }
+               break;
+       case 9:
+               switch (src[ret++]-'0')
+               {
+               case 0:
+               case 1:
+               case 2:
+               case 3:
+               case 4:
+               case 5:
+               case 8:
+                       break;
+               case 6:
+               case 7:
+               case 9:
+                       ret += 1;
+                       break;
+               default:
+                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+               }
+               break;
+       case 0:
+       default:
+               MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+               return 0;
+       }
 
-       MsgSyncContact();
+       return ret;
+}
 
-       if (ContactDbHandle.disconnect() != MSG_SUCCESS)
-               MSG_DEBUG("DB Disconnect Fail");
+
+void normalizeNumber(const char *orig, char* dest, unsigned int destSize)
+{
+       unsigned int pos = 0;
+       for (unsigned int i=0; (orig[i] && i<destSize); i++) {
+               if (isdigit(orig[i]) || (orig[i] == '+')) {
+                       dest[pos++] = orig[i];
+               }
+       }
 }
 
 
+//static void MsgContactSvcCallback(const char *view_uri, void *user_data)
+//{
+//     MSG_DEBUG("MsgContactSvcCallback is called.");
+//     if (!strcmp(CONTACT_CALLBACK_USER_DATA, (const char*)user_data)) {
+//             MSG_DEBUG("Contact Data is Changed!!!");
+//             MsgSyncContact();
+//     } else if (!strcmp(ADDRESSBOOK_CALLBACK_USER_DATA, (const char*)user_data)) {
+//             MSG_DEBUG("Address Book Data is Changed!!!");
+//             MsgSyncAddressbook();
+//     }
+//
+//     if (ContactDbHandle.disconnect() != MSG_SUCCESS)
+//             MSG_DEBUG("DB Disconnect Fail");
+//}
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
 msg_error_t MsgOpenContactSvc()
 {
-       int errCode = CTS_SUCCESS;
+       int errCode = CONTACTS_ERROR_NONE;
 
-       if (!isContactSvcOpened) {
-               errCode = contacts_svc_connect();
+       if (!isContactSvcConnected) {
+               errCode = contacts_connect();
 
-               if (errCode == CTS_SUCCESS) {
+               if (errCode == CONTACTS_ERROR_NONE) {
                        MSG_DEBUG("Connect to Contact Service Success");
-                       isContactSvcOpened = true;
+                       isContactSvcConnected = true;
                } else {
                        MSG_DEBUG("Connect to Contact Service Fail [%d]", errCode);
-                       isContactSvcOpened = false;
+                       isContactSvcConnected = false;
                        return MSG_ERR_DB_CONNECT;
                }
        } else {
@@ -72,13 +260,14 @@ msg_error_t MsgOpenContactSvc()
 
 msg_error_t MsgCloseContactSvc()
 {
-       int errCode = CTS_SUCCESS;
+       int errCode = CONTACTS_ERROR_NONE;
 
-       if (isContactSvcOpened) {
-               errCode = contacts_svc_disconnect();
+       if (isContactSvcConnected) {
+               errCode = contacts_disconnect();
 
-               if (errCode == CTS_SUCCESS) {
+               if (errCode == CONTACTS_ERROR_NONE) {
                        MSG_DEBUG("Disconnect to Contact Service Success");
+                       isContactSvcConnected = false;
                } else {
                        MSG_DEBUG("Disconnect to Contact Service Fail [%d]", errCode);
                        return MSG_ERR_DB_DISCONNECT;
@@ -91,18 +280,58 @@ msg_error_t MsgCloseContactSvc()
 
 msg_error_t MsgInitContactSvc(MsgContactChangeCB cb)
 {
-       int errCode = CTS_SUCCESS;
+//     msg_error_t err = MSG_SUCCESS;
+//     unsigned int retryCnt = 10;
 
        if (cb != NULL)
                cbFunction = cb;
 
+       phonenumberMinMatchDigit = MsgSettingGetInt(PHONENUMBER_MIN_MATCH_DIGIT);
+       MSG_DEBUG("phonenumberMinMatchDigit [%d]", phonenumberMinMatchDigit);
+
+       if (phonenumberMinMatchDigit < 1) {
+               phonenumberMinMatchDigit = DEFAULT_MIN_MATCH_DIGIT;
+       }
+
+#if 0
+       do {
+               if ((err = MsgOpenContactSvc()) != MSG_SUCCESS) {
+                       retryCnt--;
+                       MSG_DEBUG("MsgOpenContactSvc fail. Retry count left [%d]", retryCnt);
+                       usleep(100 * 1000);
+               }
+       } while (err != MSG_SUCCESS && retryCnt > 0);
+
+       if (!isContactSvcConnected) {
+               MSG_DEBUG("Contact Service Not Opened.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       // Sync contact first.
+       MsgSyncAddressbook();
+//     MsgSyncContact();
+
+       int errCode = CONTACTS_ERROR_NONE;
+
+       // Register callback function
+       errCode = contacts_db_add_changed_cb(_contacts_contact._uri, MsgContactSvcCallback, (void *)CONTACT_CALLBACK_USER_DATA);
+
+       if (errCode == CONTACTS_ERROR_NONE)
+               MSG_DEBUG("Register Contact Service Callback [_contacts_contact]");
+       else
+               MSG_DEBUG("Fail to Register Contact Service Callback [_contacts_contact] [%d]", errCode);
+
        // Register callback function
-       errCode = contacts_svc_subscribe_change(CTS_SUBSCRIBE_CONTACT_CHANGE, MsgContactSvcCallback, NULL);
+       errCode = contacts_db_add_changed_cb(_contacts_address_book._uri, MsgContactSvcCallback, (void *)ADDRESSBOOK_CALLBACK_USER_DATA);
 
-       if (errCode == CTS_SUCCESS)
-               MSG_DEBUG("Register Contact Service Callback");
+       if (errCode == CONTACTS_ERROR_NONE)
+               MSG_DEBUG("Register Contact Service Callback [_contacts_address_book]");
        else
-               MSG_DEBUG("Fail to Register Contact Service Callback [%d]", errCode);
+               MSG_DEBUG("Fail to Register Contact Service Callback [_contacts_address_book] [%d]", errCode);
+
+       if (ContactDbHandle.disconnect() != MSG_SUCCESS)
+                       MSG_DEBUG("DB Disconnect Fail");
+#endif
 
        return MSG_SUCCESS;
 }
@@ -112,86 +341,380 @@ msg_error_t MsgGetContactInfo(const MSG_ADDRESS_INFO_S *pAddrInfo, MSG_CONTACT_I
 {
        MSG_BEGIN();
 
-       MSG_DEBUG("Address Type [%d], Address Value [%s]", pAddrInfo->addressType, pAddrInfo->addressVal);
+       msg_error_t err = MSG_SUCCESS;
+
+       if ((err = MsgOpenContactSvc()) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgOpenContactSvc fail.");
+               return err;
+       }
+
+       if (!isContactSvcConnected) {
+               MSG_DEBUG("Contact Service Not Opened.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       MSG_SEC_DEBUG("Address Type [%d], Address Value [%s]", pAddrInfo->addressType, pAddrInfo->addressVal);
 
        memset(pContactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
 
        if (pAddrInfo->addressType == MSG_ADDRESS_TYPE_PLMN && strlen(pAddrInfo->addressVal) > (MAX_PHONE_NUMBER_LEN+1)) {
-               MSG_DEBUG("Phone Number is too long [%s]", pAddrInfo->addressVal);
-               return MSG_ERR_INVALID_PARAMETER;
+               MSG_SEC_DEBUG("Phone Number is too long [%s]", pAddrInfo->addressVal);
+               return MSG_ERR_UNKNOWN;
        }
 
-       int index, ret = -1;
+       int ret = 0;
+       int index = 0;
+       int count = 0;
+       contacts_query_h query = NULL;
+       contacts_filter_h filter = NULL;
+       contacts_list_h contacts = NULL;
 
-       CTSstruct* contact = NULL;
+       if (pAddrInfo->addressType == MSG_ADDRESS_TYPE_PLMN || pAddrInfo->addressType == MSG_ADDRESS_TYPE_UNKNOWN) {
+               ret = contacts_query_create(_contacts_contact_number._uri, &query);
+               ret = contacts_filter_create(_contacts_contact_number._uri, &filter);
 
-       cts_find_op recordType;
+               ret = contacts_filter_add_str(filter, _contacts_contact_number.number_filter, CONTACTS_MATCH_EXACTLY, pAddrInfo->addressVal);
 
-       if (pAddrInfo->addressType == MSG_ADDRESS_TYPE_EMAIL)
-               recordType = CTS_FIND_BY_EMAIL;
-       else
-               recordType = CTS_FIND_BY_NUMBER;
+       } else if (pAddrInfo->addressType == MSG_ADDRESS_TYPE_EMAIL) {
+               ret = contacts_query_create(_contacts_contact_email._uri, &query);
+               ret = contacts_filter_create(_contacts_contact_email._uri, &filter);
 
-       index = contacts_svc_find_contact_by(recordType, (char*)pAddrInfo->addressVal);
+               ret = contacts_filter_add_str(filter, _contacts_contact_email.email, CONTACTS_MATCH_EXACTLY, pAddrInfo->addressVal);
 
-       if (index > CTS_SUCCESS) {
-               MSG_DEBUG("Index : [%d]", index);
-               ret = contacts_svc_get_contact(index, &contact);
+       } else {
+               MSG_DEBUG("Invalid pAddrInfo->addressType.");
+               return MSG_ERR_UNKNOWN;
        }
 
-       if (ret < 0) {
-               MSG_DEBUG("No Contact Info");
-               return MSG_SUCCESS;
+       ret = contacts_query_set_filter(query, filter);
+       ret = contacts_db_get_records_with_query(query, 0, 1, &contacts);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_db_get_records_with_query() Error [%d]", ret);
+               contacts_query_destroy(query);
+               contacts_filter_destroy(filter);
+               contacts_list_destroy(contacts, true);
+               return MSG_ERR_UNKNOWN;
        }
 
-       CTSvalue* name = NULL;
-
-       ret = contacts_svc_struct_get_value(contact, CTS_CF_NAME_VALUE, &name);
+       ret = contacts_list_get_count(contacts, &count);
 
-       if (ret != CTS_SUCCESS) {
-               MSG_DEBUG("contacts_svc_struct_get_value() Error [%d]", ret);
+       if (count == 0 || ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("No Serach Data from Contact Service.");
+               contacts_query_destroy(query);
+               contacts_filter_destroy(filter);
+               contacts_list_destroy(contacts, true);
                return MSG_SUCCESS;
        }
 
-       const char* strDisplayName = contacts_svc_value_get_str(name, CTS_NAME_VAL_DISPLAY_STR);
-       const char* strFirstName = contacts_svc_value_get_str(name, CTS_NAME_VAL_FIRST_STR);
-       const char* strLastName = contacts_svc_value_get_str(name, CTS_NAME_VAL_LAST_STR);
+       contacts_query_destroy(query);
+       contacts_filter_destroy(filter);
 
-       MSG_DEBUG("Display Name : [%s], First Name : [%s], Last Name : [%s]", strDisplayName, strFirstName, strLastName);
+       contacts_record_h contact = NULL;
 
-       if (strDisplayName != NULL)
-               strncpy(pContactInfo->displayName, strDisplayName, MAX_DISPLAY_NAME_LEN);
+       if (pAddrInfo->addressType == MSG_ADDRESS_TYPE_PLMN || pAddrInfo->addressType == MSG_ADDRESS_TYPE_UNKNOWN) {
+               contacts_record_h number = NULL;
 
-       if (strFirstName != NULL)
-               strncpy(pContactInfo->firstName, strFirstName, MAX_DISPLAY_NAME_LEN);
+               ret = contacts_list_get_current_record_p(contacts, &number);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_list_get_current_record_p() Error [%d]", ret);
+                       contacts_list_destroy(contacts, true);
+                       return MSG_ERR_UNKNOWN;
+               }
 
-       if (strLastName != NULL)
-               strncpy(pContactInfo->lastName, strLastName, MAX_DISPLAY_NAME_LEN);
+               ret = contacts_record_get_int(number, _contacts_contact_number.contact_id, &index);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_int() Error [%d]", ret);
+                       contacts_list_destroy(contacts, true);
+                       return MSG_ERR_UNKNOWN;
+               }
 
-       CTSvalue* base = NULL;
+               ret = contacts_db_get_record(_contacts_contact._uri, index, &contact);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_db_get_record() Error [%d]", ret);
+                       contacts_list_destroy(contacts, true);
+                       return MSG_ERR_UNKNOWN;
+               }
+       } else if (pAddrInfo->addressType == MSG_ADDRESS_TYPE_EMAIL) {
+               contacts_record_h email = NULL;
+
+               ret = contacts_list_get_current_record_p(contacts, &email);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_list_get_current_record_p() Error [%d]", ret);
+                       contacts_list_destroy(contacts, true);
+                       return MSG_ERR_UNKNOWN;
+               }
 
-       ret = contacts_svc_struct_get_value(contact, CTS_CF_BASE_INFO_VALUE, &base);
+               ret = contacts_record_get_int(email, _contacts_contact_email.contact_id, &index);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_int() Error [%d]", ret);
+                       contacts_list_destroy(contacts, true);
+                       return MSG_ERR_UNKNOWN;
+               }
 
-       if (ret != CTS_SUCCESS) {
-               MSG_DEBUG("contacts_svc_struct_get_value() Error [%d]", ret);
-               return MSG_SUCCESS;
+               ret = contacts_db_get_record(_contacts_contact._uri, index, &contact);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_db_get_record() Error [%d]", ret);
+                       contacts_list_destroy(contacts, true);
+                       return MSG_ERR_UNKNOWN;
+               }
        }
 
-       pContactInfo->contactId = contacts_svc_value_get_int(base, CTS_BASE_VAL_ID_INT);
+       contacts_list_destroy(contacts, true);
+
+#if 0
+       // Name Info
+       contacts_record_h name = NULL;
+
+       ret = contacts_record_get_child_record_at_p(contact, _contacts_contact.name, 0, &name);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_child_record_at_p() Error [%d]", ret);
+       } else {
+               char* strName = NULL;
+               ret = contacts_record_get_str_p(name, _contacts_name.first, &strName);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               } else {
+                       if (strName != NULL) {
+                               MSG_DEBUG("strName [%s]", strName);
+                               strncpy(pContactInfo->firstName, strName, MAX_DISPLAY_NAME_LEN);
+                       }
+               }
+
+               ret = contacts_record_get_str_p(name, _contacts_name.last, &strName);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               } else {
+                       if (strName != NULL) {
+                               MSG_DEBUG("strName [%s]", strName);
+                               strncpy(pContactInfo->lastName, strName, MAX_DISPLAY_NAME_LEN);
+                       }
+               }
+
+               ret = contacts_record_get_str_p(name, _contacts_name.addition, &strName);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               } else {
+                       if (strName != NULL) {
+                               MSG_DEBUG("strName [%s]", strName);
+                               strncpy(pContactInfo->middleName, strName, MAX_DISPLAY_NAME_LEN);
+                       }
+               }
+
+               ret = contacts_record_get_str_p(name, _contacts_name.prefix, &strName);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               } else {
+                       if (strName != NULL) {
+                               MSG_DEBUG("strName [%s]", strName);
+                               strncpy(pContactInfo->prefix, strName, MAX_DISPLAY_NAME_LEN);
+                       }
+               }
+
+               ret = contacts_record_get_str_p(name, _contacts_name.suffix, &strName);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               } else {
+                       if (strName != NULL) {
+                               MSG_DEBUG("strName [%s]", strName);
+                               strncpy(pContactInfo->suffix, strName, MAX_DISPLAY_NAME_LEN);
+                       }
+               }
+       }
+#endif
+
+       ret = contacts_record_get_int(contact, _contacts_contact.id, (int*)&pContactInfo->contactId);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_db_get_record() Error [%d]", ret);
+               contacts_record_destroy(contact, true);
+               return MSG_ERR_UNKNOWN;
+       }
 
        MSG_DEBUG("Contact ID [%d]", pContactInfo->contactId);
 
-       const char* strImagePath = contacts_svc_value_get_str(base, CTS_BASE_VAL_IMG_PATH_STR);
+       ret = contacts_record_get_int(contact, _contacts_contact.address_book_id, (int*)&pContactInfo->addrbookId);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_db_get_record() Error [%d]", ret);
+               contacts_record_destroy(contact, true);
+               return MSG_ERR_UNKNOWN;
+       }
 
-       if (strImagePath != NULL)
+       MSG_DEBUG("Address Book ID [%d]", pContactInfo->addrbookId);
+
+       char* strImagePath = NULL;
+       ret = contacts_record_get_str_p(contact, _contacts_contact.image_thumbnail_path, &strImagePath);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+       }
+       if (strImagePath != NULL) {
                strncpy(pContactInfo->imagePath , strImagePath, MAX_IMAGE_PATH_LEN);
+               MSG_DEBUG("Image Path [%s]", pContactInfo->imagePath);
+       }
+
+       char* alerttonePath = NULL;
+       ret = contacts_record_get_str_p(contact, _contacts_contact.message_alert, &alerttonePath);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+       }
+
+       if (MsgAccessFile(alerttonePath, F_OK) == false) {
+               alerttonePath = NULL;
+       }
+
+       if (alerttonePath != NULL) {
+               MSG_DEBUG("alert tone Path [%s]", alerttonePath);
+               strncpy(pContactInfo->alerttonePath , alerttonePath, MSG_FILEPATH_LEN_MAX);
+       } else {
+               MSG_DEBUG("alert tone Path for this contact is default");
+               count = 0;
+               ret = contacts_record_get_child_record_count(contact, _contacts_contact.group_relation, &count);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_child_record_count() Error [%d]", ret);
+               }
+
+               contacts_record_h group_relation_record;
+
+               for (int i = 0; i < count; i++) {
+                       int group_id = 0;
+                       contacts_record_get_child_record_at_p(contact, _contacts_contact.group_relation, i, &group_relation_record);
+                       contacts_record_get_int(group_relation_record, _contacts_group_relation.group_id, &group_id);
+
+                       contacts_record_h group_record;
+                       contacts_db_get_record(_contacts_group._uri, group_id, &group_record);
+
+                       MSG_DEBUG("Group ID = [%d]", group_id);
+
+                       char *group_ringtone_path;
+                       ret = contacts_record_get_str_p(group_record, _contacts_group.message_alert, &group_ringtone_path);
+                       if (ret != CONTACTS_ERROR_NONE) {
+                               MSG_DEBUG("contacts_record_get_child_record_count() Error [%d]", ret);
+                       } else {
+                               if (group_ringtone_path) {
+                                       MSG_DEBUG("Msg alert_tone is change to [%s] as contact group", group_ringtone_path);
+                                       memset(pContactInfo->alerttonePath, 0x00, sizeof(pContactInfo->alerttonePath));
+                                       snprintf(pContactInfo->alerttonePath, sizeof(pContactInfo->alerttonePath), "%s", group_ringtone_path);
+                                       contacts_record_destroy(group_record, true);
+                                       break;
+                               }
+                       }
+                       contacts_record_destroy(group_record, true);
+               }
+       }
+
+       char* vibrationPath = NULL;
+       ret = contacts_record_get_str_p(contact, _contacts_contact.vibration, &vibrationPath);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+       }
+       if (vibrationPath != NULL) {
+               MSG_DEBUG("vibration Path [%s]", vibrationPath);
+               strncpy(pContactInfo->vibrationPath , vibrationPath, MSG_FILEPATH_LEN_MAX);
+       }
+
+       char* displayName = NULL;
+       ret = contacts_record_get_str_p(contact, _contacts_contact.display_name, &displayName);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+       }
+       if (displayName != NULL) {
+               MSG_DEBUG("displayName [%s]", displayName);
+               strncpy(pContactInfo->firstName , displayName, MAX_DISPLAY_NAME_LEN);
+       }
+
+       contacts_record_destroy(contact, true);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgGetContactSearchList(const char *pSearchVal, MSG_ADDRESS_INFO_S **pAddrInfo, int *count)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       *count = 0;
+
+       if (pSearchVal == NULL) {
+               MSG_DEBUG("pSearchVal is NULL.");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       if (pAddrInfo == NULL) {
+               MSG_DEBUG("pAddrInfo is NULL.");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       if ((err = MsgOpenContactSvc()) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgOpenContactSvc fail.");
+               return err;
+       }
+
+       if (!isContactSvcConnected) {
+               MSG_DEBUG("Contact Service Not Opened.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       MSG_SEC_DEBUG("pSearchVal [%s]", pSearchVal);
+
+       int ret = 0;
+       unsigned int index = 0;
+       contacts_query_h query = NULL;
+       contacts_filter_h filter = NULL;
+       contacts_list_h personNumbers = NULL;
+
+       ret = contacts_query_create(_contacts_person_number._uri, &query);
+       ret = contacts_filter_create(_contacts_person_number._uri, &filter);
+
+       ret = contacts_filter_add_str(filter, _contacts_person_number.display_name, CONTACTS_MATCH_CONTAINS, pSearchVal);
+       ret = contacts_query_set_filter(query, filter);
+
+       ret = contacts_db_get_records_with_query(query, 0, 0, &personNumbers);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_db_get_records_with_query() Error [%d]", ret);
+               contacts_query_destroy(query);
+               contacts_filter_destroy(filter);
+               contacts_list_destroy(personNumbers, true);
+               return MSG_ERR_UNKNOWN;
+       }
+
+       ret = contacts_list_get_count(personNumbers, count);
+       if (*count == 0 || ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("No Serach Data from Contact Service.");
+               *count = 0;
+               contacts_query_destroy(query);
+               contacts_filter_destroy(filter);
+               contacts_list_destroy(personNumbers, true);
+               return MSG_SUCCESS;
+       }
+
+       contacts_query_destroy(query);
+       contacts_filter_destroy(filter);
+
+       MSG_DEBUG(" *count [%d]", *count);
 
-       MSG_DEBUG("Image Path [%s]", pContactInfo->imagePath);
+       *pAddrInfo = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S) * (*count)];
+       memset(*pAddrInfo, 0x00, (sizeof(MSG_ADDRESS_INFO_S) * (*count)));
+
+       contacts_record_h personNumber = NULL;
+
+       while (CONTACTS_ERROR_NONE == contacts_list_get_current_record_p(personNumbers, &personNumber)) {
+               char* normalizedNumber = NULL;
+               ret = contacts_record_get_str(personNumber, _contacts_person_number.normalized_number, &normalizedNumber);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_int() Error [%d]", ret);
+               }
+               else if (normalizedNumber) {
+                       MSG_DEBUG("normalizedNumber [%s]", normalizedNumber);
+                       strncpy((*pAddrInfo)[index].addressVal, normalizedNumber, MAX_ADDRESS_VAL_LEN);
+               }
 
-       contacts_svc_value_free(base);
-       contacts_svc_value_free(name);
+               contacts_list_next(personNumbers);
+               index++;
+       }
 
-       contacts_svc_struct_free(contact);
+       contacts_list_destroy(personNumbers, true);
 
        MSG_END();
 
@@ -199,12 +722,71 @@ msg_error_t MsgGetContactInfo(const MSG_ADDRESS_INFO_S *pAddrInfo, MSG_CONTACT_I
 }
 
 
+void MsgSyncAddressbook()
+{
+       int ret = -1;
+       int changed_count = 0;
+
+       contacts_list_h addrbookListHnd = NULL;
+
+       ret = contacts_db_get_all_records(_contacts_address_book._uri, 0, 0, &addrbookListHnd);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_db_get_all_records() Error [%d]", ret);
+               contacts_list_destroy(addrbookListHnd, true);
+               return;
+       }
+
+       ret = contacts_list_get_count(addrbookListHnd, &changed_count);
+
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_list_get_count() Error [%d]", ret);
+               contacts_list_destroy(addrbookListHnd, true);
+               return;
+       }
+
+       if (changed_count>0) {
+               int addrbookList[changed_count];
+
+               for (int i = 0; i < changed_count; i++) {
+                       contacts_record_h addrbook = NULL;
+                       int addrbookId = 0;
+
+                       ret = contacts_list_get_current_record_p(addrbookListHnd, &addrbook);
+                       if (ret != CONTACTS_ERROR_NONE) {
+                               MSG_DEBUG("contacts_list_get_current_record_p() Error [%d]", ret);
+                               contacts_list_destroy(addrbookListHnd, true);
+                               return;
+                       }
+
+                       ret = contacts_record_get_int(addrbook, _contacts_address_book.id, &addrbookId);
+                       if (ret != CONTACTS_ERROR_NONE) {
+                               MSG_DEBUG("contacts_record_get_int() Error [%d]", ret);
+                               contacts_list_destroy(addrbookListHnd, true);
+                               return;
+                       }
+
+                       addrbookList[i] = addrbookId;
+
+                       ret = contacts_list_next(addrbookListHnd);
+                       if (ret != CONTACTS_ERROR_NONE) {
+                               MSG_DEBUG("contacts_list_next() Error [%d]", ret);
+                       }
+
+               }
+
+               MsgStoClearContactInfoByAddrbookIdList(&ContactDbHandle, addrbookList, (int)changed_count);
+       }
+
+       contacts_list_destroy(addrbookListHnd, true);
+}
+
+
 void MsgSyncContact()
 {
        int ret = -1;
-       int index_num = 0;
        int changed_count = 0;
        int lastSyncTime = 0;
+       int finalSyncTime = 0;
 
        /* get contact sync time */
        lastSyncTime = MsgSettingGetInt(CONTACT_SYNC_TIME);
@@ -214,49 +796,78 @@ void MsgSyncContact()
                lastSyncTime = 0;
        }
 
-       CTSiter* pIter;
+       contacts_list_h contactsList = NULL;
 
-       ret = contacts_svc_get_updated_contacts(-1, lastSyncTime, &pIter);
+       ret = contacts_db_get_changes_by_version(_contacts_contact_updated_info._uri, -1, lastSyncTime, &contactsList, &finalSyncTime);
 
-       if (ret != CTS_SUCCESS) {
-               MSG_DEBUG("contacts_svc_get_updated_contacts() Error [%d]", ret);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_db_get_changes_by_version() Error [%d]", ret);
+               contacts_list_destroy(contactsList, true);
                return;
        }
 
-       while (contacts_svc_iter_next(pIter) == CTS_SUCCESS)
-       {
-               CTSvalue *row_info = NULL;
+       ret = contacts_list_get_count(contactsList, &changed_count);
 
-               row_info = contacts_svc_iter_get_info(pIter);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_list_get_count() Error [%d]", ret);
+               contacts_list_destroy(contactsList, true);
+               return;
+       }
+
+       for (int i = 0; i < changed_count; i++)
+       {
+               int index_num = 0;
+               int type = 0;
+               contacts_record_h event = NULL;
+
+               ret = contacts_list_get_current_record_p(contactsList, &event);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_list_get_current_record_p() Error [%d]", ret);
+                       contacts_list_destroy(contactsList, true);
+                       return;
+               }
 
-               index_num = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_ID_INT);
+               ret = contacts_record_get_int(event, _contacts_contact_updated_info.contact_id, &index_num);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_int() Error [%d]", ret);
+                       contacts_list_destroy(contactsList, true);
+                       return;
+               }
 
                MSG_DEBUG("index (%d)", index_num);
 
-               int type = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_TYPE_INT);
+               ret = contacts_record_get_int(event, _contacts_contact_updated_info.type, &type);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_int() Error [%d]", ret);
+                       contacts_list_destroy(contactsList, true);
+                       return;
+               }
 
-               if (type == CTS_OPERATION_UPDATED || type == CTS_OPERATION_INSERTED) {
-                       MsgUpdateContact(index_num, type);
-               } else {// Delete
-                       MSG_DEBUG("Delete Contact");
+               MSG_DEBUG("type [%d]", type);
+
+               if (type != CONTACTS_CHANGE_INSERTED) {
                        MsgDeleteContact(index_num);
                }
 
-               if(lastSyncTime < contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_VER_INT))
-                       lastSyncTime = contacts_svc_value_get_int(row_info, CTS_LIST_CHANGE_VER_INT);
-
-               contacts_svc_value_free(row_info);
+               if (type != CONTACTS_CHANGE_DELETED) {
+                       MsgUpdateContact(index_num, type);
+               }
 
-               changed_count++;
+               ret = contacts_list_next(contactsList);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_list_next() Error [%d]", ret);
+               }
        }
 
-       MsgSettingSetInt(CONTACT_SYNC_TIME, lastSyncTime);
-       MSG_DEBUG("lastSyncTime : %d", lastSyncTime);
+       if(MsgSettingSetInt(CONTACT_SYNC_TIME, finalSyncTime) != MSG_SUCCESS)
+               MSG_DEBUG("MsgSettingSetInt fail : CONTACT_SYNC_TIME");
+       MSG_DEBUG("lastSyncTime : %d", finalSyncTime);
 
-       contacts_svc_iter_remove(pIter);
+       contacts_list_destroy(contactsList, true);
 
-       if(changed_count > 0)
-               cbFunction();
+       if(changed_count > 0) {
+               if(cbFunction) cbFunction();
+       }
 }
 
 
@@ -276,34 +887,42 @@ bool MsgInsertContact(MSG_CONTACT_INFO_S *pContactInfo, const char *pNumber)
 
 bool MsgUpdateContact(int index, int type)
 {
-       int ret = -1;
-
-       CTSstruct *contact = NULL;
+       int ret = CONTACTS_ERROR_NONE;
 
-       ret = contacts_svc_get_contact(index, &contact);
+       contacts_record_h contact = NULL;
 
-       if (ret != CTS_SUCCESS) {
-               MSG_DEBUG("contacts_svc_get_contact() Error [%d]", ret);
+       ret = contacts_db_get_record(_contacts_contact._uri, index, &contact);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_db_get_record() Error [%d]", ret);
+               contacts_record_destroy(contact, true);
                return false;
        }
 
-       // Base Info
-       CTSvalue *base = NULL;
-
-       ret = contacts_svc_struct_get_value(contact, CTS_CF_BASE_INFO_VALUE, &base);
+#if 0
+       MSG_CONTACT_INFO_S contactInfo;
+       memset(&contactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
 
-       if (ret != CTS_SUCCESS) {
-               MSG_DEBUG("contacts_svc_struct_get_value() Error [%d]", ret);
+       ret = contacts_record_get_int(contact, _contacts_contact.id, (int*)&contactInfo.contactId);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_db_get_record() Error [%d]", ret);
+               contacts_record_destroy(contact, true);
                return false;
        }
 
-       MSG_CONTACT_INFO_S contactInfo = {0};
+       MSG_DEBUG("Contact ID [%d]", contactInfo.contactId);
 
-       contactInfo.contactId = contacts_svc_value_get_int(base, CTS_BASE_VAL_ID_INT);
+       ret = contacts_record_get_int(contact, _contacts_contact.address_book_id, (int*)&contactInfo.addrbookId);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_db_get_record() Error [%d]", ret);
+       }
 
-       MSG_DEBUG("Contact ID [%d]", contactInfo.contactId);
+       MSG_DEBUG("Addressbook ID [%d]", contactInfo.addrbookId);
 
-       const char* strImagePath = contacts_svc_value_get_str(base, CTS_BASE_VAL_IMG_PATH_STR);
+       char* strImagePath = NULL;
+       ret = contacts_record_get_str_p(contact, _contacts_contact.image_thumbnail_path, &strImagePath);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+       }
 
        if (strImagePath != NULL)
                strncpy(contactInfo.imagePath , strImagePath, MAX_IMAGE_PATH_LEN);
@@ -311,61 +930,132 @@ bool MsgUpdateContact(int index, int type)
        MSG_DEBUG("Image Path [%s]", contactInfo.imagePath);
 
        // Name Info
-       CTSvalue* name = NULL;
-
-       ret = contacts_svc_struct_get_value(contact, CTS_CF_NAME_VALUE, &name);
+       contacts_record_h name = NULL;
 
-       if (ret != CTS_SUCCESS) {
-               MSG_DEBUG("contacts_svc_struct_get_value() Error [%d]", ret);
-               return MSG_SUCCESS;
-       }
+       ret = contacts_record_get_child_record_at_p(contact, _contacts_contact.name, 0, &name);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_child_record_at_p() Error [%d]", ret);
+       } else {
+               char* strName = NULL;
+               ret = contacts_record_get_str_p(name, _contacts_name.first, &strName);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               } else {
+                       if (strName != NULL) {
+                               MSG_DEBUG("strName [%s]", strName);
+                               strncpy(contactInfo.firstName, strName, MAX_DISPLAY_NAME_LEN);
+                       }
+               }
 
-       const char* strDisplayName = contacts_svc_value_get_str(name, CTS_NAME_VAL_DISPLAY_STR);
-       const char* strFirstName = contacts_svc_value_get_str(name, CTS_NAME_VAL_FIRST_STR);
-       const char* strLastName = contacts_svc_value_get_str(name, CTS_NAME_VAL_LAST_STR);
+               ret = contacts_record_get_str_p(name, _contacts_name.last, &strName);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               } else {
+                       if (strName != NULL) {
+                               MSG_DEBUG("strName [%s]", strName);
+                               strncpy(contactInfo.lastName, strName, MAX_DISPLAY_NAME_LEN);
+                       }
+               }
 
-       MSG_DEBUG("Display Name : [%s], First Name : [%s], Last Name : [%s]", strDisplayName, strFirstName, strLastName);
+               ret = contacts_record_get_str_p(name, _contacts_name.addition, &strName);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               } else {
+                       if (strName != NULL) {
+                               MSG_DEBUG("strName [%s]", strName);
+                               strncpy(contactInfo.middleName, strName, MAX_DISPLAY_NAME_LEN);
+                       }
+               }
 
-       if (strDisplayName != NULL)
-               strncpy(contactInfo.displayName, strDisplayName, MAX_DISPLAY_NAME_LEN);
+               ret = contacts_record_get_str_p(name, _contacts_name.prefix, &strName);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               } else {
+                       if (strName != NULL) {
+                               MSG_DEBUG("strName [%s]", strName);
+                               strncpy(contactInfo.prefix, strName, MAX_DISPLAY_NAME_LEN);
+                       }
+               }
 
-       if (strFirstName != NULL)
-               strncpy(contactInfo.firstName, strFirstName, MAX_DISPLAY_NAME_LEN);
+               ret = contacts_record_get_str_p(name, _contacts_name.suffix, &strName);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               } else {
+                       if (strName != NULL) {
+                               MSG_DEBUG("strName [%s]", strName);
+                               strncpy(contactInfo.suffix, strName, MAX_DISPLAY_NAME_LEN);
+                       }
+               }
 
-       if (strLastName != NULL)
-               strncpy(contactInfo.lastName, strLastName, MAX_DISPLAY_NAME_LEN);
+               MSG_SEC_DEBUG("First Name : [%s], Last Name : [%s]", contactInfo.firstName, contactInfo.lastName);
+       }
 
        MsgStoClearContactInfo(&ContactDbHandle, index);
+#endif
 
-       GSList *get_list, *cursor;
-
-       get_list = NULL;
-
-       contacts_svc_struct_get_list(contact, CTS_CF_NUMBER_LIST, &get_list);
-
-       cursor = get_list;
+       int count = 0;
+       ret = contacts_record_get_child_record_count(contact, _contacts_contact.number, &count);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_child_record_count() Error [%d]", ret);
+               contacts_record_destroy(contact, true);
+               return false;
+       }
 
-       // No phone number in contact
-       if (cursor == NULL) {
-                contacts_svc_struct_free(contact);
+       if (count > 0) {
+               for (int i=0; i < count; i++) {
+                       MSG_DEBUG("Add Contact Data");
+
+                       contacts_record_h number = NULL;
+
+                       ret = contacts_record_get_child_record_at_p(contact, _contacts_contact.number, i, &number);
+                       if (ret != CONTACTS_ERROR_NONE) {
+                               MSG_DEBUG("contacts_record_get_child_record_at_p() Error [%d]", ret);
+                               contacts_record_destroy(contact, true);
+                               return false;
+                       }
+
+                       char* strNumber = NULL;
+                       ret = contacts_record_get_str_p(number, _contacts_number.number, &strNumber);
+                       if (ret != CONTACTS_ERROR_NONE) {
+                               MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+                               contacts_record_destroy(contact, true);
+                               return false;
+                       }
+
+                       if (strNumber != NULL) {
+                               MSG_DEBUG("Number [%s]", strNumber);
+                               int strNumberLen = strlen(strNumber);
+                               char normalizeNum[strNumberLen+1];
+                               memset(normalizeNum, 0x00, sizeof(normalizeNum));
+                               if (strNumberLen > 0) {
+                                       normalizeNumber(strNumber, normalizeNum, strNumberLen);
+                                       MSG_DEBUG("normalizeNum [%s]", normalizeNum);
+                               }
+
+                               MSG_CONTACT_INFO_S contactInfo;
+                               memset(&contactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+                               MSG_ADDRESS_INFO_S addrInfo;
+                               memset(&addrInfo, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+                               strncpy(addrInfo.addressVal, normalizeNum, MAX_ADDRESS_VAL_LEN);
+
+                               if(MsgGetContactInfo(&addrInfo, &contactInfo) == MSG_SUCCESS) {
+                                       if (MsgInsertContact(&contactInfo, normalizeNum)) {
+                                               MsgStoSetConversationDisplayName(&ContactDbHandle, (int)contactInfo.contactId);
+                                       } else {
+                                               MSG_DEBUG("MsgInsertContact fail.");
+                                       }
+                               }
+                       }
+               }
+       } else {// No phone number in contact
+               contacts_record_destroy(contact, true);
                return true;
        }
 
-       for(; cursor; cursor = g_slist_next(cursor))
-       {
-               MSG_DEBUG("Add Contact Data");
-
-               const char* strNumber = contacts_svc_value_get_str((CTSvalue*)cursor->data, CTS_NUM_VAL_NUMBER_STR);
-
-               MSG_DEBUG("Number = %s", strNumber);
+//     MsgStoSetConversationDisplayName(&ContactDbHandle, index);
 
-               if (MsgInsertContact(&contactInfo, strNumber) == false)
-                       continue;
-       }
-
-       MsgStoSetConversationDisplayName(&ContactDbHandle, index);
-
-       contacts_svc_struct_free(contact);
+       contacts_record_destroy(contact, true);
 
        return true;
 }
@@ -373,112 +1063,442 @@ bool MsgUpdateContact(int index, int type)
 
 bool MsgDeleteContact(int index)
 {
-       if (MsgStoClearContactInfo(&ContactDbHandle, index) != MSG_SUCCESS)
+//     if (MsgStoClearContactInfo(&ContactDbHandle, index) != MSG_SUCCESS)
+       if (MsgStoResetContactInfo(&ContactDbHandle, index) != MSG_SUCCESS)
                return false;
 
        return true;
 }
 
-
 int MsgGetContactNameOrder()
 {
-       int ret = 0;
+//     int ret = CONTACTS_ERROR_NONE;
+       contacts_name_display_order_e order = CONTACTS_NAME_DISPLAY_ORDER_FIRSTLAST;
+
+//     if (MsgOpenContactSvc() != MSG_SUCCESS) {
+//             MSG_DEBUG("MsgOpenContactSvc fail.");
+//     }
+//
+//     if (!isContactSvcConnected) {
+//             MSG_DEBUG("Contact Service Not Opened.");
+//     } else {
+//             ret = contacts_setting_get_name_display_order(&order);
+//             if (ret != CONTACTS_ERROR_NONE) {
+//                     MSG_DEBUG("contacts_setting_get_name_display_order() Error [%d]", ret);
+//             }
+//     }
+
+       return (int)order;
+}
 
-       cts_order_type order = CTS_ORDER_NAME_FIRSTLAST;
 
-       order = contacts_svc_get_order(CTS_ORDER_OF_DISPLAY);
+msg_error_t MsgGetContactStyleDisplayName(const char *first, const char *last, const char *middle, const char *prefix, const char *suffix, int contactNameOrder, char *displayName, unsigned int size)
+{
+       if (first == NULL || last == NULL || middle == NULL || prefix == NULL || suffix == NULL || displayName == NULL || size ==0) {
+               MSG_DEBUG("Invalid parameter.");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
 
-       if (order == CTS_ORDER_NAME_FIRSTLAST)
-               ret = 0;
-       else if (order == CTS_ORDER_NAME_LASTFIRST)
-               ret = 1;
+       if (contactNameOrder == CONTACTS_NAME_DISPLAY_ORDER_FIRSTLAST) {
+               if (strlen(prefix) > 0) {
+                       strncpy(displayName, prefix, size);
+               }
 
-       return ret;
+               if (strlen(first) > 0) {
+                       if (strlen(displayName) > 0) strncat(displayName, " ", size-strlen(displayName));
+                       strncat(displayName, first, size-strlen(displayName));
+               }
+
+               if (strlen(middle) > 0) {
+                       if (strlen(displayName) > 0) strncat(displayName, " ", size-strlen(displayName));
+
+                       strncat(displayName, middle, size-strlen(displayName));
+               }
+
+               if (strlen(last) > 0) {
+                       if (strlen(displayName) > 0) strncat(displayName, " ", size-strlen(displayName));
+                       strncat(displayName, last, size-strlen(displayName));
+               }
+
+               if (strlen(suffix) > 0) {
+                       if (strlen(displayName) > 0) strncat(displayName, ", ", size-strlen(displayName));
+                       strncat(displayName, suffix, size-strlen(displayName));
+               }
+       } else {
+               if (strlen(prefix) > 0) {
+                       strncpy(displayName, prefix, size);
+               }
+
+               if (strlen(last) > 0) {
+                       if (strlen(displayName) > 0) strncat(displayName, " ", size-strlen(displayName));
+                       strncat(displayName, last, size-strlen(displayName));
+
+                       if (strlen(first) > 0 || strlen(middle) > 0 || strlen(suffix) > 0)
+                               strncat(displayName, ",", size-strlen(displayName));
+               }
+
+               if (strlen(first) > 0) {
+                       if (strlen(displayName) > 0) strncat(displayName, " ", size-strlen(displayName));
+                       strncat(displayName, first, size-strlen(displayName));
+               }
+
+               if (strlen(middle) > 0) {
+                       if (strlen(displayName) > 0) strncat(displayName, " ", size-strlen(displayName));
+                       strncat(displayName, middle, size-strlen(displayName));
+               }
+
+               if (strlen(suffix) > 0) {
+                       if (strlen(displayName) > 0) strncat(displayName, ", ", size-strlen(displayName));
+                       strncat(displayName, suffix, size-strlen(displayName));
+               }
+       }
+
+       MSG_SEC_DEBUG("displayName [%s]", displayName);
+
+       return MSG_SUCCESS;
 }
 
 
-msg_error_t MsgAddPhoneLog(const MSG_MESSAGE_INFO_S *pMsgInfo)
+void MsgAddPhoneLog(const MSG_MESSAGE_INFO_S *pMsgInfo)
 {
        msg_error_t err = MSG_SUCCESS;
 
-       MSG_DEBUG("folderId [%d], number [%s]", pMsgInfo->folderId, pMsgInfo->addressList[0].addressVal);
+       if ((err = MsgOpenContactSvc()) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgOpenContactSvc fail.");
+               return;
+       }
 
-       CTSvalue* plog;
+       if (!isContactSvcConnected) {
+               MSG_DEBUG("Contact Service Not Opened.");
+               return;
+       }
 
-       plog = contacts_svc_value_new(CTS_VALUE_PHONELOG);
+       if (pMsgInfo->nAddressCnt < 1) {
+               MSG_DEBUG("address count is [%d]", pMsgInfo->nAddressCnt);
+               return;
+       }
 
-       contacts_svc_value_set_str(plog, CTS_PLOG_VAL_NUMBER_STR, (char*)pMsgInfo->addressList[0].addressVal);
-       contacts_svc_value_set_int(plog, CTS_PLOG_VAL_LOG_TIME_INT, (int)time(NULL));
+       for (int i = 0; pMsgInfo->nAddressCnt > i; i++) {
+               int ret = 0;
+               contacts_record_h plog = NULL;
 
-       char strText[101];
-       memset(strText, 0x00, sizeof(strText));
+               ret = contacts_record_create(_contacts_phone_log._uri, &plog);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_create() Error [%d]", ret);
+                       contacts_record_destroy(plog, true);
+                       break;
+               }
 
-       if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE) {
-               strncpy(strText, pMsgInfo->msgText, 100);
-               MSG_DEBUG("msgText : %s", strText);
-       } else if (pMsgInfo->msgType.mainType == MSG_MMS_TYPE) {
-               if (strlen(pMsgInfo->subject) > 0 || pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS) {
-                       strncpy(strText, pMsgInfo->subject, 100);
-                       MSG_DEBUG("subject : %s", strText);
-               } else {
+               contacts_record_set_str(plog, _contacts_phone_log.address, (char*)pMsgInfo->addressList[i].addressVal);
+               contacts_record_set_int(plog, _contacts_phone_log.log_time, (int)time(NULL));
+
+               char strText[101];
+               memset(strText, 0x00, sizeof(strText));
+
+               if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE) {
                        strncpy(strText, pMsgInfo->msgText, 100);
-                       MSG_DEBUG("msgText : %s", strText);
+                       MSG_SEC_DEBUG("msgText : %s", strText);
+               } else if (pMsgInfo->msgType.mainType == MSG_MMS_TYPE) {
+                       if (strlen(pMsgInfo->subject) > 0 || pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS) {
+                               strncpy(strText, pMsgInfo->subject, 100);
+                               MSG_SEC_DEBUG("subject : %s", strText);
+                       } else {
+                               strncpy(strText, pMsgInfo->msgText, 100);
+                               MSG_SEC_DEBUG("msgText : %s", strText);
+                       }
+               }
+
+               contacts_record_set_str(plog, _contacts_phone_log.extra_data2, strText);
+               contacts_record_set_int(plog, _contacts_phone_log.extra_data1, (int)pMsgInfo->msgId);
+
+               if (pMsgInfo->folderId == MSG_INBOX_ID) {
+                       if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE)
+                               contacts_record_set_int(plog, _contacts_phone_log.log_type, CONTACTS_PLOG_TYPE_SMS_INCOMMING);
+                       else if (pMsgInfo->msgType.mainType == MSG_MMS_TYPE)
+                               contacts_record_set_int(plog, _contacts_phone_log.log_type, CONTACTS_PLOG_TYPE_MMS_INCOMMING);
+               } else if (pMsgInfo->folderId == MSG_OUTBOX_ID) {
+                       if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE)
+                               contacts_record_set_int(plog, _contacts_phone_log.log_type, CONTACTS_PLOG_TYPE_SMS_OUTGOING);
+                       else if (pMsgInfo->msgType.mainType == MSG_MMS_TYPE)
+                               contacts_record_set_int(plog, _contacts_phone_log.log_type, CONTACTS_PLOG_TYPE_MMS_OUTGOING);
+               } else if (pMsgInfo->folderId == MSG_SPAMBOX_ID) {
+                       if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE)
+                               contacts_record_set_int(plog, _contacts_phone_log.log_type, CONTACTS_PLOG_TYPE_SMS_BLOCKED);
+                       else if (pMsgInfo->msgType.mainType == MSG_MMS_TYPE)
+                               contacts_record_set_int(plog, _contacts_phone_log.log_type, CONTACTS_PLOG_TYPE_MMS_BLOCKED);
+               }
+
+               ret = contacts_db_insert_record(plog, NULL);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_db_insert_record() Error [%d]", ret);
                }
+
+               contacts_record_destroy(plog, true);
+       }
+}
+
+
+void MsgDeletePhoneLog(msg_message_id_t msgId)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if ((err = MsgOpenContactSvc()) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgOpenContactSvc fail.");
+               return;
        }
 
-       contacts_svc_value_set_str(plog, CTS_PLOG_VAL_SHORTMSG_STR, strText);
-       contacts_svc_value_set_int(plog, CTS_PLOG_VAL_MSGID_INT, (int)pMsgInfo->msgId);
+       MSG_DEBUG("MsgDeletePhoneLog [%d]", msgId);
 
-       if (pMsgInfo->folderId == MSG_INBOX_ID) {
-               if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE)
-                       contacts_svc_value_set_int(plog, CTS_PLOG_VAL_LOG_TYPE_INT, CTS_PLOG_TYPE_SMS_INCOMMING);
-               else if (pMsgInfo->msgType.mainType == MSG_MMS_TYPE)
-                       contacts_svc_value_set_int(plog, CTS_PLOG_VAL_LOG_TYPE_INT, CTS_PLOG_TYPE_MMS_INCOMMING);
-       } else if (pMsgInfo->folderId == MSG_OUTBOX_ID) {
-               if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE)
-                       contacts_svc_value_set_int(plog, CTS_PLOG_VAL_LOG_TYPE_INT, CTS_PLOG_TYPE_SMS_OUTGOING);
-               else if (pMsgInfo->msgType.mainType == MSG_MMS_TYPE)
-                       contacts_svc_value_set_int(plog, CTS_PLOG_VAL_LOG_TYPE_INT, CTS_PLOG_TYPE_MMS_OUTGOING);
-       } else if (pMsgInfo->folderId == MSG_SPAMBOX_ID) {
-               if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE)
-                       contacts_svc_value_set_int(plog, CTS_PLOG_VAL_LOG_TYPE_INT, CTS_PLOG_TYPE_SMS_BLOCKED);
-               else if (pMsgInfo->msgType.mainType == MSG_MMS_TYPE)
-                       contacts_svc_value_set_int(plog, CTS_PLOG_VAL_LOG_TYPE_INT, CTS_PLOG_TYPE_MMS_BLOCKED);
+       if (!isContactSvcConnected) {
+               MSG_DEBUG("Contact Service Not Opened.");
+               return;
        }
 
-       int ret = contacts_svc_insert_phonelog(plog);
+       int ret = CONTACTS_ERROR_NONE;
+       int index = 0;
+       int count = 0;
+       contacts_query_h query;
+       contacts_filter_h filter;
+       contacts_list_h plogs = NULL;
+
+       ret = contacts_query_create(_contacts_phone_log._uri, &query);
+       ret = contacts_filter_create(_contacts_phone_log._uri, &filter);
+
+       ret = contacts_filter_add_int(filter, _contacts_phone_log.extra_data1, CONTACTS_MATCH_EQUAL, (int)msgId);
+
 
-       if (ret != CTS_SUCCESS)
-               MSG_DEBUG("contacts_svc_insert_phonelog() Failed!!! [%d]", ret);
+       ret = contacts_query_set_filter(query, filter);
+       ret = contacts_db_get_records_with_query(query, 0, 1, &plogs);
 
-       contacts_svc_value_free(plog);
+       ret = contacts_list_get_count(plogs, &count);
+
+       if (count == 0) {
+               MSG_DEBUG("No Serach Data from Contact Service.");
+       } else {
+               contacts_record_h plog = NULL;
+
+               ret = contacts_list_get_current_record_p(plogs, &plog);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_list_get_current_record_p() Error [%d]", ret);
+               }
+
+               ret = contacts_record_get_int(plog, _contacts_phone_log.id, &index);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_int() Error [%d]", ret);
+               }
 
-       return err;
+               ret = contacts_db_delete_record(_contacts_phone_log._uri, index);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_record_get_int() Error [%d]", ret);
+               } else {
+                       MSG_DEBUG("contacts_db_delete_record() Success.");
+               }
+       }
+
+       contacts_query_destroy(query);
+       contacts_filter_destroy(filter);
+       contacts_list_destroy(plogs, true);
 }
 
 
-msg_error_t MsgDeletePhoneLog(msg_message_id_t msgId)
+int MsgContactSVCBeginTrans()
+{
+       //return contacts_svc_begin_trans();
+       return 0;
+}
+
+
+int MsgContactSVCEndTrans(bool bSuccess)
+{
+       //return contacts_svc_end_trans(bSuccess);
+       return 0;
+}
+
+
+bool checkBlockingMode(char *address, bool *pisFavorites)
 {
        msg_error_t err = MSG_SUCCESS;
 
-       MSG_DEBUG("MsgDeletePhoneLog [%d]", msgId);
+       if (pisFavorites != NULL) *pisFavorites = false;
+
+       bool isBlockModeOn = false;
+       bool isblock = true;
+
+       MsgSettingGetBool(VCONFKEY_SETAPPL_BLOCKINGMODE_NOTIFICATIONS, &isBlockModeOn);
+
+       int blockModeType = -1;
+
+       blockModeType = MsgSettingGetInt(VCONFKEY_SETAPPL_BLOCKINGMODE_ALLOWED_CONTACT_TYPE);
+
+       if (!isBlockModeOn)
+               isblock = false;
+       else if (blockModeType < 0)
+               isblock = false;
+
+
+       if ((err = MsgOpenContactSvc()) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgOpenContactSvc fail.");
+               return isblock;
+       }
+
+       if (!isContactSvcConnected) {
+               MSG_DEBUG("Contact Service Not Opened.");
+               return isblock;
+       }
+
+       MSG_SEC_DEBUG("Address Value [%s]", address);
+
+       if (strlen(address) > (MAX_PHONE_NUMBER_LEN+1)) {
+               MSG_SEC_DEBUG("Phone Number is too long [%s]", address);
+               return isblock;
+       }
+
+       int ret = 0;
+       int personId = 0;
+       bool isFavorites = false;
+       int count = 0;
+       contacts_query_h query = NULL;
+       contacts_filter_h filter = NULL;
+       contacts_list_h personList = NULL;
+
+       ret = contacts_query_create(_contacts_person_number._uri, &query);
+       ret = contacts_filter_create(_contacts_person_number._uri, &filter);
+
+       ret = contacts_filter_add_str(filter, _contacts_person_number.number_filter, CONTACTS_MATCH_EXACTLY, address);
+
+       ret = contacts_query_set_filter(query, filter);
+       ret = contacts_db_get_records_with_query(query, 0, 1, &personList);
 
-       int ret = contacts_svc_delete_phonelog(CTS_PLOG_DEL_BY_MSGID, msgId);
+       contacts_query_destroy(query);
+       contacts_filter_destroy(filter);
 
-       if (ret != CTS_SUCCESS)
-               MSG_DEBUG("contacts_svc_delete_phonelog() Failed!!! [%d]", ret);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_db_get_records_with_query() Error [%d]", ret);
+               contacts_list_destroy(personList, true);
+               return isblock;
+       }
+
+       ret = contacts_list_get_count(personList, &count);
+
+       if (count == 0 || ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("No Serach Data from Contact Service.");
+               contacts_list_destroy(personList, true);
+               return isblock;
+       } else if (ret == CONTACTS_ERROR_NONE && count > 0
+                       && blockModeType == 1) { // For All contacts allow in blocking mode.
+               isblock = false;
+       }
+
+       contacts_record_h person = NULL;
+
+       ret = contacts_list_get_current_record_p(personList, &person);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_list_get_current_record_p() Error [%d]", ret);
+               contacts_list_destroy(personList, true);
+               return isblock;
+       }
+
+       ret = contacts_record_get_int(person, _contacts_person_number.person_id, &personId);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_int() Error [%d]", ret);
+               contacts_list_destroy(personList, true);
+               return isblock;
+       }
+
+       MSG_DEBUG("personId [%d]", personId);
+
+       ret = contacts_record_get_bool(person, _contacts_person_number.is_favorite, &isFavorites);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_int() Error [%d]", ret);
+               contacts_list_destroy(personList, true);
+               return isblock;
+       }
 
-       return err;
+       contacts_list_destroy(personList, true);
+
+       switch (blockModeType)
+       {
+       case 2: // For Favorites allow in blocking mode.
+       {
+               if (isFavorites) isblock = false;
+               break;
+       }
+       case 3: // For Custom allow in blocking mode.
+       {
+               char *allowList = MsgSettingGetString(VCONFKEY_SETAPPL_BLOCKINGMODE_ALLOWED_CONTACT_LIST);
+               char *temp = NULL;
+               char *personIdStr = strtok_r (allowList," ,", &temp);
+               while (personIdStr != NULL)
+               {
+                       MSG_DEBUG("personIdStr [%s]", personIdStr);
+                       if (personId == atoi(personIdStr)) {
+                               MSG_DEBUG("In allow list.");
+                               isblock = false;
+                               break;
+                       }
+                       personIdStr = strtok_r (NULL, " ,", &temp);
+               }
+
+               if (allowList) {
+                       free(allowList);
+                       allowList = NULL;
+               }
+
+               break;
+       }
+       default: // Wrong blocking mode type.
+               break;
+       }
+
+       if (pisFavorites != NULL) *pisFavorites = isFavorites;
+
+       return isblock;
 }
 
 
-int MsgContactSVCBeginTrans()
+int MsgContactGetMinMatchDigit()
 {
-       return contacts_svc_begin_trans();
+       return phonenumberMinMatchDigit;
 }
 
 
-int MsgContactSVCEndTrans(bool bSuccess)
+void MsgConvertNumber(const char* pSrcNum, char* pDestNum, int destSize)
+{
+       int len;
+       const char *temp_number;
+
+       if ('+' == pSrcNum[0]) {
+               len = countryCodeLength(&pSrcNum[1]);
+               temp_number = pSrcNum + len +1;
+       } else if ('0' == pSrcNum[0]) {
+               if ('0' == pSrcNum[1]) {
+                       len = countryCodeLength(&pSrcNum[2]);
+                       temp_number = pSrcNum + len +2;
+               } else {
+                       temp_number = pSrcNum+1;
+               }
+       } else {
+               temp_number = pSrcNum;
+       }
+
+       strncpy(pDestNum, temp_number, destSize);
+}
+
+
+bool MsgIsNumber(const char* pSrc)
 {
-       return contacts_svc_end_trans(bSuccess);
+       int len = strlen(pSrc);
+
+       for(int i = 0; i < len; ++i){
+
+               if(i == 0 && pSrc[i] == '+')
+                       continue;
+
+               if(pSrc[i] < '0' || pSrc[i] >'9'){
+                       return false;
+               }
+       }
+
+       return true;
 }
+
index f4a157b..885923e 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
@@ -90,8 +90,6 @@ const char * MsgDbgCmdStr(MSG_CMD_TYPE_T cmdType)
                        return "MSG_CMD_GET_MSG_TYPE";
                case MSG_CMD_SUBMIT_REQ:
                        return "MSG_CMD_SUBMIT_REQ";
-               case MSG_CMD_CANCEL_REQ:
-                       return "MSG_CMD_CANCEL_REQ";
                case MSG_CMD_REG_SENT_STATUS_CB:
                        return "MSG_CMD_REG_SENT_STATUS_CB";
                case MSG_CMD_REG_STORAGE_CHANGE_CB:
@@ -166,10 +164,10 @@ const char * MsgDbgCmdStr(MSG_CMD_TYPE_T cmdType)
                        return "MSG_CMD_GET_SMSC_OPT";
                case MSG_CMD_GET_CB_OPT:
                        return "MSG_CMD_GET_CB_OPT";
-               case MSG_CMD_GET_SMS_SEND_OPT:
-                       return "MSG_CMD_GET_SMS_SEND_OPT";
 
 // 60
+               case MSG_CMD_GET_SMS_SEND_OPT:
+                       return "MSG_CMD_GET_SMS_SEND_OPT";
                case MSG_CMD_GET_MMS_SEND_OPT:
                        return "MSG_CMD_GET_MMS_SEND_OPT";
                case MSG_CMD_GET_MMS_RECV_OPT:
@@ -178,12 +176,17 @@ const char * MsgDbgCmdStr(MSG_CMD_TYPE_T cmdType)
                        return "MSG_CMD_GET_PUSH_MSG_OPT";
                case MSG_CMD_GET_VOICE_MSG_OPT:
                        return "MSG_CMD_GET_VOICE_MSG_OPT";
-               case MSG_CMD_GET_GENERAL_MSG_OPT:
-                       return "MSG_CMD_GET_GENERAL_MSG_OPT";
 
 // 65
+               case MSG_CMD_GET_GENERAL_MSG_OPT:
+                       return "MSG_CMD_GET_GENERAL_MSG_OPT";
+               case MSG_CMD_GET_MSG_SIZE_OPT:
+                       return "MSG_CMD_GET_MSG_SIZE_OPT";
                case MSG_CMD_SET_SMSC_OPT:
                        return "MSG_CMD_SET_SMSC_OPT";
+
+
+// 70
                case MSG_CMD_SET_CB_OPT:
                        return "MSG_CMD_SET_CB_OPT";
                case MSG_CMD_SET_SMS_SEND_OPT:
@@ -192,14 +195,49 @@ const char * MsgDbgCmdStr(MSG_CMD_TYPE_T cmdType)
                        return "MSG_CMD_SET_MMS_SEND_OPT";
                case MSG_CMD_SET_MMS_RECV_OPT:
                        return "MSG_CMD_SET_MMS_RECV_OPT";
-
-// 70
                case MSG_CMD_SET_PUSH_MSG_OPT:
                        return "MSG_CMD_SET_PUSH_MSG_OPT";
+
+// 75
                case MSG_CMD_SET_VOICE_MSG_OPT:
                        return "MSG_CMD_SET_VOICE_MSG_OPT";
                case MSG_CMD_SET_GENERAL_MSG_OPT:
                        return "MSG_CMD_SET_GENERAL_MSG_OPT";
+               case MSG_CMD_SET_MSG_SIZE_OPT:
+                       return "MSG_CMD_SET_MSG_SIZE_OPT";
+// 80
+               case MSG_CMD_REG_INCOMING_PUSH_MSG_CB:
+                       return "MSG_CMD_REG_INCOMING_PUSH_MSG_CB";
+               case MSG_CMD_PLG_INCOMING_PUSH_IND:
+                       return "MSG_CMD_PLG_INCOMING_PUSH_IND";
+               case MSG_CMD_REG_INCOMING_CB_MSG_CB:
+                       return "MSG_CMD_REG_INCOMING_CB_MSG_CB";
+               case MSG_CMD_PLG_INCOMING_CB_IND:
+                       return "MSG_CMD_PLG_INCOMING_CB_IND";
+               case MSG_CMD_ADD_PUSH_EVENT:
+                       return "MSG_CMD_ADD_PUSH_EVENT";
+//85
+               case MSG_CMD_DELETE_PUSH_EVENT:
+                       return "MSG_CMD_DELETE_PUSH_EVENT";
+               case MSG_CMD_UPDATE_PUSH_EVENT:
+                       return "MSG_CMD_UPDATE_PUSH_EVENT";
+               case MSG_CMD_DELETE_MESSAGE_BY_LIST :
+                       return "MSG_CMD_DELETE_MESSAGE_BY_LIST";
+               case MSG_CMD_SET_FILTER_ACTIVATION :
+                       return "MSG_CMD_SET_FILTER_ACTIVATION";
+               case MSG_CMD_ADD_SIM_MSG :
+                       return "MSG_CMD_ADD_SIM_MSG";
+//90
+               case MSG_CMD_PLG_RESEND_MESSAGE:
+                       return "MSG_CMD_PLG_RESEND_MESSAGE";
+               case MSG_CMD_REG_REPORT_MSG_INCOMING_CB:
+                       return "MSG_CMD_REG_REPORT_MSG_INCOMING_CB";
+#ifdef FEATURE_SMS_CDMA
+               case MSG_CMD_PLG_CHECK_UNIQUENESS:
+                       return "MSG_CMD_PLG_CHECK_UNIQUENESS";
+#endif
+               case MSG_CMD_UPDATE_IMSI:
+                       return "MSG_CMD_UPDATE_IMSI";
                default:
                        return "Unknown Command Type!!!";
        }
@@ -271,8 +309,6 @@ const char * MsgDbgEvtStr(MSG_EVENT_TYPE_T evtType)
                        return "MSG_EVENT_GET_MSG_TYPE";
                case MSG_EVENT_SUBMIT_REQ:
                        return "MSG_EVENT_SUBMIT_REQ";
-               case MSG_EVENT_CANCEL_REQ:
-                       return "MSG_EVENT_CANCEL_REQ";
                case MSG_EVENT_REG_SENT_STATUS_CB:
                        return "MSG_EVENT_REG_SENT_STATUS_CB";
                case MSG_EVENT_REG_STORAGE_CHANGE_CB:
@@ -347,10 +383,10 @@ const char * MsgDbgEvtStr(MSG_EVENT_TYPE_T evtType)
                        return "MSG_EVENT_GET_SMSC_OPT";
                case MSG_EVENT_GET_CB_OPT:
                        return "MSG_EVENT_GET_CB_OPT";
-               case MSG_EVENT_GET_SMS_SEND_OPT:
-                       return "MSG_EVENT_GET_SMS_SEND_OPT";
 
 // 60
+               case MSG_EVENT_GET_SMS_SEND_OPT:
+                       return "MSG_EVENT_GET_SMS_SEND_OPT";
                case MSG_EVENT_GET_MMS_SEND_OPT:
                        return "MSG_EVENT_GET_MMS_SEND_OPT";
                case MSG_EVENT_GET_MMS_RECV_OPT:
@@ -359,12 +395,15 @@ const char * MsgDbgEvtStr(MSG_EVENT_TYPE_T evtType)
                        return "MSG_EVENT_GET_PUSH_MSG_OPT";
                case MSG_EVENT_GET_VOICE_MSG_OPT:
                        return "MSG_EVENT_GET_VOICE_MSG_OPT";
-               case MSG_EVENT_GET_GENERAL_MSG_OPT:
-                       return "MSG_EVENT_GET_GENERAL_MSG_OPT";
 
 // 65
+               case MSG_EVENT_GET_GENERAL_MSG_OPT:
+                       return "MSG_EVENT_GET_GENERAL_MSG_OPT";
+               case MSG_EVENT_GET_MSG_SIZE_OPT:
+                       return "MSG_EVENT_GET_MSG_SIZE_OPT";
                case MSG_EVENT_SET_SMSC_OPT:
                        return "MSG_EVENT_SET_SMSC_OPT";
+// 70
                case MSG_EVENT_SET_CB_OPT:
                        return "MSG_EVENT_SET_CB_OPT";
                case MSG_EVENT_SET_SMS_SEND_OPT:
@@ -373,15 +412,51 @@ const char * MsgDbgEvtStr(MSG_EVENT_TYPE_T evtType)
                        return "MSG_EVENT_SET_MMS_SEND_OPT";
                case MSG_EVENT_SET_MMS_RECV_OPT:
                        return "MSG_EVENT_SET_MMS_RECV_OPT";
-
-// 70
                case MSG_EVENT_SET_PUSH_MSG_OPT:
                        return "MSG_EVENT_SET_PUSH_MSG_OPT";
+// 75
                case MSG_EVENT_SET_VOICE_MSG_OPT:
                        return "MSG_EVENT_SET_VOICE_MSG_OPT";
                case MSG_EVENT_SET_GENERAL_MSG_OPT:
                        return "MSG_EVENT_SET_GENERAL_MSG_OPT";
-
+               case MSG_EVENT_SET_MSG_SIZE_OPT:
+                       return "MSG_EVENT_SET_MSG_SIZE_OPT";
+//80
+               case MSG_EVENT_REG_INCOMING_PUSH_MSG_CB:
+                       return "MSG_EVENT_REG_INCOMING_PUSH_MSG_CB";
+               case MSG_EVENT_PLG_INCOMING_PUSH_MSG_IND:
+                       return "MSG_EVENT_PLG_INCOMING_PUSH_MSG_IND";
+               case MSG_EVENT_REG_INCOMING_CB_MSG_CB:
+                       return "MSG_EVENT_REG_INCOMING_CB_MSG_CB";
+               case MSG_EVENT_PLG_INCOMING_CB_MSG_IND:
+                       return "MSG_EVENT_PLG_INCOMING_CB_MSG_IND";
+               case MSG_EVENT_ADD_PUSH_EVENT:
+                       return "MSG_EVENT_ADD_PUSH_EVENT";
+//85
+               case MSG_EVENT_DELETE_PUSH_EVENT:
+                       return "MSG_EVENT_DELETE_PUSH_EVENT";
+               case MSG_EVENT_UPDATE_PUSH_EVENT:
+                       return "MSG_EVENT_UPDATE_PUSH_EVENT";
+               case MSG_EVENT_DELETE_MESSAGE_BY_LIST :
+                       return "MSG_EVENT_DELETE_MESSAGE_BY_LIST";
+               case MSG_EVENT_SET_FILTER_ACTIVATION :
+                       return "MSG_EVENT_SET_FILTER_ACTIVATION";
+               case MSG_EVENT_ADD_SIM_MSG :
+                       return "MSG_EVENT_ADD_SIM_MSG";
+
+//90
+               case MSG_EVENT_PLG_RESEND_MESSAGE:
+                       return "MSG_EVENT_PLG_RESEND_MESSAGE";
+               case MSG_EVENT_REG_REPORT_MSG_INCOMING_CB:
+                       return "MSG_EVENT_REG_REPORT_MSG_INCOMING_CB";
+               case MSG_EVENT_PLG_REPORT_MSG_INCOMING_IND:
+                       return "MSG_EVENT_PLG_REPORT_MSG_INCOMING_IND";
+#ifdef FEATURE_SMS_CDMA
+               case MSG_EVENT_PLG_CHECK_UNIQUENESS:
+                       return "MSG_EVENT_PLG_CHECK_UNIQUENESS";
+#endif
+               case MSG_EVENT_UPDATE_IMSI:
+                       return "MSG_EVENT_UPDATE_IMSI";
                default:
                        return "Unknown Event Type!!!";
        }
index 248738d..835100d 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
 #include <fcntl.h>
 #include <unistd.h>
 #include <errno.h>
+
+#if MSG_DRM_SUPPORT
+
 #include <drm_client_types.h>
 #include <drm_client.h>
 
+#endif //MSG_DRM_SUPPORT
+
 #define MSG_MAX_DRM_FILE_PATH MSG_FILEPATH_LEN_MAX
 
 bool MsgDrmRegisterFile(MSG_DRM_OPENMODE eMode, char *pBuffer, int nSize)
 {
+#if MSG_DRM_SUPPORT
        if (eMode == MSG_MODE_STREAM) {
                MSG_DEBUG("Fail(eMode == MSG_MODE_STREAM)");
                return false;
@@ -61,15 +67,19 @@ bool MsgDrmRegisterFile(MSG_DRM_OPENMODE eMode, char *pBuffer, int nSize)
 
        eDRMResult = drm_process_request(request_type, pBuffer, NULL);
        if (DRM_RETURN_SUCCESS != eDRMResult) {
-               MSG_DEBUG("drm_process_request is failed : %d", eDRMResult);
+               MSG_DEBUG("drm_process_request is failed : 0x%x", eDRMResult);
                return false;
        }
        MSG_END();
        return true;
+#else
+       return false;
+#endif
 }
 
 bool MsgDrmUnregisterFile(char *szFilename)
 {
+#if MSG_DRM_SUPPORT
        if (szFilename == NULL) {
                MSG_DEBUG("[Error] szFilename is NULL");
                return false;
@@ -86,10 +96,14 @@ bool MsgDrmUnregisterFile(char *szFilename)
        }
 
        return true;
+#else
+       return false;
+#endif
 }
 
 bool MsgDrmIsDrmFile(const char *szFilePath)
 {
+#if MSG_DRM_SUPPORT
        drm_bool_type_e isDrm;
        int eDRMResult = drm_is_drm_file(szFilePath, &isDrm);
 
@@ -99,16 +113,144 @@ bool MsgDrmIsDrmFile(const char *szFilePath)
        }
 
        return true;
+#else
+       return false;
+#endif
 }
 
 /*Added to convert the .dm files in to .dcf files since our platform supports only .dcf :: Start*/
 bool MsgDrmConvertDmtoDcfType(char *inputFile, char *outputFile)
 {
+#if MSG_DRM_SUPPORT
+       if ((NULL == inputFile) || (NULL == outputFile)) {
+               MSG_DEBUG("Invalid Input parameters");
+               return false;
+       }
+
+       if (strstr(inputFile, ".dm")) {
+               MSG_SEC_DEBUG("Current File extension is .dm %s", inputFile);
+               int ret;
+
+               FILE *fp = MsgOpenFile(inputFile, "rb");//Check fp
+
+               if (fp == NULL) {
+                       MSG_DEBUG("[File Open Fail(Errno=%d)][ErrStr=%s]", errno, strerror(errno));
+                       strncpy(outputFile, inputFile, MSG_MAX_DRM_FILE_PATH);
+                       return false;
+               }
+
+               if (MsgFseek(fp, 0L, SEEK_END) < 0) {
+                       MsgCloseFile(fp);
+                       MSG_DEBUG("MsgFseek() returns negative value!!!");
+                       return false;
+               }
+               long retVal = MsgFtell(fp);
+
+               if (retVal < 0) {
+                       MsgCloseFile(fp);
+                       MSG_DEBUG("ftell() returns negative value: [%ld]!!!", retVal);
+                       strncpy(outputFile, inputFile, MSG_MAX_DRM_FILE_PATH);
+                       return false;
+               }
+
+               unsigned long bufLen = retVal;
+               MSG_DEBUG("fopen buffer len = %d", bufLen);
+               if (MsgFseek(fp, 0, SEEK_SET) < 0) {
+                       MsgCloseFile(fp);
+                       MSG_DEBUG("MsgFseek() returns negative value!!!");
+                       return false;
+               }
+
+               unsigned char *buffer = (unsigned char*)malloc(bufLen);
+               int readed_size = 0;
+               int pathLen = strlen(inputFile);
+
+               if (buffer == NULL) {
+                       MsgCloseFile(fp);
+                       MSG_DEBUG("malloc is failed ");
+                       strncpy(outputFile, inputFile, MSG_MAX_DRM_FILE_PATH);
+                       return false;
+               }
+
+               strncpy(outputFile, inputFile, pathLen - 2);
+               strncat(outputFile, "dcf", 3);
+
+               readed_size = MsgReadFile(buffer, 1, bufLen, fp);//Check for error
+               MSG_DEBUG("fread read size = %d", readed_size);
+               if (readed_size == 0) {
+                       MsgCloseFile(fp);
+                       free(buffer);
+                       MSG_DEBUG("MsgReadFile returns 0");
+                       return false;
+               }
+
+               DRM_TRUSTED_CONVERT_HANDLE hConvert = NULL;
+               drm_trusted_opn_conv_info_s trusted_open_conv_input;
+               bzero(&trusted_open_conv_input, sizeof(drm_trusted_opn_conv_info_s));
+
+               strncpy(trusted_open_conv_input.filePath, outputFile, DRM_TRUSTED_MAX_FILEPATH_LEN-1);
+               trusted_open_conv_input.install_RO = DRM_TRUSTED_TRUE;
+
+               ret = drm_trusted_open_convert(&trusted_open_conv_input, &hConvert);
+               if (ret != DRM_RETURN_SUCCESS) {
+                       free(buffer);
+                       MsgCloseFile(fp);
+                       MSG_DEBUG("drm_trusted_open_convert() return = failed (0x%x)", ret);
+                       remove(outputFile);
+                       strncpy(outputFile, inputFile, MSG_MAX_DRM_FILE_PATH);
+                       return false;
+               }
+
+               drm_trusted_write_conv_info_s trusted_write_conv_input;
+               drm_trusted_write_conv_resp_s trusted_write_conv_output;
+
+               bzero(&trusted_write_conv_input, sizeof(drm_trusted_write_conv_info_s));
+               bzero(&trusted_write_conv_output, sizeof(drm_trusted_write_conv_resp_s));
+
+               trusted_write_conv_input.data = buffer;
+               trusted_write_conv_input.data_len = bufLen;
+
+               /*We can call drm_trusted_write_convert in loop if file size is large*/
+               ret = drm_trusted_write_convert(&trusted_write_conv_input, &trusted_write_conv_output, hConvert);
+               if (ret != DRM_RETURN_SUCCESS) {
+                       free(buffer);
+                       MsgCloseFile(fp);
+                       MSG_DEBUG("drm_trusted_write_convert() return = failed (0x%x)", ret);
+                       remove(outputFile);
+                       strncpy(outputFile, inputFile, MSG_MAX_DRM_FILE_PATH);
+                       return false;
+               }
+
+               ret = drm_trusted_close_convert(&hConvert);
+               if (ret != DRM_RETURN_SUCCESS) {
+                       free(buffer);
+                       MsgCloseFile(fp);
+                       MSG_DEBUG("drm_trusted_close_convert() return = failed (0x%x)", ret);
+                       remove(outputFile);
+                       strncpy(outputFile, inputFile, MSG_MAX_DRM_FILE_PATH);
+                       return false;
+               }
+
+               MsgCloseFile(fp);
+               free(buffer);
+       } else {
+               MSG_DEBUG("Current File extension is not .dm");
+
+               MSG_DEBUG("inputFile = (%s)", inputFile);
+               strncpy(outputFile, inputFile, MSG_MAX_DRM_FILE_PATH);
+
+               return false;
+       }
+
+       return true;
+#else
        return true;
+#endif
 }
 
 bool MsgDrmGetDrmType(const char *szFileName, MSG_DRM_TYPE *eDRMType)
 {
+#if MSG_DRM_SUPPORT
        if (szFileName == NULL || eDRMType == NULL) {
                MSG_DEBUG("Param is NULL");
                return false;
@@ -152,10 +294,14 @@ bool MsgDrmGetDrmType(const char *szFileName, MSG_DRM_TYPE *eDRMType)
        }
 
        return true;
+#else
+       return false;
+#endif
 }
 
 bool MsgDrmGetMimeTypeEx(const char *szFileName, char *szMimeType, int nMimeTypeLen)
 {
+#if MSG_DRM_SUPPORT
        if (!szFileName || !szMimeType || !nMimeTypeLen) {
                MSG_DEBUG("param is NULL");
                return false;
@@ -178,10 +324,14 @@ bool MsgDrmGetMimeTypeEx(const char *szFileName, char *szMimeType, int nMimeType
        }
 
        return true;
+#else
+       return false;
+#endif
 }
 
 bool MsgDrmGetContentID(const char *szFileName, char *szContentID, int nContentIDLen)
 {
+#if MSG_DRM_SUPPORT
        if (!szFileName || !szContentID || !nContentIDLen) {
                MSG_DEBUG("param is NULL");
                return false;
@@ -189,14 +339,14 @@ bool MsgDrmGetContentID(const char *szFileName, char *szContentID, int nContentI
 
        char strTemp[MSG_MAX_DRM_FILE_PATH + 1] = {0,};
 
-       strncpy(strTemp, szFileName, sizeof(strTemp));
+       strncpy(strTemp, szFileName, sizeof(strTemp)-1);
 
        drm_content_info_s  content_info;
        memset(&content_info, 0x00, sizeof(drm_content_info_s));
 
        int result = drm_get_content_info(strTemp, &content_info);
        if (DRM_RETURN_SUCCESS == result) {
-               MSG_DEBUG("contentID = %s", content_info.content_id);
+               MSG_SEC_DEBUG("contentID = %s", content_info.content_id);
         snprintf(szContentID, nContentIDLen, "%s", content_info.content_id);
        } else {
                MSG_DEBUG("drm_get_content_info is failed %d", result);
@@ -204,5 +354,39 @@ bool MsgDrmGetContentID(const char *szFileName, char *szContentID, int nContentI
        }
 
        return true;
+#else
+       return false;
+#endif
 }
 
+bool MsgDrmCheckRingtone(const char *ringtonePath)
+{
+#if MSG_DRM_SUPPORT
+       bool ret = false;
+
+       if (ringtonePath) {
+               drm_bool_type_e allowed = DRM_UNKNOWN;
+               drm_action_allowed_data_s data;
+               memset(&data, 0x00, sizeof(drm_action_allowed_data_s));
+               strncpy(data.file_path, ringtonePath, strlen(ringtonePath));
+               data.data = (int)DRM_SETAS_RINGTONE;
+
+               int res = drm_is_action_allowed(DRM_HAS_VALID_SETAS_STATUS, &data, &allowed);
+
+               if (res == DRM_RETURN_SUCCESS) {
+                       if (allowed == DRM_TRUE) {
+                               MSG_DEBUG("allowed [DRM_TRUE]");
+                               ret = true;
+                       }
+               } else {
+                       MSG_DEBUG("fail to drm_is_action_allowed [0x%x]", res);
+               }
+       } else {
+               MSG_DEBUG("ringtonePath is NULL.");
+       }
+
+       return ret;
+#else
+       return false;
+#endif
+}
index 28c0bfe..556c3f6 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgException.h"
index 248623d..7ad2f62 100755 (executable)
@@ -1,26 +1,25 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
 
-#include <pmapi.h>
-
 #include "MsgDebug.h"
 #include "MsgUtilStorage.h"
 #include "MsgGconfWrapper.h"
+#include "MsgException.h"
 
 #ifdef USE_GCONF
 
@@ -30,14 +29,10 @@ MSG_GOBJECT_CLIENT_S* pClient = NULL;
 
 #endif
 
-bool bAutoReject = false;
+int autoReject = 0;
 bool bUnknownAutoReject = false;
 
 
-/*==================================================================================================
-                                     DEFINES
-==================================================================================================*/
-
 
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
@@ -50,13 +45,14 @@ static void MsgVconfCB(keynode_t *key, void* data)
        if (!keyStr)
                return;
 
-       if (!strcmp(keyStr, VCONFKEY_CISSAPPL_AUTO_REJECT_BOOL)) {
-               bAutoReject = vconf_keynode_get_bool(key);
-               MSG_DEBUG("[%s] key CB called. set to [%d].", VCONFKEY_CISSAPPL_AUTO_REJECT_BOOL, bAutoReject);
-       } else if (!strcmp(keyStr, VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL)) {
+       if (!g_strcmp0(keyStr, VCONFKEY_CISSAPPL_AUTO_REJECT_INT)) {
+               autoReject = vconf_keynode_get_int(key);
+               MSG_DEBUG("[%s] key CB called. set to [%d].", VCONFKEY_CISSAPPL_AUTO_REJECT_INT, autoReject);
+       } else if (!g_strcmp0(keyStr, VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL)) {
                bUnknownAutoReject = vconf_keynode_get_bool(key);
                MSG_DEBUG("[%s] key CB called. set to [%d].", VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL, bUnknownAutoReject);
-       } else {
+       }
+       else {
                MSG_DEBUG("key did not match.");
        }
 }
@@ -194,15 +190,23 @@ msg_error_t MsgSettingHandleNewMsg(int SmsCnt, int MmsCnt)
                return MSG_ERR_SET_SETTING;
        }
 
-       if (SmsCnt == 0 && MmsCnt == 0)
-       {
-               MSG_DEBUG("No New Message.");
-       }
-       else
-       {
-               MSG_DEBUG("New Message.");
-               pm_change_state(LCD_NORMAL);
-       }
+//     if (SmsCnt == 0 && MmsCnt == 0)
+//     {
+//             MSG_DEBUG("No New Message.");
+//     }
+//     else
+//     {
+//             MSG_DEBUG("New Message.");
+//
+//             bool bNotification = true;
+//
+//             if (MsgSettingGetBool(MSG_SETTING_NOTIFICATION, &bNotification) != MSG_SUCCESS) {
+//                     MSG_DEBUG("MsgSettingGetBool is failed.");
+//             }
+//
+//             if (bNotification)
+//                     MsgChangePmState();
+//     }
 
        MSG_END();
 
@@ -218,20 +222,13 @@ msg_error_t MsgSettingSetIndicator(int SmsCnt, int MmsCnt)
        if (MsgSettingSetInt(VCONFKEY_MESSAGE_RECV_MMS_STATE, MmsCnt) != 0)
                return MSG_ERR_SET_SETTING;
 
-       /* Not used currently.
-       int sumCnt = SmsCnt + MmsCnt;
-
-       if (MsgSettingSetInt(MSG_UNREAD_CNT, sumCnt) != 0)
-               return MSG_ERR_SET_SETTING;
-       */
-
        return MSG_SUCCESS;
 }
 
 
-bool MsgSettingGetAutoReject()
+int MsgSettingGetAutoReject()
 {
-       return bAutoReject;
+       return autoReject;
 }
 
 bool MsgSettingGetUnknownAutoReject()
@@ -239,38 +236,37 @@ bool MsgSettingGetUnknownAutoReject()
        return bUnknownAutoReject;
 }
 
-
-void MsgSettingRegVconfCB()
+void MsgSettingRegVconfCBCommon(const char *pKey, _vconf_change_cb pCb)
 {
-       // Set default values.
-       MsgSettingGetBool(VCONFKEY_CISSAPPL_AUTO_REJECT_BOOL, &bAutoReject);
-       MsgSettingGetBool(VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL, &bUnknownAutoReject);
-
-       if (vconf_notify_key_changed(VCONFKEY_CISSAPPL_AUTO_REJECT_BOOL, MsgVconfCB, NULL) < 0) {
-               MSG_DEBUG("Fail to regist vconf CB with [%s]", VCONFKEY_CISSAPPL_AUTO_REJECT_BOOL);
+       if (vconf_notify_key_changed(pKey, pCb, NULL) < 0) {
+               MSG_DEBUG("Fail to regist vconf CB with [%s]", pKey);
+       } else {
+               MSG_DEBUG("Success to regist vconf CB with [%s]", pKey);
        }
+}
 
-       if (vconf_notify_key_changed(VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL, MsgVconfCB, NULL) < 0) {
-               MSG_DEBUG("Fail to regist vconf CB with [%s]", VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL);
+void MsgSettingRemoveVconfCBCommon(const char *pKey, _vconf_change_cb pCb)
+{
+       if (vconf_ignore_key_changed(pKey, pCb) < 0) {
+               MSG_DEBUG("Fail to remove vconf CB with [%s]", pKey);
+       } else {
+               MSG_DEBUG("Success to remove vconf CB with [%s]", pKey);
        }
 }
 
-void MsgSettingRemoveVconfCB()
+
+void MsgSettingRegVconfCB()
 {
-       if (vconf_ignore_key_changed(VCONFKEY_CISSAPPL_AUTO_REJECT_BOOL, MsgVconfCB) < 0) {
-               MSG_DEBUG("Fail to regist vconf CB with [%s]", VCONFKEY_CISSAPPL_AUTO_REJECT_BOOL);
-       }
+       // Set default values.
+       autoReject = MsgSettingGetInt(VCONFKEY_CISSAPPL_AUTO_REJECT_INT);
+       MsgSettingGetBool(VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL, &bUnknownAutoReject);
 
-       if (vconf_ignore_key_changed(VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL, MsgVconfCB) < 0) {
-               MSG_DEBUG("Fail to regist vconf CB with [%s]", VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL);
-       }
+       MsgSettingRegVconfCBCommon(VCONFKEY_CISSAPPL_AUTO_REJECT_INT, MsgVconfCB);
+       MsgSettingRegVconfCBCommon(VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL, MsgVconfCB);
 }
 
-void MsgSettingRegVconfCBCommon(const char *pKey, _vconf_change_cb pCb)
+void MsgSettingRemoveVconfCB()
 {
-       if (vconf_notify_key_changed(pKey, pCb, NULL) < 0) {
-               MSG_DEBUG("Fail to regist vconf CB with [%s]", pKey);
-       } else {
-               MSG_DEBUG("Success to regist vconf CB with [%s]", pKey);
-       }
+       MsgSettingRemoveVconfCBCommon(VCONFKEY_CISSAPPL_AUTO_REJECT_INT, MsgVconfCB);
+       MsgSettingRemoveVconfCBCommon(VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL, MsgVconfCB);
 }
index 940625c..0a6f571 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <sys/socket.h>
 #include <sys/ioctl.h>
 #include <sys/types.h>
 #include <sys/stat.h>
+#include <sys/smack.h>
 
 #include <errno.h>
 #include <unistd.h>
 #include <errno.h>
+#include <glib.h>
 
 #include "MsgDebug.h"
 #include "MsgException.h"
@@ -49,7 +51,7 @@ msg_error_t MsgIpcClientSocket::connect(const char* path)
        sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
 
        if (sockfd < 0) {
-               THROW(MsgException::IPC_ERROR,"socket not opened %s",strerror(errno));
+               THROW(MsgException::IPC_ERROR,"socket not opened %s",g_strerror(errno));
        }
 
        struct sockaddr_un serverSA = {0, };
@@ -61,21 +63,28 @@ msg_error_t MsgIpcClientSocket::connect(const char* path)
        int len = strlen(serverSA.sun_path) + sizeof(serverSA.sun_family);
 
        if (::connect(sockfd, (struct sockaddr *)&serverSA, len) == CUSTOM_SOCKET_ERROR) {
-               THROW(MsgException::IPC_ERROR,"cannot connect server %s", strerror(errno));
+               if(errno == EACCES)
+                       THROW(MsgException::SECURITY_ERROR,"cannot connect server %s", g_strerror(errno));
+               else
+                       THROW(MsgException::IPC_ERROR,"cannot connect server %s", g_strerror(errno));
        }
 
        /* add fd for select() */
        addfd(sockfd);
 
+       if (!wait_for_reply()) {
+               THROW(MsgException::IPC_ERROR, "wait_for_reply() error");
+       }
+
        /* read remote fd for reg func */
        char *rfd = NULL;
-       AutoPtr<char> wrap(&rfd);
-       int rlen;
+       unique_ptr<char*, void(*)(char**)> wrap(&rfd, unique_ptr_deleter);
+       unsigned int rlen;
 
        read(&rfd, &rlen);
 
        if (rfd == NULL) {
-               THROW(MsgException::IPC_ERROR,"rfd is NULL %s", strerror(errno));
+               THROW(MsgException::IPC_ERROR,"rfd is NULL %s", g_strerror(errno));
        }
 
        memcpy(&remotefd, rfd, sizeof(rlen));
@@ -117,19 +126,20 @@ void MsgIpcClientSocket::addfd(int fd)
                maxfd = fd;
 }
 
-int MsgIpcClientSocket::writen (const char *buf, int len)
+int MsgIpcClientSocket::writen (const char *buf, unsigned int len)
 {
-       int nleft, nwrite;
+       unsigned int nleft;
+       int nwrite;
 
        nleft = len;
        while (nleft > 0) {
                nwrite = ::write(sockfd, (const void*) buf, nleft);
                if (nwrite < 0) {
-                       MSG_FATAL("writen: sockfd [%d] error [%s]",  sockfd, strerror(errno));
+                       MSG_FATAL("writen: sockfd [%d] error [%s]",  sockfd, g_strerror(errno));
                        return nwrite;
-               }
-               else if (nwrite == 0)
+               } else if (nwrite == 0) {
                        break;
+               }
 
                nleft -= nwrite;
                buf += nwrite;
@@ -137,14 +147,14 @@ int MsgIpcClientSocket::writen (const char *buf, int len)
        return (len-nleft);
 }
 
-int MsgIpcClientSocket::write(const char* buf, int len)
+int MsgIpcClientSocket::write(const char* buf, unsigned int len)
 {
        if (sockfd < 0) {
                MSG_FATAL("sockfd is not opened [%d]", sockfd);
                return CUSTOM_SOCKET_ERROR;
        }
 
-       if (!buf || len <= 0) {
+       if (!buf || len == 0) {
                MSG_FATAL("buf[%p]      and len[%d] MUST NOT NULL", buf, len);
                return CUSTOM_SOCKET_ERROR;
        }
@@ -158,7 +168,7 @@ int MsgIpcClientSocket::write(const char* buf, int len)
 
        /* send the data in subsequence */
        n = writen(buf, len);
-       if (n != len) {
+       if ((unsigned int)n != len) {
                MSG_FATAL("WARNING: write data_size[%d] not matched [%d]", n, len);
                return CUSTOM_SOCKET_ERROR;
        }
@@ -166,29 +176,64 @@ int MsgIpcClientSocket::write(const char* buf, int len)
        return len;
 }
 
-int MsgIpcClientSocket::readn( char *buf, int len )
+int MsgIpcClientSocket::readn( char *buf, unsigned int len )
 {
-       int nleft, nread;
+       unsigned int nleft;
+       int nread;
 
        nleft = len;
        while (nleft > 0) {
                nread = ::read(sockfd, (void*) buf, nleft);
                if (nread < 0) {
-                       MSG_FATAL("WARNING read value %d: %s", nread, strerror(errno));
+                       MSG_FATAL("WARNING read value %d: %s", nread, g_strerror(errno));
                        return nread;
-               }
-               else if( nread == 0 )
+               } else if( nread == 0 ) {
                        break;
+               }
 
                nleft -= nread;
                buf += nread;
        }
+
        return (len-nleft);
 }
 
+bool MsgIpcClientSocket::wait_for_reply ()
+{
+       int err = -1;
+       fd_set fds;
+       struct timeval tv;
+
+       if (sockfd < 0) {
+               MSG_FATAL ("Invalid file description : [%d]", sockfd);
+               return false;
+       }
+
+       FD_ZERO(&fds);
+       FD_SET(sockfd, &fds);
+
+       tv.tv_sec  = 5; /* should be tuned */
+       tv.tv_usec = 0;
+
+       MSG_DEBUG ("wait for response [%d]", sockfd);
+       err = select(sockfd + 1, &fds, NULL, NULL, &tv);
+       if (err == -1) {
+               MSG_FATAL("select error[%d] fd[%d]", errno, sockfd);
+               return false;
+       }
+       else if (err == 0) {
+               MSG_FATAL ("select timeout fd[%d]", sockfd);
+               return false;
+       }
+
+       if (FD_ISSET(sockfd, &fds)) return true;
+
+       return false;
+}
+
 
 /* what if the buf is shorter than data? */
-int MsgIpcClientSocket::read(char** buf, int* len)
+int MsgIpcClientSocket::read(char** buf, unsigned int* len)
 {
        if (sockfd < 0) {
                MSG_FATAL("socket is not opened [%d]", sockfd);
@@ -200,29 +245,31 @@ int MsgIpcClientSocket::read(char** buf, int* len)
                return CUSTOM_SOCKET_ERROR;
        }
 
+       *len = 0;
+       char clen[sizeof(int)] = {0};
+
        /* read the data size first */
-       int n = readn((char*) len, sizeof(int));
+       int n = readn(clen, sizeof(int));
+       memcpy(len, clen, sizeof(int));
+
        if (n == CLOSE_CONNECTION_BY_SIGNAL) { /* if msgfw gets down, it signals to all IPC clients */
                MSG_FATAL("sockfd [%d] CLOSE_CONNECTION_BY_SIGNAL", sockfd);
                return n;
        }
-
        else if (n != sizeof(int)) {
                MSG_FATAL("WARNING: read header_size[%d] not matched [%d]", n, sizeof(int));
                return CUSTOM_SOCKET_ERROR;
        }
 
        /*  read the data in subsequence */
-       if ((*len) > 0) {
-               unsigned int ulen = (unsigned int)*len;
-               *buf = new char[ulen+1];
-               bzero(*buf, ulen+1);
-               n = readn(*buf, ulen);
+       unsigned int ulen = (unsigned int)*len;
+       *buf = new char[ulen];
+       bzero(*buf, ulen);
+       n = readn(*buf, ulen);
 
-               if (n !=  ulen) {
-                       MSG_FATAL("WARNING: read data_size [%d] not matched [%d]", n, ulen);
-                       return CUSTOM_SOCKET_ERROR;
-               }
+       if ((unsigned int)n !=  ulen) {
+               MSG_FATAL("WARNING: read data_size [%d] not matched [%d]", n, ulen);
+               return CUSTOM_SOCKET_ERROR;
        }
 
        return n;
@@ -269,7 +316,7 @@ msg_error_t MsgIpcServerSocket::open(const char* path)
        sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
 
        if (sockfd == CUSTOM_SOCKET_ERROR) {
-               MSG_FATAL("socket failed: %s", strerror(errno));
+               MSG_FATAL("socket failed: %s", g_strerror(errno));
                return MSG_ERR_UNKNOWN;
        }
 
@@ -285,8 +332,8 @@ msg_error_t MsgIpcServerSocket::open(const char* path)
 
        int len = strlen(local.sun_path) + sizeof(local.sun_family);
 
-       if (bind(sockfd, (struct sockaddr *)&local, len) == CUSTOM_SOCKET_ERROR) {
-               MSG_FATAL("bind: %s", strerror(errno));
+       if (::bind(sockfd, (struct sockaddr *)&local, len) == CUSTOM_SOCKET_ERROR) {
+               MSG_FATAL("bind: %s", g_strerror(errno));
                return MSG_ERR_UNKNOWN;
        }
 
@@ -304,12 +351,22 @@ msg_error_t MsgIpcServerSocket::open(const char* path)
        mode_t sock_mode = (S_IRWXU | S_IRWXG | S_IRWXO); /* has 777 permission */
 
        if (chmod(path, sock_mode) == CUSTOM_SOCKET_ERROR) {
-               MSG_FATAL("chmod: %s", strerror(errno));
+               MSG_FATAL("chmod: %s", g_strerror(errno));
+               return MSG_ERR_UNKNOWN;
+       }
+#if 0
+       if (smack_setlabel(path, "*", SMACK_LABEL_IPIN) != 0) {
+               MSG_FATAL("smack_setlabel error");
                return MSG_ERR_UNKNOWN;
        }
 
+       if (smack_setlabel(path, "@", SMACK_LABEL_IPOUT) != 0) {
+               MSG_FATAL("smack_setlabel error");
+               return MSG_ERR_UNKNOWN;
+       }
+#endif
        if (listen(sockfd, CUSTOM_SOCKET_BACKLOG) == CUSTOM_SOCKET_ERROR) {
-               MSG_FATAL("listen: %s", strerror(errno));
+               MSG_FATAL("listen: %s", g_strerror(errno));
                return MSG_ERR_UNKNOWN;
        }
 
@@ -334,7 +391,7 @@ msg_error_t MsgIpcServerSocket::accept()
        int t = sizeof(remote);
        int fd = ::accept(sockfd, (struct sockaddr *)&remote, (socklen_t*) &t);
        if (fd < 0) {
-               MSG_FATAL("accept: %s", strerror(errno));
+               MSG_FATAL("accept: %s", g_strerror(errno));
                return MSG_ERR_UNKNOWN;
        }
 
@@ -379,15 +436,16 @@ void MsgIpcServerSocket::close(int fd)
        MSG_END();
 }
 
-int MsgIpcServerSocket::readn( int fd, char *buf, int len )
+int MsgIpcServerSocket::readn( int fd, char *buf, unsigned int len )
 {
-       int nleft, nread;
+       size_t nleft;
+       int nread;
 
-       nleft = len;
+       nleft = (size_t)len;
        while (nleft > 0) {
                nread = ::read(fd, (void*)buf, nleft);
                if (nread < 0) {
-                       MSG_FATAL("read: %s", strerror(errno));
+                       MSG_FATAL("read: %s", g_strerror(errno));
                        return nread;
                }
                else if (nread == 0)
@@ -411,8 +469,12 @@ int MsgIpcServerSocket::read(int fd, char** buf, int* len )
                return CUSTOM_SOCKET_ERROR;
        }
 
+       *len = 0;
+       char clen[sizeof(int)] = {0};
+
        /* read the data size first */
-       int n = readn(fd, (char*) len, sizeof(int));
+       int n = readn(fd, clen, sizeof(int));
+       memcpy(len, clen, sizeof(int));
 
        if (n == CLOSE_CONNECTION_BY_SIGNAL) {
                MSG_FATAL("fd %d CLOSE_CONNECTION_BY_SIGNAL", fd);
@@ -425,17 +487,18 @@ int MsgIpcServerSocket::read(int fd, char** buf, int* len )
        }
 
        MSG_DEBUG("MsgLen %d", *len);
+
        if (*len == CLOSE_CONNECTION_BY_USER)
                return *len;
 
-       if ((*len) > 0) {
-               /* read the data in subsequence */
+       /* read the data in subsequence */
+       if (*len > 0) {
                unsigned int ulen = (unsigned int)*len;
                *buf = new char[ulen+1];
                bzero(*buf, ulen+1);
                n = readn(fd, *buf, ulen);
 
-               if (n != ulen) {
+               if ((unsigned int)n != ulen) {
                        MSG_FATAL("WARNING: read data_size [%d] not matched [%d]", n, ulen);
                        return CUSTOM_SOCKET_ERROR;
                }
@@ -444,9 +507,10 @@ int MsgIpcServerSocket::read(int fd, char** buf, int* len )
        return n;
 }
 
-int MsgIpcServerSocket::writen(int fd, const char *buf, int len)
+int MsgIpcServerSocket::writen(int fd, const char *buf, unsigned int len)
 {
-       int nleft, nwrite;
+       unsigned int nleft;
+       int nwrite;
 
        nleft = len;
 
@@ -456,13 +520,11 @@ int MsgIpcServerSocket::writen(int fd, const char *buf, int len)
                nwrite = ::send(fd, (const void*) buf, nleft, MSG_NOSIGNAL|MSG_DONTWAIT);
 
                if (nwrite < 0) {
-                       MSG_FATAL("write: %s", strerror(errno));
+                       MSG_FATAL("write: %s", g_strerror(errno));
                        return nwrite;
-               }
-               else if (nwrite == 0) { /* Nothing is send. */
+               } else if (nwrite == 0) { /* Nothing is send. */
                        break;
-               }
-               else {
+               } else {
                        nleft -= nwrite;
                        buf += nwrite;
                }
@@ -472,7 +534,7 @@ int MsgIpcServerSocket::writen(int fd, const char *buf, int len)
 }
 
 
-int MsgIpcServerSocket::write(int fd, const char* buf, int len)
+int MsgIpcServerSocket::write(int fd, const char* buf, unsigned int len)
 {
        MSG_BEGIN();
 
@@ -496,7 +558,7 @@ int MsgIpcServerSocket::write(int fd, const char* buf, int len)
 
        MSG_DEBUG("Writing %d bytes", n);
 
-       if (n != len) {
+       if ((unsigned int)n != len) {
                MSG_FATAL("Written byte (%d) is not matched to input byte (%d)", n, len);
                return CUSTOM_SOCKET_ERROR;
        }
diff --git a/utils/MsgJsonParser.cpp b/utils/MsgJsonParser.cpp
new file mode 100755 (executable)
index 0000000..2c1a8cb
--- /dev/null
@@ -0,0 +1,553 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <glib.h>
+#include <glib-object.h>
+#include <json-glib/json-glib.h>
+#include <json-glib/json-gobject.h>
+#include "MsgJsonParser.h"
+
+static char root_key[5] = "root";
+
+int msg_json_parser_get_value(msg_json_parser_object *json_obj)
+{
+       GValue value = { 0 };
+
+       /*Input params validation */
+       if (json_obj == NULL) {
+               MSG_DEBUG("Invalid Input Parameters");
+               return -1;
+       }
+
+       json_node_get_value((JsonNode *) json_obj->value, &value);
+
+       switch (json_node_get_value_type((JsonNode *) json_obj->value)) {
+       case G_TYPE_STRING:
+               {
+                       json_obj->type = MSG_JSON_PARSER_STRING;
+                       json_obj->value = (void *)g_value_get_string(&value);
+                       json_obj->number_value = 0;
+               }
+               break;
+       case G_TYPE_INT:
+               {
+                       json_obj->type = MSG_JSON_PARSER_INT;
+                       json_obj->value = NULL;
+                       json_obj->number_value = g_value_get_int(&value);
+               }
+               break;
+       case G_TYPE_UINT:
+               {
+                       json_obj->type = MSG_JSON_PARSER_UINT;
+                       json_obj->value = NULL;
+                       json_obj->number_value = g_value_get_uint(&value);
+               }
+               break;
+       case G_TYPE_BOOLEAN:
+               {
+                       json_obj->type = MSG_JSON_PARSER_BOOLEAN;
+                       json_obj->value = NULL;
+                       json_obj->number_value = g_value_get_boolean(&value);
+               }
+               break;
+       case G_TYPE_INT64:
+               {
+                       json_obj->type = MSG_JSON_PARSER_INT;
+                       json_obj->value = NULL;
+                       json_obj->number_value = g_value_get_int64(&value);
+               }
+               break;
+       case G_TYPE_UINT64:
+               {
+                       json_obj->type = MSG_JSON_PARSER_UINT;
+                       json_obj->value = NULL;
+                       json_obj->number_value = g_value_get_uint64(&value);
+               }
+               break;
+       case G_TYPE_DOUBLE:
+               {
+                       json_obj->type = MSG_JSON_PARSER_REAL;
+                       json_obj->value = NULL;
+                       json_obj->number_value = (double)g_value_get_double(&value);
+               }
+               break;
+       default:
+               {
+                       MSG_DEBUG(" Entering node default case");
+               }
+               break;
+       }
+
+       return 1;
+}
+
+int msg_json_parser_object_get_value(msg_json_parser_object *json_obj)
+{
+       GValue value = { 0 };
+       JsonNode *node = NULL;
+
+       /*Input params validation */
+       if (json_obj == NULL) {
+               MSG_DEBUG("Invalid Input Parameters");
+               return -1;
+       }
+       node = json_object_get_member((JsonObject *)json_obj->value, json_obj->key);
+
+       json_node_get_value((JsonNode *) node, &value);
+
+       switch (json_node_get_value_type((JsonNode *) node)) {
+       case G_TYPE_STRING:
+               {
+                       json_obj->type = MSG_JSON_PARSER_STRING;
+                       json_obj->value = (void *)g_value_get_string(&value);
+                       json_obj->number_value = 0;
+               }
+               break;
+       case G_TYPE_INT:
+               {
+                       json_obj->type = MSG_JSON_PARSER_INT;
+                       json_obj->value = NULL;
+                       json_obj->number_value = g_value_get_int(&value);
+               }
+               break;
+       case G_TYPE_UINT:
+               {
+                       json_obj->type = MSG_JSON_PARSER_UINT;
+                       json_obj->value = NULL;
+                       json_obj->number_value = g_value_get_uint(&value);
+               }
+               break;
+       case G_TYPE_BOOLEAN:
+               {
+                       json_obj->type = MSG_JSON_PARSER_BOOLEAN;
+                       json_obj->value = NULL;
+                       json_obj->number_value = g_value_get_boolean(&value);
+               }
+               break;
+       case G_TYPE_INT64:
+               {
+                       json_obj->type = MSG_JSON_PARSER_INT;
+                       json_obj->value = NULL;
+                       json_obj->number_value = g_value_get_int64(&value);
+               }
+               break;
+       case G_TYPE_UINT64:
+               {
+                       json_obj->type = MSG_JSON_PARSER_UINT;
+                       json_obj->value = NULL;
+                       json_obj->number_value = g_value_get_uint64(&value);
+               }
+               break;
+       case G_TYPE_DOUBLE:
+               {
+                       json_obj->type = MSG_JSON_PARSER_REAL;
+                       json_obj->value = NULL;
+                       json_obj->number_value = (double)g_value_get_double(&value);
+               }
+               break;
+       default:
+               {
+                       MSG_DEBUG(" Entering node default case");
+               }
+               break;
+       }
+
+       return 1;
+}
+
+msg_json_parser_handle msg_json_parser_handle_create(void)
+{
+       JsonParser *jsonParser = NULL;
+
+       jsonParser = json_parser_new();
+
+       return(msg_json_parser_handle)jsonParser;
+}
+
+void msg_json_parser_handle_destory(msg_json_parser_handle *handle)
+{
+       if (handle == NULL)
+               return;
+
+       g_object_unref(*handle);
+       *handle = NULL;
+}
+
+void msg_json_parser_parse_buffer(msg_json_parser_handle handle, const char* value, int value_len, msg_json_parser_object *json_obj)
+{
+       gboolean gRet = TRUE;
+       JsonNode *root = NULL;
+       GError *error = NULL;
+       JsonParser *jsonParser = (JsonParser *)handle;
+       JsonNodeType parentType = JSON_NODE_NULL;
+
+       /*Input params validation*/
+       if (value == NULL || value_len == 0) {
+               MSG_DEBUG("Invalid Input Parameters");
+               return ;
+       }
+
+       if (jsonParser != NULL) {
+
+               /** Loads a JSON stream from a buffer and parses it */
+               gRet = json_parser_load_from_data(jsonParser, value, value_len, &error);
+               if (gRet != TRUE) {
+                       g_error_free(error);
+               } else {
+                       /** Fetch the root node */
+                       root = json_parser_get_root(jsonParser);
+
+                       if (root != NULL) {
+
+                               json_obj->key = root_key;
+                               json_obj->value = root;
+                               parentType = json_node_get_node_type(root);
+
+                               if (parentType == JSON_NODE_VALUE) {
+                                       gRet = msg_json_parser_get_value(json_obj);
+                               } else if (parentType == JSON_NODE_OBJECT) {
+                                       json_obj->type = MSG_JSON_PARSER_OBJECT;
+                               } else if (parentType == JSON_NODE_ARRAY) {
+                                       json_obj->type = MSG_JSON_PARSER_ARRAY;
+                               } else {
+                                       json_obj->type = MSG_JSON_PARSER_NULL;
+                               }
+                       } else {
+                               json_obj->key = NULL;
+                               json_obj->value = NULL;
+                       }
+               }
+       } else {
+
+       }
+
+       return ;
+}
+
+int msg_json_parser_get_next_child(const msg_json_parser_object *parent, msg_json_parser_object *child, int index)
+{
+       int lReturn = 1;
+       JsonNodeType jNodeParentType = JSON_NODE_NULL;
+       JsonNodeType jNodeChildType = JSON_NODE_NULL;
+       JsonArray *tempArray = NULL;
+       JsonObject *tempObj = NULL;
+       GList *members = NULL;
+
+       /*Input params validation */
+       if (parent == NULL || parent->value == NULL || child == NULL || index < 0) {
+               MSG_DEBUG("Invalid Input Parameters");
+               return 0;
+       }
+
+       /** Get the JSON Parent Node Type */
+       jNodeParentType = json_node_get_node_type((JsonNode *) parent->value);
+
+       switch (jNodeParentType) {
+       case JSON_NODE_OBJECT:
+               {
+                       /** Get the JSON object from JSON Parent Node */
+                       tempObj = json_node_get_object((JsonNode *) parent->value);
+
+                       /** Get the list of keys from the object node */
+                       members = json_object_get_members(tempObj);
+
+                       /** Get the key by index from the list */
+                       child->key = (char *)g_list_nth_data(members, index);
+
+                       g_list_free(members);
+                       if (child->key == NULL) {
+                               return 0;
+                       }
+
+                       /** Get the JSONNode by key from the list */
+                       child->value = json_object_get_member(tempObj, child->key);
+
+                       /** Identify the node type of the JSOSNNode */
+                       jNodeChildType = json_node_get_node_type((JsonNode *) child->value);
+
+                       switch (jNodeChildType) {
+                       case JSON_NODE_OBJECT:
+                               {
+                                       child->type = MSG_JSON_PARSER_OBJECT;
+                               }
+                               break;
+                       case JSON_NODE_ARRAY:
+                               {
+                                       child->type = MSG_JSON_PARSER_ARRAY;
+                               }
+                               break;
+                       case JSON_NODE_VALUE:
+                               {
+                                       lReturn = msg_json_parser_get_value(child);
+                               }
+                               break;
+                       case JSON_NODE_NULL:
+                               {
+                               }
+                               break;
+                       default:
+                               {
+                                       lReturn = 0;
+                               }
+                               break;
+                       }
+
+               }
+               break;
+       case JSON_NODE_ARRAY:
+               {
+                       /** Get the JSON array from the JSON node */
+                       tempArray = json_node_get_array((JsonNode *) parent->value);
+
+                       child->key = NULL;
+
+                       if ((guint) index >= json_array_get_length(tempArray)) {
+                               return 0;
+                       }
+
+                       /** Get the JSONNode from the list of values */
+                       child->value = (void *)json_array_get_element(tempArray, index);
+                       if (child->value == NULL) {
+                               return 0;
+                       }
+                       /* Get the child type */
+                       jNodeChildType = json_node_get_node_type((JsonNode *) child->value);
+
+                       switch (jNodeChildType) {
+                       case JSON_NODE_OBJECT:
+                               {
+                                       child->type = MSG_JSON_PARSER_OBJECT;
+                               }
+                               break;
+                       case JSON_NODE_ARRAY:
+                               {
+                                       child->type = MSG_JSON_PARSER_ARRAY;
+                               }
+                               break;
+                       case JSON_NODE_VALUE:
+                               {
+                                       lReturn = msg_json_parser_get_value(child);
+                               }
+                               break;
+                       case JSON_NODE_NULL:
+                               {
+                               }
+                               break;
+                       default:
+                               {
+                                       lReturn = 0;
+                                       break;
+                               }
+                       }
+
+               }
+               break;
+       case JSON_NODE_VALUE:
+       default:
+               {
+                       child->key = NULL;
+                       child->value = NULL;
+                       lReturn = 0;
+               }
+               break;
+       }
+
+       return lReturn;
+}
+
+
+/**
+ * @fn msg_json_parser_get_child_by_name
+ * This function is used for getting the child node by it's name for
+       input node.
+ * @param [IN] \n
+ * parent: msg_json_parser_object structure pointer whose child node
+       is to be retrieved \n
+ * name: const char pointer containing key of the required child \n
+ * @param [OUT] \n
+ * child: msg_json_parser_object structure pointer. Should be allocated
+       and freed after it's use by caller. It will be filled with
+       corresponding data \n
+ * @return     Return type is int. Should be typecasted to
+       msg_json_parser_parse_status to check the return status. If
+       MSG_JSON_PARSER_PARSE_SUCCESS, then only child contains
+       valid data, else some error occured. \n
+ * @remark This API is synchronous.
+ */
+int msg_json_parser_get_child_by_name(const msg_json_parser_object *parent,
+                                       msg_json_parser_object *child,
+                                       const char *name)
+{
+       int lReturn = -1;
+       JsonObject *tempObj = NULL;
+       JsonNodeType jNodeParentType = JSON_NODE_NULL;
+       JsonNodeType jNodeChildType = JSON_NODE_NULL;
+
+       /*Input params validation */
+       if (parent == NULL || parent->value == NULL || child == NULL
+           || name == NULL) {
+               MSG_DEBUG("Invalid Input Parameters");
+               return -1;
+       }
+
+       /** Get the JSON Parent Node Type */
+       jNodeParentType = json_node_get_node_type((JsonNode *) parent->value);
+
+       switch (jNodeParentType) {
+       case JSON_NODE_OBJECT:
+               {
+                       /** Get the JSON object from JSON Parent Node */
+                       tempObj =
+                           json_node_get_object((JsonNode *) parent->value);
+
+                       /** Get the list of keys from the object node */
+                       GList *members = json_object_get_members(tempObj);
+                       if (members == NULL) {
+                               return -1;
+                       }
+
+                       /** Get the key by index from the list */
+                       char *member = NULL;
+                       for (unsigned int i = 0; i < g_list_length(members); i++) {
+
+                               member = (char *)g_list_nth_data(members, i);
+
+                               if (g_strcmp0((char *)name, member) == 0) {
+                                       child->key      = member;
+                               }
+                       }
+
+                       g_list_free(members);
+
+                       if (child->key == NULL) {
+                               return -1;
+                       }
+
+                       /** Get the JSONNode by key from the list */
+                       child->value = (JsonNode *) json_object_get_member(tempObj,     child->key);
+
+                       /** Identify the node type of the JSOSNNode */
+                       jNodeChildType = json_node_get_node_type((JsonNode *) child->value);
+
+                       switch (jNodeChildType) {
+                       case JSON_NODE_OBJECT:
+                               {
+                                       child->type = MSG_JSON_PARSER_OBJECT;
+                               }
+                               break;
+                       case JSON_NODE_ARRAY:
+                               {
+                                       child->type = MSG_JSON_PARSER_ARRAY;
+                               }
+                               break;
+                       case JSON_NODE_VALUE:
+                               {
+                                       lReturn = msg_json_parser_get_value(child);
+                               }
+                               break;
+                       case JSON_NODE_NULL:
+                               {
+
+                               }
+                               break;
+                       default:
+                               {
+                                       lReturn = -1;
+                               }
+                               break;
+                       }
+
+               }
+               break;
+       case JSON_NODE_ARRAY:
+       case JSON_NODE_VALUE:
+       default:
+               {
+                       child->key = NULL;
+                       child->value = NULL;
+                       lReturn = -1;
+               }
+               break;
+       }
+
+       return lReturn;
+}
+
+#if 0
+/**
+ * @fn msg_json_parser_get_child_count
+ * This function returns the count for a specified JSON object.
+ * @param [IN] \n
+ * object: msg_json_parser_object structure pointer whose child count
+       is to be retrieved \n
+ * @return     Return type is int. This contains the value of the child node
+       for the specified JSON object \n
+ * @remark This API is synchronous.
+ */
+int msg_json_parser_get_child_count(msg_json_parser_object *object)
+{
+       JsonNodeType jNodeParentType = JSON_NODE_NULL;
+       JsonObject *tempObj = NULL;
+       JsonArray *tempArray = NULL;
+       int count = 0;
+
+       /*Input params validation */
+       if (object == NULL || object->value == NULL) {
+               MSG_DEBUG("Invalid Input Parameters");
+               return count;
+       }
+
+       /** Get the JSON Parent Node Type */
+       jNodeParentType = json_node_get_node_type((JsonNode *) object->value);
+
+       switch (jNodeParentType) {
+       case JSON_NODE_OBJECT:
+               {
+                       MSG_DEBUG("  JSON_NODE_OBJECT ");
+                       tempObj = NULL;
+                       /** Get the JSON object from JSON Parent Node */
+                       tempObj = json_node_get_object((JsonNode *) object->value);
+                       /** Get the number of members from the object node */
+                       count = json_object_get_size(tempObj);
+               }
+               break;
+       case JSON_NODE_ARRAY:
+               {
+                       MSG_DEBUG("  JSON_NODE_ARRAY ");
+                       tempArray = NULL;
+                       /** Get the JSON array from the JSON node */
+                       tempArray =
+                           json_node_get_array((JsonNode *) object->value);
+                       /** Get the number of members from the array node */
+                       count = json_array_get_length(tempArray);
+               }
+               break;
+       case JSON_NODE_VALUE:
+       default:
+               {
+
+               }
+               break;
+       }
+
+       MSG_DEBUG("COUNT :: %d ", count);
+       return count;
+}
+#endif
index 4efaf90..26255bb 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <malloc.h>
index e9fd34e..094ee9b 100755 (executable)
@@ -1,48 +1,49 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
 #include <string.h>
-#include <sys/stat.h>
+#include <glib.h>
 #include <errno.h>
-#include <time.h>
-#include <stdlib.h>
+#include <sys/stat.h>
 
 #include "MsgTypes.h"
 #include "MsgMmsTypes.h"
+#include "MsgUtilFile.h"
 #include "MsgMmsMessage.h"
-#include "MsgDebug.h"
 #include "MsgUtilFile.h"
-#include "MsgStorageTypes.h"
-#include "MsgInternalTypes.h"
-
-
-MMS_SMIL_ROOTLAYOUT    rootlayout;
+#include "MsgSmil.h"
+#include "MsgDebug.h"
 
 static void __release_glist_element(gpointer data, gpointer user_data);
 static void __release_page_element(gpointer data, gpointer user_data);
+static msg_error_t __releasePageList(MMS_MESSAGE_DATA_S *pMsgData);
+static msg_error_t __releaseRegionList(MMS_MESSAGE_DATA_S *pMsgData);
+static msg_error_t __releaseAttachList(MMS_MESSAGE_DATA_S *pMsgData);
+static msg_error_t __releaseTransitionList(MMS_MESSAGE_DATA_S *pMsgData);
+static msg_error_t __releaseMetaList(MMS_MESSAGE_DATA_S *pMsgData);
 
-static void __release_glist_element(gpointer data, gpointer user_data)
+void __release_glist_element(gpointer data, gpointer user_data)
 {
        if(data != NULL) {
                free(data);
        }
 }
 
-static void __release_page_element(gpointer data, gpointer user_data)
+void __release_page_element(gpointer data, gpointer user_data)
 {
        if(data != NULL) {
                MMS_PAGE_S *page = (MMS_PAGE_S *)data;
@@ -66,7 +67,7 @@ static void __release_page_element(gpointer data, gpointer user_data)
        }
 }
 
-msg_error_t _MsgMmsReleasePageList(MMS_MESSAGE_DATA_S *pMsgData)
+msg_error_t __releasePageList(MMS_MESSAGE_DATA_S *pMsgData)
 {
        if (pMsgData == NULL) {
                MSG_DEBUG("pMsgData is NULL");
@@ -84,7 +85,7 @@ msg_error_t _MsgMmsReleasePageList(MMS_MESSAGE_DATA_S *pMsgData)
        return MSG_SUCCESS;
 }
 
-msg_error_t _MsgMmsReleaseRegionList(MMS_MESSAGE_DATA_S *pMsgData)
+msg_error_t __releaseRegionList(MMS_MESSAGE_DATA_S *pMsgData)
 {
        if (pMsgData == NULL) {
                MSG_DEBUG("pMsgData is NULL");
@@ -102,7 +103,7 @@ msg_error_t _MsgMmsReleaseRegionList(MMS_MESSAGE_DATA_S *pMsgData)
        return MSG_SUCCESS;
 }
 
-msg_error_t _MsgMmsReleaseAttachList(MMS_MESSAGE_DATA_S *pMsgData)
+msg_error_t __releaseAttachList(MMS_MESSAGE_DATA_S *pMsgData)
 {
        if (pMsgData == NULL) {
                MSG_DEBUG("pMsgData is NULL");
@@ -120,7 +121,7 @@ msg_error_t _MsgMmsReleaseAttachList(MMS_MESSAGE_DATA_S *pMsgData)
        return MSG_SUCCESS;
 }
 
-msg_error_t _MsgMmsReleaseTransitionList(MMS_MESSAGE_DATA_S *pMsgData)
+msg_error_t __releaseTransitionList(MMS_MESSAGE_DATA_S *pMsgData)
 {
        if (pMsgData == NULL) {
                MSG_DEBUG("pMsgData is NULL");
@@ -138,7 +139,7 @@ msg_error_t _MsgMmsReleaseTransitionList(MMS_MESSAGE_DATA_S *pMsgData)
        return MSG_SUCCESS;
 }
 
-msg_error_t _MsgMmsReleaseMetaList(MMS_MESSAGE_DATA_S *pMsgData)
+msg_error_t __releaseMetaList(MMS_MESSAGE_DATA_S *pMsgData)
 {
        if (pMsgData == NULL) {
                MSG_DEBUG("pMsgData is NULL");
@@ -156,6 +157,15 @@ msg_error_t _MsgMmsReleaseMetaList(MMS_MESSAGE_DATA_S *pMsgData)
        return MSG_SUCCESS;
 }
 
+void MsgMmsReleaseMmsLists(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       __releasePageList(pMsgData);
+       __releaseRegionList(pMsgData);
+       __releaseAttachList(pMsgData);
+       __releaseTransitionList(pMsgData);
+       __releaseMetaList(pMsgData);
+}
+
 msg_error_t _MsgMmsAddRegion(MMS_MESSAGE_DATA_S *pMsgData, MMS_SMIL_REGION* pRegion)
 {
        if(pMsgData == NULL || pRegion == NULL)
@@ -174,7 +184,7 @@ msg_error_t _MsgMmsAddPage(MMS_MESSAGE_DATA_S *pMsgData, MMS_PAGE_S *pPage)
 
        pMsgData->pagelist = g_list_append(pMsgData->pagelist, pPage);
        pMsgData->pageCnt++;
-
+       MSG_DEBUG("MmsData's Page Count : %d", pMsgData->pageCnt);
        return MSG_SUCCESS;
 }
 
@@ -185,12 +195,7 @@ msg_error_t _MsgMmsAddMedia(MMS_PAGE_S* pPage, MMS_MEDIA_S *pMedia)
 
        pPage->medialist = g_list_append(pPage->medialist, pMedia);
        pPage->mediaCnt++;
-               MSG_DEBUG("media's mediatype: %d", pMedia->mediatype);
-               MSG_DEBUG("media's filename: %s", pMedia->szFileName);
-               MSG_DEBUG("media's filepath: %s", pMedia->szFilePath);
-               MSG_DEBUG("media's contentId: %s", pMedia->szContentID);
-       MSG_DEBUG("page's media count: %d", pPage->mediaCnt);
-
+       MSG_DEBUG("Page's media count: %d", pPage->mediaCnt);
        return MSG_SUCCESS;
 }
 
@@ -227,59 +232,172 @@ msg_error_t _MsgMmsAddAttachment(MMS_MESSAGE_DATA_S *pMsgData, MMS_ATTACH_S *pAt
        return MSG_SUCCESS;
 }
 
-bool _MsgMmsFindMatchedMedia(MMS_MESSAGE_DATA_S *pMsgData, char *pszFilePath)
+int _MsgMmsGetPageCount(MMS_MESSAGE_DATA_S *pMsgData)
 {
-       if (pMsgData == NULL || pszFilePath == NULL)
-               return false;
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return 0;
+       }
 
-       if (pMsgData->pagelist) {
-               for (int pageIdx = 0; pageIdx < pMsgData->pageCnt; pageIdx++) {
-                       MMS_PAGE_S *page = (MMS_PAGE_S *)g_list_nth_data(pMsgData->pagelist, pageIdx);
+       int count = 0;
 
-                       if (page && page->medialist) {
-                               for (int mediaIdx = 0; mediaIdx < page->mediaCnt; mediaIdx++) {
-                                       MMS_MEDIA_S *media = (MMS_MEDIA_S *)g_list_nth_data(page->medialist, mediaIdx);
-                                       if (media) {
-                                               if (strcmp(pszFilePath, media->szFilePath) == 0)
-                                                       return true;
-                                       }
-                               }
-                       }
-               }
+       if (pMsgData->pagelist)
+               count = g_list_length(pMsgData->pagelist);
+
+       MSG_DEBUG("Page Count: %d", count);
+       return count;
+}
+
+MMS_PAGE_S *_MsgMmsGetPage(MMS_MESSAGE_DATA_S *pMsgData, int pageIdx)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return NULL;
        }
 
-       return false;
+       MMS_PAGE_S *page = NULL;
+
+       if (pMsgData->pagelist)
+               page = (MMS_PAGE_S *)g_list_nth_data(pMsgData->pagelist, pageIdx);
+
+       return page;
 }
 
-msg_error_t _MsgMmsAddSmilDoc(char* pSmil, MMS_MESSAGE_DATA_S* pMsgData)
+int _MsgMmsGetAttachCount(MMS_MESSAGE_DATA_S *pMsgData)
 {
-       MSG_DEBUG("MsgMmsAddSmilDoc");
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return 0;
+       }
 
-       if(pSmil == NULL || pMsgData == NULL)
-               return MSG_ERR_INVALID_PARAMETER;
+       int count = 0;
+
+       if (pMsgData->attachlist)
+               count = g_list_length(pMsgData->attachlist);
+
+       MSG_DEBUG("Attachment Count: %d", count);
+       return count;
+}
+
+MMS_ATTACH_S *_MsgMmsGetAttachment(MMS_MESSAGE_DATA_S *pMsgData, int attachIdx)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return NULL;
+       }
 
-       char    fullpath[MSG_FILEPATH_LEN_MAX] = {0,};
-       char smilFileName[MSG_FILENAME_LEN_MAX+1] = {0,};
-       time_t  RawTime = 0;
+       MMS_ATTACH_S *attach = NULL;
+       if (pMsgData->attachlist)
+               attach = (MMS_ATTACH_S *)g_list_nth_data(pMsgData->attachlist, attachIdx);
 
-       //Create smilFileName
-       time(&RawTime);
-       snprintf(smilFileName, MSG_FILENAME_LEN_MAX+1, "%lu", RawTime);
-       snprintf(fullpath, MSG_FILEPATH_LEN_MAX, "%s%s", MSG_SMIL_FILE_PATH, smilFileName);
+       return attach;
+}
 
-       if (MsgWriteSmilFile(fullpath, pSmil, strlen(pSmil)) == false) {
-               MSG_DEBUG("MsgWriteSmilFile error");
-               return MSG_ERR_MMS_ERROR;
+MMS_SMIL_REGION *_MsgMmsGetSmilRegion(MMS_MESSAGE_DATA_S *pMsgData, int regionIdx)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return NULL;
        }
-       strncpy(pMsgData->szSmilFilePath, smilFileName, MSG_FILEPATH_LEN_MAX-1);
 
-       return MSG_SUCCESS;
+       MMS_SMIL_REGION *region = NULL;
+
+       if (pMsgData->regionlist)
+               region = (MMS_SMIL_REGION *)g_list_nth_data(pMsgData->regionlist, regionIdx);
+
+       return region;
+}
+
+MMS_MEDIA_S *_MsgMmsGetMedia(MMS_PAGE_S *pPage, int mediaIdx)
+{
+       if (!pPage) {
+               MSG_FATAL("pPage is NULL");
+               return NULL;
+       }
+
+       if (mediaIdx > pPage->mediaCnt || mediaIdx < 0) {
+               MSG_FATAL("Invalid media index = %d", mediaIdx);
+               return NULL;
+       }
+
+       MMS_MEDIA_S *media = NULL;
+       if (pPage->medialist)
+               media = (MMS_MEDIA_S *)g_list_nth_data(pPage->medialist, mediaIdx);
+
+       return media;
+
+}
+
+int _MsgMmsGetTransitionCount(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return 0;
+       }
+
+       int count = 0;
+
+       if (pMsgData->transitionlist)
+               count = g_list_length(pMsgData->transitionlist);
+
+       MSG_DEBUG("Transition Count: %d", count);
+       return count;
+}
+
+MMS_SMIL_TRANSITION *_MsgMmsGetTransition(MMS_MESSAGE_DATA_S *pMsgData, int transitionIdx)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return NULL;
+       }
+
+       MMS_SMIL_TRANSITION *transition = NULL;
+       if (pMsgData->transitionlist)
+               transition = (MMS_SMIL_TRANSITION *)g_list_nth_data(pMsgData->transitionlist, transitionIdx);
+
+       return transition;
+}
+
+MMS_SMIL_META *_MsgMmsGetMeta(MMS_MESSAGE_DATA_S *pMsgData, int metaIdx)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return NULL;
+       }
+
+       MMS_SMIL_META *meta = NULL;
+
+       if (pMsgData->metalist)
+               meta = (MMS_SMIL_META *)g_list_nth_data(pMsgData->metalist, metaIdx);
+
+       return meta;
+}
+
+int    _MsgMmsGetMetaCount(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return 0;
+       }
+
+       int count = 0;
+
+       if (pMsgData->metalist)
+               count = g_list_length(pMsgData->metalist);
+
+       MSG_DEBUG("Meta Count: %d", count);
+       return count;
 }
 
+bool _MsgMmsSetRootLayout(MMS_MESSAGE_DATA_S *pMsgData, MMS_SMIL_ROOTLAYOUT *pRootlayout)
+{
+       memcpy(&pMsgData->rootlayout, pRootlayout, sizeof(MMS_SMIL_ROOTLAYOUT));
+       return true;
+}
 
-char* _MsgMmsSerializeMessageData(const MMS_MESSAGE_DATA_SpMsgData, unsigned int *pSize)
+char* _MsgMmsSerializeMessageData(const MMS_MESSAGE_DATA_S *pMsgData, unsigned int *pSize)
 {
-       MSG_DEBUG("MsgMmsSerializeMessageData");
+       MSG_BEGIN();
 
        if (pMsgData == NULL)
                return NULL;
@@ -289,71 +407,53 @@ char* _MsgMmsSerializeMessageData(const MMS_MESSAGE_DATA_S* pMsgData, unsigned i
        int pageCnt = 0;
        char *buf = NULL;
 
-       pageCnt = pMsgData->pageCnt;
+       bufsize += sizeof(int); // Page cnt
 
-       int mediaCnt = 0;
+       pageCnt = pMsgData->pageCnt;
 
        if (pMsgData->pagelist) {
+
                for (int pageIdx = 0; pageIdx < pageCnt; pageIdx++) {
-                       bufsize += sizeof(int); // Media cnt
+
+                       int mediaCnt = 0;
 
                        MMS_PAGE_S *page = (MMS_PAGE_S *)g_list_nth_data(pMsgData->pagelist, pageIdx);
+
                        mediaCnt = page->mediaCnt;
 
-                       if (page->medialist) {
-                               for (int i = 0; i < mediaCnt; i++) {
-                                       MMS_MEDIA_S *media = (MMS_MEDIA_S *)g_list_nth_data(page->medialist, i);
+                       bufsize += sizeof(int); // Media cnt
 
-                                       if (media->mediatype == MMS_SMIL_MEDIA_TEXT) {
-                                               bufsize += (sizeof(MmsSmilMediaType) + MSG_FILENAME_LEN_MAX + 2 * MSG_FILEPATH_LEN_MAX + MSG_MSG_ID_LEN + 1
-                                                       + MAX_SMIL_ALT_LEN + MAX_SMIL_REGION_ID
-#ifdef __SUPPORT_DRM__
-                                                       + sizeof(MsgDrmType) + MSG_FILEPATH_LEN_MAX
-#endif
-                                                       + MAX_SMIL_TRANSIN_ID + MAX_SMIL_TRANSOUT_ID +
-                                                       7 * sizeof(int) + 3* sizeof(bool) + sizeof(MmsTextDirection) + sizeof(MmsSmilFontType));
-                                       } else {
-                                               bufsize += (sizeof(MmsSmilMediaType) + MSG_FILENAME_LEN_MAX + 2 * MSG_FILEPATH_LEN_MAX + MSG_MSG_ID_LEN + 1
-                                                       + MAX_SMIL_ALT_LEN + MAX_SMIL_REGION_ID
-#ifdef __SUPPORT_DRM__
-                                                       + sizeof(MsgDrmType) + MSG_FILEPATH_LEN_MAX
-#endif
-                                                       + MAX_SMIL_TRANSIN_ID + MAX_SMIL_TRANSOUT_ID + 5 * sizeof(int)
-                                                       );
-                                       }
-                               }
+                       if (page->medialist) {
+                               bufsize += sizeof(MMS_MEDIA_S) * mediaCnt;
                        }
 
-                       bufsize += sizeof(int) * 6;
+                       bufsize += sizeof(int) * 6;//Dur, Begin, End, Min, Max, Repeat
                }
        }
 
        bufsize += sizeof(int); // region count;
+
        if (pMsgData->regionlist) {
                int elementSize = g_list_length(pMsgData->regionlist);
-               bufsize += elementSize * (MAX_SMIL_REGION_ID + 4 * sizeof(MMS_LENGTH) + sizeof(int) + sizeof(REGION_FIT_TYPE_T));
+               bufsize += elementSize * (sizeof(MMS_SMIL_REGION));
        }
 
        bufsize += sizeof(int); // attachment count;
        if (pMsgData->attachlist) {
                int elementSize = g_list_length(pMsgData->attachlist);
-               bufsize += elementSize * (sizeof(MimeType) + MSG_FILENAME_LEN_MAX + MSG_FILEPATH_LEN_MAX + sizeof(int)
-#ifdef __SUPPORT_DRM__
-                               + sizeof(MsgDrmType) + MSG_FILEPATH_LEN_MAX
-#endif
-                               );
+               bufsize += elementSize * sizeof(MMS_ATTACH_S);
        }
 
        bufsize += sizeof(int); // transition count;
        if (pMsgData->transitionlist) {
                int elementSize = g_list_length(pMsgData->transitionlist);
-               bufsize += elementSize * (MAX_SMIL_TRANSITION_ID + sizeof(MmsSmilTransType) + sizeof(MmsSmilTransSubType) + sizeof(int));
+               bufsize += elementSize * sizeof(MMS_SMIL_TRANSITION);
        }
 
        bufsize += sizeof(int); // meta count;
        if (pMsgData->metalist) {
                int elementSize = g_list_length(pMsgData->metalist);
-               bufsize += elementSize * (MAX_SMIL_META_ID + MAX_SMIL_META_NAME + MAX_SMIL_META_CONTENT);
+               bufsize += elementSize * sizeof(MMS_SMIL_META);
        }
 
        bufsize += sizeof(MMS_SMIL_ROOTLAYOUT);
@@ -364,151 +464,57 @@ char* _MsgMmsSerializeMessageData(const MMS_MESSAGE_DATA_S* pMsgData, unsigned i
 
        int filePathLen = strlen(pMsgData->szSmilFilePath);
 
-       bufsize += sizeof(int) + filePathLen + sizeof(int);
+       bufsize += sizeof(int) + filePathLen;
 
-       MSG_DEBUG("MsgMmsSerializeMessageData: bufsize = %d", bufsize);
+       bufsize += sizeof(int); // type
+       bufsize += sizeof(MMS_HEADER_DATA_S);
+       bufsize += sizeof(MMS_MULTIPART_DATA_S);
+
+       MSG_DEBUG("Serialize bufsize = %d", bufsize);
 
        buf = (char *)calloc(bufsize, 1);
 
-       // copy file path length
-       MSG_DEBUG("MsgMmsSerializeMessageData: smilFilePath Length = %d",  filePathLen);
+       if (buf == NULL)
+               return buf;
 
-       memcpy(buf, &filePathLen, sizeof(int));
+       int serial_index = 0;
 
+       memcpy(buf, &pMsgData->backup_type, sizeof(int));
+       MSG_DEBUG("[#%2d][%5d] backup type = %d",serial_index++, offset, pMsgData->backup_type);
        offset += sizeof(int);
 
+       //smilFilePath
+       memcpy(buf + offset , &filePathLen, sizeof(int));
+
        // copy file path
-       MSG_DEBUG("MsgMmsSerializeMessageData: smilFilePath = %s",  pMsgData->szSmilFilePath);
+       MSG_SEC_DEBUG("[#%2d][%5d] smilFilePath = %s, len = %d",serial_index++, offset, pMsgData->szSmilFilePath, filePathLen);
+       offset += sizeof(int);
 
        if (filePathLen > 0) {
                memcpy(buf + offset, pMsgData->szSmilFilePath, filePathLen);
-
                offset += filePathLen;
        }
 
        // copy page count
-       MSG_DEBUG("MsgMmsSerializeMessageData: pageCnt = %d",  pMsgData->pageCnt);
-
+       MSG_DEBUG("[#%2d][%5d] page count = %d",serial_index++, offset, pMsgData->pageCnt);
        memcpy(buf + offset, &(pMsgData->pageCnt), sizeof(int));
-
        offset += sizeof(int);
 
        if (pMsgData->pagelist) {
-               for (int pageIdx = 0; pageIdx < pageCnt; pageIdx++)
-               {
+
+               for (int pageIdx = 0; pageIdx < pageCnt; pageIdx++) {
                        MMS_PAGE_S *page = (MMS_PAGE_S *)g_list_nth_data(pMsgData->pagelist, pageIdx);
-                       mediaCnt = page->mediaCnt;
 
-                       memcpy(buf + offset, &mediaCnt, sizeof(int));
+                       MSG_DEBUG("[#%2d][%5d][%d page] media count = %d",serial_index++, offset, pageIdx, page->mediaCnt);
+                       memcpy(buf + offset, &page->mediaCnt, sizeof(int));
                        offset += sizeof(int);
 
-                       MSG_DEBUG("MsgMmsSerializeMessageData: mediaCnt = %d",  mediaCnt);
                        if (page->medialist) {
-                               for (int i = 0; i < mediaCnt; ++ i) {
+                               for (int i = 0; i < page->mediaCnt; ++ i) {
                                        MMS_MEDIA_S *media = (MMS_MEDIA_S *)g_list_nth_data(page->medialist, i);
-
-                                       memcpy(buf + offset, &(media->mediatype), sizeof(MmsSmilMediaType));
-                                       offset += sizeof(MmsSmilMediaType);
-                                       MSG_DEBUG("%d media's mediatype = %d", i, media->mediatype);
-
-                                       memcpy(buf + offset, media->szSrc, MSG_FILEPATH_LEN_MAX);
-                                       offset +=  MSG_FILEPATH_LEN_MAX;
-
-                                       memcpy(buf + offset, media->szFileName, MSG_FILENAME_LEN_MAX);
-                                       offset += MSG_FILENAME_LEN_MAX;
-                                       MSG_DEBUG("%d media's filename = %s", i, media->szFileName);
-
-                                       memcpy(buf + offset, media->szFilePath, MSG_FILEPATH_LEN_MAX);
-                                       offset += MSG_FILEPATH_LEN_MAX;
-                                       MSG_DEBUG("%d media's filepath = %s", i, media->szFilePath);
-
-                                       memcpy(buf + offset, media->szContentID, MSG_MSG_ID_LEN + 1);
-                                       offset +=  MSG_MSG_ID_LEN + 1;
-                                       MSG_DEBUG("%d media's contentID = %s", i, media->szContentID);
-
-                                       memcpy(buf + offset, media->regionId, MAX_SMIL_REGION_ID);
-                                       offset +=  MAX_SMIL_REGION_ID;
-                                       MSG_DEBUG("%d media's regionId = %s", i, media->regionId);
-
-                                       memcpy(buf + offset, media->szAlt, MAX_SMIL_ALT_LEN);
-                                       offset +=  MAX_SMIL_ALT_LEN;
-
-#ifdef __SUPPORT_DRM__
-                                       memcpy(buf + offset, &(media->drmType), sizeof(MsgDrmType));
-                                       offset +=  sizeof(MsgDrmType);
-                                       memcpy(buf + offset, media->szDrm2FullPath, MSG_FILEPATH_LEN_MAX);
-                                       offset += MSG_FILEPATH_LEN_MAX;
-#endif
-
-                                       if (media->mediatype == MMS_SMIL_MEDIA_TEXT) {
-                                               MSG_DEBUG("##### Media = TEXT #####");
-                                               memcpy(buf + offset, media->sMedia.sText.szTransInId, MAX_SMIL_TRANSIN_ID);
-                                               offset +=  MAX_SMIL_TRANSIN_ID;
-
-                                               memcpy(buf + offset, media->sMedia.sText.szTransOutId, MAX_SMIL_TRANSOUT_ID);
-                                               offset +=  MAX_SMIL_TRANSOUT_ID;
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.nRepeat), sizeof(int));
-                                               offset += sizeof(int);
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.nBegin), sizeof(int));
-                                               offset += sizeof(int);
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.nEnd), sizeof(int));
-                                               offset += sizeof(int);
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.nDurTime), sizeof(int));
-                                               offset += sizeof(int);
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.nBgColor), sizeof(int));
-                                               offset += sizeof(int);
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.bBold), sizeof(bool));
-                                               offset += sizeof(bool);
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.bUnderLine), sizeof(bool));
-                                               offset += sizeof(bool);
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.bItalic), sizeof(bool));
-                                               offset += sizeof(bool);
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.bReverse), sizeof(bool));
-                                               offset += sizeof(bool);
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.nDirection), sizeof(MmsTextDirection));
-                                               offset += sizeof(MmsTextDirection);
-
-                                               //memcpy(buf + offset, &(media->sMedia.sText.nFont), sizeof(MmsSmilFontType));
-                                               //offset += sizeof(MmsSmilFontType);
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.nSize), sizeof(int));
-                                               offset += sizeof(int);
-
-                                               memcpy(buf + offset, &(media->sMedia.sText.nColor), sizeof(int));
-                                               offset += sizeof(int);
-                                       } else {
-                                               MSG_DEBUG("##### Media = IMAGE, AUDIO, VIDEO #####");
-                                               memcpy(buf + offset, media->sMedia.sAVI.szTransInId, MAX_SMIL_TRANSIN_ID);
-                                               offset +=  MAX_SMIL_TRANSIN_ID;
-
-                                               memcpy(buf + offset, media->sMedia.sAVI.szTransOutId, MAX_SMIL_TRANSOUT_ID);
-                                               offset +=  MAX_SMIL_TRANSOUT_ID;
-
-                                               memcpy(buf + offset, &(media->sMedia.sAVI.nRepeat), sizeof(int));
-                                               offset += sizeof(int);
-
-                                               memcpy(buf + offset, &(media->sMedia.sAVI.nBegin), sizeof(int));
-                                               offset += sizeof(int);
-
-                                               memcpy(buf + offset, &(media->sMedia.sAVI.nEnd), sizeof(int));
-                                               offset += sizeof(int);
-
-                                               memcpy(buf + offset, &(media->sMedia.sAVI.nDurTime), sizeof(int));
-                                               offset += sizeof(int);
-
-                                               memcpy(buf + offset, &(media->sMedia.sAVI.nBgColor), sizeof(int));
-                                               offset += sizeof(int);
-                                       }
+                                       memcpy(buf + offset, media, sizeof(MMS_MEDIA_S));
+                                       offset += sizeof(MMS_MEDIA_S);
+                                       MSG_SEC_DEBUG("[#%2d][%5d][%d page][%d media] media type [%d],  drm type [%d], filepath [%s]", serial_index++, offset, pageIdx, i, media->mediatype, media->drmType, media->szFilePath);
                                }
                        }
 
@@ -527,571 +533,1156 @@ char* _MsgMmsSerializeMessageData(const MMS_MESSAGE_DATA_S* pMsgData, unsigned i
                }
        }
 
+       MSG_DEBUG("[#%2d][%5d] region count = %d",serial_index++, offset, pMsgData->regionCnt);
+
        memcpy(buf + offset, &pMsgData->regionCnt, sizeof(int));
        offset += sizeof(int);
-       MSG_DEBUG("pMsgData->regionCnt: %d", pMsgData->regionCnt);
 
        if (pMsgData->regionlist) {
                for (int i = 0; i < pMsgData->regionCnt; ++ i) {
                        MMS_SMIL_REGION *region = (MMS_SMIL_REGION *)g_list_nth_data(pMsgData->regionlist, i);
-
-                       memcpy(buf + offset, region->szID, MAX_SMIL_REGION_ID);
-                       offset += MAX_SMIL_REGION_ID;
-                       MSG_DEBUG("%d region's ID = %s", i, region->szID);
-                       memcpy(buf + offset, &region->nLeft, sizeof(MMS_LENGTH));
-                       offset += sizeof(MMS_LENGTH);
-                       memcpy(buf + offset, &region->nTop, sizeof(MMS_LENGTH));
-                       offset += sizeof(MMS_LENGTH);
-                       memcpy(buf + offset, &region->width, sizeof(MMS_LENGTH));
-                       offset += sizeof(MMS_LENGTH);
-                       memcpy(buf + offset, &region->height, sizeof(MMS_LENGTH));
-                       offset += sizeof(MMS_LENGTH);
-                       memcpy(buf + offset, &region->bgColor, sizeof(int));
-                       offset += sizeof(int);
-                       memcpy(buf + offset, &region->fit, sizeof(REGION_FIT_TYPE_T));
-                       offset += sizeof(REGION_FIT_TYPE_T);
+                       memcpy(buf + offset, region, sizeof(MMS_SMIL_REGION));
+                       offset += sizeof(MMS_SMIL_REGION);
                }
        }
 
+       MSG_DEBUG("[#%2d][%5d] attach count = %d",serial_index++, offset, pMsgData->attachCnt);
+
        memcpy(buf + offset, &pMsgData->attachCnt, sizeof(int));
        offset += sizeof(int);
-       MSG_DEBUG("pMsgData->attachCnt: %d", pMsgData->attachCnt);
 
        if (pMsgData->attachlist) {
                for (int i = 0; i < pMsgData->attachCnt; ++ i) {
                        MMS_ATTACH_S *attach = (MMS_ATTACH_S *)g_list_nth_data(pMsgData->attachlist, i);
-
-                       memcpy(buf + offset, &(attach->mediatype), sizeof(MimeType));
-                       offset += sizeof(MimeType);
-                       MSG_DEBUG("%d attachment's mediatype = %d", i, attach->mediatype);
-
-                       memcpy(buf + offset, attach->szFileName, MSG_FILENAME_LEN_MAX);
-                       offset += MSG_FILENAME_LEN_MAX;
-                       MSG_DEBUG("%d attachment's filename = %s", i, attach->szFileName);
-
-                       memcpy(buf + offset, attach->szFilePath, MSG_FILEPATH_LEN_MAX);
-                       offset += MSG_FILEPATH_LEN_MAX;
-                       MSG_DEBUG("%d attachment's filepath = %s", i, attach->szFilePath);
-
-                       memcpy(buf + offset, &(attach->fileSize), sizeof(int));
-                       offset +=  sizeof(int);
-                       MSG_DEBUG("%d attachment's file size = %d", i, attach->fileSize);
-
-#ifdef __SUPPORT_DRM__
-                       memcpy(buf + offset, &(attach->drmType), sizeof(MsgDrmType));
-                       offset +=  sizeof(MsgDrmType);
-                       memcpy(buf + offset, attach->szDrm2FullPath, MSG_FILEPATH_LEN_MAX);
-                       offset += MSG_FILEPATH_LEN_MAX;
-#endif
+                       memcpy(buf + offset, attach, sizeof(MMS_ATTACH_S));
+                       offset += sizeof(MMS_ATTACH_S);
+                       MSG_SEC_DEBUG("[#%2d][%5d][%d attach] attach filepath = %s, drm type = [%d]", serial_index++, offset, i, attach->szFilePath, attach->drmType);
                }
        }
 
+       MSG_DEBUG("[#%2d][%5d] transition count = %d",serial_index++, offset, pMsgData->transitionCnt);
+
        memcpy(buf + offset, &pMsgData->transitionCnt, sizeof(int));
        offset += sizeof(int);
-       MSG_DEBUG("pMsgData->transitionCnt: %d", pMsgData->transitionCnt);
-
        if (pMsgData->transitionlist) {
                for (int i = 0; i < pMsgData->transitionCnt; ++ i) {
                        MMS_SMIL_TRANSITION *transition = (MMS_SMIL_TRANSITION *)g_list_nth_data(pMsgData->transitionlist, i);
-
-                       memcpy(buf + offset, transition->szID, MAX_SMIL_TRANSITION_ID);
-                       offset += MAX_SMIL_TRANSITION_ID;
-                       MSG_DEBUG("%d transition's ID = %s", i, transition->szID);
-
-                       memcpy(buf + offset, &transition->nType, sizeof(MmsSmilTransType));
-                       offset += sizeof(MmsSmilTransType);
-                       memcpy(buf + offset, &transition->nSubType, sizeof(MmsSmilTransSubType));
-                       offset += sizeof(MmsSmilTransSubType);
-                       memcpy(buf + offset, &transition->nDur, sizeof(int));
-                       offset += sizeof(int);
+                       memcpy(buf + offset, transition, sizeof(MMS_SMIL_TRANSITION));
+                       offset += sizeof(MMS_SMIL_TRANSITION);
                }
        }
 
+       MSG_DEBUG("[#%2d][%5d] meta count = %d",serial_index++, offset, pMsgData->metaCnt);
        memcpy(buf + offset, &pMsgData->metaCnt, sizeof(int));
        offset += sizeof(int);
-       MSG_DEBUG("pMsgData->metaCnt: %d", pMsgData->metaCnt);
 
        if (pMsgData->metalist) {
                for (int i = 0; i < pMsgData->metaCnt; ++ i) {
                        MMS_SMIL_META *meta = (MMS_SMIL_META *)g_list_nth_data(pMsgData->metalist, i);
 
-                       memcpy(buf + offset, meta->szID, MAX_SMIL_META_ID);
-                       offset += MAX_SMIL_META_ID;
-                       MSG_DEBUG("%d meta's ID = %s", i, meta->szID);
-
-                       memcpy(buf + offset, meta->szName, MAX_SMIL_META_NAME);
-                       offset += MAX_SMIL_META_NAME;
-                       MSG_DEBUG("%d meta's ID = %s", i, meta->szID);
-
-                       memcpy(buf + offset, meta->szContent, MAX_SMIL_META_CONTENT);
-                       offset += MAX_SMIL_META_CONTENT;
-                       MSG_DEBUG("%d meta's ID = %s", i, meta->szID);
+                       memcpy(buf + offset, meta, sizeof(MMS_SMIL_META));
+                       offset += sizeof(MMS_SMIL_META);
                }
        }
 
+       MSG_DEBUG("[#%2d][%5d] root layout",serial_index++, offset);
        memcpy(buf + offset, &pMsgData->rootlayout, sizeof(MMS_SMIL_ROOTLAYOUT));
        offset += sizeof(MMS_SMIL_ROOTLAYOUT);
 
 #ifdef FEATURE_JAVA_MMS
+       MSG_DEBUG("[#%2d][%5d] java mms",serial_index++, offset);
        memcpy(buf + offset, &pMsgData->msgAppId, sizeof(MMS_APPID_INFO_S));
        offset += sizeof(MMS_APPID_INFO_S);
 #endif
 
+       memcpy (buf + offset, &pMsgData->header, sizeof(MMS_HEADER_DATA_S));
+       MSG_DEBUG("[#%2d][%5d] mms header",serial_index++, offset);
+       offset += sizeof(MMS_HEADER_DATA_S);
+
+       memcpy (buf + offset, &pMsgData->smil, sizeof(MMS_MULTIPART_DATA_S));
+       MSG_DEBUG("[#%2d][%5d] mms smil",serial_index++, offset);
+       offset += sizeof(MMS_MULTIPART_DATA_S);
+
        *pSize = offset;
 
+       MSG_DEBUG("Expect Buffer Size: %d, Final offset : %d", bufsize, offset);
+       MSG_END();
        return buf;
 }
 
-int _MsgMmsGetPageCount(MMS_MESSAGE_DATA_S *pMsgData)
+bool _MsgMmsDeserializeMessageData(MMS_MESSAGE_DATA_S *pMsgData, const char *pData)
 {
-       if (pMsgData == NULL) {
-               MSG_DEBUG("pMsgData is NULL");
-               return 0;
+       MSG_BEGIN();
+
+       if (pMsgData == NULL || pData == NULL) {
+               MSG_DEBUG("param is NULL. pBody = %x, pData = %x", pMsgData, pData);
+               return false;
        }
 
-       int count = 0;
+       int offset = 0;
+       int pageCnt = 0;
+       int filePathLen = 0;
 
-       if (pMsgData->pagelist)
-               count = g_list_length(pMsgData->pagelist);
+       MMS_PAGE_S *pPage = NULL;
+       MMS_MEDIA_S *pMedia = NULL;
+       MMS_SMIL_REGION *pRegion = NULL;
+       MMS_ATTACH_S *pAttach = NULL;
+       MMS_SMIL_TRANSITION *pTransition = NULL;
+       MMS_SMIL_META *pMeta = NULL;
 
-       MSG_DEBUG("Page Count: %d", count);
-       return count;
+       int serial_index = 0;
+
+       int type;
+
+       memcpy(&type, pData, sizeof(int));
+       MSG_DEBUG("[#%2d][%5d] backup type = %d",serial_index++, offset, type);
+       offset += sizeof(int);
+
+       pMsgData->backup_type = type;
+
+       memcpy(&filePathLen, pData + offset, sizeof(int));
+       MSG_DEBUG("[#%2d][%5d] smil path len = %d",serial_index, offset, filePathLen);
+       offset += sizeof(int);
+
+       if (filePathLen > MSG_FILEPATH_LEN_MAX) {
+               MSG_DEBUG("Smil File Path Length is abnormal.");
+               return false;
+       }
+
+       memset(pMsgData->szSmilFilePath, 0x00, MSG_FILEPATH_LEN_MAX);
+
+       if (filePathLen > 0) {
+               memcpy(pMsgData->szSmilFilePath, pData + offset, filePathLen);
+               MSG_DEBUG("[#%2d][%5d] smil path = %s",serial_index, offset, pMsgData->szSmilFilePath);
+               offset += filePathLen;
+       }
+
+       serial_index++;
+
+       memcpy(&(pMsgData->pageCnt), pData + offset, sizeof(int));
+       MSG_DEBUG("[#%2d][%5d] page count = %d",serial_index++, offset, pMsgData->pageCnt);
+       offset += sizeof(int);
+
+       pageCnt = pMsgData->pageCnt;
+
+       for (int j = 0; j < pageCnt; ++j) {
+               pPage = (MMS_PAGE_S *)calloc(sizeof(MMS_PAGE_S), 1);
+               if (pPage == NULL)
+                       return false;
+
+               memcpy(&pPage->mediaCnt, pData + offset, sizeof(int));
+               MSG_DEBUG("[#%2d][%5d][%d page] media count = %d", serial_index++, offset, j, pPage->mediaCnt);
+               offset += sizeof(int);
+
+               for (int i = 0; i < pPage->mediaCnt; ++i) {
+                       pMedia = (MMS_MEDIA_S *)calloc(sizeof(MMS_MEDIA_S), 1);
+                       if (pMedia == NULL) {
+                               free(pPage);
+                               return false;
+                       }
+
+                       memcpy(pMedia, pData + offset, sizeof(MMS_MEDIA_S));
+
+                       offset += sizeof(MMS_MEDIA_S);
+
+                       MSG_SEC_DEBUG("[#%2d][%5d][%d page][%d media] media type [%d], drm type [%d], filepath [%s], content type [%s]", serial_index++, offset, j, i, pMedia->mediatype, pMedia->drmType, pMedia->szFilePath, pMedia->szContentType);
+
+                       if (strlen(pMedia->szFilePath) >0) {
+                               pPage->medialist = g_list_append(pPage->medialist, pMedia);
+                       } else {
+                               free(pMedia);
+                       }
+               }
+
+               pPage->mediaCnt = g_list_length(pPage->medialist);
+
+               memcpy(&pPage->nDur , pData + offset, sizeof(int));
+               offset += sizeof(int);
+               memcpy(&pPage->nBegin , pData + offset, sizeof(int));
+               offset += sizeof(int);
+               memcpy(&pPage->nEnd , pData + offset, sizeof(int));
+               offset += sizeof(int);
+               memcpy(&pPage->nMin , pData + offset, sizeof(int));
+               offset += sizeof(int);
+               memcpy(&pPage->nMax , pData + offset, sizeof(int));
+               offset += sizeof(int);
+               memcpy(&pPage->nRepeat , pData + offset, sizeof(int));
+               offset += sizeof(int);
+
+               pMsgData->pagelist = g_list_append(pMsgData->pagelist, pPage);
+//             if (pPage->medialist) {
+//                     pMsgData->pagelist = g_list_append(pMsgData->pagelist, pPage);
+//             } else {
+//                     free(pPage);
+//                     pPage = NULL;
+//             }
+
+       }
+
+       pMsgData->pageCnt = g_list_length(pMsgData->pagelist);
+
+       //Processing Region List
+       memcpy(&pMsgData->regionCnt, pData + offset, sizeof(int));
+       MSG_DEBUG("[#%2d][%5d] region count = %d",serial_index++, offset, pMsgData->regionCnt);
+       offset += sizeof(int);
+
+       //MSG_DEBUG(" pBody->regionCnt: %d", pBody->regionCnt);
+
+       for (int i = 0; i < pMsgData->regionCnt; ++i) {
+               pRegion = (MMS_SMIL_REGION *)calloc(sizeof(MMS_SMIL_REGION), 1);
+               if (pRegion == NULL)
+                       return false;
+
+               memcpy(pRegion, pData + offset, sizeof(MMS_SMIL_REGION));
+               offset += sizeof(MMS_SMIL_REGION);
+
+               pMsgData->regionlist = g_list_append(pMsgData->regionlist, pRegion);
+       }
+
+       //Processing Attachment List
+       memcpy(&pMsgData->attachCnt, pData + offset, sizeof(int));
+       MSG_DEBUG("[#%2d][%5d] attach count = %d",serial_index++, offset, pMsgData->attachCnt);
+       offset += sizeof(int);
+
+       for (int i = 0; i < pMsgData->attachCnt; ++i) {
+               pAttach = (MMS_ATTACH_S *)calloc(sizeof(MMS_ATTACH_S), 1);
+               if (pAttach == NULL)
+                       return false;
+
+               memcpy(pAttach, pData + offset, sizeof(MMS_ATTACH_S));
+               offset += sizeof(MMS_ATTACH_S);
+
+               MSG_SEC_DEBUG("[#%2d][%5d][%d attach] drm type [%d],  attach filepath = [%s], content type = [%s]", serial_index++, offset, i, pAttach->drmType, pAttach->szFilePath, pAttach->szContentType);
+               if (strlen(pAttach->szFilePath) >0)
+                       pMsgData->attachlist = g_list_append(pMsgData->attachlist, pAttach);
+               else {
+                       free(pAttach);
+                       pAttach = NULL;
+               }
+       }
+
+       pMsgData->attachCnt = g_list_length(pMsgData->attachlist);
+
+       //Processing Transition List
+       memcpy(&pMsgData->transitionCnt, pData + offset, sizeof(int));
+       MSG_DEBUG("[#%2d][%5d] transition count = %d",serial_index++, offset, pMsgData->transitionCnt);
+       offset += sizeof(int);
+
+       for (int i = 0; i < pMsgData->transitionCnt; ++i) {
+               pTransition = (MMS_SMIL_TRANSITION *)calloc(sizeof(MMS_SMIL_TRANSITION), 1);
+               if (pTransition == NULL)
+                       return false;
+
+               memcpy(pTransition, pData + offset, sizeof(MMS_SMIL_TRANSITION));
+               offset += sizeof(MMS_SMIL_TRANSITION);
+
+               pMsgData->transitionlist = g_list_append(pMsgData->transitionlist, pTransition);
+       }
+
+       //Processing Meta List
+       memcpy(&pMsgData->metaCnt, pData + offset, sizeof(int));
+       MSG_DEBUG("[#%2d][%5d] meta count = %d",serial_index++, offset, pMsgData->metaCnt);
+       offset += sizeof(int);
+
+       for (int i = 0; i < pMsgData->metaCnt; ++i) {
+               pMeta = (MMS_SMIL_META *)calloc(sizeof(MMS_SMIL_META), 1);
+               if (pMeta == NULL)
+                       return false;
+
+               memcpy(pMeta, pData + offset, sizeof(MMS_SMIL_META));
+               offset += sizeof(MMS_SMIL_META);
+
+               pMsgData->metalist = g_list_append(pMsgData->metalist, pMeta);
+       }
+
+       MSG_DEBUG("[#%2d][%5d] root layout",serial_index++, offset);
+       memcpy(&pMsgData->rootlayout, pData + offset, sizeof(MMS_SMIL_ROOTLAYOUT));
+       offset += sizeof(MMS_SMIL_ROOTLAYOUT);
+
+#ifdef FEATURE_JAVA_MMS
+       MSG_DEBUG("[#%2d][%5d] java mms",serial_index++, offset);
+       memcpy(&pMsgData->msgAppId, pData + offset, sizeof(MMS_APPID_INFO_S));
+       offset += sizeof(MMS_APPID_INFO_S);
+//     MSG_DEBUG("java_app_id valid:%d, appId:%s repleToAppId:%s", pBody->msgAppId.valid, pBody->msgAppId.appId, pBody->msgAppId.replyToAppId);
+#endif
+
+       memcpy(&pMsgData->header, pData + offset, sizeof(MMS_HEADER_DATA_S));
+       MSG_DEBUG("[#%2d][%5d] mms header",serial_index++, offset);
+       offset += sizeof(MMS_HEADER_DATA_S);
+
+       memcpy(&pMsgData->smil, pData + offset, sizeof(MMS_MULTIPART_DATA_S));
+       MSG_DEBUG("[#%2d][%5d] mms smil",serial_index++, offset);
+       offset += sizeof(MMS_MULTIPART_DATA_S);
+
+       MSG_DEBUG("Final offset : %d", offset);
+       MSG_END();
+       return true;
 }
 
-MMS_PAGE_S *_MsgMmsGetPage(MMS_MESSAGE_DATA_S *pMsgData, int pageIdx)
+void _MsgMmsAttachPrint(MMS_ATTACH_S *attach)
 {
-       if (pMsgData == NULL) {
-               MSG_DEBUG("pMsgData is NULL");
-               return NULL;
+       if (attach == NULL) {
+               MSG_DEBUG("Invalid Parameter");
+               return;
        }
 
-       MMS_PAGE_S *page = NULL;
+       MSG_DEBUG("%-25s : %d", "Attach Mimetype", attach->mediatype);
+       MSG_SEC_DEBUG("%-25s : %s", "Attach content type", attach->szContentType);
+       MSG_SEC_DEBUG("%-25s : %s", "Attach filename", attach->szFileName);
+       MSG_SEC_DEBUG("%-25s : %s", "Attach filepath", attach->szFilePath);
+       MSG_DEBUG("%-25s : %d", "Attach filesize", attach->fileSize);
+       MSG_DEBUG("%-25s : %d", "Attach drm type", attach->drmType);
+       MSG_SEC_DEBUG("%-25s : %s", "Attach drm filepath", attach->szDrm2FullPath);
+}
 
-       if (pMsgData->pagelist)
-               page = (MMS_PAGE_S *)g_list_nth_data(pMsgData->pagelist, pageIdx);
+void _MsgMmsMediaPrint(MMS_MEDIA_S *media)
+{
+       if (media == NULL) {
+               MSG_DEBUG("Invalid Parameter");
+               return;
+       }
 
-       return page;
+       if (media->mediatype == MMS_SMIL_MEDIA_INVALID) {
+               MSG_DEBUG("%-25s : %s", "Media type","MMS_SMIL_MEDIA_INVALID");
+       } else if (media->mediatype == MMS_SMIL_MEDIA_IMG) {
+               MSG_DEBUG("%-25s : %s", "Media type","MMS_SMIL_MEDIA_IMG");
+       } else if (media->mediatype == MMS_SMIL_MEDIA_AUDIO) {
+               MSG_DEBUG("%-25s : %s", "Media type","MMS_SMIL_MEDIA_AUDIO");
+       } else if (media->mediatype == MMS_SMIL_MEDIA_VIDEO) {
+               MSG_DEBUG("%-25s : %s", "Media type","MMS_SMIL_MEDIA_VIDEO");
+       } else if (media->mediatype == MMS_SMIL_MEDIA_TEXT) {
+               MSG_DEBUG("%-25s : %s", "Media type","MMS_SMIL_MEDIA_TEXT");
+       } else if (media->mediatype == MMS_SMIL_MEDIA_ANIMATE) {
+               MSG_DEBUG("%-25s : %s", "Media type","MMS_SMIL_MEDIA_ANIMATE");
+       } else if (media->mediatype == MMS_SMIL_MEDIA_IMG_OR_VIDEO) {
+               MSG_DEBUG("%-25s : %s", "Media type","MMS_SMIL_MEDIA_REF");
+       } else {
+               MSG_DEBUG("%-25s : Unknown [%d]", "Media type", media->mediatype);
+       }
+
+       MSG_DEBUG("%-25s : %s", "Media src", media->szSrc);
+       MSG_SEC_DEBUG("%-25s : %s", "Media filename", media->szFileName);
+       MSG_SEC_DEBUG("%-25s : %s", "Media filepath", media->szFilePath);
+       MSG_SEC_DEBUG("%-25s : %s", "Media content type", media->szContentType);
+       MSG_SEC_DEBUG("%-25s : %s", "Media content id", media->szContentID);
+       MSG_SEC_DEBUG("%-25s : %s", "Media content location", media->szContentLocation);
+       MSG_SEC_DEBUG("%-25s : %s", "Media region id", media->regionId);
+       MSG_DEBUG("%-25s : %s", "Media alt", media->szAlt);
+       MSG_DEBUG("%-25s : %d", "Media drm type", media->drmType);
+       MSG_SEC_DEBUG("%-25s : %s", "Media drm filepath", media->szDrm2FullPath);
 }
 
-int _MsgMmsGetAttachCount(MMS_MESSAGE_DATA_S *pMsgData)
+void _MsgMmsPagePrint(MMS_PAGE_S *page)
 {
-       if (pMsgData == NULL) {
-               MSG_DEBUG("pMsgData is NULL");
-               return 0;
+       if (page == NULL) {
+               MSG_DEBUG("Invalid Parameter");
+               return;
        }
 
-       int count = 0;
+       MSG_DEBUG("%-25s : %d", "Page duration", page->nDur);
 
-       if (pMsgData->attachlist)
-               count = g_list_length(pMsgData->attachlist);
+       if (page->medialist) {
+               int list_count = g_list_length(page->medialist);
+               MSG_DEBUG("Media Count is [%d]", list_count);
+               for (int i = 0; i < list_count; i++) {
+                       MMS_MEDIA_S *media = (MMS_MEDIA_S *)g_list_nth_data(page->medialist, i);
+                       if (media) {
+                               MSG_DEBUG("[%d]th Media", i);
+                               _MsgMmsMediaPrint(media);
+                       } else {
+                               MSG_DEBUG("Not Exist Media Data in [%d]th", i);
+                       }
 
-       MSG_DEBUG("Attachment Count: %d", count);
-       return count;
+               }
+       }
 }
 
-MMS_ATTACH_S *_MsgMmsGetAttachment(MMS_MESSAGE_DATA_S *pMsgData, int attachIdx)
+void _MsgMmsPrint(MMS_MESSAGE_DATA_S *pMsgData)
 {
        if (pMsgData == NULL) {
-               MSG_DEBUG("pMsgData is NULL");
-               return NULL;
+               MSG_DEBUG("Invalid Parameter");
+               return;
        }
 
-       MMS_ATTACH_S *attach = NULL;
-       if (pMsgData->attachlist)
-               attach = (MMS_ATTACH_S *)g_list_nth_data(pMsgData->attachlist, attachIdx);
+       if (pMsgData->pagelist) {
+               int list_count = g_list_length(pMsgData->pagelist);
+               MSG_DEBUG("Page Count is [%d]", list_count);
+               for (int i = 0; i < list_count; i++) {
+                       MMS_PAGE_S *page = (MMS_PAGE_S *)g_list_nth_data(pMsgData->pagelist, i);
+                       if (page) {
+                               MSG_DEBUG("[%d]th Page", i);
+                               _MsgMmsPagePrint(page);
+                       } else {
+                               MSG_DEBUG("Not Exist Page Data in [%d]th", i);
+                       }
+
+               }
+       }
+
+       if (pMsgData->attachlist) {
+               int list_count = g_list_length(pMsgData->attachlist);
+               MSG_DEBUG("Attach Count is [%d]", list_count);
+               for (int i = 0; i < list_count; i++) {
+                       MMS_ATTACH_S *attach = (MMS_ATTACH_S *)g_list_nth_data(pMsgData->attachlist, i);
+                       if (attach) {
+                               MSG_DEBUG("[%d]th Attach", i);
+                               _MsgMmsAttachPrint(attach);
+                       } else {
+                               MSG_DEBUG("Not Exist Attach Data in [%d]th", i);
+                       }
+               }
+       }
 
-       return attach;
 }
 
-MMS_SMIL_REGION *_MsgMmsGetSmilRegion(MMS_MESSAGE_DATA_S *pMsgData, int regionIdx)
+MMS_ADDRESS_DATA_S *MsgMmsCreateAddress(int addressType, const char *addressVal)
 {
-       if (pMsgData == NULL) {
-               MSG_DEBUG("pMsgData is NULL");
-               return NULL;
+       MMS_ADDRESS_DATA_S * pMmsAddressData = (MMS_ADDRESS_DATA_S * )calloc(1, sizeof(MMS_ADDRESS_DATA_S));
+       if (pMmsAddressData != NULL) {
+               pMmsAddressData->address_type = addressType;
+               pMmsAddressData->address_val = strdup(addressVal);
        }
+       return pMmsAddressData;
+}
 
-       MMS_SMIL_REGION *region = NULL;
+void MsgMmsReleaseAddress(MMS_ADDRESS_DATA_S **ppMmsAddressData)
+{
+       if (ppMmsAddressData && *ppMmsAddressData) {
+               MMS_ADDRESS_DATA_S *pMmsAddressData = *ppMmsAddressData;
 
-       if (pMsgData->regionlist)
-               region = (MMS_SMIL_REGION *)g_list_nth_data(pMsgData->regionlist, regionIdx);
+               if (pMmsAddressData->address_val) {
+                       free(pMmsAddressData->address_val);
+                       pMmsAddressData->address_val = NULL;
+               }
 
-       return region;
+               free(pMmsAddressData);
+               *ppMmsAddressData = NULL;
+       }
 }
 
-MMS_MEDIA_S *_MsgMmsGetMedia(MMS_PAGE_S *pPage, int mediaIdx)
+void MsgMmsInitMultipart(MMS_MULTIPART_DATA_S *pMmsMultipart)
 {
-       if (!pPage) {
-               MSG_FATAL("pPage is NULL");
-               return NULL;
+       if (pMmsMultipart) {
+               pMmsMultipart->type = MIME_UNKNOWN;
+               pMmsMultipart->szContentType[0] = '\0';
+               pMmsMultipart->szFileName[0] = '\0';
+               pMmsMultipart->szContentID[0] = '\0';
+               pMmsMultipart->szContentLocation[0] = '\0';
+               pMmsMultipart->drmType = MSG_DRM_TYPE_NONE;
+               pMmsMultipart->szFilePath[0] = '\0';
+               pMmsMultipart->pMultipartData = NULL;
+               pMmsMultipart->nMultipartDataLen = 0;
+               pMmsMultipart->tcs_bc_level = -1;
+               pMmsMultipart->malware_allow = 0;
+               pMmsMultipart->szThumbFilePath[0] = '\0';
        }
+}
 
-       if (mediaIdx > pPage->mediaCnt || mediaIdx < 0) {
-               MSG_FATAL("Invalid media index = %d", mediaIdx);
-               return NULL;
+MMS_MULTIPART_DATA_S *MsgMmsCreateMultipart()
+{
+       MMS_MULTIPART_DATA_S *pMmsMultipart = (MMS_MULTIPART_DATA_S *)calloc(1, sizeof(MMS_MULTIPART_DATA_S));
+       if (pMmsMultipart) {
+               pMmsMultipart->type = MIME_UNKNOWN;
+               pMmsMultipart->szContentType[0] = '\0';
+               pMmsMultipart->szFileName[0] = '\0';
+               pMmsMultipart->szContentID[0] = '\0';
+               pMmsMultipart->szContentLocation[0] = '\0';
+               pMmsMultipart->drmType = MSG_DRM_TYPE_NONE;
+               pMmsMultipart->szFilePath[0] = '\0';
+               pMmsMultipart->pMultipartData = NULL;
+               pMmsMultipart->nMultipartDataLen = 0;
+               pMmsMultipart->tcs_bc_level = -1;
+               pMmsMultipart->malware_allow = 0;
+               pMmsMultipart->szThumbFilePath[0] = '\0';
        }
 
-       MMS_MEDIA_S *media = NULL;
-       if (pPage->medialist)
-               media = (MMS_MEDIA_S *)g_list_nth_data(pPage->medialist, mediaIdx);
+       return pMmsMultipart;
+}
 
-       return media;
+void MsgMmsReleaseMultipart(MMS_MULTIPART_DATA_S **ppMmsMultipart)
+{
+       if (ppMmsMultipart && *ppMmsMultipart) {
+               MMS_MULTIPART_DATA_S *pDelMmsMultipart = *ppMmsMultipart;
 
+               if (pDelMmsMultipart->pMultipartData != NULL) {
+                       g_free(pDelMmsMultipart->pMultipartData);
+                       pDelMmsMultipart->pMultipartData = NULL;
+               }
+               g_free(pDelMmsMultipart);
+               *ppMmsMultipart = NULL;
+       }
 }
 
-int _MsgMmsGetTransitionCount(MMS_MESSAGE_DATA_S *pMsgData)
+void MsgMmsInitHeader(MMS_HEADER_DATA_S *pMmsHeaderData)
 {
-       if (pMsgData == NULL) {
-               MSG_DEBUG("pMsgData is NULL");
-               return 0;
+       if (pMmsHeaderData) {
+               pMmsHeaderData->bcc = NULL;
+               pMmsHeaderData->cc = NULL;
+               pMmsHeaderData->contentLocation[0] = '\0';
+               pMmsHeaderData->szContentType[0] = '\0';
+               pMmsHeaderData->date = 0;
+               pMmsHeaderData->bDeliveryReport = false;
+               pMmsHeaderData->delivery.type = MMS_TIMETYPE_NONE;
+               pMmsHeaderData->delivery.time = 0;
+               pMmsHeaderData->expiry.type = MMS_TIMETYPE_NONE;
+               pMmsHeaderData->expiry.time = 0;
+               pMmsHeaderData->szFrom[0] = '\0';
+               pMmsHeaderData->messageClass = -1;
+               pMmsHeaderData->messageID[0]= '\0';
+               pMmsHeaderData->messageType = -1;
+               pMmsHeaderData->mmsVersion = -1;
+               pMmsHeaderData->messageSize = 0;
+               pMmsHeaderData->mmsPriority = -1;
+               pMmsHeaderData->bReadReport = 0;
+               pMmsHeaderData->bHideAddress = false;
+               pMmsHeaderData->mmsStatus = MSG_DELIVERY_REPORT_NONE;
+               pMmsHeaderData->szSubject[0] = '\0';
+               pMmsHeaderData->to = NULL;
+               pMmsHeaderData->trID[0] = '\0';
+               pMmsHeaderData->contentClass = -1;
        }
+}
 
-       int count = 0;
-
-       if (pMsgData->transitionlist)
-               count = g_list_length(pMsgData->transitionlist);
+MMS_HEADER_DATA_S *MsgMmsCreateHeader()
+{
+       MMS_HEADER_DATA_S *pMmsHeaderData = (MMS_HEADER_DATA_S * )calloc(1, sizeof(MMS_HEADER_DATA_S));
+       if (pMmsHeaderData) {
+               pMmsHeaderData->bcc = NULL;//   Bcc
+               pMmsHeaderData->cc = NULL;//    Cc
+               pMmsHeaderData->contentLocation[0] = '\0';
+               pMmsHeaderData->szContentType[0] = '\0';
+               pMmsHeaderData->date = 0;
+               pMmsHeaderData->bDeliveryReport = false; //     X-Mms-Delivery-Report
+               pMmsHeaderData->delivery.type = MMS_TIMETYPE_NONE;
+               pMmsHeaderData->delivery.time = 0;
+               pMmsHeaderData->expiry.type = MMS_TIMETYPE_NONE;
+               pMmsHeaderData->expiry.time = 0;
+               pMmsHeaderData->szFrom[0] = '\0';//     From
+               pMmsHeaderData->messageClass = -1;//Personal | Advertisement | Informational | Auto
+               pMmsHeaderData->messageID[0]= '\0';
+               pMmsHeaderData->messageType = -1;//MmsMsgType : ex) sendreq
+               pMmsHeaderData->mmsVersion = -1;//1.0 1.3
+               pMmsHeaderData->messageSize = 0; //     X-Mms-Message-Size
+               pMmsHeaderData->mmsPriority = -1;//_MSG_PRIORITY_TYPE_E : Low | Normal | High
+               pMmsHeaderData->bReadReport = 0;//      X-Mms-Read-Report
+               //      X-Mms-Report-Allowed
+               //      X-Mms-Response-Status
+               //      X-Mms-Response-Text
+               pMmsHeaderData->bHideAddress = false;// X-Mms-Sender-Visibility
+               pMmsHeaderData->mmsStatus = MSG_DELIVERY_REPORT_NONE;// X-Mms-Status
+               pMmsHeaderData->szSubject[0] = '\0';//  Subject
+               pMmsHeaderData->to = NULL;//    To
+               pMmsHeaderData->trID[0] = '\0';
+               //      X-Mms-Retrieve-Status
+               //      X-Mms-Retrieve-Text
+               //      X-Mms-Read-Status
+               //      X-Mms-Reply-Charging
+               //      X-Mms-Reply-Charging-Deadline
+               //      X-Mms-Reply-Charging-ID
+               //      X-Mms-Reply-Charging-Size
+               //      X-Mms-Previously-Sent-By
+               //      X-Mms-Previously-Sent-Date
+               //      X-Mms-Store
+               //      X-Mms-MM-State
+               //      X-Mms-MM-Flags
+               //      X-Mms-Store-Status
+               //      X-Mms-Store-Status-Text
+               //      X-Mms-Stored
+               //      X-Mms-Attributes
+               //      X-Mms-Totals
+               //      X-Mms-Mbox-Totals
+               //      X-Mms-Quotas
+               //      X-Mms-Mbox-Quotas
+               //      X-Mms-Message-Count
+               //      Content
+               //      X-Mms-Start
+               //      Additional-headers
+               //      X-Mms-Distribution-Indicator
+               //      X-Mms-Element-Descriptor
+               //      X-Mms-Limit
+               //      X-Mms-Recommended-Retrieval-Mode
+               //      X-Mms-Recommended-Retrieval-Mode-Text
+               //      X-Mms-Status-Text
+               //      X-Mms-Applic-ID
+               //      X-Mms-Reply-Applic-ID
+               //      X-Mms-Aux-Applic-Info
+               pMmsHeaderData->contentClass = -1;//text | image-basic| image-rich | video-basic | video-rich | megapixel | content-basic | content-rich
+               //      X-Mms-DRM-Content
+               //      X-Mms-Adaptation-Allowed
+               //      X-Mms-Replace-ID
+               //      X-Mms-Cancel-ID
+               //      X-Mms-Cancel-Status
+       }
 
-       MSG_DEBUG("Transition Count: %d", count);
-       return count;
+       return pMmsHeaderData;
 }
 
-MMS_SMIL_TRANSITION *_MsgMmsGetTransition(MMS_MESSAGE_DATA_S *pMsgData, int transitionIdx)
+void MsgMmsReleaseHeader(MMS_HEADER_DATA_S **ppMmHeadersData)
 {
-       if (pMsgData == NULL) {
-               MSG_DEBUG("pMsgData is NULL");
-               return NULL;
-       }
+       if (ppMmHeadersData && *ppMmHeadersData) {
+               MMS_HEADER_DATA_S *pMmsHeaderData = *ppMmHeadersData;
 
-       MMS_SMIL_TRANSITION *transition = NULL;
-       if (pMsgData->transitionlist)
-               transition = (MMS_SMIL_TRANSITION *)g_list_nth_data(pMsgData->transitionlist, transitionIdx);
+               free(pMmsHeaderData);
 
-       return transition;
+               *ppMmHeadersData = NULL;
+       }
 }
 
-MMS_SMIL_META *_MsgMmsGetMeta(MMS_MESSAGE_DATA_S *pMsgData, int metaIdx)
+MMS_DATA_S *MsgMmsCreate()
 {
-       if (pMsgData == NULL) {
-               MSG_DEBUG("pMsgData is NULL");
-               return NULL;
+       MMS_DATA_S * mms_data = (MMS_DATA_S * )calloc(1, sizeof(MMS_DATA_S));
+       if (mms_data) {
+               mms_data->header = NULL;
+               mms_data->multipartlist = NULL;
+               mms_data->smil = NULL;
        }
+       return mms_data;
+}
 
-       MMS_SMIL_META *meta = NULL;
+void MsgMmsRelease(MMS_DATA_S **ppMmsData)
+{
+       if (ppMmsData && *ppMmsData) {
+               MMS_DATA_S *pMmsData = *ppMmsData;
 
-       if (pMsgData->metalist)
-               meta = (MMS_SMIL_META *)g_list_nth_data(pMsgData->metalist, metaIdx);
+               if (pMmsData->header)
+                       MsgMmsReleaseHeader(&pMmsData->header);
 
-       return meta;
+               if (pMmsData->smil)
+                       MsgMmsReleaseMultipart(&pMmsData->smil);
+
+               MsgMmsReleaseMultipartList(&pMmsData->multipartlist);
+
+               free(pMmsData);
+
+               *ppMmsData = NULL;
+       }
 }
 
-int    _MsgMmsGetMetaCount(MMS_MESSAGE_DATA_S *pMsgData)
+static void __freeMultipartListItem(gpointer data)
 {
-       if (pMsgData == NULL) {
-               MSG_DEBUG("pMsgData is NULL");
-               return 0;
-       }
+       MMS_MULTIPART_DATA_S * pMultipart = (MMS_MULTIPART_DATA_S *)data;
 
-       int count = 0;
+       if (pMultipart) {
+               MsgMmsReleaseMultipart(&pMultipart);
+       }
+}
 
-       if (pMsgData->metalist)
-               count = g_list_length(pMsgData->metalist);
+int MsgMmsReleaseMultipartList(MMSList **ppMultipartList)
+{
+       if (ppMultipartList && *ppMultipartList) {
+               g_list_free_full(*ppMultipartList, __freeMultipartListItem);
+               *ppMultipartList = NULL;
+       }
 
-       MSG_DEBUG("Meta Count: %d", count);
-       return count;
+       return 0;
 }
 
+static void __freeAddressListItem(gpointer data)
+{
+       MMS_ADDRESS_DATA_S * pAddressData = (MMS_ADDRESS_DATA_S *)data;
+
+       MsgMmsReleaseAddress(&pAddressData);
 
-bool           _MsgMmsDeserializeMessageData(MMS_MESSAGE_DATA_S* pBody, char* pData)
+}
+
+int MsgMmsReleaseAddressList(MMSList **ppAddressList)
 {
-       MSG_DEBUG("MmsGetMsgBodyfromFile");
+       if (ppAddressList && *ppAddressList) {
+               g_list_free_full(*ppAddressList, __freeAddressListItem);
+               *ppAddressList = NULL;
+       }
 
-       if (pBody == NULL || pData == NULL) {
-               MSG_DEBUG("param is NULL. pBody = %x, pData = %x", pBody, pData);
-               return false;
+       return 0;
+}
+
+static void removeLessGreaterMark(const char *szSrcID, char *szDest, int destSize)
+{
+       char szBuf[MSG_MSG_ID_LEN + 1] = {0, };
+       int cLen = strlen(szSrcID);
+
+       if (cLen > 1 && szSrcID[0] == '<' && szSrcID[cLen - 1] == '>') {
+               strncpy(szBuf, &szSrcID[1], cLen - 2);
+               szBuf[cLen - 2] = '\0';
+       } else if (cLen > 1 && szSrcID[0] == '"' && szSrcID[cLen-1] == '"') {
+               strncpy(szBuf, &szSrcID[1], cLen - 2);
+               szBuf[cLen - 2] = '\0';
+       } else {
+               strncpy(szBuf, szSrcID, cLen);
+               szBuf[cLen] = '\0';
        }
 
-       int offset = 0;
-       int pageCnt = 0;
-       int filePathLen = 0;
+       snprintf(szDest, destSize, "%s", szBuf);
+}
 
-       MMS_PAGE_S *pPage = NULL;
-       MMS_MEDIA_S *pMedia = NULL;
-       MMS_SMIL_REGION *pRegion = NULL;
-       MMS_ATTACH_S *pAttach = NULL;
-       MMS_SMIL_TRANSITION *pTransition = NULL;
-       MMS_SMIL_META *pMeta = NULL;
+static bool IsMatchedMedia(MMS_MEDIA_S *media, MMS_MULTIPART_DATA_S *pMultipart)
+{
+       if (strlen(pMultipart->szContentID) > 0) {
 
-       memcpy(&filePathLen, pData, sizeof(int));
+               char szTempContentID[MSG_MSG_ID_LEN + 1] = {0,};
+               removeLessGreaterMark(pMultipart->szContentID, szTempContentID, sizeof(szTempContentID));
 
-       offset += sizeof(int);
+               if (strcmp(media->szContentID, szTempContentID) == 0) {
+                       return true;
+               }
 
-       MSG_DEBUG("Smil File Path Length : %d", filePathLen);
+               if (strcmp(media->szContentLocation,  szTempContentID) == 0) {
+                       return true;
+               }
+       }
 
-       if (filePathLen > MSG_FILEPATH_LEN_MAX) {
-               MSG_DEBUG("Smil File Path Length is abnormal.");
-               return false;
+       if (strlen(pMultipart->szContentLocation) > 0) {
+               if (strcmp(media->szContentID,  pMultipart->szContentLocation) == 0) {
+                       return true;
+               }
+
+               if (strcmp(media->szContentLocation,  pMultipart->szContentLocation) == 0) {
+                       return true;
+               }
        }
 
-       memset(pBody->szSmilFilePath, 0x00, MSG_FILEPATH_LEN_MAX);
+       return false;
+}
 
-       if (filePathLen > 0) {
-               memcpy(pBody->szSmilFilePath, pData + offset, filePathLen);
+static bool MmsFindAndInsertPart(MMS_MESSAGE_DATA_S *pMsgData, MMS_MULTIPART_DATA_S *pMultipart)
+{
+       bool insert_media = false;
 
-               offset += filePathLen;
-       }
+       if (pMsgData->pagelist) {
+               for (int pageIdx = 0; pageIdx < pMsgData->pageCnt; pageIdx++) {
 
-       memcpy(&(pBody->pageCnt), pData + offset, sizeof(int));
+                       MMS_PAGE_S *page = (MMS_PAGE_S *)g_list_nth_data(pMsgData->pagelist, pageIdx);
 
-       offset += sizeof(int);
+                       if (page && page->medialist) {
 
-       pageCnt = pBody->pageCnt;
+                               for (int mediaIdx = 0; mediaIdx < page->mediaCnt; mediaIdx++) {
 
-       MSG_DEBUG("MMS PAGE COUNT: %d", pageCnt);
+                                       MMS_MEDIA_S *media = (MMS_MEDIA_S *)g_list_nth_data(page->medialist, mediaIdx);
 
-       for (int j = 0; j < pageCnt; ++j) {
-               pPage = (MMS_PAGE_S *)calloc(sizeof(MMS_PAGE_S), 1);
+                                       if (media) { // add media
+                                               if (IsMatchedMedia(media, pMultipart) == true) { //matched media
+                                                       insert_media = true;
+                                                       media->drmType = pMultipart->drmType;
+                                                       snprintf(media->szFilePath, sizeof(media->szFilePath), "%s", pMultipart->szFilePath);
+                                                       snprintf(media->szFileName, sizeof(media->szFileName), "%s", pMultipart->szFileName);
+                                                       snprintf(media->szContentID, sizeof(media->szContentID), "%s", pMultipart->szContentID);
+                                                       snprintf(media->szContentLocation, sizeof(media->szContentLocation), "%s", pMultipart->szContentLocation);
+                                                       snprintf(media->szContentType, sizeof(media->szContentType), "%s", pMultipart->szContentType);
+                                                       MSG_SEC_DEBUG("InsertPart to pageIndx [%d] mediaIdx[%d] media[%p] : path = [%s], name = [%s], cid = [%s], cl = [%s], ct = [%s]"\
+                                                                       , pageIdx, mediaIdx, media, media->szFilePath, media->szFileName, media->szContentID, media->szContentLocation, media->szContentType);
+                                               }
+                                       }
+                               } //end for media list
+                       }
+               } //end for page list
+       }
 
-               memcpy(&pPage->mediaCnt, pData + offset, sizeof(int));
-               offset += sizeof(int);
-               MSG_DEBUG("MMS MEDIA COUNT: %d", pPage->mediaCnt);
+       return insert_media;
+}
 
-               for (int i = 0; i < pPage->mediaCnt; ++i) {
-                       pMedia = (MMS_MEDIA_S *)calloc(sizeof(MMS_MEDIA_S), 1);
+static bool MmsInsertPartToMmsData(MMS_MESSAGE_DATA_S *pMsgData, MMS_MULTIPART_DATA_S *pMultipart)
+{
+       MSG_BEGIN();
 
-                       memcpy(&pMedia->mediatype, pData + offset, sizeof(int));
-                       offset += sizeof(int);
+       bool isInsert = false;
 
-                       memcpy(pMedia->szSrc, pData + offset, MSG_FILEPATH_LEN_MAX);
-                       offset += MSG_FILEPATH_LEN_MAX;
+       if (pMsgData == NULL || pMultipart == NULL) {
+               return false;
+       }
 
-                       memcpy(pMedia->szFileName, pData + offset, MSG_FILENAME_LEN_MAX);
-                       offset += MSG_FILENAME_LEN_MAX;
+       isInsert = MmsFindAndInsertPart(pMsgData, pMultipart);
+
+       if (isInsert == false) {
+               MMS_ATTACH_S *attachment = NULL;
+               attachment = (MMS_ATTACH_S *)calloc(sizeof(MMS_ATTACH_S), 1);
+               if (attachment) {
+                       attachment->drmType = pMultipart->drmType;
+                       attachment->mediatype = pMultipart->type;
+                       snprintf(attachment->szContentType, sizeof(attachment->szContentType), "%s", pMultipart->szContentType);
+                       snprintf(attachment->szFilePath, sizeof(attachment->szFilePath), "%s", pMultipart->szFilePath);
+                       snprintf(attachment->szFileName, sizeof(attachment->szFileName), "%s", pMultipart->szFileName);
+                       attachment->fileSize = MsgGetFileSize(attachment->szFilePath);
+                       MSG_SEC_DEBUG("Insert Attach to attachment[%p] : path = [%s], name = [%s], ct = [%s], size = [%d]"\
+                                                       , attachment, attachment->szFilePath, attachment->szFileName, attachment->szContentType, attachment->fileSize);
+               }
 
-                       memcpy(pMedia->szFilePath, pData + offset, MSG_FILEPATH_LEN_MAX);
-                       offset += MSG_FILEPATH_LEN_MAX;
+               if (_MsgMmsAddAttachment(pMsgData, attachment) != MSG_SUCCESS) {
+                       g_free(attachment);
+                       return false;
+               }
+       }
 
-                       memcpy(pMedia->szContentID, pData + offset, MSG_MSG_ID_LEN+1);
-                       offset += MSG_MSG_ID_LEN + 1;
+       MSG_END();
+       return true;
+}
+
+int MsgMmsConvertMmsDataToMmsMessageData(MMS_DATA_S *pSrc, MMS_MESSAGE_DATA_S *pDst)
+{
+       MSG_BEGIN();
 
-                       memcpy(pMedia->regionId, pData + offset, MAX_SMIL_REGION_ID);
-                       offset += MAX_SMIL_REGION_ID;
+       bzero(pDst, sizeof(MMS_MESSAGE_DATA_S));
 
-                       memcpy(pMedia->szAlt, pData + offset, MAX_SMIL_ALT_LEN);
-                       offset += MAX_SMIL_ALT_LEN;
+       if (pSrc->smil) {
+               if (MsgAccessFile(pSrc->smil->szFilePath, F_OK)) {
+                       gchar *contents = NULL;
+                       gsize length = 0;
 
-#ifdef __SUPPORT_DRM__
-                       memcpy(&pMedia->drmType, pData + offset, sizeof(MsgDrmType));
-                       offset += sizeof(MsgDrmType);
+                       g_file_get_contents(pSrc->smil->szFilePath, &contents, &length, NULL);
 
-                       memcpy(pMedia->szDrm2FullPath, pData + offset, MSG_FILEPATH_LEN_MAX);
-                       offset += MSG_FILEPATH_LEN_MAX;
-#endif
+                       if (contents) {
+                               MsgSmilParseSmilDoc(pDst, contents);
+                               g_free(contents);
+                       }
+               } else {
+                       if (pSrc->smil->pMultipartData) {
+                               char *smil_data = (char *)calloc(1, sizeof(char)*(pSrc->smil->nMultipartDataLen + 1));
+                               if (smil_data) {
+                                       memcpy(smil_data, pSrc->smil->pMultipartData, pSrc->smil->nMultipartDataLen);
+                                       MsgSmilParseSmilDoc(pDst, smil_data);
+                                       g_free(smil_data);
+                               }
+                       }
+               }
+       }
+
+       int len = g_list_length(pSrc->multipartlist);
+       for (int i = 0; i < len; i++) {
+               MMS_MULTIPART_DATA_S *multipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(pSrc->multipartlist, i);
+               if (multipart) {
+                       MmsInsertPartToMmsData(pDst, multipart);
+               }
+       }
 
-                       if (pMedia->mediatype == MMS_SMIL_MEDIA_TEXT) {
-                               MSG_DEBUG("##### MEDIA TYPE = TEXT #####");
-                               memcpy(pMedia->sMedia.sText.szTransInId, pData + offset, MAX_SMIL_TRANSIN_ID);
-                               offset += MAX_SMIL_TRANSIN_ID;
+       MSG_END();
+       return 0;
+}
 
-                               memcpy(pMedia->sMedia.sText.szTransOutId, pData + offset, MAX_SMIL_TRANSOUT_ID);
-                               offset += MAX_SMIL_TRANSOUT_ID;
+int MsgMmsConvertMmsMessageDataToMmsData(MMS_MESSAGE_DATA_S *pSrc, MMS_DATA_S *pDst)
+{
+       MSG_BEGIN();
+
+       char *pRawData = NULL;
+
+       pDst->backup_type = pSrc->backup_type;
+
+       int pageCnt = _MsgMmsGetPageCount(pSrc);
+       if (pSrc->smil.szFilePath[0] != '\0') {
+               MMS_MULTIPART_DATA_S *pMultipart = MsgMmsCreateMultipart();
+               if (pMultipart)
+                       memcpy(pMultipart, &pSrc->smil, sizeof(MMS_MULTIPART_DATA_S));
+               pDst->smil = pMultipart;
+       } else if (pageCnt > 0) {       // Multipart related
+               MsgSmilGenerateSmilDoc(pSrc, &pRawData);
+               if (pRawData) {
+                       MMS_MULTIPART_DATA_S *pMultipart = MsgMmsCreateMultipart();
+
+                       MSG_DEBUG("%s", pRawData);
+                       if (pMultipart) {
+                               pMultipart->pMultipartData = pRawData;
+                               pMultipart->nMultipartDataLen = strlen(pRawData);
+                               pMultipart->type = MIME_APPLICATION_SMIL;
+                               snprintf(pMultipart->szContentType, sizeof(pMultipart->szContentType), "%s", "application/smil");
+                               pDst->smil = pMultipart;
+                       }
+               } else {
+                       MSG_DEBUG("Fail to Generate SmilDoc");
+               }
+       }
 
-                               memcpy(&pMedia->sMedia.sText.nRepeat, pData + offset, sizeof(int));
-                               offset += sizeof(int);
+       for (int i = 0; i < pageCnt; ++i) {
+               MMS_PAGE_S *pPage = _MsgMmsGetPage(pSrc, i);
+               if (pPage) {
+                       int mediaCnt = pPage->mediaCnt;
+                       MSG_DEBUG("PAGE %d's media Cnt: %d", i+1, mediaCnt);
+
+                       for (int j = 0; j < mediaCnt; ++j) {
+                               MMS_MEDIA_S *pMedia = _MsgMmsGetMedia(pPage, j);
+                               if ((pMedia) && (pMedia->szFilePath[0] != 0)) {
+                                       MMS_MULTIPART_DATA_S *pMultipart = MsgMmsCreateMultipart();
+                                       if (pMultipart) {
+                                               snprintf(pMultipart->szContentID, sizeof(pMultipart->szContentID), "%s", pMedia->szContentID);
+                                               snprintf(pMultipart->szContentLocation, sizeof(pMultipart->szContentLocation), "%s", pMedia->szContentLocation);
+                                               snprintf(pMultipart->szFileName, sizeof(pMultipart->szFileName), "%s", pMedia->szFileName);
+                                               snprintf(pMultipart->szFilePath, sizeof(pMultipart->szFilePath), "%s", pMedia->szFilePath);
+                                               snprintf(pMultipart->szContentType, sizeof(pMultipart->szContentType), "%s", pMedia->szContentType);
+                                               pDst->multipartlist = g_list_append(pDst->multipartlist, pMultipart);
+                                       }
+                               }
+                       }
+               }
+       }
 
-                               memcpy(&pMedia->sMedia.sText.nBegin, pData + offset, sizeof(int));
-                               offset += sizeof(int);
+       //Processing Attachment List
+       int attachCnt = _MsgMmsGetAttachCount(pSrc);
+
+       for (int i = 0; i < attachCnt; ++i) {
+               MMS_ATTACH_S *pMedia = _MsgMmsGetAttachment(pSrc, i);
+               if (pMedia->szFilePath[0] != 0) {
+                       MMS_MULTIPART_DATA_S *pMultipart = MsgMmsCreateMultipart();
+                       if (pMultipart) {
+                               snprintf(pMultipart->szContentID, sizeof(pMultipart->szContentID), "%s", pMedia->szFileName);
+                               snprintf(pMultipart->szContentLocation, sizeof(pMultipart->szContentLocation), "%s", pMedia->szFileName);
+                               snprintf(pMultipart->szFileName, sizeof(pMultipart->szFileName), "%s", pMedia->szFileName);
+                               snprintf(pMultipart->szFilePath, sizeof(pMultipart->szFilePath), "%s", pMedia->szFilePath);
+                               snprintf(pMultipart->szContentType, sizeof(pMultipart->szContentType), "%s", pMedia->szContentType);
+
+                               pDst->multipartlist = g_list_append(pDst->multipartlist, pMultipart);
+                       }
+               }
+       }
 
-                               memcpy(&pMedia->sMedia.sText.nEnd, pData + offset, sizeof(int));
-                               offset += sizeof(int);
+       MSG_END();
 
-                               memcpy(&pMedia->sMedia.sText.nDurTime, pData + offset, sizeof(int));
-                               offset += sizeof(int);
+       return 0;
+}
 
-                               memcpy(&pMedia->sMedia.sText.nBgColor, pData + offset, sizeof(int));
-                               offset += sizeof(int);
+int MsgMmsGetSmilMultipart(MMSList *pMultipartList, MMS_MULTIPART_DATA_S **smil_multipart)
+{
+       const char *smil_content_type = "application/smil";
 
-                               memcpy(&pMedia->sMedia.sText.bBold, pData + offset, sizeof(bool));
-                               offset += sizeof(bool);
+       int len = g_list_length(pMultipartList);
 
-                               memcpy(&pMedia->sMedia.sText.bUnderLine, pData + offset, sizeof(bool));
-                               offset += sizeof(bool);
+       for (int i = 0; i < len; i++) {
+               MMS_MULTIPART_DATA_S *multipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(pMultipartList, i);
 
-                               memcpy(&pMedia->sMedia.sText.bItalic, pData + offset, sizeof(bool));
-                               offset += sizeof(bool);
+               if (multipart) {
 
-                               memcpy(&pMedia->sMedia.sText.bReverse, pData + offset, sizeof(bool));
-                               offset += sizeof(bool);
+                       if (strcasecmp(multipart->szContentType, smil_content_type) == 0 ) {
+                               *smil_multipart = multipart;
+                               break;
+                       }
+               }
+       }
 
-                               memcpy(&pMedia->sMedia.sText.nDirection, pData + offset, sizeof(MmsTextDirection));
-                               offset += sizeof(MmsTextDirection);
+       return 0;
+}
 
-                               //memcpy(&pMedia->sMedia.sText.nFont, pData + offset, sizeof(MmsSmilFontType));
-                               //offset += sizeof(MmsSmilFontType);
+//get content from filepath and save to pMultipartData
+int MsgMmsSetMultipartData(MMS_MULTIPART_DATA_S *pMultipart)
+{
+       if (pMultipart->pMultipartData != NULL)
+               return 0;
 
-                               memcpy(&pMedia->sMedia.sText.nSize, pData + offset, sizeof(int));
-                               offset += sizeof(int);
+       if (g_file_get_contents(pMultipart->szFilePath, &pMultipart->pMultipartData, &pMultipart->nMultipartDataLen, NULL) == false)
+               return -1;
 
-                               memcpy(&pMedia->sMedia.sText.nColor, pData + offset, sizeof(int));
-                               offset += sizeof(int);
-                       } else {
-                               MSG_DEBUG("##### MEDIA TYPE = IMAGE, AUDIO, VIDEO #####");
-                               memcpy(pMedia->sMedia.sAVI.szTransInId, pData + offset, MAX_SMIL_TRANSIN_ID);
-                               offset += MAX_SMIL_TRANSIN_ID;
+       //Due to Get data for Backup message
+       //memset(pMultipart->szFilePath, 0x00, sizeof(pMultipart->szFilePath));
+       return 0;
+}
 
-                               memcpy(pMedia->sMedia.sAVI.szTransOutId, pData + offset, MAX_SMIL_TRANSOUT_ID);
-                               offset += MAX_SMIL_TRANSOUT_ID;
+int MsgMmsSetMultipartListData(MMS_DATA_S *pMmsData)
+{
+       MSG_BEGIN();
 
-                               memcpy(&pMedia->sMedia.sAVI.nRepeat, pData + offset, sizeof(int));
-                               offset += sizeof(int);
+       MMSList *multipart_list = pMmsData->multipartlist;
 
-                               memcpy(&pMedia->sMedia.sAVI.nBegin, pData + offset, sizeof(int));
-                               offset += sizeof(int);
+       if (multipart_list) {
 
-                               memcpy(&pMedia->sMedia.sAVI.nEnd, pData + offset, sizeof(int));
-                               offset += sizeof(int);
+               if (pMmsData->smil) {
+                       MsgMmsSetMultipartData(pMmsData->smil);
+               }
+
+               for (int i = 0; i < (int)g_list_length(multipart_list); i++) {
 
-                               memcpy(&pMedia->sMedia.sAVI.nDurTime, pData + offset, sizeof(int));
-                               offset += sizeof(int);
+                       MMS_MULTIPART_DATA_S *pMultipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(multipart_list, i);
 
-                               memcpy(&pMedia->sMedia.sAVI.nBgColor, pData + offset, sizeof(int));
-                               offset += sizeof(int);
+                       if (pMultipart) {
+                               MsgMmsSetMultipartData(pMultipart);//app file -> data
                        }
-                       pPage->medialist = g_list_append(pPage->medialist, pMedia);
                }
+       }
 
-               memcpy(&pPage->nDur , pData + offset, sizeof(int));
-               offset += sizeof(int);
-               memcpy(&pPage->nBegin , pData + offset, sizeof(int));
-               offset += sizeof(int);
-               memcpy(&pPage->nEnd , pData + offset, sizeof(int));
-               offset += sizeof(int);
-               memcpy(&pPage->nMin , pData + offset, sizeof(int));
-               offset += sizeof(int);
-               memcpy(&pPage->nMax , pData + offset, sizeof(int));
-               offset += sizeof(int);
-               memcpy(&pPage->nRepeat , pData + offset, sizeof(int));
-               offset += sizeof(int);
+       MSG_END();
+       return 0;
+}
 
-               pBody->pagelist = g_list_append(pBody->pagelist, pPage);
+//pMultipartData set to file path
+int MsgMmsSetMultipartFilePath(const char *dirPath, MMS_MULTIPART_DATA_S *pMultipart)
+{
+       if (g_file_test(dirPath, G_FILE_TEST_IS_DIR) != true) {
+               MSG_SEC_DEBUG("g_file_test is false: [%s] is not dir or not exist", dirPath);
+               return -1;
        }
 
-       //Processing Region List
-       memcpy(&pBody->regionCnt, pData + offset, sizeof(int));
-       offset += sizeof(int);
+       memset(pMultipart->szFilePath, 0x00, sizeof(pMultipart->szFilePath));
 
-       MSG_DEBUG(" pBody->regionCnt: %d", pBody->regionCnt);
+       snprintf(pMultipart->szFilePath, sizeof(pMultipart->szFilePath), "%s/%s", dirPath, pMultipart->szFileName);
 
-       for (int i = 0; i < pBody->regionCnt; ++i) {
-               pRegion = (MMS_SMIL_REGION *)calloc(sizeof(MMS_SMIL_REGION), 1);
+       if (!MsgCreateFile (pMultipart->szFilePath, pMultipart->pMultipartData, pMultipart->nMultipartDataLen)) {
+               MSG_SEC_DEBUG("Fail to set content to file [%s]", pMultipart->szFilePath);
+               return -1;
+       }
 
-               memcpy(pRegion->szID, pData + offset, MAX_SMIL_REGION_ID);
-               offset += MAX_SMIL_REGION_ID;
-               memcpy(&pRegion->nLeft, pData + offset, sizeof(MMS_LENGTH));
-               offset += sizeof(MMS_LENGTH);
-               memcpy(&pRegion->nTop, pData + offset, sizeof(MMS_LENGTH));
-               offset += sizeof(MMS_LENGTH);
-               memcpy(&pRegion->width, pData + offset, sizeof(MMS_LENGTH));
-               offset += sizeof(MMS_LENGTH);
-               memcpy(&pRegion->height, pData + offset, sizeof(MMS_LENGTH));
-               offset += sizeof(MMS_LENGTH);
-               memcpy(&pRegion->bgColor, pData + offset, sizeof(int));
-               offset += sizeof(int);
-               memcpy(&pRegion->fit, pData + offset, sizeof(REGION_FIT_TYPE_T));
-               offset += sizeof(REGION_FIT_TYPE_T);
+       return 0;
+}
+
+int MsgMmsSetMultipartListFilePath(const char *dirPath, MMS_DATA_S *pMmsData)
+{
+       MSG_BEGIN();
 
-               pBody->regionlist = g_list_append(pBody->regionlist, pRegion);
+       char working_dir[MSG_FILENAME_LEN_MAX+1] = {0,};
+
+       snprintf(working_dir, sizeof(working_dir), "%s", dirPath);
+
+       if (mkdir(working_dir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
+               if (errno == EEXIST) {
+                       MSG_SEC_DEBUG("exist dir : [%s]", working_dir);
+               } else {
+                       MSG_SEC_DEBUG("Fail to Create Dir [%s]", working_dir);
+                       return -1;
+               }
        }
 
-       //Processing Attachment List
-       memcpy(&pBody->attachCnt, pData + offset, sizeof(int));
-       offset += sizeof(int);
+       MMSList *multipart_list = pMmsData->multipartlist;
 
-       MSG_DEBUG(" pBody->attachCnt: %d", pBody->attachCnt);
+       if (pMmsData->smil) {
+               snprintf(pMmsData->smil->szFileName, sizeof(pMmsData->smil->szFileName), "%s", "smil.smil");
+               MsgMmsSetMultipartFilePath(dirPath, pMmsData->smil);
+       }
 
-       for (int i = 0; i < pBody->attachCnt; ++i) {
-               pAttach = (MMS_ATTACH_S *)calloc(sizeof(MMS_ATTACH_S), 1);
+       if (multipart_list) {
 
-               memcpy(&pAttach->mediatype, pData + offset, sizeof(MimeType));
-               offset += sizeof(MimeType);
+               for (int i = 0; i < (int)g_list_length(multipart_list); i++) {
 
-               memcpy(pAttach->szFileName, pData + offset, MSG_FILENAME_LEN_MAX);
-               offset += MSG_FILENAME_LEN_MAX;
+                       MMS_MULTIPART_DATA_S *pMultipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(multipart_list, i);
 
-               memcpy(pAttach->szFilePath, pData + offset, MSG_FILEPATH_LEN_MAX);
-               offset += MSG_FILEPATH_LEN_MAX;
+                       if (pMultipart) {
+                               MsgMmsSetMultipartFilePath(dirPath, pMultipart);//data -> svc file
+                       }
+               }
+       }
 
-               memcpy(&pAttach->fileSize, pData + offset, sizeof(int));
-               offset += sizeof(int);
+       MSG_END();
+       return 0;
+}
+
+int printMultipart(MMS_MULTIPART_DATA_S *multipart)
+{
+       if (multipart) {
+               MSG_DEBUG("multipart ptr [%p]", multipart);
+               MSG_DEBUG("type : %d", multipart->type);
+               MSG_DEBUG("type str : %s", multipart->szContentType);
+               MSG_DEBUG("cid : %s", multipart->szContentID);
+               MSG_DEBUG("cl : %s", multipart->szContentLocation);
+               MSG_DEBUG("name : %s", multipart->szFileName);
+               MSG_DEBUG("filepath : %s", multipart->szFilePath);
+               MSG_DEBUG("tcs_bc_level : %d", multipart->tcs_bc_level);
+               MSG_DEBUG("malware_allow : %d", multipart->malware_allow);
+               MSG_DEBUG("thumbfilepath : %s", multipart->szThumbFilePath);
+       }
+       return 0;
+}
 
-#ifdef __SUPPORT_DRM__
-               memcpy(&pAttach->drmType, pData + offset, sizeof(MsgDrmType));
-               offset += sizeof(MsgDrmType);
+int printMultipartList(MMSList *pMultipartList)
+{
+       int len = g_list_length(pMultipartList);
+
+       for (int i = 0; i < len; i++) {
+               MMS_MULTIPART_DATA_S *multipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(pMultipartList, i);
+
+               if (multipart) {
+                       MSG_DEBUG("[%d] multipart ptr [%p]", i,  multipart);
+                       MSG_DEBUG("type : %d", multipart->type);
+                       MSG_DEBUG("type str : %s", multipart->szContentType);
+                       MSG_DEBUG("cid : %s", multipart->szContentID);
+                       MSG_DEBUG("cl : %s", multipart->szContentLocation);
+                       MSG_DEBUG("name : %s", multipart->szFileName);
+                       MSG_DEBUG("filepath : %s", multipart->szFilePath);
+                       MSG_DEBUG("tcs_bc_level : %d", multipart->tcs_bc_level);
+                       MSG_DEBUG("malware_allow : %d", multipart->malware_allow);
+                       MSG_DEBUG("thumbfilepath : %s", multipart->szThumbFilePath);
+               }
+       }
 
-               memcpy(pAttach->szDrm2FullPath, pData + offset, MSG_FILEPATH_LEN_MAX);
-               offset += MSG_FILEPATH_LEN_MAX;
-#endif
+       return 0;
+}
 
-               pBody->attachlist = g_list_append(pBody->attachlist, pAttach);
+void _MsgMmsMultipartPrint(MMS_MULTIPART_DATA_S *multipart)
+{
+       if (multipart == NULL) {
+               MSG_DEBUG("Invalid Parameter");
+               return;
        }
 
-       //Processing Transition List
-       memcpy(&pBody->transitionCnt, pData + offset, sizeof(int));
-       offset += sizeof(int);
+       MSG_DEBUG("%-25s : %d", "Multipart type", multipart->type);
+       MSG_SEC_DEBUG("%-25s : %s", "Multipart filename", multipart->szFileName);
+       MSG_SEC_DEBUG("%-25s : %s", "Multipart filepath", multipart->szFilePath);
+       MSG_SEC_DEBUG("%-25s : %s", "Multipart content type", multipart->szContentType);
+       MSG_SEC_DEBUG("%-25s : %s", "Multipart content id", multipart->szContentID);
+       MSG_SEC_DEBUG("%-25s : %s", "Multipart content location", multipart->szContentLocation);
+       MSG_DEBUG("%-25s : %d", "Multipart drm type", multipart->drmType);
 
-       MSG_DEBUG(" pBody->transitionCnt: %d", pBody->transitionCnt);
+}
 
-       for (int i = 0; i < pBody->transitionCnt; ++i) {
-               pTransition = (MMS_SMIL_TRANSITION *)calloc(sizeof(MMS_SMIL_TRANSITION), 1);
+bool  _MsgMmsRemoveEmptyMedia(MMS_PAGE_S *pPage)
+{
+       MMS_MEDIA_S *pMedia = NULL;
 
-               memcpy(pTransition->szID, pData + offset, MAX_SMIL_TRANSITION_ID);
-               offset += MAX_SMIL_TRANSITION_ID;
+       int mediaCnt  = g_list_length(pPage->medialist);
 
-               memcpy(&pTransition->nType, pData + offset, sizeof(MmsSmilTransType));
-               offset += sizeof(MmsSmilTransType);
-               memcpy(&pTransition->nSubType, pData + offset, sizeof(MmsSmilTransSubType));
-               offset += sizeof(MmsSmilTransSubType);
-               memcpy(&pTransition->nDur, pData + offset, sizeof(int));
-               offset += sizeof(int);
+       for (int i = 0; i < mediaCnt; i++) {
 
-               pBody->transitionlist = g_list_append(pBody->transitionlist, pTransition);
-       }
+               GList *nth = g_list_nth(pPage->medialist, i);
 
-       //Processing Meta List
-       memcpy(&pBody->metaCnt, pData + offset, sizeof(int));
-       offset += sizeof(int);
+               if (nth == NULL)
+                       return false;
 
-       MSG_DEBUG(" pBody->metaCnt: %d", pBody->metaCnt);
+               pMedia = (MMS_MEDIA_S *)nth->data;
 
-       for (int i = 0; i < pBody->metaCnt; ++i) {
-               pMeta = (MMS_SMIL_META *)calloc(sizeof(MMS_SMIL_META), 1);
+               if (pMedia == NULL)
+                       continue;
 
-               memcpy(pMeta->szID, pData + offset, MAX_SMIL_META_ID);
-               offset += MAX_SMIL_META_ID;
+               if (strlen(pMedia->szFilePath) == 0) {
+                       MSG_DEBUG("Found Empty Media [%d]", i);
 
-               memcpy(pMeta->szName, pData + offset, MAX_SMIL_META_NAME);
-               offset += MAX_SMIL_META_NAME;
+                       g_free(pMedia);
 
-               memcpy(pMeta->szContent, pData + offset, MAX_SMIL_META_CONTENT);
-               offset += MAX_SMIL_META_CONTENT;
+                       nth->data = NULL;
+               }
 
-               pBody->metalist = g_list_append(pBody->metalist, pMeta);
        }
 
-       memcpy(&pBody->rootlayout, pData + offset, sizeof(MMS_SMIL_ROOTLAYOUT));
-       offset += sizeof(MMS_SMIL_ROOTLAYOUT);
+       pPage->medialist = g_list_remove_all(pPage->medialist, NULL);
 
-#ifdef FEATURE_JAVA_MMS
-       memcpy(&pBody->msgAppId, pData + offset, sizeof(MMS_APPID_INFO_S));
-       offset += sizeof(MMS_APPID_INFO_S);
-       MSG_DEBUG("java_app_id valid:%d, appId:%s repleToAppId:%s", pBody->msgAppId.valid, pBody->msgAppId.appId, pBody->msgAppId.replyToAppId);
-#endif
-       //free(pData);
+       pPage->mediaCnt = g_list_length(pPage->medialist);
 
        return true;
 }
 
-bool   _MsgMmsSetRootLayout(MMS_MESSAGE_DATA_S* pMmsMsg, MMS_SMIL_ROOTLAYOUT* pRootlayout)
+//remove media object with no filepath
+bool _MsgMmsRemoveEmptyObject(MMS_MESSAGE_DATA_S *pMmsMsg)
 {
-       memcpy(&pMmsMsg->rootlayout, pRootlayout, sizeof(MMS_SMIL_ROOTLAYOUT));
+       MMS_PAGE_S *pPage;
+
+       int pageCnt = g_list_length(pMmsMsg->pagelist);
+
+       for (int i = 0; i < pageCnt; i++) {
+
+               GList *nth = g_list_nth(pMmsMsg->pagelist, i);
+
+               if (nth == NULL)
+                       return false;
+
+               pPage = (MMS_PAGE_S *)nth->data;
+
+               if (pPage == NULL)
+                       continue;
+
+               _MsgMmsRemoveEmptyMedia(pPage);
+
+//             if (g_list_length(pPage->medialist) == 0) {
+//
+//                     MSG_DEBUG("Found Empty Page [%d]", i);
+//
+//                     g_free(pPage);
+//
+//                     nth->data = NULL;
+//             }
+       }
+
+       pMmsMsg->pagelist = g_list_remove_all(pMmsMsg->pagelist, NULL);
+
+       pMmsMsg->pageCnt = g_list_length(pMmsMsg->pagelist);
+
        return true;
 }
-
index fdcf88c..a2085ad 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <fcntl.h>     /* O_RDWR */
diff --git a/utils/MsgNotificationWrapper.cpp b/utils/MsgNotificationWrapper.cpp
deleted file mode 100755 (executable)
index 116171e..0000000
+++ /dev/null
@@ -1,622 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include "MsgDebug.h"
-#include "MsgContact.h"
-#include "MsgStorageTypes.h"
-#include "MsgNotificationWrapper.h"
-
-extern "C"
-{
-       #include <notification.h>
-}
-
-/*==================================================================================================
-                                     FUNCTION IMPLEMENTATION
-==================================================================================================*/
-msg_error_t MsgInsertNoti(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S* pMsg)
-{
-       notification_h noti = NULL;
-       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
-       bundle* args;
-
-       int contactId = 0;
-       msg_thread_id_t threadId = 0;
-       time_t msgTime = 0;
-       char tempId[6];
-       char addressVal[MAX_ADDRESS_VAL_LEN+1];
-       char firstName[MAX_DISPLAY_NAME_LEN+1], lastName[MAX_DISPLAY_NAME_LEN+1];
-       char displayName[MAX_DISPLAY_NAME_LEN+1];
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       memset(tempId, 0x00, sizeof(tempId));
-       memset(addressVal, 0x00, sizeof(addressVal));
-       memset(firstName, 0x00, sizeof(firstName));
-       memset(lastName, 0x00, sizeof(lastName));
-       memset(displayName, 0x00, sizeof(displayName));
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.CONV_ID, A.ADDRESS_VAL, A.DISPLAY_NAME, A.FIRST_NAME, A.LAST_NAME, B.DISPLAY_TIME, A.CONTACT_ID \
-                       FROM %s A, %s B WHERE B.MSG_ID=%d AND A.CONV_ID=B.CONV_ID;",
-                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, pMsg->msgId);
-
-       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
-
-       if (pDbHandle->stepQuery() == MSG_ERR_DB_ROW) {
-               threadId = pDbHandle->columnInt(0);
-
-               if (pDbHandle->columnText(1) != NULL)
-                       strncpy(addressVal, (char*)pDbHandle->columnText(1), MAX_ADDRESS_VAL_LEN);
-
-
-               char *pTempDisplayName = (char *)pDbHandle->columnText(2);
-               if (pTempDisplayName != NULL && pTempDisplayName[0] != '\0') {
-                       strncpy(displayName, pTempDisplayName, MAX_DISPLAY_NAME_LEN);
-               } else {
-                       if (pDbHandle->columnText(3) != NULL)
-                               strncpy(firstName, (char*)pDbHandle->columnText(3), MAX_DISPLAY_NAME_LEN);
-
-                       if (pDbHandle->columnText(4) != NULL)
-                               strncpy(lastName, (char*)pDbHandle->columnText(4), MAX_DISPLAY_NAME_LEN);
-
-                       int order = MsgGetContactNameOrder();
-
-                       if (order == 0) {
-                               if (firstName[0] != '\0') {
-                                       strncpy(displayName, firstName, MAX_DISPLAY_NAME_LEN);
-                               }
-
-                               if (lastName[0] != '\0') {
-                                       strncat(displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                                       strncat(displayName, lastName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-                       } else if (order == 1) {
-                               if (lastName[0] != '\0') {
-                                       strncpy(displayName, lastName, MAX_DISPLAY_NAME_LEN);
-                                       strncat(displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-
-                               if (firstName[0] != '\0') {
-                                       strncat(displayName, firstName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-                       }
-               }
-
-               msgTime = (time_t)pDbHandle->columnInt(5);
-
-               contactId = pDbHandle->columnInt(6);
-       } else {
-               pDbHandle->finalizeQuery();
-               return MSG_ERR_DB_STEP;
-       }
-
-       pDbHandle->finalizeQuery();
-
-
-       args = bundle_create();
-
-       if (pMsg->msgType.mainType == MSG_SMS_TYPE && pMsg->msgType.subType == MSG_CB_SMS) {
-
-               noti = notification_new(NOTIFICATION_TYPE_NOTI, 1, pMsg->msgId);
-               if (noti == NULL) {
-                       MSG_DEBUG("notification_new is failed.");
-                       bundle_free(args);
-                       return MSG_ERR_UNKNOWN;
-               }
-
-               noti_err = notification_set_application(noti, "org.tizen.message");
-               if (noti_err != NOTIFICATION_ERROR_NONE) {
-                       MSG_DEBUG("Fail to notification_set_application : %d", noti_err);
-               }
-
-               noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON, CB_MSG_ICON_PATH);
-               if (noti_err != NOTIFICATION_ERROR_NONE) {
-                       MSG_DEBUG("Fail to notification_set_image : %d", noti_err);
-               }
-
-               memset(&tempId, 0x00, sizeof(tempId));
-
-               snprintf(tempId, 5, "%d", threadId);
-               bundle_add(args, "threadId", tempId);
-       } else if (pMsg->msgType.mainType == MSG_SMS_TYPE && pMsg->msgType.classType == MSG_CLASS_0) {
-
-               noti = notification_new(NOTIFICATION_TYPE_NOTI, NOTIFICATION_GROUP_ID_NONE, NOTIFICATION_PRIV_ID_NONE);
-               if (noti == NULL) {
-                       MSG_DEBUG("notification_new is failed.");
-                       bundle_free(args);
-                       return MSG_ERR_UNKNOWN;
-               }
-
-               noti_err = notification_set_application(noti, "org.tizen.msg-ui-class0");
-               if (noti_err != NOTIFICATION_ERROR_NONE) {
-                       MSG_DEBUG("Fail to notification_set_application : %d", noti_err);
-               }
-
-               snprintf(tempId, 5, "%d", pMsg->msgId);
-               bundle_add(args, "msg_id", tempId);
-       } else if (pMsg->msgType.mainType == MSG_SMS_TYPE && pMsg->msgType.subType == MSG_MWI_VOICE_SMS) {
-
-               noti = notification_new(NOTIFICATION_TYPE_NOTI, 1, pMsg->msgId);
-               if (noti == NULL) {
-                       MSG_DEBUG("notification_new is failed.");
-                       bundle_free(args);
-                       return MSG_ERR_UNKNOWN;
-               }
-
-               noti_err = notification_set_application(noti, "org.tizen.message");
-               if (noti_err != NOTIFICATION_ERROR_NONE) {
-                       MSG_DEBUG("Fail to notification_set_application : %d", noti_err);
-               }
-
-               noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON, VOICE_MSG_ICON_PATH);
-               if (noti_err != NOTIFICATION_ERROR_NONE) {
-                       MSG_DEBUG("Fail to notification_set_image : %d", noti_err);
-               }
-
-               memset(&tempId, 0x00, sizeof(tempId));
-
-               snprintf(tempId, 5, "%d", threadId);
-               bundle_add(args, "threadId", tempId);
-       } else {
-               MSG_DEBUG("notification_new pMsg->msgId [%d]", pMsg->msgId);
-               noti = notification_new(NOTIFICATION_TYPE_NOTI, 1, pMsg->msgId);
-               if (noti == NULL) {
-                       MSG_DEBUG("notification_new is failed.");
-                       bundle_free(args);
-                       return MSG_ERR_UNKNOWN;
-               }
-
-               noti_err = notification_set_application(noti, "org.tizen.message");
-               if (noti_err != NOTIFICATION_ERROR_NONE) {
-                       MSG_DEBUG("Fail to notification_set_application : %d", noti_err);
-               }
-
-               noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON, NORMAL_MSG_ICON_PATH);
-               if (noti_err != NOTIFICATION_ERROR_NONE) {
-                       MSG_DEBUG("Fail to notification_set_image : %d", noti_err);
-               }
-
-               memset(&tempId, 0x00, sizeof(tempId));
-
-               snprintf(tempId, 5, "%d", threadId);
-               bundle_add(args, "threadId", tempId);
-       }
-
-       bundle_add(args, "type", "msg_id");
-
-       snprintf(tempId, 5, "%d", pMsg->msgId);
-       bundle_add(args, "msgId", tempId);
-
-       if (displayName[0] == '\0')
-               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, addressVal, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-       else
-               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, displayName, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-
-       if (pMsg->msgType.mainType == MSG_SMS_TYPE)
-               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, pMsg->msgText, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-       else
-               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, pMsg->subject, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-
-
-       if (args != NULL) {
-               noti_err = notification_set_args(noti, args, NULL);
-               if (noti_err != NOTIFICATION_ERROR_NONE) {
-                       MSG_DEBUG("Fail to notification_set_args : %d", noti_err);
-               }
-       }
-
-       noti_err = notification_set_time(noti, msgTime);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_set_time : %d", noti_err);
-       }
-
-       noti_err = notification_insert(noti, NULL);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_insert");
-       }
-
-       noti_err = notification_free(noti);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_free");
-       }
-
-       bundle_free(args);
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t MsgInsertSmsReportToNoti(MsgDbHandler *pDbHandle, msg_message_id_t msgId, msg_delivery_report_status_t status)
-{
-       notification_h noti = NULL;
-       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
-
-       char addressVal[MAX_ADDRESS_VAL_LEN+1];
-       char firstName[MAX_DISPLAY_NAME_LEN+1], lastName[MAX_DISPLAY_NAME_LEN+1];
-       char displayName[MAX_DISPLAY_NAME_LEN+1];
-       char contents[MAX_DISPLAY_NAME_LEN+1];
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       memset(addressVal, 0x00, sizeof(addressVal));
-       memset(firstName, 0x00, sizeof(firstName));
-       memset(lastName, 0x00, sizeof(lastName));
-       memset(displayName, 0x00, sizeof(displayName));
-       memset(contents, 0x00, sizeof(contents));
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.ADDRESS_VAL, A.DISPLAY_NAME, A.FIRST_NAME, A.LAST_NAME \
-                       FROM %s A, %s B WHERE B.MSG_ID = %d AND A.CONV_ID = B.CONV_ID;",
-                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, msgId);
-
-       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
-
-       if (pDbHandle->stepQuery() == MSG_ERR_DB_ROW) {
-               if (pDbHandle->columnText(0) != NULL)
-                       strncpy(addressVal, (char*)pDbHandle->columnText(0), MAX_ADDRESS_VAL_LEN);
-
-               if (pDbHandle->columnText(1) != NULL) {
-                       strncpy(displayName, (char*)pDbHandle->columnText(1), MAX_DISPLAY_NAME_LEN);
-               } else {
-                       if (pDbHandle->columnText(2) != NULL)
-                               strncpy(firstName, (char*)pDbHandle->columnText(2), MAX_DISPLAY_NAME_LEN);
-
-                       if (pDbHandle->columnText(3) != NULL)
-                               strncpy(lastName, (char*)pDbHandle->columnText(3), MAX_DISPLAY_NAME_LEN);
-
-                       int order = MsgGetContactNameOrder();
-
-                       if (order == 0) {
-                               if (firstName[0] != '\0') {
-                                       strncpy(displayName, firstName, MAX_DISPLAY_NAME_LEN);
-                               }
-
-                               if (lastName[0] != '\0') {
-                                       strncat(displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                                       strncat(displayName, lastName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-                       } else if (order == 1) {
-                               if (lastName[0] != '\0') {
-                                       strncpy(displayName, lastName, MAX_DISPLAY_NAME_LEN);
-                                       strncat(displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-
-                               if (firstName[0] != '\0') {
-                                       strncat(displayName, firstName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-                       }
-               }
-       } else {
-               MSG_DEBUG("query : %s", sqlQuery);
-
-               pDbHandle->finalizeQuery();
-
-               return MSG_ERR_DB_STEP;
-       }
-
-       pDbHandle->finalizeQuery();
-
-
-       noti = notification_new(NOTIFICATION_TYPE_NOTI, NOTIFICATION_GROUP_ID_NONE, NOTIFICATION_PRIV_ID_NONE);
-       if (noti == NULL) {
-               MSG_DEBUG("notification_new is failed.");
-               return MSG_ERR_UNKNOWN;
-       }
-
-       noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON, NOTI_MSG_ICON_PATH);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_set_image : %d", noti_err);
-       }
-
-       if (displayName[0] == '\0')
-               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, addressVal, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-       else
-               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, displayName, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-
-
-       if (status == MSG_DELIVERY_REPORT_SUCCESS)
-               snprintf(contents, MAX_DISPLAY_NAME_LEN, "Delivered.");
-       else
-               snprintf(contents, MAX_DISPLAY_NAME_LEN, "Deliver Failed.");
-
-       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, contents, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-
-       noti_err = notification_insert(noti, NULL);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_insert");
-       }
-
-       noti_err = notification_free(noti);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_free");
-       }
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t MsgInsertMmsReportToNoti(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S* pMsg)
-{
-       notification_h noti = NULL;
-       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
-
-       msg_delivery_report_status_t    deliveryStatus;
-       msg_read_report_status_t                readStatus;
-
-       char addressVal[MAX_ADDRESS_VAL_LEN+1];
-       char firstName[MAX_DISPLAY_NAME_LEN+1], lastName[MAX_DISPLAY_NAME_LEN+1];
-       char displayName[MAX_DISPLAY_NAME_LEN+1];
-       char contents[MAX_DISPLAY_NAME_LEN+1];
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       memset(addressVal, 0x00, sizeof(addressVal));
-       memset(firstName, 0x00, sizeof(firstName));
-       memset(lastName, 0x00, sizeof(lastName));
-       memset(displayName, 0x00, sizeof(displayName));
-       memset(contents, 0x00, sizeof(contents));
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.ADDRESS_VAL, A.DISPLAY_NAME, A.FIRST_NAME, A.LAST_NAME, B.DELIVERY_REPORT_STATUS, B.READ_REPORT_STATUS \
-                       FROM %s A, %s B WHERE B.MSG_ID=%d AND A.CONV_ID=B.CONV_ID;",
-                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, pMsg->msgId);
-
-       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
-
-       if (pDbHandle->stepQuery() == MSG_ERR_DB_ROW) {
-               if (pDbHandle->columnText(0) != NULL)
-                       strncpy(addressVal, (char*)pDbHandle->columnText(0), MAX_ADDRESS_VAL_LEN);
-
-
-               char *pTempDisplayName = (char *)pDbHandle->columnText(1);
-               if (pTempDisplayName != NULL && pTempDisplayName[0] != '\0') {
-                       strncpy(displayName, pTempDisplayName, MAX_DISPLAY_NAME_LEN);
-               } else {
-                       if (pDbHandle->columnText(2) != NULL)
-                               strncpy(firstName, (char*)pDbHandle->columnText(2), MAX_DISPLAY_NAME_LEN);
-
-                       if (pDbHandle->columnText(3) != NULL)
-                               strncpy(lastName, (char*)pDbHandle->columnText(3), MAX_DISPLAY_NAME_LEN);
-
-                       int order = MsgGetContactNameOrder();
-
-                       if (order == 0) {
-                               if (firstName[0] != '\0') {
-                                       strncpy(displayName, firstName, MAX_DISPLAY_NAME_LEN);
-                               }
-
-                               if (lastName[0] != '\0') {
-                                       strncat(displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                                       strncat(displayName, lastName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-                       } else if (order == 1) {
-                               if (lastName[0] != '\0') {
-                                       strncpy(displayName, lastName, MAX_DISPLAY_NAME_LEN);
-                                       strncat(displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-
-                               if (firstName[0] != '\0') {
-                                       strncat(displayName, firstName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
-                               }
-                       }
-               }
-
-               deliveryStatus = (msg_delivery_report_status_t)pDbHandle->columnInt(4);
-               readStatus = (msg_read_report_status_t)pDbHandle->columnInt(5);
-
-       } else {
-               pDbHandle->finalizeQuery();
-               return MSG_ERR_DB_STEP;
-       }
-
-       pDbHandle->finalizeQuery();
-
-       noti = notification_new(NOTIFICATION_TYPE_NOTI, NOTIFICATION_GROUP_ID_NONE, NOTIFICATION_PRIV_ID_NONE);
-       if (noti == NULL) {
-               MSG_DEBUG("notification_new is failed.");
-               return MSG_ERR_UNKNOWN;
-       }
-
-       noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON, NOTI_MSG_ICON_PATH);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_set_image : %d", noti_err);
-       }
-
-       if (displayName[0] == '\0')
-               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, addressVal, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-       else
-               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, displayName, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-
-       if (pMsg->msgType.subType == MSG_DELIVERYIND_MMS) {
-
-               switch(deliveryStatus) {
-               case MSG_DELIVERY_REPORT_NONE:
-                       noti_err = notification_free(noti);
-                       if (noti_err != NOTIFICATION_ERROR_NONE) {
-                               MSG_DEBUG("Fail to notification_free");
-                       }
-
-                       return MSG_ERR_UNKNOWN;
-
-               case MSG_DELIVERY_REPORT_EXPIRED:
-                       snprintf(contents, MAX_DISPLAY_NAME_LEN, "Expired.");
-                       break;
-
-               case MSG_DELIVERY_REPORT_REJECTED:
-                       snprintf(contents, MAX_DISPLAY_NAME_LEN, "Rejected.");
-                       break;
-
-               case MSG_DELIVERY_REPORT_DEFERRED:
-                       snprintf(contents, MAX_DISPLAY_NAME_LEN, "Deferred.");
-                       break;
-
-               case MSG_DELIVERY_REPORT_UNRECOGNISED:
-                       snprintf(contents, MAX_DISPLAY_NAME_LEN, "Unrecognised.");
-                       break;
-
-               case MSG_DELIVERY_REPORT_INDETERMINATE:
-                       snprintf(contents, MAX_DISPLAY_NAME_LEN, "Indeterminate.");
-                       break;
-
-               case MSG_DELIVERY_REPORT_FORWARDED:
-                       snprintf(contents, MAX_DISPLAY_NAME_LEN, "Forwarded.");
-                       break;
-
-               case MSG_DELIVERY_REPORT_UNREACHABLE:
-                       snprintf(contents, MAX_DISPLAY_NAME_LEN, "Unreachable.");
-                       break;
-
-               case MSG_DELIVERY_REPORT_ERROR:
-                       snprintf(contents, MAX_DISPLAY_NAME_LEN, "Error.");
-                       break;
-
-               default :
-                       snprintf(contents, MAX_DISPLAY_NAME_LEN, "Delivered.");
-               }
-
-               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, contents, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT_FOR_DISPLAY_OPTION_IS_OFF, contents, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-
-               noti_err = notification_insert(noti, NULL);
-               if (noti_err != NOTIFICATION_ERROR_NONE)
-                       MSG_DEBUG("Fail to notification_insert");
-
-       } else if (pMsg->msgType.subType == MSG_READORGIND_MMS) {
-
-               switch(readStatus) {
-               case MSG_READ_REPORT_NONE:
-                       noti_err = notification_free(noti);
-                       if (noti_err != NOTIFICATION_ERROR_NONE)
-                               MSG_DEBUG("Fail to notification_free");
-
-                       return MSG_ERR_UNKNOWN;
-
-               case MSG_READ_REPORT_IS_DELETED:
-                       snprintf(contents, MAX_DISPLAY_NAME_LEN, "Deleted.");
-                       break;
-
-               default :
-                       snprintf(contents, MAX_DISPLAY_NAME_LEN, "Read.");
-               }
-
-               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, contents, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
-
-               noti_err = notification_insert(noti, NULL);
-               if (noti_err != NOTIFICATION_ERROR_NONE) {
-                       MSG_DEBUG("Fail to notification_insert");
-               }
-       } else {
-               MSG_DEBUG("No matching subtype. subtype [%d]", pMsg->msgType.subType);
-
-               noti_err = notification_free(noti);
-               if (noti_err != NOTIFICATION_ERROR_NONE) {
-                       MSG_DEBUG("Fail to notification_free");
-               }
-               return MSG_SUCCESS;
-       }
-
-       noti_err = notification_free(noti);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_free");
-       }
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t MsgDeleteNotiByMsgId(msg_message_id_t msgId)
-{
-
-       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
-
-       MSG_DEBUG("notification_delete_by_priv_id msgId [%d]", msgId);
-
-       noti_err = notification_delete_by_priv_id(NULL, NOTIFICATION_TYPE_NOTI, msgId);
-
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_delete_by_priv_id noti_err [%d]", noti_err);
-       }
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t MsgDeleteNotiByThreadId(msg_thread_id_t ThreadId)
-{
-       notification_delete_group_by_group_id(NULL, NOTIFICATION_TYPE_NOTI, ThreadId);
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t MsgInsertTicker(const char* pTickerMsg, const char* pLocaleTickerMsg)
-{
-
-       MSG_DEBUG("pTickerMsg [%s]", pTickerMsg);
-       MSG_DEBUG("pLocaleTickerMsg [%s]", pLocaleTickerMsg);
-
-       notification_h noti = NULL;
-       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
-
-       noti = notification_new(NOTIFICATION_TYPE_NOTI, NOTIFICATION_GROUP_ID_NONE, NOTIFICATION_PRIV_ID_NONE);
-       if (noti == NULL) {
-               MSG_DEBUG("notification_new is failed.");
-               return MSG_ERR_UNKNOWN;
-       }
-
-       noti_err = notification_set_application(noti, "org.tizen.message");
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_set_application : %d", noti_err);
-       }
-
-       noti_err = notification_set_image(noti, NOTIFICATION_IMAGE_TYPE_ICON, NORMAL_MSG_ICON_PATH);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_set_image : %d", noti_err);
-       }
-
-       noti_err = notification_set_text_domain(noti, MSG_APP_PACKAGE_NAME, MSG_APP_LOCALEDIR);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_set_text_domain.");
-       }
-
-       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, pTickerMsg, pLocaleTickerMsg, NOTIFICATION_VARIABLE_TYPE_NONE);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_set_text : %d", noti_err);
-       }
-
-       noti_err = notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT_FOR_DISPLAY_OPTION_IS_OFF, pTickerMsg, pLocaleTickerMsg, NOTIFICATION_VARIABLE_TYPE_NONE);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_set_text : %d", noti_err);
-       }
-
-       noti_err = notification_set_display_applist(noti, NOTIFICATION_DISPLAY_APP_TICKER);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_set_display_applist : %d", noti_err);
-       }
-
-       noti_err = notification_insert(noti, NULL);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_set_text_domain");
-       }
-
-       noti_err = notification_free(noti);
-       if (noti_err != NOTIFICATION_ERROR_NONE) {
-               MSG_DEBUG("Fail to notification_set_text_domain");
-       }
-
-       return MSG_SUCCESS;
-}
diff --git a/utils/MsgSerialize.cpp b/utils/MsgSerialize.cpp
new file mode 100755 (executable)
index 0000000..621d4f0
--- /dev/null
@@ -0,0 +1,853 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include "MsgJsonParser.h"
+#include "MsgSerialize.h"
+#include "MsgMmsTypes.h"
+#include "MsgDebug.h"
+#include "MsgMmsMessage.h"
+
+
+#ifdef MSG_MMS_USE_JSON_DATA
+#include <glib.h>
+#include <glib-object.h>
+#include <json-glib/json-glib.h>
+#include <json-glib/json-gobject.h>
+
+typedef enum {
+       TYPE_STR,
+       TYPE_INT,
+       TYPE_ARRAY,
+       TYPE_OBJECT,
+} mms_json_data_type_e;
+
+typedef struct _mms_json_item {
+       const char *key;
+       int e_val;
+       int type;
+} mms_json_item_s;
+
+typedef enum {
+       MMS_UNKNOWN = -1,
+       MMS_HEADER = 0,
+       MMS_MULTIPART_LIST,
+       MMS_SMIL_MULTIPART,
+
+       MULTIPART_TYPE ,
+       MULTIPART_CONTENT_TYPE,
+       MULTIPART_NAME,
+       MULTIPART_FILEPATH,
+       MULTIPART_FILEDATA,
+       MULTIPART_CONTENT_ID,
+       MULTIPART_CONTENT_LOCATION,
+
+       HEADER_CONTENT_LOCATION,
+       HEADER_CONTENT_TYPE,
+       HEADER_CONTENT_TYPE_INT,
+       HEADER_DATE,
+       HEADER_DELIVERY_REPORT,
+       HEADER_DELIVERY_TIME,
+       HEADER_EXPIRY_TIME,
+       HEADER_MESSAGE_CLASS,
+       HEADER_MID,
+       HEADER_MESSAGE_TYPE,
+       HEADER_VERSION,
+       HEADER_PRIORITY,
+       HEADER_READ_REPORT,
+       HEADER_HIDE_ADDRESS,
+       HEADER_TRID,
+       HEADER_CONTENT_CLASS,
+
+       MMS_BACKUP_TYPE,
+} mms_json_enum_e;
+
+static mms_json_item_s mms_json_table[] = {
+       {"header",              MMS_HEADER,     TYPE_INT},
+       {"multipart_list",      MMS_MULTIPART_LIST, TYPE_ARRAY},
+       {"smil",                MMS_SMIL_MULTIPART,     TYPE_OBJECT},
+//multipart
+       {"mp_type",      MULTIPART_TYPE,        TYPE_INT},
+       {"mp_ct",        MULTIPART_CONTENT_TYPE,        TYPE_STR},
+       {"mp_name",      MULTIPART_NAME,        TYPE_STR},
+       {"mp_path",      MULTIPART_FILEPATH,    TYPE_STR},
+       {"mp_data",      MULTIPART_FILEDATA,    TYPE_STR},
+
+       {"mp_cid",       MULTIPART_CONTENT_ID,  TYPE_STR},
+       {"mp_cl",        MULTIPART_CONTENT_LOCATION,    TYPE_STR},
+//header
+       {"h_cl",        HEADER_CONTENT_LOCATION,        TYPE_STR},
+       {"h_ct",        HEADER_CONTENT_TYPE,    TYPE_STR},
+       {"h_ct_int",    HEADER_CONTENT_TYPE_INT,        TYPE_INT},
+       {"h_date",      HEADER_DATE, TYPE_INT},
+       {"h_d_rpt",     HEADER_DELIVERY_REPORT, TYPE_INT},
+       {"h_d_time",    HEADER_DELIVERY_TIME, TYPE_INT},
+       {"h_exp",       HEADER_EXPIRY_TIME, TYPE_INT},
+       {"h_mclass",    HEADER_MESSAGE_CLASS,   TYPE_INT},
+       {"h_mid",       HEADER_MID, TYPE_STR},
+       {"h_mtype",     HEADER_MESSAGE_TYPE,    TYPE_INT},
+       {"h_v",         HEADER_VERSION, TYPE_INT},
+       {"h_prioriy",   HEADER_PRIORITY,        TYPE_INT},
+       {"h_r_rpt",     HEADER_READ_REPORT, TYPE_INT},
+       {"h_hide_addr", HEADER_HIDE_ADDRESS, TYPE_INT},
+       {"h_tid",       HEADER_TRID,    TYPE_STR},
+       {"h_cclass",    HEADER_CONTENT_CLASS, TYPE_INT},
+       {"backup_type", MMS_BACKUP_TYPE, TYPE_INT},
+
+};
+
+mms_json_enum_e get_mms_key_type(const char * key)
+{
+       int i;
+
+       int table_count = sizeof(mms_json_table)/sizeof(mms_json_item_s);
+       if (key) {
+               for (i = 0; i < table_count; i++) {
+                       if (g_strcmp0(mms_json_table[i].key, key) == 0)
+                               return (mms_json_enum_e)mms_json_table[i].e_val;
+               }
+       }
+
+       return MMS_UNKNOWN;
+}
+
+const char *get_mms_key(mms_json_enum_e e)
+{
+       int i;
+
+       int table_count = sizeof(mms_json_table)/sizeof(mms_json_item_s);
+
+       for (i = 0; i < table_count; i++) {
+               if (mms_json_table[i].e_val == e)
+                       return mms_json_table[i].key;
+       }
+
+       return NULL;
+}
+
+int MsgSerializeHeader(const MMS_HEADER_DATA_S *pheader, JsonObject **headerObject)
+{
+       JsonObject *header_object = json_object_new();
+
+       MSG_JSON_OBJ_SET_STR(header_object, get_mms_key(HEADER_CONTENT_LOCATION), pheader->contentLocation);
+
+       MSG_JSON_OBJ_SET_STR(header_object, get_mms_key(HEADER_CONTENT_TYPE), pheader->szContentType);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_CONTENT_TYPE_INT), pheader->contentType);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_DATE), pheader->date);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_DELIVERY_REPORT), pheader->bDeliveryReport);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_DELIVERY_TIME), pheader->delivery.time);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_EXPIRY_TIME), pheader->expiry.time);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_MESSAGE_CLASS), pheader->messageClass);
+
+       MSG_JSON_OBJ_SET_STR(header_object, get_mms_key(HEADER_MID), pheader->messageID);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_MESSAGE_TYPE), pheader->messageType);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_VERSION), pheader->mmsVersion);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_PRIORITY), pheader->mmsPriority);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_READ_REPORT), pheader->bReadReport);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_HIDE_ADDRESS), pheader->bHideAddress);
+
+       MSG_JSON_OBJ_SET_STR(header_object, get_mms_key(HEADER_TRID), pheader->trID);
+
+       MSG_JSON_OBJ_SET_INT(header_object, get_mms_key(HEADER_CONTENT_CLASS), pheader->contentClass);
+
+       *headerObject = header_object;
+
+       return 0;
+}
+
+int MsgParseHeader(msg_json_parser_object *parse_obj, MMS_HEADER_DATA_S *pheader)
+{
+       MSG_BEGIN();
+
+       int index_child = 0;
+       mms_json_enum_e type;
+       msg_json_parser_object child = {};
+
+       if (parse_obj == NULL)
+               return -1;
+
+       while(msg_json_parser_get_next_child(parse_obj, &child, index_child))
+       {
+               MSG_PRINT_PARSER_OBJECT(index_child, child);
+               type = get_mms_key_type(child.key);
+
+               switch (type) {
+               case HEADER_CONTENT_LOCATION:
+                       snprintf(pheader->contentLocation, sizeof(pheader->contentLocation), "%s", (char *)child.value);
+                       break;
+               case HEADER_CONTENT_TYPE:
+                       snprintf(pheader->szContentType, sizeof(pheader->szContentType), "%s", (char *)child.value);
+                       break;
+               case HEADER_CONTENT_TYPE_INT:
+                       pheader->contentType = (int)child.number_value;
+                       break;
+               case HEADER_DATE:
+                       pheader->date = (unsigned long int)child.number_value;
+                       break;
+               case HEADER_DELIVERY_REPORT:
+                       pheader->bDeliveryReport = (bool)child.number_value;
+                       break;
+               case HEADER_DELIVERY_TIME:
+                       if ((unsigned int)child.number_value > 0) {
+                               pheader->delivery.type = MMS_TIMETYPE_RELATIVE;
+                               pheader->delivery.time = (unsigned int)child.number_value;
+                       }
+                       break;
+               case HEADER_EXPIRY_TIME:
+                       if ((unsigned int)child.number_value > 0) {
+                       pheader->expiry.type = MMS_TIMETYPE_RELATIVE;
+                       pheader->expiry.time = (unsigned int)child.number_value;
+                       }
+                       break;
+               case HEADER_MESSAGE_CLASS:
+                       pheader->messageClass = (int)child.number_value;
+                       break;
+               case HEADER_MID:
+                       snprintf(pheader->messageID, sizeof(pheader->messageID), "%s", (char *)child.value);
+                       break;
+               case HEADER_MESSAGE_TYPE:
+                       pheader->messageType = (int)child.number_value;
+                       break;
+               case HEADER_VERSION:
+                       pheader->mmsVersion = (int)child.number_value;
+                       break;
+               case HEADER_PRIORITY:
+                       pheader->mmsPriority = (int)child.number_value;
+                       break;
+               case HEADER_READ_REPORT:
+                       pheader->bReadReport = (bool)child.number_value;
+                       break;
+               case HEADER_HIDE_ADDRESS:
+                       pheader->bHideAddress = (bool)child.number_value;
+                       break;
+               case HEADER_TRID:
+                       snprintf(pheader->trID, sizeof(pheader->trID), "%s", (char *)child.value);
+                       break;
+               case HEADER_CONTENT_CLASS:
+                       pheader->contentClass = (int)child.number_value;
+                       break;
+               default:
+                       MSG_DEBUG("Not Support key = [%s], type = [%d]", child.key, type);
+                       break;
+               }
+
+               index_child++;
+       }
+
+       MSG_END();
+       return 0;
+}
+
+int MsgSerializeMultipart(const MMS_MULTIPART_DATA_S *pMultipart, JsonObject **multipartObject)
+{
+       JsonObject *object = json_object_new();
+
+       MSG_JSON_OBJ_SET_INT(object, get_mms_key(MULTIPART_TYPE), pMultipart->type);
+
+       MSG_JSON_OBJ_SET_STR(object, get_mms_key(MULTIPART_CONTENT_TYPE), pMultipart->szContentType);
+       MSG_JSON_OBJ_SET_STR(object, get_mms_key(MULTIPART_NAME), pMultipart->szFileName);
+       MSG_JSON_OBJ_SET_STR(object, get_mms_key(MULTIPART_FILEPATH), pMultipart->szFilePath);
+
+       if (pMultipart->pMultipartData) {
+               char* base64data = g_base64_encode((const guchar*)pMultipart->pMultipartData, pMultipart->nMultipartDataLen);
+               MSG_JSON_OBJ_SET_STR(object, get_mms_key(MULTIPART_FILEDATA), base64data);
+               g_free(base64data);
+       }
+
+       MSG_JSON_OBJ_SET_STR(object, get_mms_key(MULTIPART_CONTENT_ID), pMultipart->szContentID);
+       MSG_JSON_OBJ_SET_STR(object, get_mms_key(MULTIPART_CONTENT_LOCATION), pMultipart->szContentLocation);
+
+       *multipartObject = object;
+
+       return 0;
+}
+
+int MsgParseMultipartData(msg_json_parser_object *parse_obj, MMS_MULTIPART_DATA_S *pMultipart)
+{
+       MSG_BEGIN();
+
+       int index_child = 0;
+       mms_json_enum_e type;
+       msg_json_parser_object child = {};
+
+       if (parse_obj == NULL)
+               return -1;
+
+       while(msg_json_parser_get_next_child(parse_obj, &child, index_child))
+       {
+               MSG_PRINT_PARSER_OBJECT(index_child, child);
+
+               type = get_mms_key_type(child.key);
+
+               switch (type) {
+               case MULTIPART_TYPE:
+                       pMultipart->type = (MimeType)child.number_value;
+                       break;
+               case MULTIPART_CONTENT_TYPE:
+                       snprintf(pMultipart->szContentType, sizeof(pMultipart->szContentType), "%s", (char *)child.value);
+                       break;
+               case MULTIPART_NAME:
+                       snprintf(pMultipart->szFileName, sizeof(pMultipart->szFileName), "%s", (char *)child.value);
+                       break;
+               case MULTIPART_FILEPATH:
+                       snprintf(pMultipart->szFilePath, sizeof(pMultipart->szFilePath), "%s", (char *)child.value);
+                       break;
+               case MULTIPART_FILEDATA:
+                       pMultipart->pMultipartData = (char*)g_base64_decode((char *)child.value, &pMultipart->nMultipartDataLen);
+                       break;
+               case MULTIPART_CONTENT_ID:
+                       snprintf(pMultipart->szContentID, sizeof(pMultipart->szContentID), "%s", (char *)child.value);
+                       break;
+               case MULTIPART_CONTENT_LOCATION:
+                       snprintf(pMultipart->szContentLocation, sizeof(pMultipart->szContentLocation), "%s", (char *)child.value);
+                       break;
+               default:
+                       MSG_DEBUG("Not Support key = [%s], type = [%d]", child.key, type);
+                       break;
+               }
+
+               index_child++;
+       }
+
+       MSG_END();
+       return 0;
+}
+
+int MsgParseMultipartListData(msg_json_parser_object *parse_obj, MMS_DATA_S *pMsgData)
+{
+       MSG_BEGIN();
+
+       int index_child = 0;
+
+       msg_json_parser_object child = {};
+
+       if (parse_obj == NULL)
+               return -1;
+
+       while(msg_json_parser_get_next_child(parse_obj, &child, index_child))
+       {
+               if (child.value != NULL && child.type != MSG_JSON_PARSER_NULL) {
+
+                       MSG_PRINT_PARSER_OBJECT(index_child, child);
+
+                       MMS_MULTIPART_DATA_S *pMultipart= MsgMmsCreateMultipart();
+
+                       if (pMultipart) {
+                               if (MsgParseMultipartData(&child, pMultipart) == 0) {
+                                       pMsgData->multipartlist = g_list_append(pMsgData->multipartlist, pMultipart);
+                               } else {
+                                       free(pMultipart);
+                                       pMultipart = NULL;
+                               }
+                       }
+
+               } else {
+                       MSG_DEBUG("Get child : idx  = %d, key = %s, type = %d, value = %p", index_child, child.key, child.type, child.value);
+               }
+
+               index_child++;
+       }
+
+       MSG_END();
+       return 0;
+}
+
+int MsgParseMmsData(msg_json_parser_object *parse_obj, MMS_DATA_S *pMsgData)
+{
+       MSG_BEGIN();
+
+       int index_child = 0;
+       mms_json_enum_e type;
+       msg_json_parser_object child = {};
+
+       if (parse_obj == NULL)
+               return -1;
+
+       while(msg_json_parser_get_next_child(parse_obj, &child, index_child))
+       {
+               if (child.key != NULL) {
+
+                       MSG_PRINT_PARSER_OBJECT(index_child, child);
+
+                       type = get_mms_key_type(child.key);
+
+                       switch (type) {
+                       case MMS_MULTIPART_LIST:
+                               MsgParseMultipartListData(&child, pMsgData);
+                               break;
+                       case MMS_HEADER:
+                               if (pMsgData->header == NULL) {
+                                       pMsgData->header = MsgMmsCreateHeader();
+                               }
+                               if (pMsgData->header)
+                                       MsgParseHeader(&child, pMsgData->header);
+                               break;
+                       case MMS_SMIL_MULTIPART:
+                       {
+                               MMS_MULTIPART_DATA_S *pMultipart = MsgMmsCreateMultipart();
+                               if (pMultipart) {
+                                       if (MsgParseMultipartData(&child, pMultipart) == 0) {
+                                               pMsgData->smil = pMultipart;
+                                       } else {
+                                               free(pMultipart);
+                                               pMultipart = NULL;
+                                       }
+                               }
+                               break;
+                       }
+                       case MMS_BACKUP_TYPE:
+                               pMsgData->backup_type = (int)child.number_value;
+                               break;
+                       default:
+                               MSG_DEBUG("Not Support key = [%s], type = [%d]", child.key, type);
+                               break;
+                       }
+
+               } else {
+                       MSG_PRINT_PARSER_OBJECT(index_child, child);
+               }
+
+               index_child++;
+       }
+
+       MSG_END();
+       return 0;
+}
+
+
+int MsgSerializeMmsJsonData(const MMS_DATA_S *pMsgData, char **pValue)
+{
+       MSG_BEGIN();
+
+       if (pMsgData == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       JsonGenerator *generator;
+       JsonNode *root;
+
+       JsonObject *object_main, *object_header;
+       JsonArray *array_multipart;
+
+       gsize len = 0;
+
+       generator = json_generator_new();
+
+       root = json_node_new(JSON_NODE_OBJECT);
+
+       object_main = json_object_new();
+
+       MSG_JSON_OBJ_SET_INT(object_main, get_mms_key(MMS_BACKUP_TYPE), pMsgData->backup_type);
+
+       //smil multipart
+       if (pMsgData->smil) {
+               JsonObject *smil_object = NULL;
+
+               MsgSerializeMultipart(pMsgData->smil, &smil_object);
+               MSG_JSON_OBJ_SET_OBJ(object_main, get_mms_key(MMS_SMIL_MULTIPART), smil_object);
+       }
+
+       if (pMsgData->multipartlist) {
+               //multipart
+               array_multipart = json_array_new();
+
+               int list_count = g_list_length(pMsgData->multipartlist);
+
+               MSG_DEBUG("Page Count is [%d]", list_count);
+
+               for (int i = 0; i < list_count; i++) {
+
+                       MMS_MULTIPART_DATA_S *multipart = (MMS_MULTIPART_DATA_S *)g_list_nth_data(pMsgData->multipartlist, i);
+
+                       if (multipart) {
+                               JsonObject *multipart_object = NULL;
+
+                               MsgSerializeMultipart(multipart, &multipart_object);
+
+                               MSG_JSON_ARRAY_ADD_OBJECT(array_multipart, multipart_object);
+
+                       } else {
+                               MSG_DEBUG("Not Exist Multipart Data in [%d]th", i);
+                       }
+               }
+
+               MSG_JSON_OBJ_SET_ARRAY(object_main, get_mms_key(MMS_MULTIPART_LIST), array_multipart);
+       }
+
+       //header
+       if (pMsgData->header) {
+               MsgSerializeHeader(pMsgData->header, &object_header);
+
+               MSG_JSON_OBJ_SET_OBJ(object_main, get_mms_key(MMS_HEADER), object_header);
+       }
+
+       json_node_take_object(root, object_main);
+
+       json_generator_set_root(generator, root);
+
+       *pValue = json_generator_to_data(generator, &len);
+       MSG_BEGIN();
+       MSG_DEBUG("Serialized Data : %s", *pValue);
+
+       json_node_free(root);
+
+       g_object_unref(generator);
+
+       MSG_END();
+
+       return 0;
+}
+
+
+int MsgDeserializeMmsJsonData(char* value, int value_len, MMS_DATA_S **ppMmsData)
+{
+       MSG_BEGIN();
+
+       int ret = 0;
+
+       msg_json_parser_handle parser_handle = NULL;
+       msg_json_parser_object root = {};
+       MMS_DATA_S *pMmsData = NULL;
+
+       pMmsData = MsgMmsCreate();
+
+       parser_handle = msg_json_parser_handle_create();
+
+       msg_json_parser_parse_buffer(parser_handle, value, value_len, &root);
+
+       MSG_DEBUG("Deserialized : %s", value);
+
+       MSG_DEBUG("root : key = %s, type = %d, value = %p", root.key, root.type, root.value);
+
+       ret = MsgParseMmsData(&root, pMmsData);
+       if (ret != 0) {
+               MSG_DEBUG("Fail to MsgParseMessageData, ret = %d", ret);
+               MsgMmsRelease(&pMmsData);
+       } else {
+               *ppMmsData = pMmsData;
+       }
+
+       msg_json_parser_handle_destory(&parser_handle);
+
+       MSG_END();
+
+       return ret;
+}
+#endif
+
+
+int MsgSerializeMms(const MMS_DATA_S *pMsgData, char **pValue)
+{
+       MSG_BEGIN();
+
+       if (pMsgData == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       int bufsize = 0;
+
+       int isExistHeader = 0, isExistSmil = 0, isExistMultipart = 0;
+       int multipart_cnt = 0;
+       char *buf = NULL;
+       int i;
+
+       bufsize += sizeof(int); // back-up type
+
+//     int bcc_cnt = g_list_length(pMsgData->header->bcc);
+//     int cc_cnt = g_list_length(pMsgData->header->cc);
+       int to_cnt = 0;
+
+       bufsize += sizeof(int); // check header data
+
+       if (pMsgData->header) {
+               isExistHeader = 1;
+
+               bufsize += sizeof(MMS_HEADER_DATA_S); // header
+
+               to_cnt = g_list_length(pMsgData->header->to);
+
+               bufsize += sizeof(int);
+
+               MSG_DEBUG("Address \"to\" count = [%d]", to_cnt);
+
+               for (i = 0; i < to_cnt; i++) {
+                       MMS_ADDRESS_DATA_S *addr_data = (MMS_ADDRESS_DATA_S *)g_list_nth_data(pMsgData->header->to, i);
+                       if (addr_data && addr_data->address_val) {
+                               bufsize += (sizeof(int) + sizeof(int) + strlen(addr_data->address_val)); // type, length, address
+                       }
+               }
+       }
+
+       bufsize += sizeof(int); // check smil data
+
+       if (pMsgData->smil) {
+               isExistSmil = 1;
+               bufsize += (sizeof(MMS_MULTIPART_DATA_S) + (sizeof(char)*pMsgData->smil->nMultipartDataLen)); // smil data
+       }
+
+       bufsize += sizeof(int); // check multipart list data
+
+       if (pMsgData->multipartlist) {
+               isExistMultipart = 1;
+               multipart_cnt = g_list_length(pMsgData->multipartlist);
+
+               bufsize += sizeof(int); // multipart count
+
+               for (i = 0; i < multipart_cnt; i++) {
+                       MMS_MULTIPART_DATA_S *multipart_data = (MMS_MULTIPART_DATA_S *)g_list_nth_data(pMsgData->multipartlist, i);
+                       bufsize += sizeof(MMS_MULTIPART_DATA_S) + (sizeof(char)*multipart_data->nMultipartDataLen);
+               }
+       }
+
+       MSG_DEBUG("Serialize bufsize = %d", bufsize);
+
+       buf = (char *)calloc(1, bufsize);
+       if (buf == NULL)
+               return -1;
+
+       int serial_index = 0;
+       int offset = 0;
+
+       // 1. Backup type
+       memcpy(buf, &pMsgData->backup_type, sizeof(int));
+       MSG_DEBUG("[#%2d][%5d] backup type = %d", serial_index++, offset, pMsgData->backup_type);
+       offset += sizeof(int);
+
+       // 2. Header Data
+       memcpy(buf + offset, &isExistHeader, sizeof(int));
+       offset += sizeof(int);
+
+       if (pMsgData->header) {
+               memcpy(buf + offset, pMsgData->header, sizeof(MMS_HEADER_DATA_S));
+               offset += sizeof(MMS_HEADER_DATA_S);
+
+               // address
+               memcpy(buf + offset, &to_cnt, sizeof(int));
+               MSG_DEBUG("[#%2d][%5d] TO Count = %d", serial_index++, offset, to_cnt);
+               offset += sizeof(int);
+
+               for (i = 0; i < to_cnt; i++) {
+                       MMS_ADDRESS_DATA_S *to_addr = (MMS_ADDRESS_DATA_S *)g_list_nth_data(pMsgData->header->to, i);
+                       if (to_addr && to_addr->address_val) {
+                               memcpy(buf + offset, &to_addr->address_type, sizeof(int));
+                               MSG_DEBUG("[#%2d][%5d] address type = %d", serial_index++, offset, to_addr->address_type);
+                               offset += sizeof(int);
+                               memcpy(buf + offset, to_addr->address_val, sizeof(char)*MAX_ADDRESS_VAL_LEN);
+                               MSG_SEC_DEBUG("[#%2d][%5d] address val = %s", serial_index++, offset, to_addr->address_val);
+                               offset += sizeof(char)*MAX_ADDRESS_VAL_LEN;
+                       }
+               }
+       }
+
+       // 3. Smil Data
+       memcpy(buf + offset, &isExistSmil, sizeof(int));
+       offset += sizeof(int);
+
+       if (pMsgData->smil) {
+               memcpy(buf + offset, pMsgData->smil, sizeof(MMS_MULTIPART_DATA_S));
+               offset += sizeof(MMS_MULTIPART_DATA_S);
+
+               MSG_DEBUG("SMIL file path = [%s]", pMsgData->smil->szFilePath);
+               MSG_DEBUG("SMIL nMultipartDataLen = [%d]", pMsgData->smil->nMultipartDataLen);
+
+               if (pMsgData->smil->pMultipartData) {
+                       memcpy(buf + offset, pMsgData->smil->pMultipartData, sizeof(char)*pMsgData->smil->nMultipartDataLen);
+                       MSG_DEBUG("[#%2d][%5d] smil data = %s", serial_index++, offset, pMsgData->smil->pMultipartData);
+                       offset += sizeof(char)*pMsgData->smil->nMultipartDataLen;
+               }
+       }
+
+       // 4. Multipart list data
+       memcpy(buf + offset, &isExistMultipart, sizeof(int));
+       offset += sizeof(int);
+
+       if (pMsgData->multipartlist) {
+               MSG_DEBUG("Multipart list count = [ %d]", multipart_cnt);
+               memcpy(buf + offset, &multipart_cnt, sizeof(int));
+               offset += sizeof(int);
+
+               for (i = 0; i < multipart_cnt; i++) {
+                       MMS_MULTIPART_DATA_S *multipart_data = (MMS_MULTIPART_DATA_S *)g_list_nth_data(pMsgData->multipartlist, i);
+                       MSG_DEBUG("multipart_data = [%p]", multipart_data);
+                       if (multipart_data) {
+                               memcpy(buf + offset, multipart_data, sizeof(MMS_MULTIPART_DATA_S));
+                               offset += sizeof(MMS_MULTIPART_DATA_S);
+
+                               MSG_DEBUG("Multipart file path = [%s]", multipart_data->szFilePath);
+
+                               if (multipart_data->pMultipartData) {
+                                       memcpy(buf + offset, multipart_data->pMultipartData, sizeof(char)*multipart_data->nMultipartDataLen);
+                                       MSG_DEBUG("[#%2d][%5d] multipart data ptr = %p", serial_index++, offset, multipart_data->pMultipartData);
+                                       offset += sizeof(char)*multipart_data->nMultipartDataLen;
+                               }
+                       }
+               }
+       }
+
+       *pValue = buf;
+
+       MSG_DEBUG("Expect Buffer Size: %d, Final offset : %d", bufsize, offset);
+
+       MSG_END();
+
+       return bufsize;
+}
+
+
+int MsgDeserializeMmsData(char* value, int value_len, MMS_DATA_S **ppMmsData)
+{
+       MSG_BEGIN();
+
+       if (value == NULL) {
+               MSG_DEBUG("Serialized data is NULL");
+               return -1;
+       }
+
+       MMS_DATA_S *pMmsData = NULL;
+
+       int isExistHeader = 0, isExistSmil = 0, isExistMultipart = 0;
+       int addr_cnt = 0;
+       int multipart_cnt = 0;
+
+       int deserial_index = 0;
+       int offset = 0;
+       int i = 0;
+
+       pMmsData = MsgMmsCreate();
+       *ppMmsData = pMmsData;
+       if (pMmsData == NULL)
+               return -1;
+
+
+       // 1. Backup type
+       memcpy(&(pMmsData->backup_type), value, sizeof(int));
+       MSG_DEBUG("[#%2d][%5d] backup type = %d", deserial_index++, offset, pMmsData->backup_type);
+       offset += sizeof(int);
+
+       // 2. Header Data
+       memcpy(&isExistHeader, value + offset, sizeof(int));
+       offset += sizeof(int);
+
+       if (isExistHeader) {
+               pMmsData->header = (MMS_HEADER_DATA_S *)calloc(1, sizeof(MMS_HEADER_DATA_S));
+               if (pMmsData->header == NULL)
+                       return -1;
+
+               memcpy(pMmsData->header, value + offset, sizeof(MMS_HEADER_DATA_S));
+               offset += sizeof(MMS_HEADER_DATA_S);
+
+               memcpy(&addr_cnt, value + offset, sizeof(int));
+               offset += sizeof(int);
+
+               pMmsData->header->to = NULL;
+
+               for (i = 0; i < addr_cnt; i++) {
+                       MMS_ADDRESS_DATA_S* to_addr = (MMS_ADDRESS_DATA_S*)calloc(1, sizeof(MMS_ADDRESS_DATA_S));
+                       if (to_addr == NULL)
+                               return -1;
+
+                       memcpy(&(to_addr->address_type), value + offset, sizeof(int));
+                       MSG_DEBUG("[#%2d][%5d] address type = %d", deserial_index++, offset, to_addr->address_type);
+                       offset += sizeof(int);
+
+                       memcpy(to_addr->address_val, value + offset, sizeof(char)*MAX_ADDRESS_VAL_LEN);
+                       MSG_SEC_DEBUG("[#%2d][%5d] address val = %s", deserial_index++, offset, to_addr->address_val);
+                       offset += sizeof(char)*MAX_ADDRESS_VAL_LEN;
+
+                       pMmsData->header->to = g_list_append(pMmsData->header->to, (void *)to_addr);
+               }
+       }
+
+       // 3. Smil Data
+       memcpy(&isExistSmil, value + offset, sizeof(int));
+       offset += sizeof(int);
+
+       if (isExistSmil) {
+               pMmsData->smil = (MMS_MULTIPART_DATA_S *)calloc(1, sizeof(MMS_MULTIPART_DATA_S));
+               if (pMmsData->smil == NULL)
+                       return -1;
+
+               memcpy(pMmsData->smil, value + offset, sizeof(MMS_MULTIPART_DATA_S));
+               offset += sizeof(MMS_MULTIPART_DATA_S);
+
+               MSG_DEBUG("SMIL file path = [%s]", pMmsData->smil->szFilePath);
+               MSG_DEBUG("SMIL nMultipartDataLen = [%d]", pMmsData->smil->nMultipartDataLen);
+
+               if (pMmsData->smil->nMultipartDataLen > 0) {
+                       pMmsData->smil->pMultipartData = (char *)calloc(1, sizeof(char)*pMmsData->smil->nMultipartDataLen);
+                       if (pMmsData->smil->pMultipartData == NULL)
+                               return -1;
+
+                       memcpy(pMmsData->smil->pMultipartData, value + offset, sizeof(char)*pMmsData->smil->nMultipartDataLen);
+                       MSG_DEBUG("[#%2d][%5d] smil data ptr = %p", deserial_index++, offset, pMmsData->smil->pMultipartData);
+                       offset += sizeof(char)*pMmsData->smil->nMultipartDataLen;
+               } else {
+                       pMmsData->smil->pMultipartData = NULL;
+               }
+       }
+
+       // 4. Multipart list data
+       memcpy(&isExistMultipart, value + offset, sizeof(int));
+       offset += sizeof(int);
+
+       if (isExistMultipart) {
+               memcpy(&multipart_cnt, value + offset, sizeof(int));
+               offset += sizeof(int);
+
+               MSG_DEBUG("Multipart list count = [ %d]", multipart_cnt);
+
+               pMmsData->multipartlist = NULL;
+
+               for (i = 0; i < multipart_cnt; i++) {
+                       MMS_MULTIPART_DATA_S *multipart_data = (MMS_MULTIPART_DATA_S *)calloc(1, sizeof(MMS_MULTIPART_DATA_S));
+                       if (multipart_data == NULL)
+                               return -1;
+
+                       memcpy(multipart_data, value + offset, sizeof(MMS_MULTIPART_DATA_S));
+                       offset += sizeof(MMS_MULTIPART_DATA_S);
+
+                       MSG_DEBUG("Multipart file path = [%s]", multipart_data->szFilePath);
+
+                       if (multipart_data->nMultipartDataLen > 0) {
+                               multipart_data->pMultipartData = (char *)calloc(1, sizeof(char)*multipart_data->nMultipartDataLen);
+                               if (multipart_data->pMultipartData == NULL) {
+                                       free(multipart_data);
+                                       return -1;
+                               }
+
+                               memcpy(multipart_data->pMultipartData, value + offset, sizeof(char)*multipart_data->nMultipartDataLen);
+                               MSG_DEBUG("[#%2d][%5d] multipart_data ptr = %p", deserial_index++, offset, multipart_data->pMultipartData);
+                               offset += sizeof(char)*multipart_data->nMultipartDataLen;
+                       } else {
+                               multipart_data->pMultipartData = NULL;
+                       }
+                       pMmsData->multipartlist = g_list_append(pMmsData->multipartlist, (void *)multipart_data);
+               }
+       }
+
+       MSG_DEBUG("Final offset : %d", offset);
+
+       MSG_END();
+       return 0;
+}
diff --git a/utils/MsgSmil.cpp b/utils/MsgSmil.cpp
new file mode 100755 (executable)
index 0000000..295ebe6
--- /dev/null
@@ -0,0 +1,2008 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include <ctype.h>
+#include <libxml/parser.h>
+#include <libxml/tree.h>
+
+#include "MsgMmsMessage.h"
+#include "MsgInternalTypes.h"
+#include "MsgSmil.h"
+#include "MsgDebug.h"
+
+#define INVALID_HOBJ   -1
+#define MSG_SMIL_MAX_DOC       1
+#define MSG_SMIL_COLOR_SIZE    10
+#define MSG_STDSTR_SHORT       0x7F
+
+typedef int HMsgSmil; //SmilDoc Handle
+
+typedef enum _SMIL_ELEMENT_T {
+       ELEMENT_SMIL,
+       ELEMENT_HEAD,
+       ELEMENT_LAYOUT,
+       ELEMENT_ROOTLAYOUT,
+       ELEMENT_REGION,
+       ELEMENT_TRANSITION,
+       ELEMENT_META,
+       ELEMENT_BODY,
+       ELEMENT_PAR,
+       ELEMENT_PARAM,
+       ELEMENT_TEXT,
+       ELEMENT_IMG,
+       ELEMENT_AUDIO,
+       ELEMENT_VIDEO,
+       ELEMENT_REF,
+       ELEMENT_ANIMATE,
+       ELEMENT_MAX,
+} SMIL_ELEMENT_T;
+
+typedef enum _SMIL_ATTRIBUTE_T {
+       ATTRIBUTE_UNKNOWN = -1,
+       ATTRIBUTE_ID,
+       ATTRIBUTE_TOP,
+       ATTRIBUTE_LEFT,
+       ATTRIBUTE_WIDTH,
+       ATTRIBUTE_HEIGHT,
+       ATTRIBUTE_FIT,
+       ATTRIBUTE_BGCOLOR,
+       ATTRIBUTE_DUR,
+       ATTRIBUTE_SRC,
+       ATTRIBUTE_COLOR,
+       ATTRIBUTE_BOLD,
+       ATTRIBUTE_UNDERLINE,
+       ATTRIBUTE_ITALIC,
+       ATTRIBUTE_REVERSE,
+       ATTRIBUTE_DIRECTION,
+       ATTRIBUTE_SIZE,
+       ATTRIBUTE_FONT,
+       ATTRIBUTE_REGION,
+       ATTRIBUTE_NAME,
+       ATTRIBUTE_VALUE,
+       ATTRIBUTE_ALT,
+       ATTRIBUTE_TYPE,
+       ATTRIBUTE_SUBTYPE,
+       ATTRIBUTE_CONTENT,
+       ATTRIBUTE_FGCOLOR,
+       ATTRIBUTE_TEXTFORMAT,
+       ATTRIBUTE_TRANSIN,
+       ATTRIBUTE_TRANSOUT,
+       ATTRIBUTE_BEGIN,
+       ATTRIBUTE_END,
+       ATTRIBUTE_REPEAT_COUNT,
+} SMIL_ATTRIBUTE_T;
+
+typedef struct _MsgSmilDoc {
+       xmlDocPtr pSmilDoc;
+       xmlNodePtr pstRootNode;
+} MsgSmilDoc;
+
+/* static variables */
+static char gszEmptyRawDoc[] = "<smil><head><layout></layout></head><body></body></smil>";
+
+__thread MsgSmilDoc *__gpaMsgSmilDoc[MSG_SMIL_MAX_DOC]={NULL, };
+__thread char gszColor[MSG_SMIL_COLOR_SIZE + 1] = {0, };
+
+__thread bool gCmd[ELEMENT_MAX] = {false, };
+__thread MMS_SMIL_ROOTLAYOUT gRootlayout = {};
+__thread MMS_SMIL_REGION *gRegion = NULL;
+__thread MMS_PAGE_S *gPage = NULL;
+__thread MMS_MEDIA_S *gMedia = NULL;
+__thread MMS_SMIL_TRANSITION *gTransition = NULL;
+__thread MMS_SMIL_META *gMeta = NULL;
+
+//For Parse Smil
+static int MsgSmilGetColorValue(xmlChar *content);
+static int MsgSmilGetTime(char *pValue);
+static int MsgSmilAtoIHexa(char *pInput);
+static int MsgSmilGetElementID(char *pString);
+static int MsgSmilGetAttrID(char *pString);
+static int MsgSmilGetFontSizeValue(char *pString);
+static bool MsgSmilGetFontAttrib(char *pString);
+static MmsTextDirection MsgSmilGetFontDirection(char *pString);
+static MmsSmilFontType MsgSmilGetFontTypeValue(char *pString);
+
+static xmlNodePtr MsgSmilGetNodeByElementName(xmlNodePtr pstNode, char *pszName);
+
+//For Generate Smil
+static HMsgSmil MsgSmilCreateEmptySmilDoc(void);
+static HMsgSmil MsgSmilCreateSmilDoc(char *pszRawData);
+static bool MsgSmilDestroyDoc(HMsgSmil hSmilDoc);
+static bool IsValidSmilDocNo(int nSmilDocNo);
+static char *MsgSmilGetRawData(HMsgSmil hSmilDoc);
+
+static const char *MsgSmilColorValueToString(int nValue);
+
+static bool MsgSmilAddPage(HMsgSmil hSmilDoc, MMS_PAGE_S *pstSmilPage);
+static bool MsgSmilAddRootLayout(HMsgSmil hSmilDoc, MMS_SMIL_ROOTLAYOUT *pstSmilRootLayout);
+static bool MsgSmilAddRegion(HMsgSmil hSmilDoc, MMS_SMIL_REGION *pstSmilRegion);
+static bool MsgSmilAddMedia(HMsgSmil hSmilDoc, int nPageNo, int nMediaIdx, MMS_MEDIA_S *pstSmilMedia, char *pszContentID);
+static xmlNode *MsgSmilCreateTextNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID);
+static xmlNode *MsgSmilCreateMMNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID);
+static bool MsgSmilInsertFirstChild(xmlNode *pParent, xmlNode *pNode);
+static bool MsgSmilInsertNode(xmlNode *pParent, xmlNode *pLeftSibling, xmlNode *pNode);
+static void MsgSmilSetAttribute(xmlNode *pNode, char *szField, char *szValue);
+
+
+int MsgSmilGetColorValue(xmlChar *content)
+{
+       int color;
+       char color_inp[9] = {0,};
+
+       if (content[0] == '#') {        // RGB value
+               snprintf(color_inp, sizeof(color_inp),"FF%s", (char *)&content[1]);
+               color = MsgSmilAtoIHexa(color_inp);
+       } else if (content[0] == '0' && (content[1] == 'x' || content[1] == 'X')) {
+               snprintf(color_inp, sizeof(color_inp),"%s", (char *)&content[2]);
+               color = MsgSmilAtoIHexa(color_inp);
+       } else {
+               MSG_DEBUG("Invalid Color Value");
+               color = 0x00000000;
+       }
+
+       return color;
+}
+
+
+const char *MsgSmilColorValueToString(int nValue)
+{
+       unsigned char alpha = (nValue & 0xFF000000) >> 24;
+       unsigned char red = (nValue & 0xFF0000) >> 16;
+       unsigned char green = (nValue & 0x00FF00) >> 8;
+       unsigned char blue = nValue & 0x0000FF;
+
+       if (alpha == 0xFF) {
+               snprintf(gszColor, sizeof(gszColor), "#%02x%02x%02x", red, green, blue);
+       } else {
+               snprintf(gszColor, sizeof(gszColor), "0x%02x%02x%02x%02x", alpha, red, green, blue);
+       }
+
+       MSG_DEBUG("color value : [%s]", gszColor);
+
+       return gszColor;
+}
+
+
+int MsgSmilAtoIHexa(char *pInput)
+{
+       int res = 0;
+       int len = 0;
+       int temp = 1;
+       int i  = 0;
+       int j = 0;
+       char *pOutput = NULL;
+
+       len = strlen(pInput);
+       pOutput = (char *)malloc(len + 1);
+
+       if (pOutput == NULL) {
+               MSG_DEBUG("Memory full");
+               goto __CATCH;
+       }
+
+       memset(pOutput, 0, len + 1);
+
+       for (i = len - 1; i >= 0; i--) {
+               for (j = 0; j < (len - 1 - i); j++) {
+                       temp *= 16;
+               }
+
+               switch (pInput[i]) {
+               case '0':
+                       pOutput[i] = 0;
+                       break;
+
+               case '1':
+                       pOutput[i] = 1;
+                       break;
+
+               case '2':
+                       pOutput[i] = 2;
+                       break;
+
+               case '3':
+                       pOutput[i] = 3;
+                       break;
+
+               case '4':
+                       pOutput[i] = 4;
+                       break;
+
+               case '5':
+                       pOutput[i] = 5;
+                       break;
+
+               case '6':
+                       pOutput[i] = 6;
+                       break;
+
+               case '7':
+                       pOutput[i] = 7;
+                       break;
+
+               case '8':
+                       pOutput[i] = 8;
+                       break;
+
+               case '9':
+                       pOutput[i] = 9;
+                       break;
+
+               case 'a':
+               case 'A':
+                       pOutput[i] = 10;
+                       break;
+
+               case 'b':
+               case 'B':
+                       pOutput[i] = 11;
+                       break;
+
+               case 'c':
+               case 'C':
+                       pOutput[i] = 12;
+                       break;
+
+               case 'd':
+               case 'D':
+                       pOutput[i] = 13;
+                       break;
+
+               case 'e':
+               case 'E':
+                       pOutput[i] = 14;
+                       break;
+
+               case 'f':
+               case 'F':
+                       pOutput[i] = 15;
+                       break;
+               }
+
+               res += (pOutput[i] * temp);
+               temp = 1;
+       }
+
+__CATCH:
+
+       if (pOutput) {
+               free(pOutput);
+               pOutput = NULL;
+       }
+
+       return res;
+}
+
+int MsgSmilGetTime(char *pValue)
+{
+       char *pTemp = NULL;
+       bool bMSec = false;
+       int retVal = 0;
+       int i = 0;
+
+       if (pValue == NULL || pValue[0] == '\0')
+               return 0;
+
+       /* Default time unit -> millisecond */
+       if (strstr(pValue, "msec"))
+               bMSec = true;
+
+       if (strstr(pValue, "ms"))
+               bMSec = true;
+
+       pTemp = (char *)malloc(strlen(pValue) + 1);
+
+       if (NULL == pTemp) {
+               MSG_DEBUG("malloc for <time> attribute is failed");
+               return 0;
+       }
+
+       while (isdigit(pValue[i])) {
+               pTemp[i] = pValue[i];
+               i++;
+       }
+       pTemp[i] = '\0';
+
+       /* Detect 's' and 'ms' here */
+       retVal = atoi(pTemp);
+
+       if (bMSec == false)
+               retVal *= 1000;
+
+       if (pTemp) {
+               free(pTemp);
+               pTemp = NULL;
+       }
+
+       return retVal;
+}
+
+int MsgSmilGetElementID(char *pString)
+{
+       if (!strcmp(pString, "smil"))
+               return ELEMENT_SMIL;
+       else if (!strcmp(pString, "head"))
+               return ELEMENT_HEAD;
+       else if (!strcmp(pString, "layout"))
+               return ELEMENT_LAYOUT;
+       else if (!strcmp(pString, "root-layout"))
+               return ELEMENT_ROOTLAYOUT;
+       else if (!strcmp(pString, "region"))
+               return ELEMENT_REGION;
+       else if (!strcmp(pString, "body"))
+               return ELEMENT_BODY;
+       else if (!strcmp(pString, "par"))
+               return ELEMENT_PAR;
+       else if (!strcmp(pString, "param"))
+               return ELEMENT_PARAM;
+       else if (!strcmp(pString, "text"))
+               return ELEMENT_TEXT;
+       else if (!strcmp(pString, "img"))
+               return ELEMENT_IMG;
+       else if (!strcmp(pString, "audio"))
+               return ELEMENT_AUDIO;
+       else if (!strcmp(pString, "video"))
+               return ELEMENT_VIDEO;
+       else if (!strcmp(pString, "ref"))
+               return ELEMENT_REF;
+       else if (!strcmp(pString, "animate"))
+               return ELEMENT_ANIMATE;
+       else if (!strcmp(pString, "root-layout"))
+               return ELEMENT_HEAD;
+       else if (!strcmp(pString, "transition"))
+               return ELEMENT_TRANSITION;
+       else if (!strcmp(pString, "meta"))
+               return ELEMENT_META;
+       else
+               return -1;
+}
+
+int MsgSmilGetAttrID(char *pString)
+{
+       if (!strcmp(pString, "id"))
+               return ATTRIBUTE_ID;
+       else if (!strcmp(pString, "top"))
+               return ATTRIBUTE_TOP;
+       else if (!strcmp(pString, "left"))
+               return ATTRIBUTE_LEFT;
+       else if (!strcmp(pString, "width"))
+               return ATTRIBUTE_WIDTH;
+       else if (!strcmp(pString, "height"))
+               return ATTRIBUTE_HEIGHT;
+       else if (!strcmp(pString, "fit"))
+               return ATTRIBUTE_FIT;
+       else if (!strcmp(pString, "backgroundColor") || !strcmp(pString, "background-color"))
+               return ATTRIBUTE_BGCOLOR;
+       else if (!strcmp(pString, "dur"))
+               return ATTRIBUTE_DUR;
+       else if (!strcmp(pString, "src"))
+               return ATTRIBUTE_SRC;
+       else if (!strcmp(pString, "color"))
+               return ATTRIBUTE_COLOR;
+       else if (!strcmp(pString, "bold"))
+               return ATTRIBUTE_BOLD;
+       else if (!strcmp(pString, "underline"))
+               return ATTRIBUTE_UNDERLINE;
+       else if (!strcmp(pString, "italic"))
+               return ATTRIBUTE_ITALIC;
+       else if (!strcmp(pString, "reverse"))
+               return ATTRIBUTE_REVERSE;
+       else if (!strcmp(pString, "direction"))
+               return ATTRIBUTE_DIRECTION;
+       else if (!strcmp(pString, "size"))
+               return ATTRIBUTE_SIZE;
+       else if (!strcmp(pString, "font"))
+               return ATTRIBUTE_FONT;
+       else if (!strcmp(pString, "region"))
+               return ATTRIBUTE_REGION;
+       else if (!strcmp(pString, "name"))
+               return ATTRIBUTE_NAME;
+       else if (!strcmp(pString, "value"))
+               return ATTRIBUTE_VALUE;
+       else if (!strcmp(pString, "alt"))
+               return ATTRIBUTE_ALT;
+       else if (!strcmp(pString, "type"))
+               return ATTRIBUTE_TYPE;
+       else if (!strcmp(pString, "subtype"))
+               return ATTRIBUTE_SUBTYPE;
+       else if (!strcmp(pString, "content"))
+               return ATTRIBUTE_CONTENT;
+       else if (!strcmp(pString, "transIn"))
+               return ATTRIBUTE_TRANSIN;
+       else if (!strcmp(pString, "transOut"))
+               return ATTRIBUTE_TRANSOUT;
+       else if (!strcmp(pString, "begin"))
+               return ATTRIBUTE_BEGIN;
+       else if (!strcmp(pString, "end"))
+               return ATTRIBUTE_END;
+       else if (!strcmp(pString, "repeatCount"))
+               return ATTRIBUTE_REPEAT_COUNT;
+
+       return -1;
+}
+
+bool MsgSmilGetFontAttrib(char *pString)
+{
+       if (!strcmp(pString, "true"))
+               return true;
+       else
+               return false;
+}
+
+MmsTextDirection MsgSmilGetFontDirection(char *pString)
+{
+       MmsTextDirection direction = MMS_TEXT_DIRECTION_INVALID;
+
+       if (!strcmp(pString, "right"))
+               direction = MMS_TEXT_DIRECTION_RIGHT;
+       else if (!strcmp(pString, "down"))
+               direction = MMS_TEXT_DIRECTION_DOWN;
+
+       return direction;
+}
+
+int MsgSmilGetFontSizeValue(char *pString)
+{
+       if (!strcmp(pString, "small"))
+               return MMS_SMIL_FONT_SIZE_SMALL;
+       else if (!strcmp(pString, "normal"))
+               return MMS_SMIL_FONT_SIZE_NORMAL;
+       else if (!strcmp(pString, "large"))
+               return MMS_SMIL_FONT_SIZE_LARGE;
+       else
+               return atoi(pString);
+}
+
+MmsSmilFontType MsgSmilGetFontTypeValue(char *pString)
+{
+
+       if (!strcmp(pString, "normal"))
+               return MMS_SMIL_FONT_TYPE_NORMAL;
+       else if (!strcmp(pString, "italic"))
+               return MMS_SMIL_FONT_TYPE_ITALIC;
+       else if (!strcmp(pString, "bold"))
+               return MMS_SMIL_FONT_TYPE_BOLD;
+       else if (!strcmp(pString, "underline"))
+               return MMS_SMIL_FONT_TYPE_UNDERLINE;
+       else
+               return MMS_SMIL_FONT_TYPE_NORMAL;
+}
+
+HMsgSmil MsgSmilCreateEmptySmilDoc(void)
+{
+       HMsgSmil hMmsSmil;
+
+       MSG_BEGIN();
+
+       hMmsSmil = MsgSmilCreateSmilDoc(gszEmptyRawDoc);
+
+       MSG_DEBUG("Create an empty smilDoc.(Handle = %d)", hMmsSmil);
+
+       MSG_END();
+
+       return hMmsSmil;
+}
+
+HMsgSmil MsgSmilCreateSmilDoc(char *pszRawData)
+{
+       int nSmilDocNo = 0;
+       xmlNodePtr stRootNode;
+
+       MSG_BEGIN();
+
+       // Destroy smil doc if present
+       if (NULL != __gpaMsgSmilDoc[nSmilDocNo]) {
+
+               if (false == MsgSmilDestroyDoc(nSmilDocNo)) {
+                       MSG_DEBUG("MsgSmilDestroyDoc: Failed!");
+               }
+       }
+
+       for (nSmilDocNo = 0; nSmilDocNo < MSG_SMIL_MAX_DOC; nSmilDocNo++) {
+               if (NULL == __gpaMsgSmilDoc[nSmilDocNo])
+                       break;
+       }
+
+       if (MSG_SMIL_MAX_DOC == nSmilDocNo) {
+               MSG_DEBUG("SmilDoc table is full. Can't create.");
+               return INVALID_HOBJ;
+       }
+       __gpaMsgSmilDoc[nSmilDocNo] = (MsgSmilDoc*)malloc(sizeof(MsgSmilDoc));
+       if (NULL ==  __gpaMsgSmilDoc[nSmilDocNo]) {
+               MSG_DEBUG("Memory Allocation Failed.");
+               return INVALID_HOBJ;
+       }
+       memset(__gpaMsgSmilDoc[nSmilDocNo], 0, sizeof(MsgSmilDoc));
+
+       __gpaMsgSmilDoc[nSmilDocNo]->pSmilDoc = xmlParseMemory(pszRawData, strlen(pszRawData));
+       if (NULL == __gpaMsgSmilDoc[nSmilDocNo]->pSmilDoc) {
+
+               if (false == MsgSmilDestroyDoc(nSmilDocNo)) {
+                       MSG_DEBUG("MsgSmilDestroyDoc: Failed!");
+               }
+               return INVALID_HOBJ;
+       }
+
+       stRootNode = xmlDocGetRootElement(__gpaMsgSmilDoc[nSmilDocNo]->pSmilDoc);
+       if (NULL == stRootNode) {
+               MSG_DEBUG("Empty document");
+               if (false == MsgSmilDestroyDoc(nSmilDocNo)) {
+                       MSG_DEBUG("MsgSmilDestroyDoc: Failed!");
+               }
+               return INVALID_HOBJ;
+       }
+
+       if (xmlStrcmp(stRootNode->name, (const xmlChar *) "smil")) {
+               MSG_DEBUG("Document of the wrong type, root node != smil");
+               if (false == MsgSmilDestroyDoc(nSmilDocNo)) {
+                       MSG_DEBUG("MsgSmilDestroyDoc: Failed!");
+               }
+               return INVALID_HOBJ;
+       }
+
+       __gpaMsgSmilDoc[nSmilDocNo]->pstRootNode = stRootNode;
+
+       MSG_END();
+       return ((HMsgSmil)nSmilDocNo);
+}
+
+bool MsgSmilDestroyDoc(HMsgSmil hSmilDoc)
+{
+       int nSmilDocNo = (int)hSmilDoc;
+       bool bFlag = true;
+       MSG_BEGIN();
+
+       if (0 <= nSmilDocNo &&
+               nSmilDocNo < MSG_SMIL_MAX_DOC &&
+               __gpaMsgSmilDoc[nSmilDocNo]) {
+               if (__gpaMsgSmilDoc[nSmilDocNo]->pSmilDoc) {
+                       xmlFreeDoc(__gpaMsgSmilDoc[nSmilDocNo]->pSmilDoc);
+               }
+
+               if (__gpaMsgSmilDoc[nSmilDocNo]->pstRootNode) {
+                       //Need to Check
+               }
+               free(__gpaMsgSmilDoc[nSmilDocNo]);
+               __gpaMsgSmilDoc[nSmilDocNo] = NULL;
+       } else {
+               MSG_DEBUG("Invalid SmilDoc(hSmilDoc:%d)", nSmilDocNo);
+               bFlag =  false;
+       }
+
+       MSG_END();
+       return bFlag;
+}
+
+bool IsValidSmilDocNo(int nSmilDocNo)
+{
+       bool bIsValidSmil = false;
+
+       MSG_BEGIN();
+
+       if (0 <= nSmilDocNo &&
+               nSmilDocNo < MSG_SMIL_MAX_DOC &&
+               __gpaMsgSmilDoc[nSmilDocNo] &&
+               __gpaMsgSmilDoc[nSmilDocNo]->pSmilDoc) {
+               bIsValidSmil = true;
+       }
+
+       MSG_END();
+       return bIsValidSmil;
+}
+
+char *MsgSmilGetRawData(HMsgSmil hSmilDoc)
+{
+       int nSmilDocNo = (int)hSmilDoc;
+       char *pszRawData = NULL;
+
+       MSG_BEGIN();
+
+       if (IsValidSmilDocNo(nSmilDocNo)) {
+               //xmlSaveFormatFileEnc("-", __gpaMmsSmilDoc[nSmilDocNo]->pSmilDoc, "UTF-8", 1);
+               xmlDocDumpMemory(__gpaMsgSmilDoc[nSmilDocNo]->pSmilDoc, (xmlChar **)(&pszRawData) , NULL);
+               if (NULL == pszRawData) {
+                       MSG_DEBUG("Invalid pSmilDoc (now wellformed document)");
+               }
+               MSG_END();
+       } else {
+               MSG_DEBUG("Invalid SmilDoc(hSmilDoc:%d)", nSmilDocNo);
+       }
+       return pszRawData;
+}
+
+bool MsgSmilAddPage(HMsgSmil hSmilDoc, MMS_PAGE_S *pstSmilPage)
+{
+       int nSmilDocNo = hSmilDoc;
+
+       MSG_BEGIN();
+
+       bool ret = true;
+
+       if (IsValidSmilDocNo(nSmilDocNo)) {
+               xmlNodePtr pstParElement;
+               xmlNodePtr pstBodyElement;
+               xmlNodePtr pstParList;
+               char szBuf[MSG_STDSTR_SHORT] = {0, };
+
+               pstBodyElement = MsgSmilGetNodeByElementName(__gpaMsgSmilDoc[nSmilDocNo]->pstRootNode, (char *)"body");
+
+               if (NULL == pstBodyElement) {
+                       MSG_DEBUG("There is no <body> node. Can't create <par> node.");
+                       return false;
+               }
+
+               /* Create "par"  node and insert it */
+               pstParElement = xmlNewNode(NULL, (xmlChar *)"par");
+
+               if (NULL == pstParElement) {
+                       MSG_DEBUG("Can't create <par> node. (from XmlParser)");
+                       return false;
+               }
+
+               MSG_SEC_DEBUG("Par Element Name = %s", (char *)pstParElement->name);
+
+               /* Add attributes to "par" */
+               if (pstSmilPage->nDur > 0) {
+                       snprintf(szBuf, MSG_STDSTR_SHORT, "%dms", pstSmilPage->nDur);
+                       xmlSetProp(pstParElement, (const xmlChar *)"dur", (const xmlChar *)szBuf);
+                       MSG_DEBUG("[Set Attribute] : dur : [%s]", szBuf);
+               }
+
+               /* Find the insertion point : right sibling of the last <par> node or first child of <body> */
+               pstParList = xmlGetLastChild(pstBodyElement);
+
+               if (pstParList) {
+                       ret = MsgSmilInsertNode(pstBodyElement, pstParList, pstParElement);
+                       if (ret == false)
+                               xmlFreeNode(pstParElement);
+               } else {
+                       ret = MsgSmilInsertFirstChild(pstBodyElement, pstParElement);
+                       if (ret == false)
+                               xmlFreeNode(pstParElement);
+               }
+       } else {
+               MSG_DEBUG("Invalid SmilDoc(hSmilDoc:%d)", nSmilDocNo);
+               return false;
+       }
+
+
+       return ret;
+}
+
+bool MsgSmilAddRootLayout(HMsgSmil hSmilDoc, MMS_SMIL_ROOTLAYOUT *pstSmilRootLayout)
+{
+       int nSmilDocNo = hSmilDoc;
+       xmlNodePtr pstRootLayout = NULL;
+       xmlNodePtr pstLayoutList = NULL;
+       xmlNodePtr pstRootLayoutList = NULL;
+       char szBuf[MSG_STDSTR_SHORT] = {0, };
+
+       MSG_BEGIN();
+
+       if (IsValidSmilDocNo(nSmilDocNo)) {
+               pstLayoutList = MsgSmilGetNodeByElementName(__gpaMsgSmilDoc[nSmilDocNo]->pstRootNode, (char *)"layout");
+
+               if (NULL == pstLayoutList) {
+                       MSG_DEBUG("There is no <layout> node. Can't create <root-layout> node.");
+                       return false;
+               }
+               MSG_SEC_DEBUG("Layout Element Name = %s ", (char *)pstLayoutList->name);
+
+               pstRootLayoutList = MsgSmilGetNodeByElementName(__gpaMsgSmilDoc[nSmilDocNo]->pstRootNode, (char *)"root-layout");
+
+               if (NULL != pstRootLayoutList) {
+                       MSG_DEBUG("There is <root-layout> node already");
+                       MSG_SEC_DEBUG("Root Layout Element Name = %s", (char *)pstRootLayoutList->name);
+                       return false;
+               }
+               /* Create "root-layout" node and insert it */
+               pstRootLayout = xmlNewNode(NULL, (xmlChar *)"root-layout");
+               if (NULL == pstRootLayout) {
+                       MSG_DEBUG("Can't create <root-layout> node. (from XmlParser)");
+                       return false;
+               }
+               MSG_SEC_DEBUG("Root Layout Element Name = %s", (char *)pstRootLayout->name);
+
+               if (pstSmilRootLayout->bBgColor == true) {      // Replace value later
+                       if ( ( (pstSmilRootLayout->bgColor & 0xFF000000) >> 24 ) > 0) {//check alpha value
+                               xmlSetProp(pstRootLayout, (const xmlChar *)"backgroundColor", (const xmlChar *)MsgSmilColorValueToString(pstSmilRootLayout->bgColor));
+                       }
+               }
+
+
+               //width
+               if (true == pstSmilRootLayout->width.bUnitPercent) {
+                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRootLayout->width.value);
+                       xmlSetProp(pstRootLayout, (const xmlChar *)"width", (const xmlChar *)szBuf);
+               } else {
+                       if (pstSmilRootLayout->width.value > 0) {
+                               snprintf(szBuf, MSG_STDSTR_SHORT, "%d", pstSmilRootLayout->width.value);
+                               xmlSetProp(pstRootLayout, (const xmlChar *)"width", (const xmlChar *)szBuf);
+                       } else {
+                               MSG_DEBUG("Set Width : default value [100%%]");
+                               xmlSetProp(pstRootLayout, (const xmlChar *)"width", (const xmlChar *)"100%");
+                       }
+               }
+
+               //Height
+               if (true == pstSmilRootLayout->height.bUnitPercent) {
+                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRootLayout->height.value);
+                       xmlSetProp(pstRootLayout, (const xmlChar *)"height", (const xmlChar *)szBuf);
+               } else {
+                       if (pstSmilRootLayout->height.value > 0) {
+                               snprintf(szBuf, MSG_STDSTR_SHORT, "%d", pstSmilRootLayout->height.value);
+                               xmlSetProp(pstRootLayout, (const xmlChar *)"height", (const xmlChar *)szBuf);
+                       } else {
+
+                               xmlSetProp(pstRootLayout, (const xmlChar *)"height", (const xmlChar *)"100%");
+                       }
+               }
+
+               xmlAddChild(pstLayoutList, pstRootLayout);
+
+               return true;
+       } else {
+               MSG_DEBUG("Invalid SmilDoc(hSmilDoc:%d)", nSmilDocNo);
+               return false;
+       }
+
+}
+
+bool MsgSmilAddRegion(HMsgSmil hSmilDoc, MMS_SMIL_REGION *pstSmilRegion)
+{
+       int nSmilDocNo = hSmilDoc;
+
+       MSG_BEGIN();
+
+       if (IsValidSmilDocNo(nSmilDocNo)) {
+               int nRootWidth = 0;
+               int nRootHeight = 0;
+               xmlNodePtr pstRegion;
+               xmlNodePtr pstLayoutList;
+               xmlNodePtr pstRootLayoutList;
+               xmlAttrPtr pAttribute;
+               char szBuf[MSG_STDSTR_SHORT] = {0, };
+
+               pstLayoutList = MsgSmilGetNodeByElementName(__gpaMsgSmilDoc[nSmilDocNo]->pstRootNode, (char *)"layout");
+               if (NULL == pstLayoutList) {
+                       MSG_DEBUG(" There is no <layout> node. Can't create <region> node");
+                       return false;
+               }
+
+               /* Find the insertion point : right sibling of the last root-layout node or first child of pLayout */
+               pstRootLayoutList = MsgSmilGetNodeByElementName(__gpaMsgSmilDoc[nSmilDocNo]->pstRootNode, (char *)"root-layout");
+
+               if (NULL == pstRootLayoutList) {
+                       MSG_DEBUG("There is no <root-layout> node. Can't create <root-layout> node.");
+                       return false;
+               } else {
+                       pAttribute =  pstRootLayoutList->properties;
+               }
+
+               if (NULL == pAttribute) {
+                       MSG_DEBUG("There is no Attribute in <root-layout> node.");
+                       return false;
+               }
+
+               xmlAttrPtr pstAttr = pAttribute;
+               for ( ; pstAttr; pstAttr = pstAttr->next) {
+                       int     attrType;
+                       MSG_SEC_DEBUG("AttributeType: (%s, %s) ", pstAttr->name, pstAttr->children->content);
+                       switch (attrType = MsgSmilGetAttrID((char *)pstAttr->name)) {
+                       case ATTRIBUTE_WIDTH:
+                               {
+//                                     int bUnitPercent;
+
+//                                     if (strchr((char *)pstAttr->children->content, '%'))
+//                                             bUnitPercent = true;
+//                                     else
+//                                             bUnitPercent = false;
+
+                                       nRootWidth = atoi((char *)pstAttr->children->content);
+                               }
+                               break;
+
+                       case ATTRIBUTE_HEIGHT:
+                               {
+//                                     int bUnitPercent;
+
+//                                     if (strchr((char *)pstAttr->children->content, '%'))
+//                                             bUnitPercent = true;
+//                                     else
+//                                             bUnitPercent = false;
+
+                                       nRootHeight = atoi((char *)pstAttr->children->content);
+                               }
+                               break;
+                       }
+               }
+
+
+               /* Add attributes */
+               if (pstSmilRegion) {
+                       /* Create "region" node and insert it */
+                       pstRegion = xmlNewNode(NULL, (xmlChar *)"region");
+                       if (NULL == pstRegion) {
+                               MSG_DEBUG("Can't create <region> node. (from XmlParser)");
+                               return false;
+                       }
+
+                       MSG_SEC_DEBUG("Region Element Name = %s", (char *)pstRegion->name);
+
+                       if (strlen(pstSmilRegion->szID) > 0) {
+                               xmlSetProp(pstRegion, (const xmlChar *)"id", (const xmlChar *)pstSmilRegion->szID);
+                               MSG_DEBUG("[Set Attribute] : Region Id : [%s]", pstSmilRegion->szID);
+                       }
+
+                       if (pstSmilRegion->bBgColor == true) {
+                               MSG_DEBUG(" [Set Attribute] : BkGrd Color");
+                               if ( ( (pstSmilRegion->bgColor & 0xFF000000) >> 24 ) > 0) {
+                                       xmlSetProp(pstRegion, (const xmlChar *)"backgroundColor", (const xmlChar *)MsgSmilColorValueToString(pstSmilRegion->bgColor));
+                                       MSG_DEBUG("[Set Attribute] : backgroundColor [%s]", MsgSmilColorValueToString(pstSmilRegion->bgColor));
+                               }
+                       }
+
+
+                       if (true == pstSmilRegion->width.bUnitPercent) {
+                               if (pstSmilRegion->width.value > 0) {
+                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRegion->width.value);
+                                       xmlSetProp(pstRegion, (const xmlChar *)"width", (const xmlChar *)szBuf);
+                                       MSG_DEBUG("[Set Attribute] : Width : [%s]", szBuf);
+                               }
+                       } else {
+                               // Note: nRootWidth should be in terms of value(pixel) not unitpercent(%)
+                               // Validation should be done before this.
+                               if (pstSmilRegion->width.value >= 0 &&
+                                       pstSmilRegion->width.value <= nRootWidth &&
+                                       nRootWidth != 0) {
+                                       int iWidth = (pstSmilRegion->width.value * 100) / nRootWidth;
+
+                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", iWidth);
+                                       xmlSetProp(pstRegion, (const xmlChar *)"width", (const xmlChar *)szBuf);
+                                       MSG_DEBUG("[Set Attribute] : Width : [%s]", szBuf);
+                               }
+                       }
+
+                       if (true == pstSmilRegion->height.bUnitPercent) {
+                               if (pstSmilRegion->height.value > 0) {
+                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRegion->height.value);
+                                       xmlSetProp(pstRegion, (const xmlChar *)"height", (const xmlChar *)szBuf);
+                                       MSG_DEBUG("[Set Attribute] : Height : [%s]", szBuf);
+                               }
+                       } else {
+                               // Note: nRootHeight should be in terms of value(pixel) not unitpercent(%)
+                               // Validation should be done before this.
+                               if (pstSmilRegion->height.value >= 0 &&
+                                       pstSmilRegion->height.value <= nRootHeight &&
+                                       nRootHeight != 0) {
+                                       int iHeight = (pstSmilRegion->height.value * 100) / nRootHeight;
+
+                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", iHeight);
+                                       xmlSetProp(pstRegion, (const xmlChar *)"height", (const xmlChar *)szBuf);
+
+                                       MSG_DEBUG("[Set Attribute] : Height : [%s]", szBuf);
+                               }
+                       }
+
+                       if (true == pstSmilRegion->nLeft.bUnitPercent) {
+                               if (pstSmilRegion->nLeft.value > 0) {
+                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRegion->nLeft.value);
+                                       xmlSetProp(pstRegion, (const xmlChar *)"left", (const xmlChar *)szBuf);
+
+                                       MSG_DEBUG("[Set Attribute] : Left : [%s]", szBuf);
+                               }
+                       } else {
+                               // Note: nRootWidth should be in terms of value(pixel) not unitpercent(%)
+                               // Validation should be done before this.
+                               if (pstSmilRegion->nLeft.value >= 0 && nRootWidth != 0) {
+                                       int iLeft = (pstSmilRegion->nLeft.value * 100) / nRootWidth;
+
+                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", iLeft);
+                                       xmlSetProp(pstRegion, (const xmlChar *)"left", (const xmlChar *)szBuf);
+                                       MSG_DEBUG("[Set Attribute] : Left : [%s]", szBuf);
+                               }
+                       }
+
+                       if (true == pstSmilRegion->nTop.bUnitPercent) {
+                               if (pstSmilRegion->nTop.value > 0) {
+                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", pstSmilRegion->nTop.value);
+                                       xmlSetProp(pstRegion, (const xmlChar *)"top", (const xmlChar *)szBuf);
+                                       MSG_DEBUG("[Set Attribute] : Top : [%s]", szBuf);
+                               }
+                       } else {
+                               // Note: nRootHeight should be in terms of value(pixel) not unitpercent(%)
+                               // Validation should be done before this.
+                               if (pstSmilRegion->nTop.value >= 0 && nRootHeight != 0) {
+                                       int iTop = (pstSmilRegion->nTop.value * 100) / nRootHeight;
+
+                                       snprintf(szBuf, MSG_STDSTR_SHORT, "%d%%", iTop);
+                                       xmlSetProp(pstRegion, (const xmlChar *)"top", (const xmlChar *)szBuf);
+                                       MSG_DEBUG("[Set Attribute] : Top : [%s]", szBuf);
+                               }
+                       }
+
+                       //Fit Attribute
+                       if (MMSUI_IMAGE_REGION_FIT_MEET == pstSmilRegion->fit) {
+                               xmlSetProp(pstRegion, (const xmlChar *)"fit", (const xmlChar *)"meet");
+                               MSG_DEBUG("[Set Attribute] : fit : [meet]");
+                       } else if (MMSUI_IMAGE_REGION_FIT_HIDDEN == pstSmilRegion->fit) {
+                               xmlSetProp(pstRegion, (const xmlChar *)"fit", (const xmlChar *)"hidden");
+                               MSG_DEBUG("[Set Attribute] : fit : [hidden]");
+                       }
+
+                       MsgSmilInsertNode(pstLayoutList, pstRootLayoutList, pstRegion);
+
+               } else
+                       MSG_DEBUG("There is no attribute in <region> node");
+
+               MSG_END();
+               return true;
+       } else {
+               MSG_DEBUG("Invalid SmilDoc(hSmilDoc:%d)", nSmilDocNo);
+               return false;
+       }
+}
+
+bool MsgSmilAddMedia( HMsgSmil hSmilDoc, int nPageNo, int nMediaIdx, MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
+{
+       int nSmilDocNo = hSmilDoc;
+
+       MSG_BEGIN();
+
+       if (NULL == pszContentID) {
+               MSG_DEBUG(" Content Id is NULL");
+               return false;
+       }
+       memset(pszContentID, 0, sizeof(pstSmilMedia->szContentID));
+       if (IsValidSmilDocNo(nSmilDocNo)) {
+               int nIndex = 0;
+               xmlNode *pstMedia;
+               xmlNode *pstLastChild;
+               xmlNodePtr pstParList;
+               char *pszExt ;
+
+               pstParList = MsgSmilGetNodeByElementName(__gpaMsgSmilDoc[nSmilDocNo]->pstRootNode, (char *)"par");
+
+               if (NULL == pstParList) {
+                       MSG_DEBUG("There is no <par> node. Can't create <media> node.");
+                       return false;
+               }
+
+               for (nIndex = 0; (pstParList &&  nIndex < nPageNo); nIndex++) {
+                       pstParList = pstParList->next;
+               }
+
+               if (NULL == pstParList) {
+                       MSG_DEBUG("There is no such page node. Can't insert <media> node.");
+                       return false;
+               }
+
+               /* Find insertion point and make a contentID */
+               pstLastChild = xmlGetLastChild(pstParList);
+
+               pszExt = strrchr(pstSmilMedia->szFileName, '.');
+               if (pszExt && !strrchr(pszExt, '/'))
+                       snprintf(pszContentID, MSG_MSG_ID_LEN+1, "%lu_%lu%s", (unsigned long)nPageNo, (unsigned long)nMediaIdx, pszExt);
+               else
+                       snprintf(pszContentID, MSG_MSG_ID_LEN+1, "%lu_%lu", (unsigned long)nPageNo, (unsigned long)nMediaIdx);
+
+               snprintf(pstSmilMedia->szContentLocation, sizeof(pstSmilMedia->szContentLocation), "%s", pstSmilMedia->szFileName);
+
+               /* Create <media> node and insert set attribute */
+               switch (pstSmilMedia->mediatype) {
+               case MMS_SMIL_MEDIA_TEXT:
+                       pstMedia = MsgSmilCreateTextNode(pstSmilMedia, pszContentID);
+                       break;
+               case MMS_SMIL_MEDIA_AUDIO:
+               case MMS_SMIL_MEDIA_VIDEO:
+               case MMS_SMIL_MEDIA_IMG:
+                       pstMedia = MsgSmilCreateMMNode(pstSmilMedia, pszContentID);
+                       break;
+               default:
+                       MSG_DEBUG("Invalid media type. Can't insert such-<media> node.");
+                       return false;
+               }
+
+               if (NULL == pstMedia) {
+                       MSG_DEBUG("Can't create <media> node. (from XmlParser) (media-type:%d)", pstSmilMedia->mediatype);
+                       return false;
+               }
+
+               /* Find the insertion point : the last child of <par> node */
+               if (pstLastChild)
+                       MsgSmilInsertNode(pstParList, pstLastChild, pstMedia);
+               else
+                       MsgSmilInsertFirstChild(pstParList, pstMedia);
+
+               MSG_END();
+               return true;
+       } else {
+               MSG_DEBUG("Invalid SmilDoc(hSmilDoc:%d)", nSmilDocNo);
+               return false;
+       }
+}
+
+xmlNode *MsgSmilCreateTextNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
+{
+       xmlNode *pstMedia = NULL;
+       xmlNode *pstParam = NULL;
+       char szBuf[MSG_STDSTR_SHORT] = {0, };
+       char szSizeBuf[MSG_STDSTR_SHORT] = {0, };
+
+       MSG_BEGIN();
+
+       pstMedia = xmlNewNode(NULL, (xmlChar *)"text");
+       if (NULL == pstMedia) {
+               MSG_DEBUG("Can't create <Text> node.");
+               return NULL;
+       }
+
+       /* Add attributes */
+       if (pstSmilMedia) {
+
+               if (strlen(pstSmilMedia->regionId) > 0) {
+                       xmlSetProp(pstMedia, (const xmlChar *)"region", (const xmlChar *)pstSmilMedia->regionId);
+                       MSG_DEBUG("[Set Attribute] Region Id : [%s]", pstSmilMedia->regionId);
+               }
+
+               if (pstSmilMedia->sMedia.sText.nBegin > 0) {
+                       snprintf (szBuf, sizeof(szBuf), "%dms", pstSmilMedia->sMedia.sText.nBegin);
+                       xmlSetProp(pstMedia, (const xmlChar *)"begin", (const xmlChar *) szBuf);
+                       MSG_DEBUG("[Set Attribute] Begin : [%s]", szBuf);
+               }
+
+               if (pstSmilMedia->sMedia.sText.nDurTime > 0) {
+                       snprintf (szBuf, sizeof(szBuf), "%dms", pstSmilMedia->sMedia.sText.nDurTime);
+                       xmlSetProp(pstMedia, (const xmlChar *)"dur", (const xmlChar *)szBuf);
+                       MSG_DEBUG("[Set Attribute] Duration : [%s]", szBuf);
+               }
+
+               if (strlen(pstSmilMedia->szAlt) > 0) {
+                       snprintf (szBuf, sizeof(szBuf), "%s", pstSmilMedia->szAlt);
+                       xmlSetProp(pstMedia, (const xmlChar *)"alt", (const xmlChar *)szBuf);
+                       MSG_DEBUG("[Set Attribute] Alternate : [%s]", szBuf);
+               }
+
+#if 0
+               char szFilePathWithCid[MSG_MSG_ID_LEN + 5];     // for "cid:"
+
+               snprintf (szFilePathWithCid, sizeof(szFilePathWithCid), "cid:%s", pszContentID);
+               MsgSmilSetAttribute(pstMedia, (char *)"src", szFilePathWithCid);
+#endif
+               if (strlen(pstSmilMedia->szContentLocation) > 0) {
+                       MsgSmilSetAttribute(pstMedia, (char *)"src", pstSmilMedia->szContentLocation); //using content Location in Smil
+                       MSG_DEBUG("[Set Attribute] Src : [%s]", pstSmilMedia->szContentLocation);
+               }
+
+               if ( ( (pstSmilMedia->sMedia.sText.nColor & 0xFF000000) >> 24 ) > 0) {
+                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
+
+                       if (NULL == pstParam) {
+                               MSG_DEBUG("Cannot create <param> node");
+                               return false;
+                       }
+
+                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"foreground-color");
+                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)MsgSmilColorValueToString(pstSmilMedia->sMedia.sText.nColor));
+
+                       MSG_DEBUG("[Set param] Font Foreground Color : [0x%08x]", pstSmilMedia->sMedia.sText.nColor);
+
+                       MsgSmilInsertFirstChild(pstMedia, pstParam);
+               }
+
+               if ( ( (pstSmilMedia->sMedia.sText.nBgColor & 0xFF000000) >> 24 ) > 0) {
+                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
+
+                       if (NULL == pstParam) {
+                               MSG_DEBUG("Cannot create <param> node");
+                               return false;
+                       }
+
+                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"background-color");
+                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)MsgSmilColorValueToString(pstSmilMedia->sMedia.sText.nBgColor));
+
+                       MSG_DEBUG("[Set param] Font Background Color : [0x%08x]", pstSmilMedia->sMedia.sText.nBgColor);
+
+                       MsgSmilInsertFirstChild(pstMedia, pstParam);
+               }
+
+               if (pstSmilMedia->sMedia.sText.nSize > 0) {
+                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
+                       if (NULL == pstParam) {
+                               MSG_DEBUG(" __MmsCreateTextNode: cannot create <param> node");
+                               return false;
+                       }
+
+                       if (pstSmilMedia->sMedia.sText.nSize  <= MMS_SMIL_FONT_SIZE_SMALL) {
+                               snprintf(szSizeBuf, sizeof(szSizeBuf), "%s", "small");
+                       } else if ((pstSmilMedia->sMedia.sText.nSize  > MMS_SMIL_FONT_SIZE_SMALL) && (pstSmilMedia->sMedia.sText.nSize  < MMS_SMIL_FONT_SIZE_LARGE)) {
+                               snprintf(szSizeBuf, sizeof(szSizeBuf), "%s", "normal");
+                       } else {
+                               snprintf(szSizeBuf, sizeof(szSizeBuf), "%s", "large");
+                       }
+
+                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"textsize");
+                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)szSizeBuf);
+
+                       MSG_DEBUG("[Set param] textsize : [%s]", szSizeBuf);
+
+                       MsgSmilInsertFirstChild(pstMedia, pstParam);
+               }
+
+               if (pstSmilMedia->sMedia.sText.bBold == true) {
+                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
+                       if (NULL == pstParam) {
+                               MSG_DEBUG(" __MmsCreateTextNode: cannot create <param> node");
+                               return false;
+                       }
+
+                       snprintf(szSizeBuf, sizeof(szSizeBuf), "%s", "bold");
+
+                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"textattribute");
+                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)szSizeBuf);
+
+                       MSG_DEBUG("[Set param] textattribute : [%s]", szSizeBuf);
+
+                       MsgSmilInsertFirstChild(pstMedia, pstParam);
+               }
+
+               if (pstSmilMedia->sMedia.sText.bItalic == true) {
+                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
+                       if (NULL == pstParam) {
+                               MSG_DEBUG(" __MmsCreateTextNode: cannot create <param> node");
+                               return false;
+                       }
+
+                       snprintf(szSizeBuf, sizeof(szSizeBuf), "%s", "italic");
+
+                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"textattribute");
+                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)szSizeBuf);
+
+                       MSG_DEBUG("[Set param] textattribute : [%s]", szSizeBuf);
+
+                       MsgSmilInsertFirstChild(pstMedia, pstParam);
+               }
+
+               if (pstSmilMedia->sMedia.sText.bUnderLine == true) {
+                       pstParam = xmlNewNode(NULL, (xmlChar *)"param");
+                       if (NULL == pstParam) {
+                               MSG_DEBUG(" __MmsCreateTextNode: cannot create <param> node");
+                               return false;
+                       }
+
+                       snprintf(szSizeBuf, sizeof(szSizeBuf), "%s", "underline");
+
+                       xmlSetProp(pstParam, (const xmlChar *)"name", (const xmlChar *)"textattribute");
+                       xmlSetProp(pstParam, (const xmlChar *)"value", (const xmlChar *)szSizeBuf);
+
+                       MSG_DEBUG("[Set param] textattribute : [%s]", szSizeBuf);
+
+                       MsgSmilInsertFirstChild(pstMedia, pstParam);
+               }
+       }
+
+       MSG_END();
+       return pstMedia;
+}
+
+xmlNode *MsgSmilCreateMMNode(MMS_MEDIA_S *pstSmilMedia, char *pszContentID)
+{
+       xmlNode *pstMedia = NULL;
+       char szBuf[MSG_STDSTR_SHORT] = {0, };
+
+       MSG_BEGIN();
+
+       if (!pstSmilMedia)
+               return NULL;
+
+       switch (pstSmilMedia->mediatype) {
+       case MMS_SMIL_MEDIA_AUDIO:
+               pstMedia = xmlNewNode(NULL, (xmlChar *)"audio");
+               break;
+
+       case MMS_SMIL_MEDIA_VIDEO:
+               pstMedia = xmlNewNode(NULL, (xmlChar *)"video");
+               break;
+
+       case MMS_SMIL_MEDIA_IMG:
+               pstMedia = xmlNewNode(NULL, (xmlChar *)"img");
+               break;
+       default:
+               MSG_DEBUG("Invalid media type. Can't insert such-<media> node.");
+               return NULL;
+       }
+
+       if (pstMedia) {
+
+               if (strlen(pstSmilMedia->regionId) > 0) {
+                       xmlSetProp(pstMedia, (const xmlChar *)"region", (const xmlChar *)pstSmilMedia->regionId);
+                       MSG_DEBUG("[Set Attribute] Region Id : [%s]", pstSmilMedia->regionId);
+               }
+
+#if 0 //set src attribute cid
+               char szFilePathWithCid[MSG_MSG_ID_LEN + 5];     // for "cid:"
+               snprintf (szFilePathWithCid, sizeof(szFilePathWithCid), "cid:%s", pszContentID);
+               MsgSmilSetAttribute(pstMedia, (char *)"src", szFilePathWithCid);
+#endif
+               if (strlen(pstSmilMedia->szContentLocation) > 0) {
+                       MsgSmilSetAttribute(pstMedia, (char *)"src", pstSmilMedia->szContentLocation); //using content Location in Smil
+                       MSG_DEBUG("[Set Attribute] src : [%s]", pstSmilMedia->szContentLocation);
+               }
+
+               if (pstSmilMedia->sMedia.sAVI.nBegin > 0) {
+                       snprintf (szBuf, sizeof(szBuf), "%dms", pstSmilMedia->sMedia.sAVI.nBegin);
+                       xmlSetProp(pstMedia, (const xmlChar *)"begin", (const xmlChar *)szBuf);
+                       MSG_DEBUG("[Set Attribute] begin : [%s]", szBuf);
+               }
+
+               if (pstSmilMedia->sMedia.sAVI.nDurTime > 0) {
+                       snprintf (szBuf, sizeof(szBuf), "%dms", pstSmilMedia->sMedia.sAVI.nDurTime);
+                       xmlSetProp(pstMedia, (const xmlChar *)"dur", (const xmlChar *)szBuf);
+                       MSG_DEBUG("[Set Attribute] dur : [%s]", szBuf);
+               }
+
+               if (strlen(pstSmilMedia->szAlt) > 0) {
+                       snprintf (szBuf, sizeof(szBuf), "%s", pstSmilMedia->szAlt);
+                       xmlSetProp(pstMedia, (const xmlChar *)"alt", (const xmlChar *)szBuf);
+                       MSG_DEBUG("[Set Attribute] alt : [%s]", szBuf);
+               }
+       } else {
+               MSG_DEBUG("There is no attribute in such-<media> node");
+       }
+
+       MSG_END();
+       return pstMedia;
+}
+
+bool MsgSmilInsertFirstChild(xmlNode *pstParent, xmlNode *pstCurr)
+{
+       bool bFlag = true;
+
+       MSG_BEGIN();
+
+        if (NULL == xmlAddChild(pstParent, pstCurr)) {
+                MSG_SEC_DEBUG("%s Node not added", pstCurr->name);
+               bFlag = false;
+        }
+
+        MSG_END();
+        return bFlag;
+}
+
+bool MsgSmilInsertNode(xmlNode *pstParent, xmlNode *pstLeftSibling, xmlNode *pstCurr)
+{
+       MSG_BEGIN();
+       bool bFlag = true;
+
+       if (pstLeftSibling) {
+               /* Parent Node is Unused */
+
+               while (pstLeftSibling->next !=NULL)
+                       pstLeftSibling = pstLeftSibling->next;
+
+                if (NULL == xmlAddNextSibling(pstLeftSibling, pstCurr)) {
+                        MSG_SEC_DEBUG("%s Node not added", pstCurr->name);
+                       bFlag = false;
+                }
+       } else {
+                if (NULL == xmlAddChild(pstParent, pstCurr)) {
+                        MSG_SEC_DEBUG("%s Node not added", pstCurr->name);
+                       bFlag = false;
+                }
+       }
+       MSG_END();
+       return bFlag;
+}
+
+void MsgSmilSetAttribute(xmlNode *pNode, char *szField, char *szValue)
+{
+       MSG_BEGIN();
+
+       if (pNode && szField && strlen(szField)) {
+               if (szValue && strlen(szValue)) {
+                       xmlSetProp(pNode, (const xmlChar *)szField, (const xmlChar *)szValue);
+               } else {
+                       xmlSetProp(pNode, (const xmlChar *)szField, (const xmlChar *)"");
+               }
+       }
+
+       MSG_END();
+}
+
+xmlNodePtr MsgSmilGetNodeByElementName(xmlNodePtr pstNode, char *pszName)
+{
+
+       if ((NULL != pstNode) && (NULL != pszName)) {
+               xmlNodePtr pstTempNode;
+               xmlNodePtr pstReturnNode;
+
+               pstTempNode = pstNode;
+
+               for ( ; pstTempNode; pstTempNode = pstTempNode->next) {
+
+                       if (0 == strcasecmp((char *)pstTempNode->name, pszName)) {
+                               MSG_SEC_DEBUG("Find Node : name [%s][%p]", (char *)pstTempNode->name, pstTempNode);
+                               return pstTempNode;
+                       }
+
+                       if (pstTempNode->children) {
+                               pstReturnNode = MsgSmilGetNodeByElementName(pstTempNode->children, pszName);
+                               if (NULL != pstReturnNode) {
+                                       return pstReturnNode;
+                               }
+                       }
+
+               }
+       }
+       return NULL;
+}
+
+void MsgSmilParseNode(MMS_MESSAGE_DATA_S *pMmsMsg, xmlNode *a_node, int depth)
+{
+       MSG_BEGIN();
+
+       int elementType;
+       int attrType;
+
+       xmlNode *cur_node = NULL;
+
+       if (depth == 0) {//init
+               memset(gCmd, 0x00, ELEMENT_MAX);
+               memset(&gRootlayout, 0x00, sizeof(MMS_SMIL_ROOTLAYOUT));
+               gRegion = NULL;
+               gPage = NULL;
+               gMedia = NULL;
+               gTransition = NULL;
+               gMeta = NULL;
+       }
+
+       for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
+               MSG_SEC_DEBUG("## [%d] node type : [Element], name: [%s] ##", depth, cur_node->name);
+
+               if (cur_node->type == XML_ELEMENT_NODE) {
+                       // Get Smil Element =====================================================
+
+                       switch (elementType = MsgSmilGetElementID((char *)cur_node->name)) {
+                       case ELEMENT_ROOTLAYOUT:
+                               gCmd[ELEMENT_ROOTLAYOUT] = true;
+                               break;
+
+                       case ELEMENT_REGION:
+                               if (gRegion) {
+                                       MSG_DEBUG("region exist");
+                                       return;
+                               }
+
+                               gRegion = (MMS_SMIL_REGION *)calloc(1, sizeof(MMS_SMIL_REGION));
+                               gCmd[ELEMENT_REGION] = true;
+                               break;
+
+                       case ELEMENT_TRANSITION:
+                               if (gTransition) {
+                                       MSG_DEBUG("Transition exist");
+                                       return;
+                               }
+
+                               gTransition = (MMS_SMIL_TRANSITION *)calloc(1, sizeof(MMS_SMIL_TRANSITION));
+                               gCmd[ELEMENT_TRANSITION] = true;
+                               break;
+
+                       case ELEMENT_META:
+                               if (gMeta) {
+                                       MSG_DEBUG("Meta exist");
+                                       return;
+                               }
+
+                               gMeta = (MMS_SMIL_META *)calloc(1, sizeof(MMS_SMIL_META));
+                               gCmd[ELEMENT_META] = true;
+                               break;
+
+                       case ELEMENT_PAR:
+                               if (gPage) {
+                                       MSG_DEBUG("Page exist");
+                                       return;
+                               }
+
+                               gPage = (MMS_PAGE_S *)calloc(1, sizeof(MMS_PAGE_S));
+                               gCmd[ELEMENT_PAR] = true;
+                               break;
+
+                       case ELEMENT_PARAM: // Need to check the original element type
+                               gCmd[ELEMENT_PARAM] = true;
+                               break;
+
+                       case ELEMENT_TEXT:
+                               if (gMedia) {
+                                       MSG_DEBUG("Media exist");
+                                       return;
+                               }
+
+                               gMedia = (MMS_MEDIA_S *)calloc(1, sizeof(MMS_MEDIA_S));
+                               gMedia->mediatype = MMS_SMIL_MEDIA_TEXT;
+                               gCmd[ELEMENT_TEXT] = true;
+                               break;
+
+                       case ELEMENT_IMG:
+                               if (gMedia) {
+                                       MSG_DEBUG("Media exist");
+                                       return;
+                               }
+
+                               gMedia = (MMS_MEDIA_S *)calloc(1, sizeof(MMS_MEDIA_S));
+                               gMedia->mediatype = MMS_SMIL_MEDIA_IMG;
+                               gCmd[ELEMENT_IMG] = true;
+                               break;
+
+                       case ELEMENT_AUDIO:
+                               if (gMedia) {
+                                       MSG_DEBUG("Media exist");
+                                       return;
+                               }
+
+                               gMedia = (MMS_MEDIA_S *)calloc(1, sizeof(MMS_MEDIA_S));
+                               gMedia->mediatype = MMS_SMIL_MEDIA_AUDIO;
+                               gCmd[ELEMENT_AUDIO] = true;
+                               break;
+
+                       case ELEMENT_VIDEO:
+                               if (gMedia) {
+                                       MSG_DEBUG("Media exist");
+                                       return;
+                               }
+
+                               gMedia = (MMS_MEDIA_S *)calloc(1, sizeof(MMS_MEDIA_S));
+                               gMedia->mediatype = MMS_SMIL_MEDIA_VIDEO;
+                               gCmd[ELEMENT_VIDEO] = true;
+                               break;
+
+                       case ELEMENT_REF:
+                               if (gMedia) {
+                                       MSG_DEBUG("Media exist");
+                                       return;
+                               }
+
+                               gMedia = (MMS_MEDIA_S *)calloc(1, sizeof(MMS_MEDIA_S));
+                               gMedia->mediatype = MMS_SMIL_MEDIA_IMG_OR_VIDEO;
+                               gCmd[ELEMENT_REF] = true;
+                               break;
+
+                       case ELEMENT_ANIMATE:
+                               if (gMedia) {
+                                       MSG_DEBUG("Media exist");
+                                       return;
+                               }
+
+                               gMedia = (MMS_MEDIA_S *)calloc(1, sizeof(MMS_MEDIA_S));
+                               gMedia->mediatype = MMS_SMIL_MEDIA_ANIMATE;
+                               gCmd[ELEMENT_ANIMATE] = true;
+                               break;
+
+                       default:
+                               MSG_DEBUG("Unsupported element type [%d]", elementType);
+                               break;
+                       }
+
+                       //Get Smil Attribute =====================================================
+                       xmlAttr *pAttr = cur_node->properties;
+
+                       SMIL_ATTRIBUTE_T paramType = ATTRIBUTE_UNKNOWN;
+
+                       for ( ; pAttr; pAttr = pAttr->next) {
+
+                               MSG_SEC_DEBUG("## attribute type : name [%s] value [%s] ##", pAttr->name, pAttr->children->content);
+
+                               switch (attrType = MsgSmilGetAttrID((char *)pAttr->name)) {
+                               case ATTRIBUTE_ID:
+                                       {
+                                               if (gCmd[ELEMENT_REGION] && gRegion) {
+                                                       strncpy(gRegion->szID, (char *)pAttr->children->content, MAX_SMIL_REGION_ID - 1);
+                                               } else if (gCmd[ELEMENT_TRANSITION] && gTransition) {
+                                                       strncpy(gTransition->szID, (char *)pAttr->children->content, MAX_SMIL_TRANSITION_ID - 1);
+                                               } else if (gCmd[ELEMENT_META] && gMeta) {
+                                                       strncpy(gMeta->szID, (char *)pAttr->children->content, MAX_SMIL_META_ID - 1);
+                                               }
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_TOP:
+                                       {
+                                               int bUnitPercent;
+                                               int value;
+
+                                               if (strchr((char *)pAttr->children->content, '%'))
+                                                       bUnitPercent = true;
+                                               else
+                                                       bUnitPercent = false;
+
+                                               value = atoi((char *)pAttr->children->content);
+
+                                               if (gCmd[ELEMENT_REGION] && gRegion) {
+                                                       gRegion->nTop.bUnitPercent = bUnitPercent;
+                                                       gRegion->nTop.value = value;
+                                               }
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_LEFT:
+                                       {
+                                               int bUnitPercent;
+                                               int value;
+
+                                               if (strchr((char *)pAttr->children->content, '%'))
+                                                       bUnitPercent = true;
+                                               else
+                                                       bUnitPercent = false;
+
+                                               value = atoi((char *)pAttr->children->content);
+
+                                               if (gCmd[ELEMENT_REGION] && gRegion) {
+                                                       gRegion->nLeft.bUnitPercent = bUnitPercent;
+                                                       gRegion->nLeft.value = value;
+                                               }
+                                       }
+                                       break;
+
+
+                               case ATTRIBUTE_WIDTH:
+                                       {
+                                               int bUnitPercent;
+                                               int value;
+
+                                               if (strchr((char *)pAttr->children->content, '%'))
+                                                       bUnitPercent = true;
+                                               else
+                                                       bUnitPercent = false;
+
+                                               value = atoi((char *)pAttr->children->content);
+
+                                               if (gCmd[ELEMENT_ROOTLAYOUT]) {
+                                                       gRootlayout.width.bUnitPercent = bUnitPercent;
+                                                       gRootlayout.width.value = value;
+                                               } else if (gCmd[ELEMENT_REGION] && gRegion) {
+                                                       gRegion->width.bUnitPercent = bUnitPercent;
+                                                       gRegion->width.value = value;
+                                               }
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_HEIGHT:
+                                       {
+                                               int bUnitPercent;
+                                               int value;
+
+                                               if (strchr((char *)pAttr->children->content, '%'))
+                                                       bUnitPercent = true;
+                                               else
+                                                       bUnitPercent = false;
+
+                                               value = atoi((char *)pAttr->children->content);
+
+                                               if (gCmd[ELEMENT_ROOTLAYOUT]) {
+                                                       gRootlayout.height.bUnitPercent = bUnitPercent;
+                                                       gRootlayout.height.value = value;
+                                               } else if (gCmd[ELEMENT_REGION] && gRegion) {
+                                                       gRegion->height.bUnitPercent = bUnitPercent;
+                                                       gRegion->height.value = value;
+                                               }
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_FIT:
+                                       if (gCmd[ELEMENT_REGION] && gRegion) {
+                                               if (!strcmp((char *)pAttr->children->content, "meet")) {
+                                                       gRegion->fit = MMSUI_IMAGE_REGION_FIT_MEET;
+                                               } else {
+                                                       gRegion->fit = MMSUI_IMAGE_REGION_FIT_HIDDEN;
+                                               }
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_BGCOLOR:
+                                       if (gCmd[ELEMENT_ROOTLAYOUT]) {
+                                               gRootlayout.bBgColor = true;
+                                               gRootlayout.bgColor = MsgSmilGetColorValue(pAttr->children->content);
+                                       } else if (gCmd[ELEMENT_REGION] && gRegion) {
+                                               gRegion->bBgColor = true;
+                                               gRegion->bgColor = MsgSmilGetColorValue(pAttr->children->content);
+                                       } else if (gCmd[ELEMENT_TEXT] && gMedia) {
+                                               gMedia->sMedia.sText.nBgColor = MsgSmilGetColorValue(pAttr->children->content);
+                                       } else if (gMedia) {
+                                               gMedia->sMedia.sAVI.nBgColor = MsgSmilGetColorValue(pAttr->children->content);
+                                       }
+
+                                       break;
+
+                               case ATTRIBUTE_DUR:
+                                       if (gCmd[ELEMENT_PAR] && gPage) {
+                                               if (elementType == ELEMENT_PAR)
+                                                       gPage->nDur =  MsgSmilGetTime((char *)pAttr->children->content);
+                                       } else if (gCmd[ELEMENT_TRANSITION] && gTransition) {
+                                               gTransition->nDur =  MsgSmilGetTime((char *)pAttr->children->content);
+                                       } else if (gCmd[ELEMENT_TEXT] && gMedia) {
+                                               gMedia->sMedia.sText.nDurTime =  MsgSmilGetTime((char *)pAttr->children->content);
+                                       } else if (gMedia) {
+                                               gMedia->sMedia.sAVI.nDurTime =  MsgSmilGetTime((char *)pAttr->children->content);
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_SRC:
+                               {
+                                       if (gMedia) {
+                                               char szContentID[MSG_MSG_ID_LEN + 1] = {0,};
+                                               int cLen;
+
+                                               snprintf(szContentID, sizeof(szContentID), "%s", (char *)pAttr->children->content);
+
+                                               cLen = strlen(szContentID);
+                                               if (!strncasecmp(szContentID, "cid:", 4)) {
+                                                       strncpy(gMedia->szContentID, szContentID + 4, cLen - 4);
+                                                       gMedia->szContentID[cLen - 4] = '\0';
+                                               } else {
+                                                       strncpy(gMedia->szContentID, szContentID, cLen);
+                                                       gMedia->szContentID[cLen] = '\0';
+                                               }
+                                       }
+                                       break;
+                               }
+                               case ATTRIBUTE_COLOR:
+                                       if (gCmd[ELEMENT_TEXT] && gMedia)
+                                               gMedia->sMedia.sText.nColor = MsgSmilGetColorValue(pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_SIZE:
+                                       if (gCmd[ELEMENT_TEXT] && gMedia)
+                                               gMedia->sMedia.sText.nSize = atoi((char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_BOLD:
+                                       if (gCmd[ELEMENT_TEXT] && gMedia) {
+                                               gMedia->sMedia.sText.bBold = MsgSmilGetFontAttrib((char *)pAttr->children->content);
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_UNDERLINE:
+                                       if (gCmd[ELEMENT_TEXT] && gMedia)
+                                               gMedia->sMedia.sText.bUnderLine = MsgSmilGetFontAttrib((char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_ITALIC:
+                                       if (gCmd[ELEMENT_TEXT] && gMedia)
+                                               gMedia->sMedia.sText.bItalic = MsgSmilGetFontAttrib((char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_REVERSE:
+                                       if (gCmd[ELEMENT_TEXT] && gMedia)
+                                               gMedia->sMedia.sText.bReverse = MsgSmilGetFontAttrib((char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_DIRECTION:
+                                       if (gCmd[ELEMENT_TEXT] && gMedia)
+                                               gMedia->sMedia.sText.nDirection = MsgSmilGetFontDirection((char *)pAttr->children->content);
+                                       break;
+                               case ATTRIBUTE_REGION:
+                                       if (gMedia) {
+                                               strncpy(gMedia->regionId, (char *)pAttr->children->content, MAX_SMIL_REGION_ID - 1);
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_TRANSIN:
+                                       if (gMedia) {
+                                               if (gCmd[ELEMENT_TEXT] )
+                                                       strncpy(gMedia->sMedia.sText.szTransInId, (char *)pAttr->children->content, MAX_SMIL_TRANSIN_ID - 1);
+                                               else
+                                                       strncpy(gMedia->sMedia.sAVI.szTransInId, (char *)pAttr->children->content, MAX_SMIL_TRANSIN_ID - 1);
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_TRANSOUT:
+                                       if (gMedia) {
+                                               if (gCmd[ELEMENT_TEXT])
+                                                       strncpy(gMedia->sMedia.sText.szTransOutId, (char *)pAttr->children->content, MAX_SMIL_TRANSOUT_ID - 1);
+                                               else
+                                                       strncpy(gMedia->sMedia.sAVI.szTransOutId, (char *)pAttr->children->content, MAX_SMIL_TRANSOUT_ID - 1);
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_BEGIN:
+                                       if (gMedia) {
+                                               if (gCmd[ELEMENT_TEXT])
+                                                       gMedia->sMedia.sText.nBegin = MsgSmilGetTime((char *)pAttr->children->content);
+                                               else
+                                                       gMedia->sMedia.sAVI.nBegin = MsgSmilGetTime((char *)pAttr->children->content);
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_END:
+                                       if (gMedia) {
+                                               if (gCmd[ELEMENT_TEXT])
+                                                       gMedia->sMedia.sText.nEnd = MsgSmilGetTime((char *)pAttr->children->content);
+                                               else
+                                                       gMedia->sMedia.sAVI.nEnd = MsgSmilGetTime((char *)pAttr->children->content);
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_REPEAT_COUNT:
+                                       if (gMedia) {
+                                               if (gCmd[ELEMENT_TEXT])
+                                                       gMedia->sMedia.sText.nRepeat = atoi((char *)pAttr->children->content);
+                                               else
+                                                       gMedia->sMedia.sAVI.nRepeat = atoi((char *)pAttr->children->content);
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_NAME:
+                                       if (gCmd[ELEMENT_PARAM]) {
+
+                                               if (!strcmp((char *)pAttr->children->content, "foreground-color") || !strcmp((char *)pAttr->children->content, "foregroundcolor"))
+                                                       paramType = ATTRIBUTE_FGCOLOR;
+                                               else if (!strcmp((char *)pAttr->children->content, "background-color") || !strcmp((char *)pAttr->children->content, "backgroundcolor"))
+                                                       paramType = ATTRIBUTE_BGCOLOR;
+                                               else if (!strcmp((char *)pAttr->children->content, "textsize"))
+                                                       paramType = ATTRIBUTE_SIZE;
+                                               else if (!strcmp((char *)pAttr->children->content, "textattribute"))
+                                                       paramType = ATTRIBUTE_TEXTFORMAT;
+
+                                       } else if (gCmd[ELEMENT_META] && gMeta) {
+                                               strncpy(gMeta->szName, (char *)pAttr->children->content, MAX_SMIL_META_NAME - 1);
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_VALUE:
+
+                                       if (paramType == ATTRIBUTE_SIZE && gCmd[ELEMENT_TEXT] && gMedia)
+                                               gMedia->sMedia.sText.nSize = MsgSmilGetFontSizeValue((char *)pAttr->children->content);
+                                       else if (paramType == ATTRIBUTE_FGCOLOR && gCmd[ELEMENT_TEXT] && gMedia)
+                                               gMedia->sMedia.sText.nColor =  MsgSmilGetColorValue(pAttr->children->content);
+                                       else if (paramType == ATTRIBUTE_BGCOLOR && gCmd[ELEMENT_TEXT] && gMedia)
+                                               gMedia->sMedia.sText.nBgColor =  MsgSmilGetColorValue(pAttr->children->content);
+                                       else if (paramType == ATTRIBUTE_TEXTFORMAT && gCmd[ELEMENT_TEXT] && gMedia) {
+                                               MmsSmilFontType fontType;
+
+                                               fontType = MsgSmilGetFontTypeValue((char *)pAttr->children->content);
+
+                                               if (fontType == MMS_SMIL_FONT_TYPE_BOLD)
+                                                       gMedia->sMedia.sText.bBold = true;
+                                               else
+                                                       gMedia->sMedia.sText.bBold = false;
+
+                                               if (fontType == MMS_SMIL_FONT_TYPE_ITALIC)
+                                                       gMedia->sMedia.sText.bItalic = true;
+                                               else
+                                                       gMedia->sMedia.sText.bItalic = false;
+
+                                               if (fontType == MMS_SMIL_FONT_TYPE_UNDERLINE)
+                                                       gMedia->sMedia.sText.bUnderLine = true;
+                                               else
+                                                       gMedia->sMedia.sText.bUnderLine = false;
+                                       }
+                                       paramType = ATTRIBUTE_UNKNOWN;
+                                       break;
+
+                               case ATTRIBUTE_ALT:
+                                       if (gMedia) {
+                                               strncpy(gMedia->szAlt, (char *)pAttr->children->content, MAX_SMIL_ALT_LEN - 1);
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_TYPE:
+                                       if (gTransition) {
+                                               gTransition->nType = (MmsSmilTransType)atoi((char *)pAttr->children->content);
+
+                                               switch (gTransition->nType) {
+                                               case MMS_SMIL_TRANS_SLIDEWIPE:
+                                                       gTransition->nSubType = MMS_SMIL_TRANS_SUB_FROM_LEFT;
+                                                       break;
+                                               case MMS_SMIL_TRANS_BARWIPE:
+                                                       gTransition->nSubType = MMS_SMIL_TRANS_SUB_TOP_TO_BOTTOM;
+                                                       break;
+                                               case MMS_SMIL_TRANS_BARNDOORWIPE:
+                                                       gTransition->nSubType = MMS_SMIL_TRANS_SUB_HORIZONTAL;
+                                                       break;
+                                               default:
+                                                       gTransition->nSubType = MMS_SMIL_TRANS_SUB_NONE;
+                                                       break;
+                                               }
+                                       }
+                                       break;
+
+                               case ATTRIBUTE_SUBTYPE:
+                                       if (gTransition)
+                                               gTransition->nSubType = (MmsSmilTransSubType)atoi((char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_CONTENT:
+                                       if (gMeta)
+                                               strncpy(gMeta->szContent, (char *)pAttr->children->content, MAX_SMIL_META_CONTENT - 1);
+                                       break;
+
+                               default:
+                                       MSG_DEBUG("Undefined Attribute was found!!!!!");
+                                       break;
+                               }
+                       }
+
+                       if (cur_node->children) {//child first
+                               MsgSmilParseNode(pMmsMsg, cur_node->children, depth + 1);
+                       }
+
+                       if (elementType == ELEMENT_REGION && gRegion) {
+                               _MsgMmsAddRegion(pMmsMsg, gRegion);
+                               gRegion = NULL;
+                       } else if (elementType ==  ELEMENT_PAR && gPage) {
+                               _MsgMmsAddPage(pMmsMsg, gPage);
+                               gPage = NULL;
+                       } else if ((elementType == ELEMENT_TEXT || elementType == ELEMENT_IMG || elementType == ELEMENT_AUDIO || elementType == ELEMENT_VIDEO || elementType == ELEMENT_ANIMATE || elementType == ELEMENT_REF)
+                                       && gCmd[ELEMENT_PAR] && gPage && gMedia) {
+                               _MsgMmsAddMedia(gPage, gMedia);
+                               gMedia = NULL;
+                       } else if (elementType == ELEMENT_ROOTLAYOUT) {
+                               _MsgMmsSetRootLayout(pMmsMsg, &gRootlayout);
+                       } else if (elementType == ELEMENT_TRANSITION  && gTransition) {
+                               _MsgMmsAddTransition(pMmsMsg, gTransition);
+                               gTransition = NULL;
+                       } else if (elementType == ELEMENT_META && gMeta) {
+                               _MsgMmsAddMeta(pMmsMsg, gMeta);
+                               gMeta = NULL;
+                       }
+
+                       if (elementType >= ELEMENT_SMIL)
+                               gCmd[elementType] = false;
+
+                       paramType = ATTRIBUTE_UNKNOWN;
+               }
+       }
+
+       MSG_END();
+}
+
+bool MsgSmilParseSmilDoc(MMS_MESSAGE_DATA_S *pstMsgMmsBody, const char *pSmilDoc)
+{
+       MSG_BEGIN();
+
+       xmlDocPtr doc;
+       xmlNodePtr cur;
+
+       if (pSmilDoc == NULL || strlen(pSmilDoc) == 0) {
+               MSG_DEBUG("Invalid Parameter : pSmilDoc [%p]", pSmilDoc);
+               return false;
+       }
+
+       MSG_SEC_INFO("Parse Smil : [%s]", pSmilDoc);
+
+       doc = xmlParseMemory(pSmilDoc, strlen(pSmilDoc));
+       if (doc == NULL) {
+               MSG_DEBUG("Failed xmlParseMemory");
+               return false;
+       }
+
+       cur = xmlDocGetRootElement(doc);
+       if (cur == NULL) {
+               MSG_DEBUG("Failed xmlDocGetRootElement");
+               xmlFreeDoc(doc);
+               return false;
+       }
+
+       if (xmlStrcmp(cur->name, (const xmlChar *) "smil")) {
+               MSG_DEBUG("document of the wrong type, root node != smil");
+               xmlFreeDoc(doc);
+               return false;
+       }
+
+       MsgSmilParseNode(pstMsgMmsBody, cur, 0);
+
+       xmlFreeDoc(doc);
+       MSG_END();
+       return true;
+}
+
+bool MsgSmilGenerateSmilDoc(MMS_MESSAGE_DATA_S *pstMsgMmsBody, char **ppSmilDoc)
+{
+       MSG_BEGIN();
+
+       HMsgSmil hSmilDoc = INVALID_HOBJ;
+       int nIndex;
+       int nMediaIndex;
+       int nTotalPageNum;
+       int nTotalMediaNum;
+       int nRegionCount;
+       MMS_PAGE_S *pstPage;
+       MMS_MEDIA_S *pstMedia;
+       MMS_SMIL_REGION *pstRegion;
+       char *pszRawData;
+
+       hSmilDoc = MsgSmilCreateEmptySmilDoc();
+       if (INVALID_HOBJ == hSmilDoc) {
+               MSG_DEBUG("Invalid SmilDoc[%d]",hSmilDoc);
+               return false;
+       }
+       // Add Root Layout to Smil Document
+       if (false == MsgSmilAddRootLayout(hSmilDoc, &(pstMsgMmsBody->rootlayout))) {
+               MSG_DEBUG("MsgSmilAddRootLayout Failed");
+               MsgSmilDestroyDoc(hSmilDoc);
+       }
+       //Add Region list to Smil Document
+       nRegionCount = pstMsgMmsBody->regionCnt;
+       MSG_DEBUG(" Region Count = [%d]",nRegionCount);
+       for (nIndex = 0; nIndex < nRegionCount; nIndex++) {
+
+               pstRegion = _MsgMmsGetSmilRegion(pstMsgMmsBody, nIndex);
+               if (NULL == pstRegion) {
+                       MSG_DEBUG("pstRegion is NULL");
+                       MsgSmilDestroyDoc(hSmilDoc);
+                       return false;
+               }
+
+               if (false == MsgSmilAddRegion(hSmilDoc, pstRegion)) {
+                       MSG_DEBUG("Adding Region to smil doc failed");
+                       MsgSmilDestroyDoc(hSmilDoc);
+                       return false;
+               }
+       }
+
+       // Add page list to Smil Document
+       nTotalPageNum = pstMsgMmsBody->pageCnt ;
+       MSG_DEBUG(" Page Count = [%d]",nTotalPageNum);
+       for (nIndex = 0; nIndex < nTotalPageNum; nIndex++) {
+
+               pstPage = _MsgMmsGetPage(pstMsgMmsBody, nIndex);
+               if (NULL == pstPage) {
+                       MSG_DEBUG("pstPage is NULL");
+                       MsgSmilDestroyDoc(hSmilDoc);
+                       return false;
+               }
+
+               // Add page to smil doc
+               if (false == MsgSmilAddPage(hSmilDoc, pstPage)) {
+                       MSG_DEBUG("Adding page to smil doc failed");
+                       MsgSmilDestroyDoc(hSmilDoc);
+                       return false;
+               }
+
+               nTotalMediaNum = pstPage->mediaCnt;
+               MSG_DEBUG(" Media Count = [%d]",nTotalMediaNum);
+               for (nMediaIndex = 0; nMediaIndex < nTotalMediaNum; nMediaIndex++) {
+
+                       pstMedia = _MsgMmsGetMedia(pstPage, nMediaIndex);
+                       if (NULL == pstMedia) {
+                               MSG_DEBUG("pMedia is NULL");
+                               MsgSmilDestroyDoc(hSmilDoc);
+                               return false;
+                       }
+
+                       if (false == MsgSmilAddMedia(hSmilDoc, nIndex, nMediaIndex, pstMedia, pstMedia->szContentID)) {
+                               MSG_DEBUG("MsgSmilAddMedia failed");
+                               MsgSmilDestroyDoc(hSmilDoc);
+                               return false;
+                       }
+               }
+       }
+
+       pszRawData = MsgSmilGetRawData(hSmilDoc);
+       if (NULL == pszRawData) {
+               MSG_DEBUG("MsgSmilGetRawData failed");
+               MsgSmilDestroyDoc(hSmilDoc);
+               return false;
+       }
+
+       if (ppSmilDoc) {
+               *ppSmilDoc = pszRawData;
+               MSG_SEC_INFO("Generated Smil : [%s]", pszRawData);
+       }
+
+       MsgSmilDestroyDoc(hSmilDoc);
+       MSG_END();
+       return true;
+}
diff --git a/utils/MsgSoundPlayer.cpp b/utils/MsgSoundPlayer.cpp
deleted file mode 100755 (executable)
index 15fd2f0..0000000
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include <wait.h>
-
-#include "MsgHelper.h"
-#include "MsgDebug.h"
-#include "MsgGconfWrapper.h"
-#include "MsgSettingTypes.h"
-#include "MsgSoundPlayer.h"
-
-#include <alarm.h>
-
-/*==================================================================================================
-                                     VARIABLES
-==================================================================================================*/
-static bool g_bRepeat = false;
-static alarm_id_t g_alarmId = 0;
-
-
-/*==================================================================================================
-                                     FUNCTION IMPLEMENTATION
-==================================================================================================*/
-
-
-void MsgSoundPlayStart()
-{
-       MSG_BEGIN();
-
-       // Run helper App
-       pid_t childpid;
-       childpid = fork();
-
-       if (childpid == -1)
-       {
-               MSG_DEBUG("Failed to fork");
-       }
-
-       if (childpid == 0)
-       {
-               MSG_DEBUG("Child Process - Run helper app for Sound");
-
-               execl("/usr/bin/msg-helper", MSG_SOUND_START, NULL);
-
-               MSG_DEBUG("Faild to run helper app for Sound");
-
-               exit(0);
-       }
-       else if (childpid != 0)
-       {
-               MSG_DEBUG("Parent Process - Mms Plugin Storage.");
-       }
-
-       if (g_bRepeat == false)
-               g_bRepeat = MsgSoundSetRepeatAlarm();
-
-       MSG_END();
-}
-
-void MsgSoundPlayStop()
-{
-       MSG_BEGIN();
-
-       // Run helper App
-       pid_t childpid;
-       childpid = fork();
-
-       if (childpid == -1)
-       {
-               MSG_DEBUG("Failed to fork");
-       }
-
-       if (childpid == 0)
-       {
-               MSG_DEBUG("Child Process - Run helper app for Sound");
-
-               execl("/usr/bin/msg-helper", MSG_SOUND_STOP, NULL);
-
-               MSG_DEBUG("Faild to run helper app for Sound");
-
-               exit(0);
-       }
-       else if (childpid != 0)
-       {
-               MSG_DEBUG("Parent Process - Mms Plugin Storage.");
-       }
-
-       MSG_END();
-}
-
-
-bool MsgSoundSetRepeatAlarm()
-{
-       bool bRet = false;
-
-       int nRepeatValue = 0;
-       long    nRepeatTime = 0;
-
-       nRepeatValue = MsgSettingGetInt(MSG_ALERT_TONE);
-
-       switch (nRepeatValue)
-       {
-               case MSG_ALERT_TONE_ONCE:
-                       nRepeatTime = 0;
-               break;
-
-               case MSG_ALERT_TONE_2MINS:
-                       nRepeatTime = 2;
-               break;
-
-               case MSG_ALERT_TONE_5MINS:
-                       nRepeatTime = 5;
-               break;
-
-               case MSG_ALERT_TONE_10MINS:
-                       nRepeatTime = 10;
-               break;
-
-               default:
-                       MSG_DEBUG("Invalid Repetition time");
-               break;
-       }
-
-       MSG_DEBUG("nRepeatTime = %d", nRepeatTime);
-
-       if (nRepeatTime > 0)
-       {
-               bRet = MsgSoundCreateRepeatAlarm(nRepeatTime);
-       }
-
-       return bRet;
-}
-
-
-bool MsgSoundCreateRepeatAlarm(int RepeatTime)
-{
-       MSG_BEGIN();
-
-       time_t current_time;
-       struct tm current_tm;
-
-       time(&current_time);
-
-       localtime_r(&current_time, &current_tm);
-
-       int retval =0;
-
-       retval = alarmmgr_init("msg-service-tools");
-
-       if (retval != 0)
-       {
-               MSG_FATAL("alarmmgr_init() error [%d]", retval);
-               return false;
-       }
-
-       alarm_info_t* alarm_info;
-       alarm_date_t target_time;
-
-       alarm_info = alarmmgr_create_alarm();
-
-       target_time.year = 0;
-       target_time.month = 0;
-       target_time.day = 0;
-
-       if (current_tm.tm_min+RepeatTime < 60)
-       {
-               target_time.hour = current_tm.tm_hour;
-               target_time.min = current_tm.tm_min+RepeatTime;
-       }
-       else
-       {
-               if (current_tm.tm_hour < 12)
-               {
-                       target_time.hour = current_tm.tm_hour+1;
-               }
-               else
-               {
-                       target_time.hour = (current_tm.tm_hour+1)%12;
-               }
-
-               target_time.min = (current_tm.tm_min+RepeatTime)%60;
-       }
-
-       target_time.sec = current_tm.tm_sec;
-
-       alarmmgr_set_time(alarm_info, target_time);
-       alarmmgr_set_repeat_mode(alarm_info, ALARM_REPEAT_MODE_ONCE, 0);
-       alarmmgr_set_type(alarm_info, ALARM_TYPE_VOLATILE);
-       alarmmgr_add_alarm_with_localtime(alarm_info, NULL, &g_alarmId);
-
-       retval = alarmmgr_set_cb(MsgSoundRepeatAlarmCB, NULL);
-
-       if (retval != 0)
-       {
-               MSG_DEBUG("alarmmgr_set_cb() error [%d]", retval);
-               return false;
-       }
-
-       MSG_DEBUG("Repeat Alarm Time : [%d-%d-%d %d:%d:%d]",
-               target_time.year,target_time.month,target_time.day,
-               target_time.hour, target_time.min, target_time.sec);
-
-       MSG_END();
-
-       return true;
-}
-
-
-int MsgSoundRepeatAlarmCB(int TimerId, void *pUserParam)
-{
-       MSG_BEGIN();
-
-       g_bRepeat = false;
-
-       if (MsgSoundGetUnreadMsgCnt() <= 0)
-       {
-               MSG_DEBUG("no unread msg");
-
-               return 0;
-       }
-
-       MsgSoundPlayStart();
-
-       MSG_END();
-
-       return 0;
-}
-
-
-int MsgSoundGetUnreadMsgCnt()
-{
-       int unreadCnt = 0;
-
-       // Get SMS Count
-       unreadCnt = MsgSettingGetInt(VCONFKEY_MESSAGE_RECV_SMS_STATE);
-
-       // Get MMS Count
-       unreadCnt += MsgSettingGetInt(VCONFKEY_MESSAGE_RECV_MMS_STATE);
-
-       MSG_DEBUG("unread count : [%d]", unreadCnt);
-
-       return unreadCnt;
-}
-
-void MsgSoundInitRepeatAlarm()
-{
-       MSG_BEGIN();
-
-       int nRepeatValue = 0;
-       long    nRepeatTime = 0;
-
-       g_bRepeat = false;
-
-       if (MsgSoundGetUnreadMsgCnt() <= 0) {
-               MSG_DEBUG("no unread msg");
-               return;
-       }
-
-       nRepeatValue = MsgSettingGetInt(MSG_ALERT_TONE);
-
-       switch (nRepeatValue)
-       {
-               case MSG_ALERT_TONE_ONCE:
-                       nRepeatTime = 0;
-               break;
-
-               case MSG_ALERT_TONE_2MINS:
-                       nRepeatTime = 2;
-               break;
-
-               case MSG_ALERT_TONE_5MINS:
-                       nRepeatTime = 5;
-               break;
-
-               case MSG_ALERT_TONE_10MINS:
-                       nRepeatTime = 10;
-               break;
-
-               default:
-                       MSG_DEBUG("Invalid Repetition time");
-               break;
-       }
-
-       MSG_DEBUG("nRepeatTime = %d", nRepeatTime);
-
-       if (nRepeatTime > 0)
-               MsgSoundPlayStart();
-
-       MSG_END();
-}
diff --git a/utils/MsgSpamFilter.cpp b/utils/MsgSpamFilter.cpp
deleted file mode 100755 (executable)
index 554e00e..0000000
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#include "MsgDebug.h"
-#include "MsgUtilFile.h"
-#include "MsgCppTypes.h"
-#include "MsgGconfWrapper.h"
-#include "MsgSpamFilter.h"
-
-/*==================================================================================================
-                                     FUNCTION IMPLEMENTATION
-==================================================================================================*/
-msg_error_t MsgSetFilterOperation(bool bSetFlag)
-{
-       MSG_BEGIN();
-
-       if (MsgSettingSetBool(MSG_BLOCK_MESSAGE, bSetFlag) != MSG_SUCCESS) {
-               MSG_DEBUG("Error to set config data [%s]", MSG_BLOCK_MESSAGE);
-               return MSG_ERR_SET_SETTING;
-       }
-
-       MSG_END();
-
-       return MSG_SUCCESS;
-}
-
-
-msg_error_t MsgGetFilterOperation(bool *pSetFlag)
-{
-       MSG_BEGIN();
-
-       MsgSettingGetBool(MSG_BLOCK_MESSAGE, pSetFlag);
-
-       MSG_END();
-
-       return MSG_SUCCESS;
-}
-
-
-bool MsgCheckFilter(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S *pMsgInfo)
-{
-       MSG_BEGIN();
-
-       msg_error_t err = MSG_SUCCESS;
-
-       // =======================================================================
-       // Check Filter Operation
-       // =======================================================================
-       bool filterFlag = false;
-
-       MsgGetFilterOperation(&filterFlag);
-
-       if (filterFlag == false) {
-               MSG_DEBUG("filter operation is not working");
-               return false;
-       }
-
-       // =======================================================================
-       // Check Filter by Address
-       // =======================================================================
-       int rowCnt = 0;
-
-       MSG_DEBUG("pMsg->addressList[0].addressVal [%s]", pMsgInfo->addressList[0].addressVal);
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILTER_ID FROM %s WHERE FILTER_TYPE = %d AND '%s' = FILTER_VALUE \
-                       UNION SELECT FILTER_ID FROM %s WHERE FILTER_TYPE = %d AND '%s' LIKE SUBSTR(FILTER_VALUE,1)||'%%' \
-                       UNION SELECT FILTER_ID FROM %s WHERE FILTER_TYPE = %d AND '%s' LIKE '%%'||SUBSTR(FILTER_VALUE,1)||'%%';",
-                       MSGFW_FILTER_TABLE_NAME, MSG_FILTER_BY_ADDRESS_SAME, pMsgInfo->addressList[0].addressVal,
-                       MSGFW_FILTER_TABLE_NAME, MSG_FILTER_BY_ADDRESS_START, pMsgInfo->addressList[0].addressVal,
-                       MSGFW_FILTER_TABLE_NAME, MSG_FILTER_BY_ADDRESS_INCLUDE, pMsgInfo->addressList[0].addressVal);
-
-       err = pDbHandle->getTable(sqlQuery, &rowCnt);
-
-       if (rowCnt > 0) {
-               MSG_DEBUG("Msg is Filtered by Address : [%s]", pMsgInfo->addressList[0].addressVal);
-
-               pDbHandle->freeTable();
-
-               pMsgInfo->folderId = MSG_SPAMBOX_ID;
-
-               return true;
-       } else {
-               MSG_DEBUG("Msg is NOT Filtered by Address : [%s]", pMsgInfo->addressList[0].addressVal);
-
-               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
-
-               pDbHandle->freeTable();
-       }
-
-       // =======================================================================
-       // Check Filter by Subject
-       // =======================================================================
-       // Get Filter List
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILTER_VALUE FROM %s WHERE FILTER_TYPE = %d;",
-                       MSGFW_FILTER_TABLE_NAME, MSG_FILTER_BY_WORD);
-
-       rowCnt = 0;
-
-       err = pDbHandle->getTable(sqlQuery, &rowCnt);
-
-       if (err != MSG_SUCCESS) {
-               MSG_DEBUG("MsgGetTable() Error [%d] : [%s]", err, sqlQuery);
-
-               pDbHandle->freeTable();
-
-               return false;
-       }
-
-       char filterValue[MAX_FILTER_VALUE_LEN+1];
-
-       char* pData = NULL;
-       AutoPtr<char> buf(&pData);
-
-       int fileSize = 0;
-       bool bFiltered = false;
-
-       for (int i = 1; i <= rowCnt; i++)
-       {
-               memset(filterValue, 0x00, sizeof(filterValue));
-
-               pDbHandle->getColumnToString(i, MAX_FILTER_VALUE_LEN, filterValue);
-
-               MSG_DEBUG("filterValue [%s]", filterValue);
-
-               if (strlen(filterValue) <= 0) continue;
-
-               if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE && pMsgInfo->msgType.subType == MSG_NORMAL_SMS) {
-                       if (pMsgInfo->bTextSms == false) {
-                               if (MsgOpenAndReadFile(pMsgInfo->msgData, &pData, &fileSize) == false) {
-                                       pDbHandle->freeTable();
-                                       return false;
-                               }
-                               MSG_DEBUG("file data [%s]", pData);
-                       } else {
-                               if (pMsgInfo->dataSize > 0) {
-                                       pData = new char[pMsgInfo->dataSize+1];
-
-                                       strncpy(pData, pMsgInfo->msgText, pMsgInfo->dataSize);
-                                       pData[strlen(pMsgInfo->msgText)] = '\0';
-                               }
-                       }
-               } else if(pMsgInfo->msgType.mainType == MSG_MMS_TYPE) {
-                       if (strlen(pMsgInfo->subject) > 0) {
-                               pData = new char[strlen(pMsgInfo->subject)+1];
-
-                               strncpy(pData, pMsgInfo->subject, strlen(pMsgInfo->subject));
-                               pData[strlen(pMsgInfo->subject)] = '\0';
-                       }
-               }
-
-               // NULL value check
-               if (pData == NULL) {
-                       MSG_DEBUG("pData is NULL");
-
-                       bFiltered = false;
-                       break;
-               }
-
-               MSG_DEBUG("pData [%s]", pData);
-
-               if (strcasestr(pData, filterValue) != NULL) {
-                       MSG_DEBUG("Msg is Filtered by Subject [%s] Data [%s]", filterValue, pData);
-
-                       bFiltered = true;
-                       break;
-               }
-       }
-
-       pDbHandle->freeTable();
-
-       if (bFiltered == true) {
-               MSG_DEBUG("Msg is Filtered by Subject");
-
-               pMsgInfo->folderId = MSG_SPAMBOX_ID;
-
-               return true;
-       } else {
-               MSG_DEBUG("Msg is NOT Filtered by Subject");
-       }
-
-       MSG_END();
-
-       return false;
-}
index dc5461d..c1581ac 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
 #include <unistd.h>
 #include <string.h>
 #include <stdlib.h>
+#include <map>
+#include <sys/mman.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <pthread.h>
 
 #include "MsgDebug.h"
 #include "MsgSqliteWrapper.h"
@@ -28,45 +33,40 @@ extern "C"
        #include <db-util.h>
 }
 
+Mutex MsgDbHandler::mx;
 
 /*==================================================================================================
                                      VARIABLES
 ==================================================================================================*/
-__thread sqlite3 *handle = NULL;
-__thread sqlite3_stmt *stmt = NULL;
-//__thread char **result = NULL;
-
+//__thread sqlite3 *handle = NULL;
+//__thread sqlite3_stmt *stmt = NULL;
 
 /*==================================================================================================
                                      IMPLEMENTATION OF MsgDbHandler - Member Functions
 ==================================================================================================*/
 MsgDbHandler::MsgDbHandler()
 {
-       handle = NULL;
-       stmt = NULL;
        result = NULL;
+       handle = NULL;
+       stmt   = NULL;
+       mmapMx = NULL;
+       shm_fd = -1;
 }
 
 
 MsgDbHandler::~MsgDbHandler()
 {
-       if(handle != NULL)
-               disconnect();
-
-       if(stmt != NULL)
-               finalizeQuery();
-
-       if(result != NULL)
-               freeTable();
+       freeTable();
+       finalizeQuery();
+       if (disconnect() != MSG_SUCCESS)
+               MSG_DEBUG("DB disconnect is failed.");
 }
 
-
 msg_error_t MsgDbHandler::connect()
 {
        int ret = 0;
 
-       if (handle == NULL)
-       {
+       if (handle == NULL) {
                char strDBName[64];
 
                memset(strDBName, 0x00, sizeof(strDBName));
@@ -74,19 +74,14 @@ msg_error_t MsgDbHandler::connect()
 
                ret = db_util_open(strDBName, &handle, DB_UTIL_REGISTER_HOOK_METHOD);
 
-               if (ret == SQLITE_OK)
-               {
+               if (ret == SQLITE_OK) {
                        MSG_DEBUG("DB Connect Success : [%p]", handle);
                        return MSG_SUCCESS;
-               }
-               else
-               {
+               } else {
                        MSG_DEBUG("DB Connect Fail [%d]", ret);
                        return MSG_ERR_DB_CONNECT;
                }
-       }
-       else
-       {
+       } else {
                MSG_DEBUG("DB Connect exist : [%p]", handle);
        }
 
@@ -98,18 +93,14 @@ msg_error_t MsgDbHandler::disconnect()
 {
        int ret = 0;
 
-       if (handle != NULL)
-       {
+       if (handle != NULL) {
                ret = db_util_close(handle);
 
-               if (ret == SQLITE_OK)
-               {
+               if (ret == SQLITE_OK) {
                        handle = NULL;
                        MSG_DEBUG("DB Disconnect Success");
                        return MSG_SUCCESS;
-               }
-               else
-               {
+               } else {
                        MSG_DEBUG("DB Disconnect Fail [%d]", ret);
                        return MSG_ERR_DB_DISCONNECT;
                }
@@ -128,8 +119,7 @@ bool MsgDbHandler::checkTableExist(const char *pTableName)
        memset(strQuery, 0x00, sizeof(strQuery));
        snprintf(strQuery, sizeof(strQuery), "select count(name) from sqlite_master where name='%s'", pTableName);
 
-       if (getTable(strQuery, &nRowCnt) != MSG_SUCCESS)
-       {
+       if (getTable(strQuery, &nRowCnt, NULL) != MSG_SUCCESS) {
                freeTable();
                return false;
        }
@@ -148,56 +138,60 @@ bool MsgDbHandler::checkTableExist(const char *pTableName)
 
 msg_error_t MsgDbHandler::execQuery(const char *pQuery)
 {
-       int ret = 0;
+//     int ret = 0;
 
-       if (!pQuery)
+       if (!pQuery)
                return MSG_ERR_INVALID_PARAMETER;
 
+       MutexLocker lock(mx);
+
        if(connect() != MSG_SUCCESS)
                return MSG_ERR_DB_DISCONNECT;
 
-       ret = sqlite3_exec(handle, pQuery, 0, 0, NULL);
-
-       if (ret == SQLITE_OK)
-       {
-               MSG_DEBUG("Execute Query Success");
-               return MSG_SUCCESS;
+       if (prepareQuery(pQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to prepareQuery.");
+               return MSG_ERR_DB_EXEC;
        }
-       else
-       {
-               MSG_DEBUG("Execute Query Fail [%d]", ret);
+
+       if (stepQuery() == MSG_ERR_DB_STEP) {
+               MSG_DEBUG("Fail to stepQuery.");
+               finalizeQuery();
                return MSG_ERR_DB_EXEC;
        }
 
+       finalizeQuery();
+
        return MSG_SUCCESS;
 }
 
 
-msg_error_t MsgDbHandler::getTable(const char *pQuery, int *pRowCnt)
+msg_error_t MsgDbHandler::getTable(const char *pQuery, int *pRowCnt, int *pColumnCnt)
 {
        int ret = 0;
 
        *pRowCnt = 0;
+       if (pColumnCnt)
+               *pColumnCnt = 0;
 
        if(connect() != MSG_SUCCESS)
                return MSG_ERR_DB_DISCONNECT;
 
        freeTable();
-       ret = sqlite3_get_table(handle, pQuery, &result, pRowCnt, 0, NULL);
+       MSG_DEBUG("[%s]", pQuery);
+       ret = sqlite3_get_table(handle, pQuery, &result, pRowCnt, pColumnCnt, NULL);
 
-       if (ret == SQLITE_OK)
-       {
-               if (*pRowCnt == 0)    // when the no record return 'MSG_ERR_DB_NORECORD'
-               {
+       if (ret == SQLITE_OK) {
+               if (*pRowCnt == 0) {// when the no record return 'MSG_ERR_DB_NORECORD'
                        MSG_DEBUG("No Query Result");
                        return MSG_ERR_DB_NORECORD;
                }
 
                MSG_DEBUG("Get Table Success");
                return MSG_SUCCESS;
-       }
-       else
-       {
+       } else if (ret == SQLITE_BUSY) {
+               MSG_DEBUG("The database file is locked [%d]", ret);
+               return MSG_ERR_DB_BUSY;
+       } else {
                MSG_DEBUG("Get Table Fail [%d]", ret);
                return MSG_ERR_DB_GETTABLE;
        }
@@ -208,8 +202,7 @@ msg_error_t MsgDbHandler::getTable(const char *pQuery, int *pRowCnt)
 
 void MsgDbHandler::freeTable()
 {
-       if (result)
-       {
+       if (result) {
                sqlite3_free_table(result);
                result = NULL;
        }
@@ -227,6 +220,16 @@ msg_error_t MsgDbHandler::bindText(const char *pBindStr, int index)
 }
 
 
+msg_error_t MsgDbHandler::bindInt(const int pBindint, int index)
+{
+       int ret = 0;
+
+       ret = sqlite3_bind_int(stmt, index, pBindint);
+
+       return ret;
+}
+
+
 msg_error_t MsgDbHandler::bindBlob(const void * pBindBlob, int size, int index)
 {
        int ret = 0;
@@ -246,15 +249,12 @@ msg_error_t MsgDbHandler::prepareQuery(const char *pQuery)
        if(connect() != MSG_SUCCESS)
                return MSG_ERR_DB_DISCONNECT;
 
-
-       if ((ret = sqlite3_prepare_v2(handle, pQuery, strlen(pQuery), &stmt, NULL)) == SQLITE_OK)
-       {
+       if ((ret = sqlite3_prepare_v2(handle, pQuery, strlen(pQuery), &stmt, NULL)) == SQLITE_OK) {
                MSG_DEBUG("Prepare Query Success");
                return MSG_SUCCESS;
-       }
-       else
-       {
-               MSG_DEBUG("Prepare Query Fail [%d]", ret);
+       } else {
+               MSG_ERR("Prepare Query Fail [%d]", ret);
+               finalizeQuery();
                return MSG_ERR_DB_PREPARE;
        }
 
@@ -268,19 +268,15 @@ msg_error_t MsgDbHandler::stepQuery()
 
        ret = sqlite3_step(stmt);
 
-       if (ret == SQLITE_ROW)
-       {
+       if (ret == SQLITE_ROW) {
                MSG_DEBUG("MsgStepQuery() SQLITE_ROW");
                return MSG_ERR_DB_ROW;
-       }
-       else if (ret == SQLITE_DONE)
-       {
+       } else if (ret == SQLITE_DONE) {
                MSG_DEBUG("MsgStepQuery() SQLITE_DONE");
                return MSG_ERR_DB_DONE;
-       }
-       else
-       {
-               MSG_DEBUG("MsgStepQuery() Fail [%d]", ret);
+       } else {
+               MSG_ERR("MsgStepQuery() Fail [%d]", ret);
+               finalizeQuery();
                return MSG_ERR_DB_STEP;
        }
 
@@ -288,6 +284,13 @@ msg_error_t MsgDbHandler::stepQuery()
 }
 
 
+void MsgDbHandler::resetQuery()
+{
+       if (stmt)
+               sqlite3_reset(stmt);
+}
+
+
 void MsgDbHandler::finalizeQuery()
 {
        if(stmt != NULL)
@@ -313,6 +316,85 @@ const void* MsgDbHandler::columnBlob(int ColumnIndex)
        return sqlite3_column_blob(stmt, ColumnIndex);
 }
 
+void MsgDbHandler::getMmapMutex(const char *shm_file_name)
+{
+       MSG_BEGIN();
+
+       if(!shm_file_name) {
+               MSG_FATAL ("NULL INPUT_PARAM");
+               return;
+       }
+
+       MSG_DEBUG("** mapping begin **");
+
+        /*  open shm_file_name at first. Otherwise, the num of files in /proc/pid/fd will be increasing  */
+       shm_fd = shm_open(shm_file_name, O_RDWR, 0);
+       if (shm_fd == -1) {
+               MSG_FATAL("shm_open error [%d]", errno);
+               return;
+       }
+
+       pthread_mutex_t *tmp = (pthread_mutex_t *)mmap(NULL, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE, MAP_SHARED, shm_fd, 0);
+       if (tmp == MAP_FAILED) {
+               MSG_FATAL("mmap error [%d]", errno);
+               return;
+       }
+       mmapMx = tmp;
+}
+
+void MsgDbHandler::freeMmapMutex()
+{
+       MSG_BEGIN();
+       if (!mmapMx) {
+               getMmapMutex(SHM_FILE_FOR_DB_LOCK);
+       }
+
+       if (mmapMx) {
+               int err = munmap(mmapMx, sizeof(pthread_mutex_t));
+               MSG_FATAL("pthread_mutex_munmap error [%d]", err);
+       }
+
+       MSG_END();
+}
+
+
+void MsgDbHandler::shm_mutex_timedlock (int sec)
+{
+       MSG_BEGIN();
+       if (!mmapMx) {
+               MSG_DEBUG("mmapMx not initd");
+               return;
+       }
+
+       struct timespec abs_time;
+       clock_gettime(CLOCK_REALTIME, &abs_time);
+       abs_time.tv_sec += sec;
+
+       int err = pthread_mutex_timedlock(mmapMx, &abs_time);
+
+       if (err == EOWNERDEAD) {
+               err = pthread_mutex_consistent(mmapMx);
+               MSG_DEBUG("Previous owner is dead with lock. Fix mutex");
+       }
+       else if (err != 0) {
+               MSG_FATAL("pthread_mutex_timedlock error [%d]", errno);
+               return;
+       }
+
+       MSG_END();
+}
+
+void MsgDbHandler::shm_mutex_unlock()
+{
+       MSG_BEGIN();
+       if(!mmapMx) {
+               MSG_DEBUG("mmapMx not initd");
+               return;
+       }
+
+       pthread_mutex_unlock(mmapMx);
+       MSG_END();
+}
 
 msg_error_t MsgDbHandler::beginTrans()
 {
@@ -321,16 +403,17 @@ msg_error_t MsgDbHandler::beginTrans()
        if(connect() != MSG_SUCCESS)
                return MSG_ERR_DB_DISCONNECT;
 
+       if (!mmapMx) {
+               getMmapMutex(SHM_FILE_FOR_DB_LOCK);
+       }
+       shm_mutex_timedlock(2);
 
-       ret = sqlite3_exec(handle, "BEGIN deferred;", 0, 0, NULL);
+       ret = sqlite3_exec(handle, "BEGIN DEFERRED TRANSACTION;", 0, 0, NULL);
 
-       if (ret == SQLITE_OK)
-       {
+       if (ret == SQLITE_OK) {
                MSG_DEBUG("Begin Transaction Success");
                return MSG_SUCCESS;
-       }
-       else
-       {
+       } else {
                MSG_DEBUG("Begin Transaction Fail [%d]", ret);
                return MSG_ERR_DB_EXEC;
        }
@@ -347,24 +430,20 @@ msg_error_t MsgDbHandler::endTrans(bool Success)
                return MSG_ERR_DB_DISCONNECT;
 
 
-       if (Success == true)
-       {
-               ret = sqlite3_exec(handle, "END;", 0, 0, NULL);
-       }
-       else
-       {
-               ret = sqlite3_exec(handle, "rollback", 0, 0, NULL);
-               ret = sqlite3_exec(handle, "END;", 0, 0, NULL);
+       if (Success) {
+               ret = sqlite3_exec(handle, "COMMIT TRANSACTION;", 0, 0, NULL);
+       } else {
+               ret = sqlite3_exec(handle, "ROLLBACK TRANSACTION;", 0, 0, NULL);
        }
 
-       if (ret == SQLITE_OK)
-       {
+       shm_mutex_unlock();
+
+       if (ret == SQLITE_OK) {
                MSG_DEBUG("End Transaction Success");
                return MSG_SUCCESS;
-       }
-       else
-       {
+       } else {
                MSG_DEBUG("End Transaction Fail [%d]", ret);
+               if (Success) endTrans(false);
                return MSG_ERR_DB_EXEC;
        }
 
@@ -378,8 +457,7 @@ int MsgDbHandler::getColumnToInt(int RowIndex)
 
        int nTemp = 0;
 
-       if (pTemp == NULL)
-       {
+       if (pTemp == NULL) {
                MSG_DEBUG("NULL");
                return nTemp;
        }
@@ -394,8 +472,7 @@ char MsgDbHandler::getColumnToChar(int RowIndex)
 {
        char* pTemp = result[RowIndex];
 
-       if (pTemp == NULL)
-       {
+       if (pTemp == NULL) {
                MSG_DEBUG("NULL");
                return '\0';
        }
@@ -404,12 +481,24 @@ char MsgDbHandler::getColumnToChar(int RowIndex)
 }
 
 
+char *MsgDbHandler::getColumnToString(int RowIndex)
+{
+       char* pTemp = result[RowIndex];
+
+       if (pTemp == NULL) {
+               MSG_DEBUG("NULL");
+               return NULL;
+       }
+
+       return pTemp;
+}
+
+
 void MsgDbHandler::getColumnToString(int RowIndex, int Length, char *pString)
 {
        char* pTemp = result[RowIndex];
 
-       if (pTemp == NULL)
-       {
+       if (pTemp == NULL) {
                MSG_DEBUG("NULL");
                return;
        }
@@ -426,24 +515,21 @@ msg_error_t MsgDbHandler::getRowId(const char *pTableName, unsigned int *pRowId)
        if (pTableName == NULL || pRowId == NULL)
                return MSG_ERR_INVALID_PARAMETER;
 
-       MSG_DEBUG("Table Name [%s]", pTableName);
+       MSG_SEC_DEBUG("Table Name [%s]", pTableName);
 
        memset(strQuery, 0x00, sizeof(strQuery));
        snprintf(strQuery, sizeof(strQuery), "select max(rowid) from %s", pTableName);
 
-       ret = getTable(strQuery, &nRowCnt);
+       ret = getTable(strQuery, &nRowCnt, NULL);
 
-       if (ret == SQLITE_OK)
-       {
+       if (ret == SQLITE_OK) {
                nRowId = getColumnToInt(1);
 
                if ((nRowCnt <= 1) && (nRowId == 0))
                        *pRowId = 1;
                else
                        *pRowId = nRowId + 1;
-       }
-       else
-       {
+       } else {
                MSG_DEBUG("MsgGetRowId failed");
                *pRowId = 0;
                freeTable();
@@ -458,9 +544,6 @@ msg_error_t MsgDbHandler::getRowId(const char *pTableName, unsigned int *pRowId)
 }
 
 
-/*==================================================================================================
-                                     FUNCTION IMPLEMENTATION
-==================================================================================================*/
 void MsgReleaseMemoryDB()
 {
        int freeSize = 0;
@@ -470,3 +553,76 @@ void MsgReleaseMemoryDB()
        MSG_DEBUG("freed memory size (bytes) : [%d]", freeSize);
 }
 
+
+msg_error_t MsgConvertStrWithEscape(const char *input, char **output)
+{
+       if (input == NULL || output == NULL || strlen(input) == 0) {
+               MSG_DEBUG("MSG_ERR_INVALID_PARAMETER");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       int inputSize = 0;
+       int i = 0;
+       int j = 0;
+
+       inputSize = strlen(input);
+       MSG_DEBUG("Size of input string [%d]", inputSize);
+
+       char tmpStr[(inputSize*2)+3];
+       memset(tmpStr, 0x00, sizeof(tmpStr));
+
+       tmpStr[j++] = '%';
+
+       for(i=0;i<inputSize;i++) {
+               if (input[i] == '\'' || input[i] == '_' || input[i] == '%' || input[i] == '\\') {
+                       tmpStr[j++] = MSGFW_DB_ESCAPE_CHAR;
+               }
+               tmpStr[j++] = input[i];
+       }
+       tmpStr[j++] = '%';
+       tmpStr[j] = '\0';
+
+       *output = strdup(tmpStr);
+
+       return MSG_SUCCESS;
+}
+
+typedef std::map<pthread_t, MsgDbHandler*> dbMap_t;
+dbMap_t gDbHandles;
+pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
+
+MsgDbHandler *getDbHandle()
+{
+       pthread_t self = pthread_self();
+       MsgDbHandler *tmp = NULL;
+
+       pthread_mutex_lock(&mu);
+       dbMap_t::iterator it = gDbHandles.find(self);
+       if (it == gDbHandles.end()) {
+               MSG_DEBUG("New DB handle added.");
+               tmp = new MsgDbHandler();
+               gDbHandles.insert ( std::pair<pthread_t,MsgDbHandler*>(self,tmp));
+
+       } else {
+               tmp = it->second;
+       }
+       pthread_mutex_unlock(&mu);
+
+       return tmp;
+}
+
+void removeDbHandle()
+{
+       pthread_t self = pthread_self();
+       MsgDbHandler *tmp = NULL;
+
+       pthread_mutex_lock(&mu);
+       dbMap_t::iterator it = gDbHandles.find(self);
+       if (it != gDbHandles.end()) {
+               tmp = it->second;
+               delete tmp;
+               gDbHandles.erase (it);
+       }
+       pthread_mutex_unlock(&mu);
+}
+
diff --git a/utils/MsgTextConvert.cpp b/utils/MsgTextConvert.cpp
new file mode 100755 (executable)
index 0000000..53e9769
--- /dev/null
@@ -0,0 +1,1190 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include <glib.h>
+
+#include "MsgDebug.h"
+#include "MsgTextConvert.h"
+#include "MsgCppTypes.h"
+
+using namespace std;
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgConvertText - Member Functions
+==================================================================================================*/
+MsgTextConvert* MsgTextConvert::pInstance = NULL;
+
+MsgTextConvert::MsgTextConvert()
+{
+       extCharList.clear();
+       ucs2toGSM7DefList.clear();
+       ucs2toGSM7ExtList.clear();
+       ucs2toTurkishList.clear();
+       ucs2toSpanishList.clear();
+       ucs2toPortuList.clear();
+       replaceCharList.clear();
+
+       extCharList[0x000C] = MSG_CHAR_GSM7EXT;
+       extCharList[0x005B] = MSG_CHAR_GSM7EXT;
+       extCharList[0x005C] = MSG_CHAR_GSM7EXT;
+       extCharList[0x005D] = MSG_CHAR_GSM7EXT;
+       extCharList[0x005E] = MSG_CHAR_GSM7EXT;
+       extCharList[0x007B] = MSG_CHAR_GSM7EXT;
+       extCharList[0x007C] = MSG_CHAR_GSM7EXT;
+       extCharList[0x007D] = MSG_CHAR_GSM7EXT;
+       extCharList[0x007E] = MSG_CHAR_GSM7EXT;
+       extCharList[0x20AC] = MSG_CHAR_GSM7EXT;
+
+       extCharList[0x00E7] = MSG_CHAR_TURKISH;
+       extCharList[0x011E] = MSG_CHAR_TURKISH;
+       extCharList[0x011F] = MSG_CHAR_TURKISH;
+       extCharList[0x01E6] = MSG_CHAR_TURKISH;
+       extCharList[0x01E7] = MSG_CHAR_TURKISH;
+       extCharList[0x0130] = MSG_CHAR_TURKISH;
+       extCharList[0x0131] = MSG_CHAR_TURKISH;
+       extCharList[0x015E] = MSG_CHAR_TURKISH;
+       extCharList[0x015F] = MSG_CHAR_TURKISH;
+
+       extCharList[0x00C1] = MSG_CHAR_SPANISH;
+       extCharList[0x00E1] = MSG_CHAR_SPANISH;
+       extCharList[0x00CD] = MSG_CHAR_SPANISH;
+       extCharList[0x00ED] = MSG_CHAR_SPANISH;
+       extCharList[0x00D3] = MSG_CHAR_SPANISH;
+       extCharList[0x00F3] = MSG_CHAR_SPANISH;
+       extCharList[0x00DA] = MSG_CHAR_SPANISH;
+       extCharList[0x00FA] = MSG_CHAR_SPANISH;
+
+       extCharList[0x00D4] = MSG_CHAR_PORTUGUESE;
+       extCharList[0x00F4] = MSG_CHAR_PORTUGUESE;
+       extCharList[0x00CA] = MSG_CHAR_PORTUGUESE;
+       extCharList[0x00EA] = MSG_CHAR_PORTUGUESE;
+       extCharList[0x00C0] = MSG_CHAR_PORTUGUESE;
+       extCharList[0x00E7] = MSG_CHAR_PORTUGUESE;
+       extCharList[0x00C3] = MSG_CHAR_PORTUGUESE;
+       extCharList[0x00E3] = MSG_CHAR_PORTUGUESE;
+       extCharList[0x00D5] = MSG_CHAR_PORTUGUESE;
+       extCharList[0x00F5] = MSG_CHAR_PORTUGUESE;
+       extCharList[0x00C2] = MSG_CHAR_PORTUGUESE;
+       extCharList[0x00E2] = MSG_CHAR_PORTUGUESE;
+
+       for (unsigned char i = 0; i < 128; i++)
+       {
+               ucs2toGSM7DefList[g_GSM7BitToUCS2[i]] = i;
+       }
+
+       // GSM 7 bit Extension
+       ucs2toGSM7ExtList[0x005B] = 0x3C; // [
+       ucs2toGSM7ExtList[0x005D] = 0x3E; // ]
+       ucs2toGSM7ExtList[0x007B] = 0x28; // {
+       ucs2toGSM7ExtList[0x007D] = 0x29; // }
+       ucs2toGSM7ExtList[0x000C] = 0x0A; // Page Break
+       ucs2toGSM7ExtList[0x005C] = 0x2F; /* \ */
+       ucs2toGSM7ExtList[0x005E] = 0x14; // ^
+       ucs2toGSM7ExtList[0x007C] = 0x40; // |
+       ucs2toGSM7ExtList[0x007E] = 0x3D; // ~
+       ucs2toGSM7ExtList[0x20AC] = 0x65; // €
+
+       // Turkish
+       ucs2toTurkishList[0x005B] = 0x3C; // [
+       ucs2toTurkishList[0x005D] = 0x3E; // ]
+       ucs2toTurkishList[0x007B] = 0x28; // {
+       ucs2toTurkishList[0x007D] = 0x29; // }
+       ucs2toTurkishList[0x000C] = 0x0A; // Page Break
+       ucs2toTurkishList[0x005C] = 0x2F; /* \ */
+       ucs2toTurkishList[0x005E] = 0x14; // ^
+       ucs2toTurkishList[0x007C] = 0x40; // |
+       ucs2toTurkishList[0x007E] = 0x3D; // ~
+       ucs2toTurkishList[0x20AC] = 0x65; // €
+       ucs2toTurkishList[0x00E7] = 0x63; // c LATIN SMALL LETTER S WITH CEDILLA
+       ucs2toTurkishList[0x011E] = 0x47; // G LATIN CAPITAL LETTER G WITH BREVE
+       ucs2toTurkishList[0x011F] = 0x67; // g LATIN SMALL LETTER G WITH BREVE
+       ucs2toTurkishList[0x01E6] = 0x47; // G LATIN CAPITAL LETTER G WITH CARON
+       ucs2toTurkishList[0x01E7] = 0x67; // g LATIN SMALL LETTER G WITH CARON
+       ucs2toTurkishList[0x0130] = 0x49; // I LATIN CAPITAL LETTER I WITH DOT ABOVE
+       ucs2toTurkishList[0x0131] = 0x69; // i LATIN SMALL LETTER DOTLESS
+       ucs2toTurkishList[0x015E] = 0x53; // S LATIN CAPITAL LETTER S WITH CEDILLA
+       ucs2toTurkishList[0x015F] = 0x73; // s LATIN SMALL LETTER S WITH CEDILLA
+
+       // Spanish
+       ucs2toSpanishList[0x005B] = 0x3C; // [
+       ucs2toSpanishList[0x005D] = 0x3E; // ]
+       ucs2toSpanishList[0x007B] = 0x28; // {
+       ucs2toSpanishList[0x007D] = 0x29; // }
+       ucs2toSpanishList[0x000C] = 0x0A; // Page Break
+       ucs2toSpanishList[0x005C] = 0x2F; /* \ */
+       ucs2toSpanishList[0x005E] = 0x14; // ^
+       ucs2toSpanishList[0x007C] = 0x40; // |
+       ucs2toSpanishList[0x007E] = 0x3D; // ~
+       ucs2toSpanishList[0x20AC] = 0x65; // €
+       ucs2toSpanishList[0x00C1] = 0x41; // A LATIN CAPITAL LETTER A WITH ACUTE
+       ucs2toSpanishList[0x00E1] = 0x61; // a LATIN SMALL LETTER A WITH ACUTE
+       ucs2toSpanishList[0x00CD] = 0x49; // I LATIN CAPITAL LETTER I WITH ACUTE
+       ucs2toSpanishList[0x00ED] = 0x69; // i LATIN SMALL LETTER I WITH ACUTE
+       ucs2toSpanishList[0x00D3] = 0x4F; // O LATIN CAPITAL LETTER O WITH ACUTE
+       ucs2toSpanishList[0x00F3] = 0x6F; // o LATIN SMALL LETTER O WITH ACUTE
+       ucs2toSpanishList[0x00DA] = 0x55; // U LATIN CAPITAL LETTER U WITH ACUTE
+       ucs2toSpanishList[0x00FA] = 0x75; // u LATIN SMALL LETTER U WITH ACUTE
+
+       // Portuguese
+       ucs2toPortuList[0x005B] = 0x3C; // [
+       ucs2toPortuList[0x005D] = 0x3E; // ]
+       ucs2toPortuList[0x007B] = 0x28; // {
+       ucs2toPortuList[0x007D] = 0x29; // }
+       ucs2toPortuList[0x000C] = 0x0A; // Page Break
+       ucs2toPortuList[0x005C] = 0x2F; /* \ */
+       ucs2toPortuList[0x005E] = 0x14; // ^
+       ucs2toPortuList[0x007C] = 0x40; // |
+       ucs2toPortuList[0x007E] = 0x3D; // ~
+       ucs2toPortuList[0x20AC] = 0x65; // €
+       ucs2toPortuList[0x00D4] = 0x0B; // O LATIN CAPITAL LETTER O WITH CIRCUMFLEX
+       ucs2toPortuList[0x00F4] = 0x0C; // o LATIN SMALL LETTER O WITH CIRCUMFLEX
+       ucs2toPortuList[0x00C1] = 0x0E; // A LATIN CAPITAL LETTER A WITH ACUTE
+       ucs2toPortuList[0x00E1] = 0x0F; // a LATIN SMALL LETTER A WITH ACUTE
+       ucs2toPortuList[0x00CA] = 0x1F; // E LATIN CAPITAL LETTER E WITH CIRCUMFLEX
+       ucs2toPortuList[0x00EA] = 0x05; // e LATIN SMALL LETTER E WITH CIRCUMFLEX
+       ucs2toPortuList[0x00C0] = 0x41; // A LATIN CAPITAL LETTER A WITH GRAVE
+       ucs2toPortuList[0x00E7] = 0x09; // c LATIN SMALL LETTER C WITH CEDILLA
+       ucs2toPortuList[0x00CD] = 0x49; // I LATIN CAPITAL LETTER I WITH ACUTE
+       ucs2toPortuList[0x00ED] = 0x69; // i LATIN SMALL LETTER I WITH ACUTE
+       ucs2toPortuList[0x00D3] = 0x4F; // O LATIN CAPITAL LETTER O WITH ACUTE
+       ucs2toPortuList[0x00F3] = 0x6F; // o LATIN SMALL LETTER O WITH ACUTE
+       ucs2toPortuList[0x00DA] = 0x55; // U LATIN CAPITAL LETTER U WITH ACUTE
+       ucs2toPortuList[0x00FA] = 0x75; // u LATIN SMALL LETTER U WITH ACUTE
+       ucs2toPortuList[0x00C3] = 0x61; // A LATIN CAPITAL LETTER A WITH TILDE
+       ucs2toPortuList[0x00E3] = 0x7B; // a LATIN SMALL LETTER A WITH TILDE
+       ucs2toPortuList[0x00D5] = 0x5C; // O LATIN CAPITAL LETTER O WITH TILDE
+       ucs2toPortuList[0x00F5] = 0x7C; // o LATIN SMALL LETTER O WITH TILDE
+       ucs2toPortuList[0x00C2] = 0x61; // A LATIN CAPITAL LETTER A WITH CIRCUMFLEX
+       ucs2toPortuList[0x00E2] = 0x7F; // a LATIN SMALL LETTER A WITH CIRCUMFLEX
+       ucs2toPortuList[0x03A6] = 0x12; // Φ GREEK CAPITAL LETTER PHI
+       ucs2toPortuList[0x0393] = 0x13; // Γ GREEK CAPITAL LETTER GAMMA
+       ucs2toPortuList[0x03A9] = 0x15; // Ω GREEK CAPITAL LETTER OMEGA
+       ucs2toPortuList[0x03A0] = 0x16; // Π GREEK CAPITAL LETTER PI
+       ucs2toPortuList[0x03A8] = 0x17; // Ψ GREEK CAPITAL LETTER PSI
+       ucs2toPortuList[0x03A3] = 0x18; // Σ GREEK CAPITAL LETTER SIGMA
+       ucs2toPortuList[0x0398] = 0x19; // Θ GREEK CAPITAL LETTER THETA
+
+
+       // character replacement table
+       replaceCharList[0x00E0] = 0x61; // a LATIN SMALL LETTER A WITH GRAVE
+       replaceCharList[0x00E1] = 0x61; // a LATIN SMALL LETTER A WITH ACUTE
+       replaceCharList[0x00E2] = 0x61; // a LATIN SMALL LETTER A WITH CIRCUMFLEX
+       replaceCharList[0x00E3] = 0x61; // a LATIN SMALL LETTER A WITH TILDE
+       replaceCharList[0x00E4] = 0x61; // a LATIN SMALL LETTER A WITH DIAERESIS
+       replaceCharList[0x00E5] = 0x61; // a LATIN SMALL LETTER A WITH RING ABOVE
+       replaceCharList[0x00E6] = 0x61; // a LATIN SMALL LETTER AE
+       replaceCharList[0x0101] = 0x61; // a LATIN SMALL LETTER A WITH MACRON
+       replaceCharList[0x0103] = 0x61; // a LATIN SMALL LETTER A WITH BREVE
+       replaceCharList[0x0105] = 0x61; // a LATIN SMALL LETTER A WITH OGONEK
+       replaceCharList[0x01CE] = 0x61; // a LATIN SMALL LETTER A WITH CARON
+
+       replaceCharList[0x00C0] = 0x41; // A LATIN CAPITAL LETTER A WITH GRAVE
+       replaceCharList[0x00C1] = 0x41; // A LATIN CAPITAL LETTER A WITH ACUTE
+       replaceCharList[0x00C2] = 0x41; // A LATIN CAPITAL LETTER A WITH CIRCUMFLEX
+       replaceCharList[0x00C3] = 0x41; // A LATIN CAPITAL LETTER A WITH TILDE
+       replaceCharList[0x00C4] = 0x41; // A LATIN CAPITAL LETTER A WITH DIAERESIS
+       replaceCharList[0x00C5] = 0x41; // A LATIN CAPITAL LETTER A WITH RING ABOVE
+       replaceCharList[0x00C6] = 0x41; // A LATIN CAPITAL LETTER AE
+       replaceCharList[0x0100] = 0x41; // A LATIN CAPITAL LETTER A WITH MACRON
+       replaceCharList[0x0102] = 0x41; // A LATIN CAPITAL LETTER A WITH BREVE
+       replaceCharList[0x0104] = 0x41; // A LATIN CAPITAL LETTER A WITH OGONEK
+       replaceCharList[0x01CD] = 0x41; // A LATIN CAPITAL LETTER A WITH CARON
+
+       replaceCharList[0x00E7] = 0x63; // c LATIN SMALL LETTER C WITH CEDILLA
+       replaceCharList[0x0107] = 0x63; // c LATIN SMALL LETTER C WITH ACUTE
+       replaceCharList[0x0109] = 0x63; // c LATIN SMALL LETTER C WITH CIRCUMFLEX
+       replaceCharList[0x010B] = 0x63; // c LATIN SMALL LETTER C WITH DOT ABOVE
+       replaceCharList[0x010D] = 0x63; // c LATIN SMALL LETTER C WITH CARON
+
+       replaceCharList[0x00C7] = 0x43; // C LATIN CAPITAL LETTER C WITH CEDILLA
+       replaceCharList[0x0106] = 0x43; // C LATIN CAPITAL LETTER C WITH ACUTE
+       replaceCharList[0x0108] = 0x43; // C LATIN CAPITAL LETTER C WITH CIRCUMFLEX
+       replaceCharList[0x010A] = 0x43; // C LATIN CAPITAL LETTER C WITH DOT ABOVE
+       replaceCharList[0x010C] = 0x43; // C LATIN CAPITAL LETTER C WITH CARON
+
+       replaceCharList[0x010F] = 0x64; // d LATIN SMALL LETTER D WITH CARON
+       replaceCharList[0x0111] = 0x64; // d LATIN SMALL LETTER D WITH STROKE
+
+       replaceCharList[0x010E] = 0x44; // D LATIN CAPITAL LETTER D WITH CARON
+       replaceCharList[0x0110] = 0x44; // D LATIN CAPITAL LETTER D WITH STROKE
+
+       replaceCharList[0x00E8] = 0x65; // e LATIN SMALL LETTER E WITH GRAVE
+       replaceCharList[0x00E9] = 0x65; // e LATIN SMALL LETTER E WITH ACUTE
+       replaceCharList[0x00EA] = 0x65; // e LATIN SMALL LETTER E WITH CIRCUMFLEX
+       replaceCharList[0x00EB] = 0x65; // e LATIN SMALL LETTER E WITH DIAERESIS
+       replaceCharList[0x0113] = 0x65; // e LATIN SMALL LETTER E WITH MACRON
+       replaceCharList[0x0115] = 0x65; // e LATIN SMALL LETTER E WITH BREVE
+       replaceCharList[0x0117] = 0x65; // e LATIN SMALL LETTER E WITH DOT ABOVE
+       replaceCharList[0x0119] = 0x65; // e LATIN SMALL LETTER E WITH OGONEK
+       replaceCharList[0x011B] = 0x65; // e LATIN SMALL LETTER E WITH CARON
+       replaceCharList[0x0259] = 0x65; // e LATIN SMALL LETTER SCHWA
+
+       replaceCharList[0x00C8] = 0x45; // E LATIN CAPITAL LETTER E WITH GRAVE
+       replaceCharList[0x00C9] = 0x45; // E LATIN CAPITAL LETTER E WITH ACUTE
+       replaceCharList[0x00CA] = 0x45; // E LATIN CAPITAL LETTER E WITH CIRCUMFLEX
+       replaceCharList[0x00CB] = 0x45; // E LATIN CAPITAL LETTER E WITH DIAERESIS
+       replaceCharList[0x0112] = 0x45; // E LATIN CAPITAL LETTER E WITH MACRON
+       replaceCharList[0x0114] = 0x45; // E LATIN CAPITAL LETTER E WITH BREVE
+       replaceCharList[0x0116] = 0x45; // E LATIN CAPITAL LETTER E WITH DOT ABOVE
+       replaceCharList[0x0118] = 0x45; // E LATIN CAPITAL LETTER E WITH OGONEK
+       replaceCharList[0x011A] = 0x45; // E LATIN CAPITAL LETTER E WITH CARON
+       replaceCharList[0x018F] = 0x45; // E LATIN CAPITAL LETTER SCHWA
+
+       replaceCharList[0x011D] = 0x67; // g LATIN SMALL LETTER G WITH CIRCUMFLEX
+       replaceCharList[0x011F] = 0x67; // g LATIN SMALL LETTER G WITH BREVE
+       replaceCharList[0x0121] = 0x67; // g LATIN SMALL LETTER G WITH DOT ABOVE
+       replaceCharList[0x0123] = 0x67; // g LATIN SMALL LETTER G WITH CEDILLA
+       replaceCharList[0x01E7] = 0x67; // g LATIN SMALL LETTER G WITH CARON
+       replaceCharList[0x01F5] = 0x67; // g LATIN SMALL LETTER G WITH ACUTE
+       replaceCharList[0x1E21] = 0x67; // g LATIN SMALL LETTER G WITH MACRON
+
+       replaceCharList[0x011C] = 0x47; // G LATIN CAPITAL LETTER G WITH CIRCUMFLEX
+       replaceCharList[0x011E] = 0x47; // G LATIN CAPITAL LETTER G WITH BREVE
+       replaceCharList[0x0120] = 0x47; // G LATIN CAPITAL LETTER G WITH DOT ABOVE
+       replaceCharList[0x0122] = 0x47; // G LATIN CAPITAL LETTER G WITH CEDILLA
+       replaceCharList[0x01E6] = 0x47; // G LATIN CAPITAL LETTER G WITH CARON
+       replaceCharList[0x01F4] = 0x47; // G LATIN CAPITAL LETTER G WITH ACUTE
+       replaceCharList[0x1E20] = 0x47; // G LATIN CAPITAL LETTER G WITH MACRON
+
+       replaceCharList[0x00EC] = 0x69; // i LATIN SMALL LETTER I WITH GRAVE
+       replaceCharList[0x00ED] = 0x69; // i LATIN SMALL LETTER I WITH ACUTE
+       replaceCharList[0x00EE] = 0x69; // i LATIN SMALL LETTER I WITH CIRCUMFLEX
+       replaceCharList[0x00EF] = 0x69; // i LATIN SMALL LETTER I WITH DIAERESIS
+       replaceCharList[0x0129] = 0x69; // i LATIN SMALL LETTER I WITH TILDE
+       replaceCharList[0x012B] = 0x69; // i LATIN SMALL LETTER I WITH MACRON
+       replaceCharList[0x012D] = 0x69; // i LATIN SMALL LETTER I WITH BREVE
+       replaceCharList[0x012F] = 0x69; // i LATIN SMALL LETTER I WITH OGONEK
+       replaceCharList[0x01D0] = 0x69; // i LATIN SMALL LETTER I WITH CARON
+       replaceCharList[0x0131] = 0x69; // i LATIN SMALL LETTER DOTLESS I
+
+       replaceCharList[0x00CC] = 0x49; // I LATIN CAPITAL LETTER I WITH GRAVE
+       replaceCharList[0x00CD] = 0x49; // I LATIN CAPITAL LETTER I WITH ACUTE
+       replaceCharList[0x00CE] = 0x49; // I LATIN CAPITAL LETTER I WITH CIRCUMFLEX
+       replaceCharList[0x00CF] = 0x49; // I LATIN CAPITAL LETTER I WITH DIAERESIS
+       replaceCharList[0x0128] = 0x49; // I LATIN CAPITAL LETTER I WITH TILDE
+       replaceCharList[0x012A] = 0x49; // I LATIN CAPITAL LETTER I WITH MACRON
+       replaceCharList[0x012C] = 0x49; // I LATIN CAPITAL LETTER I WITH BREVE
+       replaceCharList[0x012E] = 0x49; // I LATIN CAPITAL LETTER I WITH OGONEK
+       replaceCharList[0x0130] = 0x49; // I LATIN CAPITAL LETTER I WITH DOT ABOVE
+
+       replaceCharList[0x0137] = 0x6B; // k LATIN SMALL LETTER K WITH CEDILLA
+
+       replaceCharList[0x0136] = 0x4B; // K LATIN CAPITAL LETTER K WITH CEDILLA
+
+       replaceCharList[0x013A] = 0x6C; // l LATIN SMALL LETTER L WITH ACUTE
+       replaceCharList[0x013C] = 0x6C; // l LATIN SMALL LETTER L WITH CEDILLA
+       replaceCharList[0x013E] = 0x6C; // l LATIN SMALL LETTER L WITH CARON
+       replaceCharList[0x0140] = 0x6C; // l LATIN SMALL LETTER L WITH MIDDLE DOT
+       replaceCharList[0x0142] = 0x6C; // l LATIN SMALL LETTER L WITH STROKE
+
+       replaceCharList[0x0139] = 0x4C; // L LATIN CAPITAL LETTER L WITH ACUTE
+       replaceCharList[0x013B] = 0x4C; // L LATIN CAPITAL LETTER L WITH CEDILLA
+       replaceCharList[0x013D] = 0x4C; // L LATIN CAPITAL LETTER L WITH CARON
+       replaceCharList[0x013F] = 0x4C; // L LATIN CAPITAL LETTER L WITH MIDDLE DOT
+       replaceCharList[0x0141] = 0x4C; // L LATIN CAPITAL LETTER L WITH STROKE
+
+       replaceCharList[0x00F1] = 0x6E; // n LATIN SMALL LETTER N WITH TILDE
+       replaceCharList[0x0144] = 0x6E; // n LATIN SMALL LETTER N WITH ACUTE
+       replaceCharList[0x0146] = 0x6E; // n LATIN SMALL LETTER N WITH CEDILLA
+       replaceCharList[0x0148] = 0x6E; // n LATIN SMALL LETTER N WITH CARON
+
+       replaceCharList[0x00D1] = 0x4E; // N LATIN CAPITAL LETTER N WITH TILDE
+       replaceCharList[0x0143] = 0x4E; // N LATIN CAPITAL LETTER N WITH ACUTE
+       replaceCharList[0x0145] = 0x4E; // N LATIN CAPITAL LETTER N WITH CEDILLA
+       replaceCharList[0x0147] = 0x4E; // N LATIN CAPITAL LETTER N WITH CARON
+
+       replaceCharList[0x00F2] = 0x6F; // o LATIN SMALL LETTER O WITH GRAVE
+       replaceCharList[0x00F3] = 0x6F; // o LATIN SMALL LETTER O WITH ACUTE
+       replaceCharList[0x00F4] = 0x6F; // o LATIN SMALL LETTER O WITH CIRCUMFLEX
+       replaceCharList[0x00F5] = 0x6F; // o LATIN SMALL LETTER O WITH TILDE
+       replaceCharList[0x00F6] = 0x6F; // o LATIN SMALL LETTER O WITH DIAERESIS
+       replaceCharList[0x00F8] = 0x6F; // o LATIN SMALL LETTER O WITH STROKE
+       replaceCharList[0x014D] = 0x6F; // o LATIN SMALL LETTER O WITH MACRON
+       replaceCharList[0x014F] = 0x6F; // o LATIN SMALL LETTER O WITH BREVE
+       replaceCharList[0x01D2] = 0x6F; // o LATIN SMALL LETTER O WITH CARON
+       replaceCharList[0x01EB] = 0x6F; // o LATIN SMALL LETTER O WITH OGONEK
+       replaceCharList[0x0151] = 0x6F; // o LATIN SMALL LETTER O WITH DOUBLE ACUTE
+       replaceCharList[0x0153] = 0x6F; // LATIN SMALL LIGATURE OE
+
+       replaceCharList[0x00D2] = 0x4F; // O LATIN CAPITAL LETTER O WITH GRAVE
+       replaceCharList[0x00D3] = 0x4F; // O LATIN CAPITAL LETTER O WITH ACUTE
+       replaceCharList[0x00D4] = 0x4F; // O LATIN CAPITAL LETTER O WITH CIRCUMFLEX
+       replaceCharList[0x00D5] = 0x4F; // O LATIN CAPITAL LETTER O WITH TILDE
+       replaceCharList[0x00D6] = 0x4F; // O LATIN CAPITAL LETTER O WITH DIAERESIS
+       replaceCharList[0x00D8] = 0x4F; // O LATIN CAPITAL LETTER O WITH STROKE
+       replaceCharList[0x014C] = 0x4F; // O LATIN CAPITAL LETTER O WITH MACRON
+       replaceCharList[0x014E] = 0x4F; // O LATIN CAPITAL LETTER O WITH BREVE
+       replaceCharList[0x01D1] = 0x4F; // O LATIN CAPITAL LETTER O WITH CARON
+       replaceCharList[0x01EA] = 0x4F; // O LATIN CAPITAL LETTER O WITH OGONEK
+       replaceCharList[0x0150] = 0x4F; // O LATIN CAPITAL LETTER O WITH DOUBLE ACUTE
+       replaceCharList[0x0152] = 0x4F; // LATIN CAPITAL LIGATURE OE
+
+       replaceCharList[0x0155] = 0x72; // r LATIN SMALL LETTER R WITH ACUTE
+       replaceCharList[0x0157] = 0x72; // r LATIN SMALL LETTER R WITH CEDILLA
+       replaceCharList[0x0159] = 0x72; // r LATIN SMALL LETTER R WITH CARON
+
+       replaceCharList[0x0154] = 0x52; // R LATIN CAPITAL LETTER R WITH ACUTE
+       replaceCharList[0x0156] = 0x52; // R LATIN CAPITAL LETTER R WITH CEDILLA
+       replaceCharList[0x0158] = 0x52; // R LATIN CAPITAL LETTER R WITH CARON
+
+       replaceCharList[0x015B] = 0x73; // s LATIN SMALL LETTER S WITH ACUTE
+       replaceCharList[0x015D] = 0x73; // s LATIN SMALL LETTER S WITH CIRCUMFLEX
+       replaceCharList[0x015F] = 0x73; // s LATIN SMALL LETTER S WITH CEDILLA
+       replaceCharList[0x0161] = 0x73; // s LATIN SMALL LETTER S WITH CARON
+
+       replaceCharList[0x015A] = 0x53; // S LATIN CAPITAL LETTER S WITH ACUTE
+       replaceCharList[0x015C] = 0x53; // S LATIN CAPITAL LETTER S WITH CIRCUMFLEX
+       replaceCharList[0x015E] = 0x53; // S LATIN CAPITAL LETTER S WITH CEDILLA
+       replaceCharList[0x0160] = 0x53; // S LATIN CAPITAL LETTER S WITH CARON
+
+       replaceCharList[0x00FE] = 0x74; // t LATIN CAPITAL LETTER THORN
+       replaceCharList[0x0163] = 0x74; // t LATIN SMALL LETTER T WITH CEDILLA
+       replaceCharList[0x0165] = 0x74; // t LATIN SMALL LETTER T WITH CARON
+       replaceCharList[0x0167] = 0x74; // t LATIN SMALL LETTER T WITH STROKE
+       replaceCharList[0x021B] = 0x74; // t LATIN SMALL LETTER T WITH COMMA BELOW
+
+       replaceCharList[0x00DE] = 0x54; // T LATIN CAPITAL LETTER THORN
+       replaceCharList[0x0162] = 0x54; // T LATIN CAPITAL LETTER T WITH CEDILLA
+       replaceCharList[0x0164] = 0x54; // T LATIN CAPITAL LETTER T WITH CARON
+       replaceCharList[0x0166] = 0x54; // T LATIN CAPITAL LETTER T WITH STROKE
+
+       replaceCharList[0x00F9] = 0x75; // u LATIN SMALL LETTER U WITH GRAVE
+       replaceCharList[0x00FA] = 0x75; // u LATIN SMALL LETTER U WITH ACUTE
+       replaceCharList[0x00FB] = 0x75; // u LATIN SMALL LETTER U WITH CIRCUMFLEX
+       replaceCharList[0x00FC] = 0x75; // u LATIN SMALL LETTER U WITH DIAERESIS
+       replaceCharList[0x0169] = 0x75; // u LATIN SMALL LETTER U WITH TILDE
+       replaceCharList[0x016B] = 0x75; // u LATIN SMALL LETTER U WITH MACRON
+       replaceCharList[0x016D] = 0x75; // u LATIN SMALL LETTER U WITH BREVE
+       replaceCharList[0x016F] = 0x75; // u LATIN SMALL LETTER U WITH RING ABOVE
+       replaceCharList[0x0171] = 0x75; // u LATIN SMALL LETTER U WITH DOUBLE ACUTE
+       replaceCharList[0x0173] = 0x75; // u LATIN SMALL LETTER U WITH OGONEK
+       replaceCharList[0x01D4] = 0x75; // u LATIN SMALL LETTER U WITH CARON
+
+       replaceCharList[0x00D9] = 0x55; // U LATIN CAPITAL LETTER U WITH GRAVE
+       replaceCharList[0x00DA] = 0x55; // U LATIN CAPITAL LETTER U WITH ACUTE
+       replaceCharList[0x00DB] = 0x55; // U LATIN CAPITAL LETTER U WITH CIRCUMFLEX
+       replaceCharList[0x00DC] = 0x55; // U LATIN CAPITAL LETTER U WITH DIAERESIS
+       replaceCharList[0x0168] = 0x55; // U LATIN CAPITAL LETTER U WITH TILDE
+       replaceCharList[0x016A] = 0x55; // U LATIN CAPITAL LETTER U WITH MACRON
+       replaceCharList[0x016C] = 0x55; // U LATIN CAPITAL LETTER U WITH BREVE
+       replaceCharList[0x016E] = 0x55; // U LATIN CAPITAL LETTER U WITH RING ABOVE
+       replaceCharList[0x0170] = 0x55; // U LATIN CAPITAL LETTER U WITH DOUBLE ACUTE
+       replaceCharList[0x0172] = 0x55; // U LATIN CAPITAL LETTER U WITH OGONEK
+       replaceCharList[0x01D3] = 0x55; // U LATIN CAPITAL LETTER U WITH CARON
+
+       replaceCharList[0x00FD] = 0x79; // y LATIN SMALL LETTER Y WITH ACUTE
+       replaceCharList[0x00FF] = 0x79; // y LATIN SMALL LETTER Y WITH DIAERESIS
+       replaceCharList[0x0177] = 0x79; // y LATIN SMALL LETTER Y WITH CIRCUMFLEX
+       replaceCharList[0x0233] = 0x79; // y LATIN SMALL LETTER Y WITH MACRON
+       replaceCharList[0x1EF3] = 0x79; // y LATIN SMALL LETTER Y WITH GRAVE
+       replaceCharList[0x1EF9] = 0x79; // y LATIN SMALL LETTER Y WITH TILDE
+
+       replaceCharList[0x00DD] = 0x59; // Y LATIN CAPITAL LETTER Y WITH ACUTE
+       replaceCharList[0x0176] = 0x59; // Y LATIN CAPITAL LETTER Y WITH CIRCUMFLEX
+       replaceCharList[0x0178] = 0x59; // Y LATIN CAPITAL LETTER Y WITH DIAERESIS
+       replaceCharList[0x0232] = 0x59; // Y LATIN CAPITAL LETTER Y WITH MACRON
+       replaceCharList[0x1EF2] = 0x59; // Y LATIN CAPITAL LETTER Y WITH GRAVE
+       replaceCharList[0x1EF8] = 0x59; // Y LATIN CAPITAL LETTER Y WITH TILDE
+
+       replaceCharList[0x017A] = 0x7A; // z LATIN SMALL LETTER Z WITH ACUTE
+       replaceCharList[0x017C] = 0x7A; // z LATIN SMALL LETTER Z WITH DOT ABOVE
+       replaceCharList[0x017E] = 0x7A; // z LATIN SMALL LETTER Z WITH CARON
+
+       replaceCharList[0x0179] = 0x5A; // Z LATIN CAPITAL LETTER Z WITH ACUTE
+       replaceCharList[0x017B] = 0x5A; // Z LATIN CAPITAL LETTER Z WITH DOT ABOVE
+       replaceCharList[0x017D] = 0x5A; // Z LATIN CAPITAL LETTER Z WITH CARON
+}
+
+
+MsgTextConvert::~MsgTextConvert()
+{
+       extCharList.clear();
+       ucs2toGSM7DefList.clear();
+       ucs2toGSM7ExtList.clear();
+       ucs2toTurkishList.clear();
+       ucs2toSpanishList.clear();
+       ucs2toPortuList.clear();
+       replaceCharList.clear();
+}
+
+
+MsgTextConvert* MsgTextConvert::instance()
+{
+       if (!pInstance) {
+               MSG_DEBUG("pInstance is NULL. Now creating instance.");
+               pInstance = new MsgTextConvert();
+       }
+
+       return pInstance;
+}
+
+
+int MsgTextConvert::convertUTF8ToGSM7bit(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, OUT MSG_LANGUAGE_ID_T *pLangId, OUT bool *bIncludeAbnormalChar)
+{
+       int utf8Length = 0;
+       int gsm7bitLength = 0;
+       int ucs2Length = 0;
+
+       if (srcTextLen <= 0 && pSrcText) {
+               utf8Length = strlen((char*)pSrcText);
+               srcTextLen = utf8Length;
+       } else {
+               utf8Length = srcTextLen;
+       }
+
+       int maxUCS2Length = utf8Length;         // max # of UCS2 chars, NOT bytes. when all utf8 chars are only one byte, UCS2Length is maxUCS2 Length. otherwise (ex: 2 bytes of UTF8 is one char) UCS2Length must be  less than utf8Length
+
+       WCHAR *pUCS2Text = NULL;
+       unique_ptr<WCHAR*, void(*)(WCHAR**)> buf(&pUCS2Text, unique_ptr_deleter);
+       pUCS2Text = (WCHAR *)new char[maxUCS2Length * sizeof(WCHAR)];
+       memset(pUCS2Text, 0x00, maxUCS2Length * sizeof(WCHAR));
+
+       MSG_DEBUG("srcTextLen = %d", srcTextLen);
+       MSG_DEBUG("temp buffer size = %d", maxUCS2Length * sizeof(WCHAR));
+       MSG_DEBUG("max dest Length = %d", maxLength);
+
+       ucs2Length = convertUTF8ToUCS2((unsigned char*)pUCS2Text, maxUCS2Length * sizeof(WCHAR), pSrcText, srcTextLen);
+       gsm7bitLength = convertUCS2ToGSM7bit(pDestText, maxLength, (unsigned char*)pUCS2Text, ucs2Length, pLangId, bIncludeAbnormalChar);
+
+       return gsm7bitLength;
+}
+
+
+/**
+       if srcTextLen ispSrcText should be null terminated
+return :
+               byte length of converted UCS2 characters
+                       -1 : converting error
+*/
+int MsgTextConvert::convertUTF8ToUCS2(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen)
+{
+       int textLen;
+       unsigned char *unicodeTemp = (unsigned char*)pDestText;
+       int ucs2Length = 0;
+       int remainedBuffer = maxLength;
+
+#ifdef CONVERT_DUMP
+       int srcLen = srcTextLen;
+       const unsigned char * pTempSrcText = pSrcText;
+       const unsigned char * pTempDestText = pDestText;
+#endif
+
+       if(maxLength == 0 || pSrcText == NULL || pDestText ==  NULL) {
+               MSG_DEBUG("UTF8 to UCS2 Failed as text length is 0\n");
+               return -1;
+       }
+
+       // null terminated string
+       if ( srcTextLen == -1 ) {
+               textLen = strlen((char*)pSrcText);
+               srcTextLen = textLen;
+       } else {
+               textLen = srcTextLen;
+       }
+
+       GIConv cd;
+       int err=0;
+
+       cd = g_iconv_open("UTF16BE", "UTF8");
+
+       if (cd > 0) {
+               err = g_iconv(cd, (char**)&pSrcText, (gsize*)&textLen, (char**)&unicodeTemp, (gsize*)&remainedBuffer);
+       }
+
+       if(err < 0) {
+               MSG_DEBUG("Error in g_iconv.");
+               ucs2Length = -1;
+       } else {
+               ucs2Length = maxLength - remainedBuffer;
+       }
+
+#ifdef CONVERT_DUMP
+       MSG_DEBUG("\n########## Dump UTF8 -> UCS2\n");
+       convertDumpTextToHex((unsigned char*)pTempSrcText, srcLen);
+       convertDumpTextToHex((unsigned char*)pTempDestText, ucs2Length);
+#endif
+
+       g_iconv_close(cd);
+
+       return ucs2Length;
+}
+
+#ifndef FEATURE_SMS_CDMA
+int MsgTextConvert::convertUTF8ToAuto(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, OUT MSG_LANGUAGE_ID_T *pLangId, OUT msg_encode_type_t *pCharType)
+{
+       int utf8Length = 0;
+       int gsm7bitLength = 0;
+       int ucs2Length = 0;
+
+       bool bUnknown = false;
+
+       utf8Length = srcTextLen;
+
+       int maxUCS2Length = utf8Length;         // max # of UCS2 chars, NOT bytes. when all utf8 chars are only one byte, UCS2Length is maxUCS2 Length. otherwise (ex: 2 bytes of UTF8 is one char) UCS2Length must be  less than utf8Length
+       WCHAR pUCS2Text[maxUCS2Length];
+       memset(pUCS2Text, 0x00, maxUCS2Length * sizeof(WCHAR));
+
+       MSG_DEBUG("srcTextLen = %d", srcTextLen);
+       MSG_DEBUG("temp buffer size = %d", maxUCS2Length * sizeof(WCHAR));
+       MSG_DEBUG("max dest Length = %d", maxLength);
+
+       ucs2Length = convertUTF8ToUCS2((unsigned char*)pUCS2Text, maxUCS2Length * sizeof(WCHAR), pSrcText, srcTextLen);
+
+       if(ucs2Length < 0) {
+               *pCharType = MSG_ENCODE_8BIT;
+
+               if (srcTextLen <= maxLength) {
+                       memcpy(pDestText, pSrcText, srcTextLen);
+                       return srcTextLen;
+               } else {
+                       memcpy(pDestText, pSrcText, maxLength);
+                       return maxLength;
+               }
+       } else {
+               gsm7bitLength = convertUCS2ToGSM7bit(pDestText, maxLength, (unsigned char*)pUCS2Text, ucs2Length, pLangId, &bUnknown);
+
+               if (bUnknown == true) {
+                       *pCharType = MSG_ENCODE_UCS2;
+
+                       if (ucs2Length > 0) {
+                               if(ucs2Length <= maxLength) {
+                                       memcpy(pDestText, pUCS2Text, ucs2Length);
+                                       return ucs2Length;
+                               } else {
+                                       memcpy(pDestText, pUCS2Text, maxLength);
+                                       return maxLength;
+                               }
+                       }
+               } else {
+                       *pCharType = MSG_ENCODE_GSM7BIT;
+               }
+
+               return gsm7bitLength;
+       }
+}
+#else
+
+int MsgTextConvert::convertUTF8ToAuto(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, OUT msg_encode_type_t *pCharType)
+{
+       int utf8Length = 0;
+       int gsm7bitLength = 0;
+       int ucs2Length = 0;
+
+       bool bUnknown = false;
+
+       utf8Length = srcTextLen;
+
+       int maxUCS2Length = utf8Length;         // max # of UCS2 chars, NOT bytes. when all utf8 chars are only one byte, UCS2Length is maxUCS2 Length. otherwise (ex: 2 bytes of UTF8 is one char) UCS2Length must be  less than utf8Length
+       WCHAR pUCS2Text[maxUCS2Length];
+       memset(pUCS2Text, 0x00, maxUCS2Length * sizeof(WCHAR));
+
+       MSG_DEBUG("srcTextLen = %d", srcTextLen);
+       MSG_DEBUG("temp buffer size = %d", maxUCS2Length * sizeof(WCHAR));
+       MSG_DEBUG("max dest Length = %d", maxLength);
+
+       ucs2Length = convertUTF8ToUCS2((unsigned char*)pUCS2Text, maxUCS2Length * sizeof(WCHAR), pSrcText, srcTextLen);
+
+       if(ucs2Length < 0) {
+               *pCharType = MSG_ENCODE_8BIT;
+
+               if (srcTextLen <= maxLength) {
+                       memcpy(pDestText, pSrcText, srcTextLen);
+                       return srcTextLen;
+               } else {
+                       memcpy(pDestText, pSrcText, maxLength);
+                       return maxLength;
+               }
+       } else {
+               gsm7bitLength = convertUCS2ToASCII(pDestText, maxLength, (unsigned char*)pUCS2Text, ucs2Length, &bUnknown);
+
+               if (bUnknown == true) {
+                       *pCharType = MSG_ENCODE_UCS2;
+
+                       if (ucs2Length > 0) {
+                               if (ucs2Length <= maxLength) {
+                                       memcpy(pDestText, pUCS2Text, ucs2Length);
+                                       return ucs2Length;
+                               } else {
+                                       memcpy(pDestText, pUCS2Text, maxLength);
+                                       return maxLength;
+                               }
+                       }
+               } else {
+                       *pCharType = MSG_ENCODE_ASCII7BIT;
+               }
+
+               return gsm7bitLength;
+       }
+}
+#endif
+
+/**
+return:
+               bytelength of UTF8 text
+*/
+int MsgTextConvert::convertGSM7bitToUTF8(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, IN MSG_LANG_INFO_S *pLangInfo)
+{
+       int utf8Length = 0;
+       int ucs2Length = 0;
+       int maxUCS2Length = srcTextLen;         // max # of UCS2 chars, NOT bytes. when all gsm7 chars are only one byte(-there is no extenstion), UCS2Length is maxUCS2 Length. otherwise(ex: gsm7 char starts with 0x1b) UCS2Length must be less than gsm7 legnth
+
+       WCHAR pUCS2Text[maxUCS2Length];
+       memset(pUCS2Text, 0x00, maxUCS2Length * sizeof(WCHAR));
+
+       MSG_DEBUG("srcTextLen = %d\n", srcTextLen);
+       MSG_DEBUG("max dest Length = %d\n", maxLength);
+
+       ucs2Length = convertGSM7bitToUCS2((unsigned char*)pUCS2Text, maxUCS2Length * sizeof(WCHAR), pSrcText, srcTextLen, pLangInfo);
+       utf8Length = convertUCS2ToUTF8(pDestText, maxLength, (unsigned char*)pUCS2Text, ucs2Length);
+
+       return utf8Length;
+}
+
+
+/**
+args:
+       OUT unsigned char *pDestText
+       IN int maxLength                : max byte length of destination text
+       IN const unsigned char *pSrcText
+       IN  int srcTextLen              : byte length of UCS2 source text
+return :
+               byte length of converted UTF8 characters
+                       -1 : The alpha isn't the gsm 7bit code
+*/
+int MsgTextConvert::convertUCS2ToUTF8(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN  int srcTextLen)
+{
+       int remainedBuffer = maxLength;
+       int utf8Length;
+
+#ifdef CONVERT_DUMP
+       int srcLen = srcTextLen;
+       const unsigned char *pTempSrcText = pSrcText;
+#endif
+       unsigned char *pTempDestText = pDestText;
+
+       if (srcTextLen == 0 || pSrcText == NULL || pDestText ==  NULL || maxLength == 0) {
+               MSG_ERR("UCS2 to UTF8 Failed as text length is 0\n");
+               return false;
+       }
+
+       GIConv cd;
+       int err = 0;
+
+       cd = g_iconv_open( "UTF8", "UTF16BE" );
+
+       if (cd > 0) {
+               err = g_iconv(cd, (char**)&pSrcText, (gsize*)&srcTextLen, (char**)&pDestText, (gsize*)&remainedBuffer);
+       }
+
+       if (err != 0)
+               MSG_ERR("g_iconv() return value = %d", err);
+
+       utf8Length = maxLength - remainedBuffer;
+       pTempDestText[utf8Length] = 0x00;
+
+#ifdef CONVERT_DUMP
+       MSG_DEBUG("\n########## Dump UCS2 -> UTF8\n");
+       convertDumpTextToHex((unsigned char*)pTempSrcText, srcLen);
+       convertDumpTextToHex((unsigned char*)pTempDestText, utf8Length);
+#endif
+
+       g_iconv_close(cd);
+
+       return utf8Length;
+}
+
+
+int MsgTextConvert::convertEUCKRToUTF8(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN  int srcTextLen)
+{
+       int remainedBuffer = maxLength;
+       int utf8Length;
+
+#ifdef CONVERT_DUMP
+       int srcLen = srcTextLen;
+       const unsigned char * pTempSrcText = pSrcText;
+#endif
+       unsigned char * pTempDestText = pDestText;
+
+       if(srcTextLen == 0 || pSrcText == NULL || pDestText ==  NULL || maxLength == 0) {
+               MSG_DEBUG("EUCKR to UTF8 Failed as text length is 0\n");
+               return false;
+       }
+
+       GIConv cd;
+       int err=0;
+
+       cd = g_iconv_open( "UTF8", "EUCKR" );
+
+       if (cd > 0) {
+               err = g_iconv(cd, (char**)&pSrcText, (gsize*)&srcTextLen, (char**)&pDestText, (gsize*)&remainedBuffer);
+       }
+
+       MSG_DEBUG("g_iconv() return value = %d", err);
+
+       utf8Length = maxLength - remainedBuffer;
+       pTempDestText[utf8Length] = 0x00;
+
+#ifdef CONVERT_DUMP
+       MSG_DEBUG("\n########## Dump EUCKR -> UTF8\n");
+       convertDumpTextToHex((unsigned char*)pTempSrcText, srcLen);
+       convertDumpTextToHex((unsigned char*)pTempDestText, utf8Length);
+#endif
+
+       g_iconv_close(cd);
+
+       return utf8Length;
+}
+
+
+int MsgTextConvert::convertSHIFTJISToUTF8(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN  int srcTextLen)
+{
+       int remainedBuffer = maxLength;
+       int utf8Length;
+
+#ifdef CONVERT_DUMP
+       int srcLen = srcTextLen;
+       const unsigned char * pTempSrcText = pSrcText;
+#endif
+       unsigned char * pTempDestText = pDestText;
+
+       if(srcTextLen == 0 || pSrcText == NULL || pDestText ==  NULL || maxLength == 0) {
+               MSG_DEBUG("EUCKR to UTF8 Failed as text length is 0\n");
+               return false;
+       }
+
+       GIConv cd;
+       int err=0;
+
+       cd = g_iconv_open( "UTF8", "SHIFT-JIS" );
+
+       if (cd > 0) {
+               err = g_iconv(cd, (char**)&pSrcText, (gsize*)&srcTextLen, (char**)&pDestText, (gsize*)&remainedBuffer);
+       }
+
+       MSG_DEBUG("g_iconv() return value = %d", err);
+
+       utf8Length = maxLength - remainedBuffer;
+       pTempDestText[utf8Length] = 0x00;
+
+#ifdef CONVERT_DUMP
+       MSG_DEBUG("\n########## Dump SHIFT-JIS -> UTF8\n");
+       convertDumpTextToHex((unsigned char*)pTempSrcText, srcLen);
+       convertDumpTextToHex((unsigned char*)pTempDestText, utf8Length);
+#endif
+
+       g_iconv_close(cd);
+
+       return utf8Length;
+}
+
+
+/**
+
+args:
+               unsigned char *pDestText
+               int maxLength                           : max destination buffer size
+               const unsigned char *pSrcText
+               int srcTextLen                          : BYTE length of src text (UCS2)
+return:
+               bytelength of gsm7bit text
+               -1 : converting error
+*/
+int MsgTextConvert::convertUCS2ToGSM7bit(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, OUT MSG_LANGUAGE_ID_T *pLangId, OUT bool *bIncludeAbnormalChar)
+{
+       // for UNICODE
+       int outTextLen = 0;
+       unsigned char lowerByte, upperByte;
+
+       if (srcTextLen == 0 || pSrcText == NULL || pDestText ==  NULL || maxLength == 0) {
+               MSG_DEBUG("Invalid parameter.");
+               return -1;
+       }
+
+       std::map<unsigned short, unsigned char>::iterator itChar;
+       std::map<unsigned short, unsigned char>::iterator itExt;
+       std::map<unsigned short, unsigned char>::iterator itReplace;
+
+       MSG_CHAR_TYPE_T currType = MSG_CHAR_DEFAULT;
+       MSG_CHAR_TYPE_T newType = MSG_CHAR_DEFAULT;
+
+       unsigned short inText;
+
+       // Get Language Type by checking each character
+       for (int index = 0; index < srcTextLen; index++)
+       {
+               upperByte = pSrcText[index++];
+               lowerByte = pSrcText[index];
+
+               inText = (upperByte << 8) & 0xFF00;
+
+               inText = inText | lowerByte;
+
+               itExt = extCharList.find(inText);
+
+               if (itExt != extCharList.end()) {
+                       newType = (MSG_CHAR_TYPE_T)itExt->second;
+
+                       if (newType >= currType) {
+                               if (inText == 0x00e7 && currType <= MSG_CHAR_TURKISH)
+                                       currType = MSG_CHAR_TURKISH;
+                               else
+                                       currType = newType;
+                       }
+               }
+       }
+
+       MSG_DEBUG("charType : [%d]", currType);
+
+       for (int index = 0; index < srcTextLen; index++)
+       {
+               upperByte = pSrcText[index++];
+               lowerByte = pSrcText[index];
+
+               inText = (upperByte << 8) & 0xFF00;
+               inText = inText | lowerByte;
+
+               // Check Default Char
+               itChar = ucs2toGSM7DefList.find(inText);
+
+               if (itChar != ucs2toGSM7DefList.end()) {
+                       pDestText[outTextLen++] = (unsigned char)itChar->second;
+               } else {
+                       if (currType == MSG_CHAR_GSM7EXT) {
+                               itExt = ucs2toGSM7ExtList.find(inText);
+
+                               if (itExt != ucs2toGSM7ExtList.end()) {
+                                       // prevent buffer overflow
+                                       if (maxLength <= outTextLen + 1) {
+                                               MSG_DEBUG("Buffer Full.");
+                                               break;
+                                       }
+
+                                       pDestText[outTextLen++] = 0x1B;
+                                       pDestText[outTextLen++] = (unsigned char)itExt->second;
+                               } else {
+                                       itReplace = replaceCharList.find(inText);
+                                       if (itReplace != replaceCharList.end()) {
+                                               pDestText[outTextLen++] = (unsigned char)itReplace->second;
+                                       } else {
+                                               pDestText[outTextLen++] = 0x3F;
+                                       }
+                                       *bIncludeAbnormalChar = true;
+                                       MSG_DEBUG("Abnormal character is included. inText : [%04x]", inText);
+                               }
+                       } else if (currType == MSG_CHAR_TURKISH) {
+                               *pLangId = MSG_LANG_ID_TURKISH;
+
+                               itExt = ucs2toTurkishList.find(inText);
+
+                               if (itExt != ucs2toTurkishList.end()) {
+                                       // prevent buffer overflow
+                                       if (maxLength <= outTextLen + 1) {
+                                               MSG_DEBUG("Buffer Full.");
+                                               break;
+                                       }
+
+                                       pDestText[outTextLen++] = 0x1B;
+                                       pDestText[outTextLen++] = (unsigned char)itExt->second;
+                               } else {
+                                       itReplace = replaceCharList.find(inText);
+                                       if (itReplace != replaceCharList.end()) {
+                                               pDestText[outTextLen++] = (unsigned char)itReplace->second;
+                                       } else {
+                                               pDestText[outTextLen++] = 0x3F;
+                                       }
+                                       *bIncludeAbnormalChar = true;
+                                       MSG_DEBUG("Abnormal character is included. inText : [%04x]", inText);
+                               }
+                       } else if (currType == MSG_CHAR_SPANISH) {
+                               *pLangId = MSG_LANG_ID_SPANISH;
+
+                               itExt = ucs2toSpanishList.find(inText);
+
+                               if (itExt != ucs2toSpanishList.end()) {
+                                       // prevent buffer overflow
+                                       if (maxLength <= outTextLen + 1) {
+                                               MSG_DEBUG("Buffer Full.");
+                                               break;
+                                       }
+
+                                       pDestText[outTextLen++] = 0x1B;
+                                       pDestText[outTextLen++] = (unsigned char)itExt->second;
+                               } else {
+                                       itReplace = replaceCharList.find(inText);
+                                       if (itReplace != replaceCharList.end()) {
+                                               pDestText[outTextLen++] = (unsigned char)itReplace->second;
+                                       } else {
+                                               pDestText[outTextLen++] = 0x3F;
+                                       }
+                                       *bIncludeAbnormalChar = true;
+                                       MSG_DEBUG("Abnormal character is included. inText : [%04x]", inText);
+                               }
+                       } else if (currType == MSG_CHAR_PORTUGUESE) {
+                               *pLangId = MSG_LANG_ID_PORTUGUESE;
+
+                               itExt = ucs2toPortuList.find(inText);
+
+                               if (itExt != ucs2toPortuList.end()) {
+                                       // prevent buffer overflow
+                                       if (maxLength <= outTextLen + 1) {
+                                               MSG_DEBUG("Buffer Full.");
+                                               break;
+                                       }
+
+                                       pDestText[outTextLen++] = 0x1B;
+                                       pDestText[outTextLen++] = (unsigned char)itExt->second;
+                               } else {
+                                       itReplace = replaceCharList.find(inText);
+                                       if (itReplace != replaceCharList.end()) {
+                                               pDestText[outTextLen++] = (unsigned char)itReplace->second;
+                                       } else {
+                                               pDestText[outTextLen++] = 0x3F;
+                                       }
+                                       *bIncludeAbnormalChar = true;
+                                       MSG_DEBUG("Abnormal character is included. inText : [%04x]", inText);
+                               }
+                       } else {
+                               itReplace = replaceCharList.find(inText);
+                               if (itReplace != replaceCharList.end()) {
+                                       pDestText[outTextLen++] = (unsigned char)itReplace->second;
+                               } else {
+                                       pDestText[outTextLen++] = 0x3F;
+                               }
+                               *bIncludeAbnormalChar = true;
+                               MSG_DEBUG("Abnormal character is included. inText : [%04x]", inText);
+                       }
+               }
+
+               // prevent buffer overflow
+               if (maxLength <= outTextLen) {
+                       MSG_DEBUG("Buffer full.");
+                       break;
+               }
+       }
+
+#ifdef CONVERT_DUMP
+       MSG_DEBUG("\n########## Dump UCS2 -> GSM7bit\n");
+       convertDumpTextToHex((unsigned char*)pSrcText, srcTextLen);
+       convertDumpTextToHex((unsigned char*)pDestText, outTextLen);
+#endif
+
+       return outTextLen;
+}
+
+
+int MsgTextConvert::convertUCS2ToASCII(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, OUT bool *pUnknown)
+{
+       // for UNICODE
+       int outTextLen = 0;
+       unsigned char lowerByte, upperByte;
+
+       if (srcTextLen == 0 || pSrcText == NULL || pDestText ==  NULL || maxLength == 0) {
+               MSG_DEBUG("UCS2 to GSM7bit Failed as text length is 0\n");
+               return -1;
+       }
+
+       std::map<unsigned short, unsigned char>::iterator itChar;
+       std::map<unsigned short, unsigned char>::iterator itExt;
+
+       unsigned short inText;
+
+       for (int index = 0; index < srcTextLen; index++)
+       {
+               upperByte = pSrcText[index++];
+               lowerByte = pSrcText[index];
+
+               inText = (upperByte << 8) & 0xFF00;
+               inText = inText | lowerByte;
+
+               // Check Default Char
+               if (inText > 0x007f) {
+                       MSG_DEBUG("Abnormal character is included. inText : [%04x]", inText);
+                       *pUnknown = true;
+                       return 0;
+               }
+
+               pDestText[outTextLen++] = (unsigned char)inText;
+
+               // prevent buffer overflow
+               if (maxLength <= outTextLen) {
+                       MSG_DEBUG("Buffer full\n");
+                       break;
+               }
+
+       }
+
+#ifdef CONVERT_DUMP
+       MSG_DEBUG("\n########## Dump UCS2 -> GSM7bit\n");
+       convertDumpTextToHex((unsigned char*)pSrcText, srcTextLen);
+       convertDumpTextToHex((unsigned char*)pDestText, outTextLen);
+#endif
+
+       return outTextLen;
+}
+
+
+/**
+ args :
+               unsigned char *pDestText                                : destination text (UCS2) - byte order depends on local byte order
+               const unsigned char *pSrcText           : source text (gsm7bit)
+               int maxLength                   : max destination buffer size
+               int srcTextLen                  : byte length of source text (gsm7bit)
+ return :
+               byte length of converted UCS2 characters
+                       -1 : The alpha isn't the gsm 7bit code
+*/
+int MsgTextConvert::convertGSM7bitToUCS2(OUT unsigned char *pDestText, IN int maxLength, IN const unsigned char *pSrcText, IN int srcTextLen, IN MSG_LANG_INFO_S *pLangInfo)
+{
+       int outTextLen = 0;
+       unsigned char lowerByte = 0, upperByte = 0;
+
+       if (srcTextLen == 0 || pSrcText == NULL || pDestText ==  NULL || maxLength == 0) {
+               MSG_ERR("UCS2 to GSM7bit Failed as text length is 0\n");
+               return -1;
+       }
+
+       for (int i = 0; i<srcTextLen; i++)
+       {
+               if (maxLength == 0) {
+                       break;
+               }
+
+               if (pSrcText[i] >= 0x80) {
+                       //error
+                       MSG_ERR(">>>>>>>a_pTextString[i]=%x, The alpha isn't the gsm 7bit code, Never Come here!!!\n", pSrcText[i]);
+                       return -1;
+               }
+
+               if (pLangInfo->bLockingShift == true) { // National Language Locking Shift
+                       MSG_DEBUG("Locking Shift [%d]", pLangInfo->lockingLang);
+
+                       if (pLangInfo->lockingLang == MSG_LANG_ID_TURKISH) {
+                               // Check Escape
+                               if (g_TurkishLockingToUCS2[pSrcText[i]] == 0x001B) {
+                                       i++;
+
+                                       if (pLangInfo->bSingleShift == true) { // National Language Single Shift
+                                               MSG_DEBUG("Single Shift [%d]", pLangInfo->singleLang);
+
+                                               if (pLangInfo->singleLang == MSG_LANG_ID_TURKISH) {
+                                                       lowerByte = g_TurkishSingleToUCS2[pSrcText[i]] & 0x00FF;
+                                                       upperByte = (g_TurkishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                               } else if (pLangInfo->singleLang == MSG_LANG_ID_SPANISH) {
+                                                       lowerByte = g_SpanishSingleToUCS2[pSrcText[i]] & 0x00FF;
+                                                       upperByte = (g_SpanishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                               } else if (pLangInfo->singleLang == MSG_LANG_ID_PORTUGUESE) {
+                                                       lowerByte = g_PortuSingleToUCS2[pSrcText[i]] & 0x00FF;
+                                                       upperByte = (g_PortuSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                               } else {
+                                                       lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
+                                                       upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                               }
+                                       } else { // GSM 7 bit Default Alphabet Extension Table
+                                               lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
+                                               upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                       }
+                               } else { // TURKISH - National Language Locking Shift
+                                       lowerByte = g_TurkishLockingToUCS2[pSrcText[i]] & 0x00FF;
+                                       upperByte = (g_TurkishLockingToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                               }
+                       } else if (pLangInfo->lockingLang == MSG_LANG_ID_PORTUGUESE) {
+                               // Check Escape
+                               if (g_PortuLockingToUCS2[pSrcText[i]] == 0x001B) {
+                                       i++;
+
+                                       if (pLangInfo->bSingleShift == true) { // National Language Single Shift
+                                               MSG_DEBUG("Single Shift [%d]", pLangInfo->singleLang);
+
+                                               if (pLangInfo->singleLang == MSG_LANG_ID_TURKISH) {
+                                                       lowerByte = g_TurkishSingleToUCS2[pSrcText[i]] & 0x00FF;
+                                                       upperByte = (g_TurkishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                               } else if (pLangInfo->singleLang == MSG_LANG_ID_SPANISH) {
+                                                       lowerByte = g_SpanishSingleToUCS2[pSrcText[i]] & 0x00FF;
+                                                       upperByte = (g_SpanishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                               } else if (pLangInfo->singleLang == MSG_LANG_ID_PORTUGUESE) {
+                                                       lowerByte = g_PortuSingleToUCS2[pSrcText[i]] & 0x00FF;
+                                                       upperByte = (g_PortuSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                               } else {
+                                                       lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
+                                                       upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                               }
+                                       } else { // GSM 7 bit Default Alphabet Extension Table
+                                               lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
+                                               upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                       }
+                               } else { // PORTUGUESE - National Language Locking Shift
+                                       lowerByte = g_PortuLockingToUCS2[pSrcText[i]] & 0x00FF;
+                                       upperByte = (g_PortuLockingToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                               }
+                       }
+               } else {
+                       // Check Escape
+                       if (g_GSM7BitToUCS2[pSrcText[i]] == 0x001B) {
+                               i++;
+
+                               if (pLangInfo->bSingleShift == true) { // National Language Single Shift
+                                       MSG_DEBUG("Single Shift [%d]", pLangInfo->singleLang);
+
+                                       if (pLangInfo->singleLang == MSG_LANG_ID_TURKISH) {
+                                               lowerByte = g_TurkishSingleToUCS2[pSrcText[i]] & 0x00FF;
+                                               upperByte = (g_TurkishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                       } else if (pLangInfo->singleLang == MSG_LANG_ID_SPANISH) {
+                                               lowerByte = g_SpanishSingleToUCS2[pSrcText[i]] & 0x00FF;
+                                               upperByte = (g_SpanishSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                       } else if (pLangInfo->singleLang == MSG_LANG_ID_PORTUGUESE) {
+                                               lowerByte = g_PortuSingleToUCS2[pSrcText[i]] & 0x00FF;
+                                               upperByte = (g_PortuSingleToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                       } else {
+                                               lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
+                                               upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                                       }
+                               } else { // GSM 7 bit Default Alphabet Extension Table
+                                       lowerByte = g_GSM7BitExtToUCS2[pSrcText[i]] & 0x00FF;
+                                       upperByte = (g_GSM7BitExtToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                               }
+                       } else {
+                               lowerByte = g_GSM7BitToUCS2[pSrcText[i]] & 0x00FF;
+                               upperByte = (g_GSM7BitToUCS2[pSrcText[i]] & 0xFF00) >> 8;
+                       }
+               }
+
+               pDestText[outTextLen++] = upperByte;
+               pDestText[outTextLen++] = lowerByte;
+               maxLength -= 2;
+       }
+
+#ifdef CONVERT_DUMP
+       MSG_DEBUG("\n########## Dump GSM7bit -> UCS2\n");
+       convertDumpTextToHex((unsigned char*)pSrcText, srcTextLen);
+       convertDumpTextToHex((unsigned char*)pDestText, outTextLen);
+#endif
+
+       return outTextLen;
+}
+
+
+void MsgTextConvert::convertDumpTextToHex(const unsigned char *pText, int length)
+{
+       MSG_DEBUG("=======================================");
+       MSG_DEBUG("   Dump Text To Hex - Length :%d\n", length);
+       MSG_DEBUG("=======================================");
+
+       for (int i = 0; i < length; i++ )
+       {
+               MSG_DEBUG("[%02x]", pText[i]);
+       }
+
+       MSG_DEBUG("=======================================");
+}
index b8deb33..857890c 100755 (executable)
@@ -1,17 +1,17 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include <stdio.h>
@@ -23,6 +23,8 @@
 #include <string.h>
 #include <dirent.h>
 #include <unistd.h>    //sync()
+#include <fcntl.h>
+#include <libgen.h>
 
 #include "MsgStorageTypes.h"
 #include "MsgDebug.h"
@@ -44,7 +46,7 @@ FILE *MsgOpenFile(const char *filepath, const char *opt)
                return NULL;
        }
 
-       MSG_DEBUG("[FILE] filepath : [%s], opt [%s]", filepath, opt);
+       MSG_SEC_DEBUG("[FILE] filepath : [%s], opt [%s]", filepath, opt);
 
        FILE *pFile = NULL;
 
@@ -199,7 +201,7 @@ bool MsgCreateFileName(char *pFileName)
 
        try {
                if (clock_gettime(CLOCK_REALTIME, &ts) < 0) {
-                       MSG_DEBUG("clock_gettime() error: %s", strerror(errno));
+                       MSG_DEBUG("clock_gettime() error: %s", g_strerror(errno));
                        return false;
                }
 
@@ -221,26 +223,31 @@ bool MsgCreateFileName(char *pFileName)
 
 bool MsgOpenAndReadFile(const char *pFileName, char **ppData, int *pDataSize)
 {
+       if (!pFileName || !ppData || !pDataSize) {
+               MSG_ERR("Invalid params!! pFileName=%x, ppData=%x, pDataSize=%x", pFileName, ppData, pDataSize);
+               return false;
+       }
+
        MSG_DEBUG("MsgOpenAndReadFile");
 
        FILE *pFile = NULL;
 
        char fullPath[MAX_FULL_PATH_SIZE] = {0};
 
-       snprintf(fullPath, MAX_FULL_PATH_SIZE, MSG_IPC_DATA_PATH"%s", pFileName);
-       MSG_DEBUG("open file name: %s", fullPath);
+       snprintf(fullPath, MAX_FULL_PATH_SIZE, "%s%s", MSG_IPC_DATA_PATH, pFileName);
+       MSG_SEC_DEBUG("open file name: %s", fullPath);
 
 
        pFile = MsgOpenFile(fullPath, "rb");
 
        if (pFile == NULL) {
-               MSG_DEBUG("File Open Error: %s", strerror(errno));
+               MSG_DEBUG("File Open Error: %s", g_strerror(errno));
                return false;
        }
 
        if (MsgFseek(pFile, 0L, SEEK_END) < 0) {
                MsgCloseFile(pFile);
-               MSG_DEBUG("File Read Error: %s", strerror(errno));
+               MSG_DEBUG("File Read Error: %s", g_strerror(errno));
                return false;
        }
 
@@ -253,17 +260,18 @@ bool MsgOpenAndReadFile(const char *pFileName, char **ppData, int *pDataSize)
                return false;
        }
 
-       *ppData = new char[FileSize];
+       *ppData = new char[FileSize+1];
+       memset(*ppData, 0x00, (FileSize+1));
 
        if (MsgFseek(pFile, 0L, SEEK_SET) < 0) {
                MsgCloseFile(pFile);
-               MSG_DEBUG("File seek Error: %s", strerror(errno));
+               MSG_DEBUG("File seek Error: %s", g_strerror(errno));
                return false;
        }
 
        if (MsgReadFile(*ppData, sizeof(char), FileSize, pFile) != (size_t)FileSize) {
                MsgCloseFile(pFile);
-               MSG_DEBUG("File Read Error: %s", strerror(errno));
+               MSG_DEBUG("File Read Error: %s", g_strerror(errno));
                return false;
        }
 
@@ -280,7 +288,7 @@ bool MsgReadFileForDecode(FILE *pFile, char *pBuf, int length, int *nSize)
        MSG_BEGIN();
 
        if (MsgFseek(pFile, 0L, SEEK_CUR) < 0) {
-               MSG_DEBUG("File Seek Error: %s", strerror(errno));
+               MSG_DEBUG("File Seek Error: %s", g_strerror(errno));
                MsgCloseFile(pFile);
                return false;
        }
@@ -301,36 +309,36 @@ bool MsgWriteIpcFile(const char *pFileName, const char *pData, int DataSize)
 
        char fullPath[MAX_FULL_PATH_SIZE] = {0};
 
-       snprintf(fullPath, MAX_FULL_PATH_SIZE, MSG_IPC_DATA_PATH"%s", pFileName);
+       snprintf(fullPath, MAX_FULL_PATH_SIZE, "%s%s", MSG_IPC_DATA_PATH, pFileName);
 
        FILE *pFile = MsgOpenFile(fullPath, "wb+");
 
        if (pFile == NULL) {
-               MSG_DEBUG("File Open Error: %s", strerror(errno));
+               MSG_DEBUG("File Open Error: %s", g_strerror(errno));
                return false;
        }
 
        if (MsgFseek(pFile, 0L, SEEK_SET) < 0) {
                MsgCloseFile(pFile);
-               MSG_DEBUG("File Seek Error: %s", strerror(errno));
+               MSG_DEBUG("File Seek Error: %s", g_strerror(errno));
                return false;
        }
 
        if (MsgWriteFile(pData, sizeof(char), DataSize, pFile) != (size_t)DataSize) {
                MsgCloseFile(pFile);
-               MSG_DEBUG("File Write Error: %s", strerror(errno));
+               MSG_DEBUG("File Write Error: %s", g_strerror(errno));
                return false;
        }
 
        MsgFflush(pFile);
        MsgCloseFile(pFile);
 
-       if (chmod(fullPath, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP ) != 0) {
-               MSG_DEBUG("File chmod Error: %s", strerror(errno));
+       if (MsgChmod(fullPath, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP ) == false) {
+               MSG_DEBUG("File chmod Error: %s", g_strerror(errno));
        }
 
-       if (chown(fullPath, 0, 6502 ) != 0) {
-               MSG_DEBUG("File chown Error: %s", strerror(errno));
+       if (MsgChown(fullPath, 0, 6502 ) == false) {
+               MSG_DEBUG("File chown Error: %s", g_strerror(errno));
        }
 
        return true;
@@ -346,20 +354,20 @@ int MsgReadSmilFile(const char *pFileName, char **ppData)
        int     nSize = 0;
        char fullPath[MAX_FULL_PATH_SIZE] = {0};
 
-       snprintf(fullPath, MAX_FULL_PATH_SIZE, MSG_SMIL_FILE_PATH"%s", pFileName);
+       snprintf(fullPath, MAX_FULL_PATH_SIZE, "%s%s", MSG_SMIL_FILE_PATH, pFileName);
 
-       MSG_DEBUG("open file name: %s", fullPath);
+       MSG_SEC_DEBUG("open file name: %s", fullPath);
 
        FILE *pFile = MsgOpenFile(fullPath, "rb");
 
        if (pFile == NULL) {
-               MSG_DEBUG("File Open Error: %s", strerror(errno));
+               MSG_DEBUG("File Open Error: %s", g_strerror(errno));
                return -1;
        }
 
        if (MsgFseek(pFile, 0L, SEEK_END) < 0) {
                MsgCloseFile(pFile);
-               MSG_DEBUG("File Seek Error: %s", strerror(errno));
+               MSG_DEBUG("File Seek Error: %s", g_strerror(errno));
                return -1;
        }
 
@@ -372,23 +380,23 @@ int MsgReadSmilFile(const char *pFileName, char **ppData)
        }
 
        *ppData = new char[FileSize + 1];
+       memset(*ppData, 0x00, (FileSize+1));
 
        if (MsgFseek(pFile, 0L, SEEK_SET) < 0) {
                MsgCloseFile(pFile);
-               MSG_DEBUG("File Sead Error: %s", strerror(errno));
+               MSG_DEBUG("File Sead Error: %s", g_strerror(errno));
                return -1;
        }
 
        if (MsgReadFile(*ppData, sizeof(char), FileSize, pFile) != (size_t)FileSize) {
                MsgCloseFile(pFile);
-               MSG_DEBUG("File Read Error: %s", strerror(errno));
+               MSG_DEBUG("File Read Error: %s", g_strerror(errno));
                return -1;
        }
 
-       ppData[FileSize] = '\0';
+       //ppData[FileSize] = '\0';
 
        nSize = FileSize;
-
        MsgCloseFile(pFile);
 
        return nSize;
@@ -404,28 +412,28 @@ bool MsgWriteSmilFile(const char *pFilePath,char *pData, int DataSize)
 
        if (mkdir(MSG_SMIL_FILE_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
                if (errno == EEXIST) {
-                       MSG_DEBUG("The %s already exists", MSG_SMIL_FILE_PATH);
+                       MSG_SEC_DEBUG("The %s already exists", MSG_SMIL_FILE_PATH);
                } else {
-                       MSG_DEBUG("Error while mkdir %s", MSG_SMIL_FILE_PATH);
+                       MSG_SEC_DEBUG("Error while mkdir %s", MSG_SMIL_FILE_PATH);
                }
        }
 
        FILE *pFile = MsgOpenFile(pFilePath, "wb+");
 
        if (pFile == NULL) {
-               MSG_DEBUG("File Open Error: %s", strerror(errno));
+               MSG_DEBUG("File Open Error: %s", g_strerror(errno));
                return false;
        }
 
        if (MsgFseek(pFile, 0L, SEEK_SET) < 0) {
                MsgCloseFile(pFile);
-               MSG_DEBUG("File Seek Error: %s", strerror(errno));
+               MSG_DEBUG("File Seek Error: %s", g_strerror(errno));
                return false;
        }
 
        if (MsgWriteFile(pData, sizeof(char), DataSize, pFile) != (size_t)DataSize) {
                MsgCloseFile(pFile);
-               MSG_DEBUG("File Write Error: %s", strerror(errno));
+               MSG_DEBUG("File Write Error: %s", g_strerror(errno));
                return false;
        }
 
@@ -451,12 +459,12 @@ void MsgDeleteFile(const char *pFileName)
        char fullPath[MAX_FULL_PATH_SIZE] = {0};
 
        try {
-               snprintf(fullPath, MAX_FULL_PATH_SIZE, MSG_IPC_DATA_PATH"%s", pFileName);
+               snprintf(fullPath, MAX_FULL_PATH_SIZE, "%s%s", MSG_IPC_DATA_PATH, pFileName);
 
                MSG_DEBUG("%s", fullPath);
 
                if (remove(fullPath) != 0)
-                       MSG_FATAL("File Delete Error [%s]: %s", fullPath, strerror(errno));
+                       MSG_FATAL("File Delete Error [%s]: %s", fullPath, g_strerror(errno));
        } catch (exception &e) {
                MSG_FATAL ("%s", e.what());
        }
@@ -474,10 +482,10 @@ void MsgDeleteSmilFile(const char *pFileName)
        try {
                char fullPath[MAX_FULL_PATH_SIZE] = {0};
 
-               snprintf(fullPath, MAX_FULL_PATH_SIZE, MSG_SMIL_FILE_PATH"%s", pFileName);
+               snprintf(fullPath, MAX_FULL_PATH_SIZE, "%s%s", MSG_SMIL_FILE_PATH, pFileName);
 
                if (remove(fullPath) != 0)
-                       MSG_FATAL("File Delete Error [%s]: %s", fullPath, strerror(errno));
+                       MSG_FATAL("File Delete Error [%s]: %s", fullPath, g_strerror(errno));
        } catch (exception &e) {
                MSG_FATAL("%s", e.what());
        }
@@ -496,13 +504,13 @@ bool MsgGetFileSize(const char *pFilePath, int *nSize)
        pFile = MsgOpenFile(pFilePath, "rb");
 
        if (!pFile) {
-               MSG_DEBUG("File Open error: %s", strerror(errno));
+               MSG_DEBUG("File Open error: %s", g_strerror(errno));
                return false;
        }
 
        if (MsgFseek(pFile, 0L, SEEK_END) < 0) {
                MsgCloseFile(pFile);
-               MSG_FATAL("File Read Error: %s", strerror(errno));
+               MSG_FATAL("File Read Error: %s", g_strerror(errno));
                return false;
        }
 
@@ -519,7 +527,7 @@ FILE *MsgOpenMMSFile(char *pFileName)
        int len;
 
        if (!pFileName) {
-               MSG_DEBUG("pFileName NULL: %s", strerror(errno));
+               MSG_DEBUG("pFileName NULL: %s", g_strerror(errno));
                return NULL;
        }
 
@@ -542,13 +550,13 @@ FILE *MsgOpenMMSFile(char *pFileName)
        FILE *pFile = MsgOpenFile(fullPath, "wb+");
 
        if (pFile == NULL) {
-               MSG_FATAL("File Open Error: %s", strerror(errno));
+               MSG_FATAL("File Open Error: %s", g_strerror(errno));
                return NULL;
        }
 
        if (MsgFseek(pFile, 0L, SEEK_CUR) < 0) {
                MsgCloseFile(pFile);
-               MSG_DEBUG("File Read Error: %s", strerror(errno));
+               MSG_DEBUG("File Read Error: %s", g_strerror(errno));
                return NULL;
        }
 
@@ -618,8 +626,8 @@ bool MsgOpenCreateAndOverwriteFile(char *pFullPath, char *pBuff, int TotalLength
        MsgFflush(pFile);
        MsgCloseFile(pFile);
 
-       if (chmod(pFullPath, file_mode) < 0)
-               MSG_FATAL("File chmod Error: %s", strerror(errno));
+       if (!MsgChmod(pFullPath, file_mode))
+               MSG_FATAL("File chmod Error: %s", g_strerror(errno));
 
        return true;
 }
@@ -641,7 +649,7 @@ char *MsgOpenAndReadMmsFile( const char *szFilePath, int offset, int size, int *
        pFile = MsgOpenFile( szFilePath, "rb" );
 
        if (pFile == NULL) {
-               MSG_DEBUG("MsgOpenAndReadMmsFile: [ERROR] Can't open filepath", strerror(errno));
+               MSG_DEBUG("MsgOpenAndReadMmsFile: [ERROR] Can't open filepath", g_strerror(errno));
                goto __CATCH;
        }
 
@@ -653,21 +661,21 @@ char *MsgOpenAndReadMmsFile( const char *szFilePath, int offset, int size, int *
        } else {
                readSize = size;
        }
-
-       if (readSize > FM_READ_WRITE_BUFFER_MAX) {
-               MSG_DEBUG("MsgOpenAndReadMmsFile: File size tried to read too big");
-               goto __CATCH;
-       }
+// restore Kies backup data size greater than FM_READ_WRITE_BUFFER_MAX
+//     if (readSize > FM_READ_WRITE_BUFFER_MAX) {
+//             MSG_DEBUG("MsgOpenAndReadMmsFile: File size tried to read too big");
+//             goto __CATCH;
+//     }
 
        pData = (char *)malloc(readSize + 1);
        if ( NULL == pData ) {
-               MSG_DEBUG( "MsgOpenAndReadMmsFile: [ERROR] pData MemAlloc Fail", strerror(errno) );
+               MSG_DEBUG( "MsgOpenAndReadMmsFile: [ERROR] pData MemAlloc Fail", g_strerror(errno) );
                goto __CATCH;
        }
        memset( pData, 0, readSize + 1 );
 
        if (MsgFseek( pFile, offset, SEEK_SET) < 0) {
-               MSG_DEBUG( "MsgOpenAndReadMmsFile: [ERROR] FmSeekFile failed", strerror(errno) );
+               MSG_DEBUG( "MsgOpenAndReadMmsFile: [ERROR] FmSeekFile failed", g_strerror(errno) );
                goto __CATCH;
        }
 
@@ -701,13 +709,14 @@ __CATCH:
 // it is equivalent to "rm -rf pDirPath"
 int MsgRmRf(char *pDirPath)
 {
-       struct dirent *d;
+       struct dirent *d = NULL;
+       struct dirent entry;
        DIR *dir;
 
        dir = opendir(pDirPath);
 
        if (dir == NULL) {
-               MSG_FATAL("error opendir: %s", strerror(errno));
+               MSG_FATAL("error opendir: %s", g_strerror(errno));
                return -1;
        }
 
@@ -717,12 +726,13 @@ int MsgRmRf(char *pDirPath)
 
        if (path == NULL) {
                MSG_DEBUG("path is NULL");
+               closedir(dir);
                return -1;
        }
 
        bzero(path, size);
 
-       while ((d = readdir(dir)) != NULL) {
+       for (readdir_r(dir, &entry, &d); d != NULL; readdir_r(dir, &entry, &d)) {
                if (d->d_type == DT_DIR) {
                        snprintf(path, size, "%s/%s", pDirPath, d->d_name);
 
@@ -738,7 +748,7 @@ int MsgRmRf(char *pDirPath)
 
                                closedir(dir);
 
-                               MSG_FATAL("error rmdir: %s", strerror(errno));
+                               MSG_FATAL("error rmdir: %s", g_strerror(errno));
 
                                return -1;
                        }
@@ -755,11 +765,12 @@ int MsgRmRf(char *pDirPath)
 
                                closedir(dir);
 
-                               MSG_FATAL("error remove: %s", strerror(errno));
+                               MSG_FATAL("error remove: %s", g_strerror(errno));
 
                                return -1;
                        }
                }
+               d = NULL;
        }
 
        closedir(dir);
@@ -776,7 +787,7 @@ int MsgGetFileSize(const char *pFileName)
        struct stat file_stat;
 
        if (lstat(pFileName, &file_stat)) {
-               MSG_FATAL("error lstat: %s", strerror(errno));
+               MSG_FATAL("error lstat: %s", g_strerror(errno));
                return -1;
        }
 
@@ -787,23 +798,29 @@ int MsgGetFileSize(const char *pFileName)
 // it is equivalent to "du dir_path"
 unsigned int MsgDu(const char *pDirPath)
 {
-       struct dirent *d;
+       struct dirent *d = NULL;
+       struct dirent entry;
        DIR *dir;
 
        dir = opendir(pDirPath);
 
        if (dir == NULL) {
-               MSG_FATAL("error opendir: %s", strerror(errno));
+               MSG_FATAL("error opendir: %s", g_strerror(errno));
                return -1;
        }
 
        int size = strlen(pDirPath) + 256;
        char *path = (char*)malloc(size);
+       if (path == NULL) {
+               closedir(dir);
+               return -1;
+       }
+
        bzero(path, size);
 
        unsigned int totalFileSize = 0;
 
-       while ((d = readdir(dir)) != NULL) {
+       for (readdir_r(dir, &entry, &d); d != NULL; readdir_r(dir, &entry, &d)) {
                if( d->d_type == DT_DIR) {
                        snprintf(path, size, "%s/%s", pDirPath, d->d_name);
 
@@ -814,6 +831,8 @@ unsigned int MsgDu(const char *pDirPath)
 
                        if (dirSize == 0) {
                                MSG_FATAL("error MsgDu");
+                               closedir(dir);
+                               free(path);
                                return dirSize;
                        }
 
@@ -824,11 +843,14 @@ unsigned int MsgDu(const char *pDirPath)
 
                        if (fileSize < 0) {
                                MSG_FATAL("error MsgGetFileSize");
+                               closedir(dir);
+                               free(path);
                                return fileSize;
                        }
 
                        totalFileSize += fileSize;
                }
+               d = NULL;
        }
 
        closedir(dir);
@@ -853,19 +875,19 @@ bool MsgAppendFile(const char *pFilePath, const char *pData, int DataSize)
        FILE *pFile = MsgOpenFile(fullPath, "a+");
 
        if (pFile == NULL) {
-               MSG_FATAL("File Open Error: %s", strerror(errno));
+               MSG_FATAL("File Open Error: %s", g_strerror(errno));
                return false;
        }
 
        if (MsgFseek(pFile, 0L, SEEK_CUR) < 0) {
                MsgCloseFile(pFile);
-               MSG_FATAL("File Sead Error: %s", strerror(errno));
+               MSG_FATAL("File Sead Error: %s", g_strerror(errno));
                return false;
        }
 
        if (MsgWriteFile(pData, sizeof(char), DataSize, pFile) != (size_t)DataSize) {
                MsgCloseFile(pFile);
-               MSG_FATAL("File Write Error: %s", strerror(errno));
+               MSG_FATAL("File Write Error: %s", g_strerror(errno));
                return false;
        }
 
@@ -878,30 +900,176 @@ bool MsgAppendFile(const char *pFilePath, const char *pData, int DataSize)
 void MsgMmsInitDir()
 {
        struct dirent *d = NULL;
+       struct dirent entry;
        DIR* dir = NULL;
 
        dir = opendir(MSG_DATA_PATH);
 
        if (dir == NULL) {
-               MSG_FATAL("error opendir: %s", strerror(errno));
+               MSG_FATAL("error opendir: %s", g_strerror(errno));
                return;
        }
 
-       // Remove temporal Mms folder (/opt/data/msg-service/msgdata/*.dir)
-       while ((d = readdir(dir)) != NULL) {
+       // Remove temporal Mms folder (/opt/usr/data/msg-service/msgdata/*.dir)
+       for (readdir_r(dir, &entry, &d); d != NULL; readdir_r(dir, &entry, &d)) {
                if (d->d_type == DT_DIR) {
                        if ((strcmp(".", d->d_name) == 0) || (strcmp("..", d->d_name) == 0))
                                continue;
 
                        if(strstr(d->d_name, ".dir") != NULL) {
                                char filePath[MSG_FILEPATH_LEN_MAX] = {0,};
-                               snprintf(filePath, MSG_FILEPATH_LEN_MAX, MSG_DATA_PATH"%s", d->d_name);
+                               snprintf(filePath, MSG_FILEPATH_LEN_MAX, "%s%s", MSG_DATA_PATH, d->d_name);
 
                                MsgRmRf(filePath);
                                rmdir(filePath);
                        }
                }
+               d = NULL;
        }
 
        closedir(dir);
 }
+
+//mode : R_OK, W_OK, X_OK, or the existence test F_OK.
+bool MsgAccessFile(const char *filepath, int mode)
+{
+       int ret;
+       if (filepath == NULL) {
+               MSG_DEBUG("filepath is NULL");
+               return false;
+       }
+
+       MSG_SEC_DEBUG("request access path = %s, mode = %d", filepath, mode);
+
+       ret = access(filepath, mode);
+
+
+       if (ret) {
+               MSG_DEBUG("Fail to access file, ret = %d", ret);
+               return false;
+       }
+
+       return true;
+}
+
+
+bool MsgChmod(const char *filepath, int mode)
+{
+       struct stat lstat_info;
+       struct stat fstat_info;
+       int fd;
+
+       if (lstat(filepath, &lstat_info) == -1) {
+               MSG_SEC_DEBUG("No such file as [%s].", filepath);
+               return false;
+       }
+
+       fd = open(filepath, O_RDONLY);
+
+       if (fd == -1) {
+               MSG_SEC_DEBUG("Fail to open [%s].", filepath);
+               return false;
+       }
+
+       if (fstat(fd, &fstat_info) == -1) {
+               MSG_SEC_DEBUG("Fail to fstat [%s].", filepath);
+               close(fd);
+               return false;
+       }
+
+       if (lstat_info.st_mode == fstat_info.st_mode &&
+                       lstat_info.st_ino == fstat_info.st_ino  &&
+                       lstat_info.st_dev == fstat_info.st_dev) {
+               if (fchmod(fd, mode) < 0) {
+                       MSG_SEC_DEBUG("Fail to fchmod [%s].", filepath);
+                       close(fd);
+                       return false;
+               }
+       }
+
+       close(fd);
+       return true;
+}
+
+
+bool MsgChown(const char *filepath, int uid, int gid)
+{
+       struct stat lstat_info;
+       struct stat fstat_info;
+       int fd;
+
+       if (lstat(filepath, &lstat_info) == -1) {
+               MSG_SEC_DEBUG("No such file as [%s].", filepath);
+               return false;
+       }
+
+       fd = open(filepath, O_RDONLY);
+
+       if (fd == -1) {
+               MSG_SEC_DEBUG("Fail to open [%s].", filepath);
+               return false;
+       }
+
+       if (fstat(fd, &fstat_info) == -1) {
+               MSG_SEC_DEBUG("Fail to fstat [%s].", filepath);
+               close(fd);
+               return false;
+       }
+
+       if (lstat_info.st_mode == fstat_info.st_mode &&
+                       lstat_info.st_ino == fstat_info.st_ino  &&
+                       lstat_info.st_dev == fstat_info.st_dev) {
+               if (fchown(fd, uid, gid) < 0) {
+                       MSG_SEC_DEBUG("Fail to fchown [%s].", filepath);
+                       close(fd);
+                       return false;
+               }
+       }
+
+       close(fd);
+       return true;
+}
+
+bool MsgCreateFile(const char *pFilePath,char *pData, int DataSize)
+{
+       if(!pFilePath) {
+               MSG_DEBUG("pFilePath is NULL");
+               return false;
+       }
+
+       FILE *pFile = MsgOpenFile(pFilePath, "wb+");
+
+       if (pFile == NULL) {
+               MSG_DEBUG("File Open Error: %s", g_strerror(errno));
+               return false;
+       }
+
+       if (MsgFseek(pFile, 0L, SEEK_SET) < 0) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Seek Error: %s", g_strerror(errno));
+               return false;
+       }
+
+       if (MsgWriteFile(pData, sizeof(char), DataSize, pFile) != (size_t)DataSize) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Write Error: %s", g_strerror(errno));
+               return false;
+       }
+
+       MsgFflush(pFile);
+       MsgFsync( pFile);
+       MsgCloseFile(pFile);
+
+       return true;
+}
+
+char *MsgGetDirName(char *file_path)
+{
+       return g_path_get_dirname(file_path);
+}
+
+
+char *MsgGetFileName(char *file_path)
+{
+       return g_path_get_basename(file_path);
+}
index a45a11c..57e4b0f 100755 (executable)
@@ -1,26 +1,60 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
 #include "MsgDebug.h"
+#include "MsgContact.h"
 #include "MsgUtilFunction.h"
 
+#include <system_info.h>
+
+bool b_feature_check_flag = false;
+bool b_feature_telephony = false;
+bool b_feature_telephony_mms = false;
+
  /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
 
+bool MsgCheckFeatureSupport(const char *feature_name)
+{
+       bool result = false;
+
+       if (b_feature_check_flag == false) {
+               if (system_info_get_platform_bool(MSG_TELEPHONY_FEATURE, &b_feature_telephony) != SYSTEM_INFO_ERROR_NONE)
+                       MSG_INFO("fail to system_info_get_platform_bool [%s]", MSG_TELEPHONY_FEATURE);
+               if (system_info_get_platform_bool(MSG_TELEPHONY_MMS_FEATURE, &b_feature_telephony_mms) != SYSTEM_INFO_ERROR_NONE)
+                       MSG_INFO("fail to system_info_get_platform_bool [%s]", MSG_TELEPHONY_MMS_FEATURE);
+
+               MSG_INFO("[%s] feature is [%d]", MSG_TELEPHONY_FEATURE, b_feature_telephony);
+               MSG_INFO("[%s] feature is [%d]", MSG_TELEPHONY_MMS_FEATURE, b_feature_telephony_mms);
+
+               b_feature_check_flag = true;
+       }
+
+       if (!g_strcmp0(feature_name, MSG_TELEPHONY_FEATURE)) {
+               result = b_feature_telephony;
+       } else if (!g_strcmp0(feature_name, MSG_TELEPHONY_MMS_FEATURE)) {
+               result = b_feature_telephony_mms;
+       } else {
+               result = false;
+       }
+
+       return result;
+}
+
 // Encoders
 int MsgEncodeCountInfo(MSG_COUNT_INFO_S *pCountInfo, char **ppDest)
 {
@@ -94,11 +128,11 @@ int MsgEncodeMsgId(msg_message_id_t *pMsgId, char **ppDest)
 }
 
 
-int MsgEncodeMsgInfo(MSG_MESSAGE_INFO_S *pMsgInfo, char **ppDest)
+int MsgEncodeMsgInfo(const MSG_MESSAGE_INFO_S *pMsgInfo, char **ppDest)
 {
        int dataSize = 0;
 
-       dataSize = sizeof(MSG_MESSAGE_INFO_S);
+       dataSize = sizeof(MSG_MESSAGE_INFO_S) + (sizeof(MSG_ADDRESS_INFO_S)*pMsgInfo->nAddressCnt);
 
        *ppDest = (char*)new char[dataSize];
 
@@ -108,6 +142,11 @@ int MsgEncodeMsgInfo(MSG_MESSAGE_INFO_S *pMsgInfo, char **ppDest)
 
        p = (void*)((char*)p + sizeof(MSG_MESSAGE_INFO_S));
 
+       for (int i=0; i < pMsgInfo->nAddressCnt; i++) {
+               memcpy(p, &(pMsgInfo->addressList[i]), sizeof(MSG_ADDRESS_INFO_S));
+               p = (void*)((char*)p + sizeof(MSG_ADDRESS_INFO_S));
+       }
+
        return dataSize;
 }
 
@@ -116,7 +155,7 @@ int MsgEncodeMsgInfo(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S* pSendO
 {
        int dataSize = 0;
 
-       dataSize = (sizeof(MSG_MESSAGE_INFO_S) + sizeof(MSG_SENDINGOPT_INFO_S));
+       dataSize = (sizeof(MSG_MESSAGE_INFO_S) + sizeof(MSG_SENDINGOPT_INFO_S) + (sizeof(MSG_ADDRESS_INFO_S)*pMsgInfo->nAddressCnt));
 
        *ppDest = (char*)new char[dataSize];
 
@@ -128,9 +167,17 @@ int MsgEncodeMsgInfo(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S* pSendO
 
        memcpy(p, pSendOptInfo, sizeof(MSG_SENDINGOPT_INFO_S));
 
+       p = (void*)((char*)p + sizeof(MSG_SENDINGOPT_INFO_S));
+
+       for (int i=0; i < pMsgInfo->nAddressCnt; i++) {
+               memcpy(p, &(pMsgInfo->addressList[i]), sizeof(MSG_ADDRESS_INFO_S));
+               p = (void*)((char*)p + sizeof(MSG_ADDRESS_INFO_S));
+       }
+
        return dataSize;
 }
 
+
 int MsgEncodeFolderList(msg_struct_list_s *pFolderList, char **ppDest)
 {
        int count = 0, dataSize = 0;
@@ -157,6 +204,7 @@ int MsgEncodeFolderList(msg_struct_list_s *pFolderList, char **ppDest)
        return dataSize;
 }
 
+
 int MsgEncodeFilterList(msg_struct_list_s *pFilterList, char **ppDest)
 {
        int count = 0, dataSize = 0;
@@ -357,17 +405,50 @@ int MsgEncodeStorageChangeData(const msg_storage_change_type_t storageChangeType
 }
 
 
-int MsgEncodeReportStatus(MSG_REPORT_STATUS_INFO_S* pReportStatus, char **ppDest)
+int MsgEncodeReportMsgData(const msg_report_type_t msgReportType, const MSG_MESSAGE_INFO_S *pMsgInfo, char **ppDest)
+{
+       int dataSize = 0;
+       int addr_len = 0;
+
+       addr_len = strlen(pMsgInfo->addressList->addressVal);
+
+       dataSize = sizeof(msg_report_type_t) + sizeof(msg_message_id_t) + sizeof(int) + addr_len;
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, &msgReportType, sizeof(msg_report_type_t));
+       p = (void*)((char*)p + sizeof(msg_report_type_t));
+
+       memcpy(p, &(pMsgInfo->msgId), sizeof(msg_message_id_t));
+       p = (void*)((char*)p + sizeof(msg_message_id_t));
+
+       memcpy(p, &addr_len, sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       memcpy(p, &(pMsgInfo->addressList->addressVal), addr_len);
+       p = (void*)((char*)p + addr_len);
+
+       return dataSize;
+}
+
+
+int MsgEncodeReportStatus(MSG_REPORT_STATUS_INFO_S* pReportStatus, int count, char **ppDest)
 {
        int dataSize = 0;
 
-       dataSize = (sizeof(MSG_REPORT_STATUS_INFO_S));
+       dataSize = (sizeof(MSG_REPORT_STATUS_INFO_S)*count + sizeof(int));
 
        *ppDest = (char*)new char[dataSize];
 
        void* p = (void*)*ppDest;
 
-       memcpy(p, pReportStatus, dataSize);
+       memcpy(p, &count, sizeof(int));
+
+       p = (void*)((int)p + sizeof(int));
+
+       memcpy(p, pReportStatus, sizeof(MSG_REPORT_STATUS_INFO_S)*count);
 
        return dataSize;
 }
@@ -427,6 +508,23 @@ void MsgDecodeMemSize(char *pSrc, unsigned int *memsize)
 }
 
 
+void MsgDecodeMsgInfo(char *pSrc, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       memcpy(pMsgInfo, pSrc, sizeof(MSG_MESSAGE_INFO_S));
+
+       pSrc = pSrc + sizeof(MSG_MESSAGE_INFO_S);
+
+       pMsgInfo->addressList = NULL;
+
+       pMsgInfo->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S) * pMsgInfo->nAddressCnt];
+       memset(pMsgInfo->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S) * pMsgInfo->nAddressCnt);
+
+       for (int i=0; i<pMsgInfo->nAddressCnt; i++) {
+               memcpy(&(pMsgInfo->addressList[i]), pSrc + (sizeof(MSG_ADDRESS_INFO_S)*i), sizeof(MSG_ADDRESS_INFO_S));
+       }
+}
+
+
 void MsgDecodeMsgInfo(char *pSrc, MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S* pSendOptInfo)
 {
        memcpy(pMsgInfo, pSrc, sizeof(MSG_MESSAGE_INFO_S));
@@ -434,8 +532,23 @@ void MsgDecodeMsgInfo(char *pSrc, MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_I
        pSrc = pSrc + sizeof(MSG_MESSAGE_INFO_S);
 
        memcpy(pSendOptInfo, pSrc, sizeof(MSG_SENDINGOPT_INFO_S));
+
+       pSrc = pSrc + sizeof(MSG_SENDINGOPT_INFO_S);
+
+
+       if(pMsgInfo->nAddressCnt > 0) {
+               pMsgInfo->addressList = NULL;
+
+               pMsgInfo->addressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S) * pMsgInfo->nAddressCnt];
+               memset(pMsgInfo->addressList, 0x00, sizeof(MSG_ADDRESS_INFO_S) * pMsgInfo->nAddressCnt);
+
+               for (int i=0; i<pMsgInfo->nAddressCnt; i++) {
+                       memcpy(&(pMsgInfo->addressList[i]), pSrc + (sizeof(MSG_ADDRESS_INFO_S)*i), sizeof(MSG_ADDRESS_INFO_S));
+               }
+       }
 }
 
+
 void MsgDecodeRecipientList(char *pSrc, MSG_RECIPIENTS_LIST_S *pRecipientList)
 {
        int count = 0;
@@ -467,17 +580,20 @@ void MsgDecodeFolderList(char *pSrc, msg_struct_list_s *pFolderList)
        if( count > 0 )
        {
                pFolderList->nCount = count;
-               pFolderList->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_FOLDER_INFO_S *)*count];
-
+               pFolderList->msg_struct_info = (msg_struct_t *)calloc(count, sizeof(msg_struct_t));
+               if (pFolderList->msg_struct_info == NULL)
+               {
+                       pFolderList->nCount = 0;
+                       return;
+               }
                msg_struct_s *pInfoTmp = NULL;
 
                for (int i = 0; i < count; i++)
                {
-
-                       pFolderList->msg_struct_info[i] = (msg_struct_t )new char[sizeof(msg_struct_s)];
+                       pFolderList->msg_struct_info[i] = (msg_struct_t )new msg_struct_s;
                        pInfoTmp = (msg_struct_s *)pFolderList->msg_struct_info[i];
                        pInfoTmp->type = MSG_STRUCT_FOLDER_INFO;
-                       pInfoTmp->data = new char[sizeof(MSG_FOLDER_INFO_S)];
+                       pInfoTmp->data = new MSG_FOLDER_INFO_S;
                        memcpy(pInfoTmp->data, pSrc, sizeof(MSG_FOLDER_INFO_S));
                        pSrc = pSrc + sizeof(MSG_FOLDER_INFO_S);
                }
@@ -489,6 +605,7 @@ void MsgDecodeFolderList(char *pSrc, msg_struct_list_s *pFolderList)
        }
 }
 
+
 void MsgDecodeFilterList(char *pSrc, msg_struct_list_s *pFilterList)
 {
        int count = 0;
@@ -499,16 +616,21 @@ void MsgDecodeFilterList(char *pSrc, msg_struct_list_s *pFilterList)
        if( count > 0 )
        {
                pFilterList->nCount = count;
-               pFilterList->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_FILTER_S *)*count];
+               pFilterList->msg_struct_info = (msg_struct_t *)calloc(count, sizeof(MSG_FILTER_S *));
+
+               if (pFilterList->msg_struct_info == NULL) {
+                       pFilterList->nCount = 0;
+                       return;
+               }
 
                msg_struct_s *pStructTmp = NULL;
 
                for (int i = 0; i < count; i++)
                {
-                       pFilterList->msg_struct_info[i] = (msg_struct_t )new char[sizeof(msg_struct_s)];
+                       pFilterList->msg_struct_info[i] = (msg_struct_t )new msg_struct_s;
                        pStructTmp = (msg_struct_s *)pFilterList->msg_struct_info[i];
                        pStructTmp->type = MSG_STRUCT_FILTER;
-                       pStructTmp->data = new char[sizeof(MSG_FILTER_S)];
+                       pStructTmp->data = new MSG_FILTER_S;
                        memcpy(pStructTmp->data, pSrc, sizeof(MSG_FILTER_S));
                        pSrc = pSrc + sizeof(MSG_FILTER_S);
                }
@@ -533,6 +655,7 @@ void MsgDecodeMsgType(char *pSrc, MSG_MESSAGE_TYPE_S* pMsgType)
        memcpy(pMsgType, pSrc, sizeof(MSG_MESSAGE_TYPE_S));
 }
 
+
 void   MsgDecodeContactCount(char *pSrc,  MSG_THREAD_COUNT_INFO_S *pMsgThreadCountList)
 {
        int count = 0;
@@ -564,33 +687,39 @@ void      MsgDecodeContactCount(char *pSrc,  MSG_THREAD_COUNT_INFO_S *pMsgThreadCount
 }
 
 
-void   MsgDecodeReportStatus(char *pSrc,  MSG_REPORT_STATUS_INFO_S *pReportStatus)
+void MsgDecodeReportStatus(char *pSrc,  msg_struct_list_s *report_list)
 {
        int count = 0;
 
        if(pSrc == NULL)
                return;
 
-       memcpy(&count, pSrc, sizeof(msg_delivery_report_status_t));
-       pSrc = pSrc + sizeof(msg_delivery_report_status_t);
-       pReportStatus->deliveryStatus = count;
+       memcpy(&count, pSrc, sizeof(int));
+       pSrc = pSrc + sizeof(int);
 
+       report_list->nCount = count;
 
-       memcpy(&count, pSrc, sizeof(time_t));
-       pSrc = pSrc + sizeof(time_t);
-       pReportStatus->deliveryStatusTime = count;
+       msg_struct_t *report_status =  (msg_struct_t *)new char[sizeof(msg_struct_t)*count];
+       for (int i = 0; i < count; i++) {
 
+               msg_struct_s *report_status_item = new msg_struct_s;
+               report_status_item->type = MSG_STRUCT_REPORT_STATUS_INFO;
+               report_status_item->data = new MSG_REPORT_STATUS_INFO_S;
+               memset(report_status_item->data, 0x00, sizeof(MSG_REPORT_STATUS_INFO_S));
 
-       memcpy(&count, pSrc, sizeof(msg_read_report_status_t));
-       pSrc = pSrc + sizeof(msg_read_report_status_t);
-       pReportStatus->readStatus = count;
+               MSG_REPORT_STATUS_INFO_S *report_status_info =  (MSG_REPORT_STATUS_INFO_S *)report_status_item->data;
+               memcpy(report_status_info, pSrc, sizeof(MSG_REPORT_STATUS_INFO_S));
 
+               pSrc = pSrc + sizeof(MSG_REPORT_STATUS_INFO_S);
 
-       memcpy(&count, pSrc, sizeof(time_t));
-       pSrc = pSrc + sizeof(time_t);
-       pReportStatus->readStatusTime = count;
+               report_status[i] = (msg_struct_t)report_status_item;
 
+               MSG_DEBUG("Report_type = %d, status addr = %s, status = %d, time = %d",
+                               report_status_info->type, report_status_info->addressVal,
+                               report_status_info->status, report_status_info->statusTime);
+       }
 
+       report_list->msg_struct_info = report_status;
        return;
 }
 
@@ -609,6 +738,11 @@ int MsgMakeEvent(const void *pData, int DataSize, MSG_EVENT_TYPE_T MsgEvent, msg
 {
        MSG_EVENT_S* pMsgEvent = NULL;
 
+       if (*ppEvent) {
+               MSG_DEBUG("*ppEvent is not NULL.");
+               delete [] (char *)*ppEvent;
+       }
+
        *ppEvent = (MSG_EVENT_S*)new char[sizeof(MSG_EVENT_S) + DataSize];
 
        pMsgEvent = (MSG_EVENT_S*)*ppEvent;
@@ -693,3 +827,258 @@ int msg_verify_email(const char *raw)
 
        return MSG_SUCCESS;
 }
+
+
+char* msg_clean_country_code(char *src)
+{
+       int ret = 1;
+
+       switch (src[ret++]-'0')
+       {
+               case 1:
+               case 7:
+                       break;
+               case 2:
+                       switch (src[ret++]-'0')
+                       {
+                               case 0:
+                               case 7:
+                                       break;
+                               case 1:
+                               case 2:
+                               case 3:
+                               case 4:
+                               case 5:
+                               case 6:
+                               case 8:
+                               case 9:
+                                       ret += 1;
+                                       break;
+                               default:
+                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+                                       break;
+                       }
+                       break;
+               case 3:
+                       switch (src[ret++]-'0')
+                       {
+                               case 0:
+                               case 1:
+                               case 2:
+                               case 3:
+                               case 4:
+                               case 6:
+                               case 9:
+                                       break;
+                               case 5:
+                               case 7:
+                               case 8:
+                                       ret += 1;
+                                       break;
+                               default:
+                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+                                       break;
+                       }
+                       break;
+               case 4:
+                       switch (src[ret++]-'0')
+                       {
+                               case 0:
+                               case 1:
+                               case 3:
+                               case 4:
+                               case 5:
+                               case 6:
+                               case 7:
+                               case 8:
+                               case 9:
+                                       break;
+                               case 2:
+                                       ret += 1;
+                                       break;
+                               default:
+                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+                                       break;
+                       }
+                       break;
+               case 5:
+                       switch (src[ret++]-'0')
+                       {
+                               case 1:
+                               case 2:
+                               case 3:
+                               case 4:
+                               case 5:
+                               case 6:
+                               case 7:
+                               case 8:
+                                       break;
+                               case 0:
+                               case 9:
+                                       ret += 1;
+                                       break;
+                               default:
+                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+                                       break;
+                       }
+                       break;
+               case 6:
+                       switch (src[ret++]-'0')
+                       {
+                               case 0:
+                               case 1:
+                               case 2:
+                               case 3:
+                               case 4:
+                               case 5:
+                               case 6:
+                                       break;
+                               case 7:
+                               case 8:
+                               case 9:
+                                       ret += 1;
+                                       break;
+                               default:
+                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+                                       break;
+                       }
+                       break;
+               case 8:
+                       switch (src[ret++]-'0')
+                       {
+                               case 1:
+                               case 2:
+                               case 4:
+                               case 6:
+                                       break;
+                               case 0:
+                               case 3:
+                               case 5:
+                               case 7:
+                               case 8:
+                               case 9:
+                                       ret += 1;
+                                       break;
+                               default:
+                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+                                       break;
+                       }
+                       break;
+               case 9:
+                       switch (src[ret++]-'0')
+                       {
+                               case 0:
+                               case 1:
+                               case 2:
+                               case 3:
+                               case 4:
+                               case 5:
+                               case 8:
+                                       break;
+                               case 6:
+                               case 7:
+                               case 9:
+                                       ret += 1;
+                                       break;
+                               default:
+                                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+                                       break;
+                       }
+                       break;
+               case 0:
+               default:
+                       MSG_DEBUG("The parameter(src:%s) has invalid character set", src);
+                       return src;
+       }
+
+       return &src[ret];
+}
+
+
+char* msg_normalize_number(char *src)
+{
+       char *normalized_number;
+
+       if ('+' == src[0])
+               normalized_number = msg_clean_country_code(src);
+       else if ('0' == src[0])
+               normalized_number = src+1;
+       else
+               normalized_number = src;
+
+       MSG_DEBUG("src = %s, normalized = %s", src, normalized_number);
+
+       return normalized_number;
+}
+
+
+msg_error_t MsgMakeSortRule(const MSG_SORT_RULE_S *pSortRule, char *pSqlSort)
+{
+       char sql[128];
+       char order[6];
+
+       memset(sql, 0x00, sizeof(sql));
+       memset(order, 0x00, sizeof(order));
+
+       if (pSortRule->bAscending == true)
+               strncpy(order, "ASC", 5);
+       else
+               strncpy(order, "DESC", 5);
+
+       int nameOrder = MsgGetContactNameOrder();
+
+       switch (pSortRule->sortType)
+       {
+               case MSG_SORT_BY_DISPLAY_FROM :
+                       if (nameOrder == 0)
+                               snprintf(sql, sizeof(sql), "ORDER BY B.FIRST_NAME %s, B.LAST_NAME %s, B.ADDRESS_VAL, A.DISPLAY_TIME DESC;", order, order);
+                       else
+                               snprintf(sql, sizeof(sql), "ORDER BY B.LAST_NAME %s, B.FIRST_NAME %s, B.ADDRESS_VAL, A.DISPLAY_TIME DESC;", order, order);
+                       break;
+               case MSG_SORT_BY_DISPLAY_TO :
+                       if (nameOrder == 0)
+                               snprintf(sql, sizeof(sql), "ORDER BY B.FIRST_NAME %s, B.LAST_NAME %s, B.ADDRESS_VAL, A.DISPLAY_TIME DESC;", order, order);
+                       else
+                               snprintf(sql, sizeof(sql), "ORDER BY B.LAST_NAME %s, B.FIRST_NAME %s, B.ADDRESS_VAL, A.DISPLAY_TIME DESC;", order, order);
+                       break;
+               case MSG_SORT_BY_DISPLAY_TIME :
+                       snprintf(sql, sizeof(sql), "ORDER BY DISPLAY_TIME %s;", order);
+                       break;
+               case MSG_SORT_BY_MSG_TYPE :
+                       snprintf(sql, sizeof(sql), "ORDER BY MAIN_TYPE %s, DISPLAY_TIME DESC;", order);
+                       break;
+               case MSG_SORT_BY_READ_STATUS :
+                       snprintf(sql, sizeof(sql), "ORDER BY READ_STATUS %s, DISPLAY_TIME DESC;", order);
+                       break;
+               case MSG_SORT_BY_STORAGE_TYPE :
+                       snprintf(sql, sizeof(sql), "ORDER BY A.STORAGE_ID %s, A.DISPLAY_TIME DESC;", order);
+                       break;
+               case MSG_SORT_BY_THREAD_NAME :
+                       if (nameOrder == 0)
+                               snprintf(sql, sizeof(sql), "ORDER BY FIRST_NAME %s, LAST_NAME %s;", order, order);
+                       else
+                               snprintf(sql, sizeof(sql), "ORDER BY LAST_NAME %s, FIRST_NAME %s;", order, order);
+                       break;
+               case MSG_SORT_BY_THREAD_DATE :
+                       snprintf(sql, sizeof(sql), "ORDER BY MSG_TIME %s;", order);
+                       break;
+               case MSG_SORT_BY_THREAD_COUNT :
+                       snprintf(sql, sizeof(sql), "ORDER BY UNREAD_CNT %s;", order);
+                       break;
+               default :
+                       snprintf(sql, sizeof(sql), "ORDER BY A.DISPLAY_TIME %s;", order);
+                       break;
+       }
+
+       memcpy(pSqlSort, sql, strlen(sql));
+
+       return MSG_SUCCESS;
+}
+bool msg_is_valid_email(char *pAddress)
+{
+       if (!pAddress || pAddress[0] == 0)
+               return false;
+       if (!strchr (pAddress, MSG_UTIL_CH_EMAIL_AT))
+               return false;
+       return true;
+}
index 525e41b..1f2b03d 100755 (executable)
@@ -1,37 +1,47 @@
 /*
-* Copyright 2012  Samsung Electronics Co., Ltd
-*
-* Licensed under the Flora License, Version 1.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*    http://www.tizenopensource.org/license
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
 */
 
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <tr1/unordered_set>
+#include <queue>
+#include <glib.h>
+
 #include "MsgDebug.h"
 #include "MsgUtilFile.h"
 #include "MsgContact.h"
 #include "MsgCppTypes.h"
 #include "MsgGconfWrapper.h"
-#include "MsgNotificationWrapper.h"
+#include "MsgUtilFunction.h"
 #include "MsgUtilStorage.h"
 
-#include <sys/stat.h>
-#include <sys/vfs.h>
-
+//#include <sys/stat.h>
+//#include <sys/vfs.h>
+#include <storage.h>
 
-static int msgCntLimit[MSG_COUNT_LIMIT_MAILBOX_TYPE_MAX][MSG_COUNT_LIMIT_MSG_TYPE_MAX] = {{1500, 500, 0, 50, 50}, {50, 50, 0, 0, 0}, {1000, 250, 0, 0, 0}, {50, 50, 0, 0, 0}, {0, 0, 200, 0, 0}};
+static int msgCntLimit[MSG_COUNT_LIMIT_MAILBOX_TYPE_MAX][MSG_COUNT_LIMIT_MSG_TYPE_MAX] = {{10, 10, 0, 10, 10}, {5, 10, 0, 0, 0}, {10, 10, 0, 0, 0}, {10, 10, 0, 0, 0}, {0, 0, 10, 0, 0}};
 
+using namespace std;
 
+#define ITERATION_SIZE 200
 /*==================================================================================================
                                      FUNCTION IMPLEMENTATION
 ==================================================================================================*/
+
 unsigned int MsgStoAddMessageTable(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsgInfo)
 {
        MSG_BEGIN();
@@ -48,7 +58,7 @@ unsigned int MsgStoAddMessageTable(MsgDbHandler *pDbHandle, const MSG_MESSAGE_IN
        int fileSize = 0;
 
        char* pFileData = NULL;
-       AutoPtr<char> buf(&pFileData);
+       unique_ptr<char*, void(*)(char**)> buf(&pFileData, unique_ptr_deleter);
 
        // Get File Data
        if (pMsgInfo->bTextSms == false) {
@@ -58,31 +68,40 @@ unsigned int MsgStoAddMessageTable(MsgDbHandler *pDbHandle, const MSG_MESSAGE_IN
                MSG_DEBUG("file size [%d]", fileSize);
        }
 
+       char keyName[MAX_VCONFKEY_NAME_LEN];
+       memset(keyName, 0x00, sizeof(keyName));
+       snprintf(keyName, sizeof(keyName), "%s/%d", MSG_SIM_IMSI, pMsgInfo->sim_idx);
+
+       char *imsi = MsgSettingGetString(keyName);
+
        // Add Message
        char sqlQuery[MAX_QUERY_LEN+1];
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, %d, %d, %ld, %d, %d, %d, %d, %d, %d, %ld, %d, ?, ?, ?, ?, %d, 0, %d, 0, 0);",
+       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, %d, %d, %u, %d, %d, %d, %d, %d, %d, %d, %d, ?, '', '', ?, 0, %d, '%s');",
                        MSGFW_MESSAGE_TABLE_NAME, msgId, pMsgInfo->threadId, pMsgInfo->folderId, pMsgInfo->storageId, pMsgInfo->msgType.mainType,
-                       pMsgInfo->msgType.subType, pMsgInfo->displayTime, pMsgInfo->dataSize, pMsgInfo->networkStatus, pMsgInfo->bRead, pMsgInfo->bProtected,
-                       pMsgInfo->priority, pMsgInfo->direction, 0, pMsgInfo->bBackup, MSG_DELIVERY_REPORT_NONE, MSG_READ_REPORT_NONE);
+                       pMsgInfo->msgType.subType, (unsigned int)pMsgInfo->displayTime, pMsgInfo->dataSize, pMsgInfo->networkStatus, pMsgInfo->bRead, pMsgInfo->bProtected,
+                       pMsgInfo->priority, pMsgInfo->direction, 0, pMsgInfo->bBackup, pMsgInfo->sim_idx, imsi);
 
        MSG_DEBUG("QUERY : %s", sqlQuery);
 
+       g_free(imsi);
+       imsi = NULL;
+
        if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
                return 0;
 
        pDbHandle->bindText(pMsgInfo->subject, 1);
 
-       pDbHandle->bindText(pMsgInfo->msgData, 2);
-
-       pDbHandle->bindText(pMsgInfo->thumbPath, 3);
+       if (pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS) {
+               pDbHandle->bindText("", 2);
+       } else {
+               if (pMsgInfo->bTextSms == false)
+                       pDbHandle->bindText(pFileData, 2);
+               else
+                       pDbHandle->bindText(pMsgInfo->msgText, 2);
 
-       if (pMsgInfo->bTextSms == false)
-               pDbHandle->bindText(pFileData, 4);
-       else
-               pDbHandle->bindText(pMsgInfo->msgText, 4);
+       }
 
        if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
                pDbHandle->finalizeQuery();
@@ -136,15 +155,6 @@ msg_error_t MsgStoSetReadStatus(MsgDbHandler *pDbHandle, msg_message_id_t msgId,
                return MSG_ERR_STORAGE_ERROR;
        }
 
-       int smsCnt = 0, mmsCnt = 0;
-
-       smsCnt = MsgStoGetUnreadCnt(pDbHandle, MSG_SMS_TYPE);
-       mmsCnt = MsgStoGetUnreadCnt(pDbHandle, MSG_MMS_TYPE);
-
-       MsgSettingSetIndicator(smsCnt, mmsCnt);
-
-       MsgDeleteNotiByMsgId(msgId);
-
        return MSG_SUCCESS;
 }
 
@@ -182,23 +192,22 @@ msg_error_t MsgStoCheckMsgCntFull(MsgDbHandler *pDbHandle, const MSG_MESSAGE_TYP
 
        msg_error_t err = MSG_SUCCESS;
 
-       struct statfs buf = {0};
-
-       if (statfs(MSG_DATA_ROOT_PATH, &buf) == -1) {
-               MSG_DEBUG("statfs(\"%s\") failed - %d", MSG_DATA_ROOT_PATH);
+       struct statvfs s;
+       double freeSpace;
+       int r;
+       r = storage_get_internal_memory_size(&s);
+       if (r < 0)
                return MSG_ERR_STORAGE_ERROR;
+       else {
+               freeSpace = (double)s.f_bsize*s.f_bavail;
+               MSG_DEBUG("Free space of storage is [%lu] MB.", freeSpace);
+
+               if (freeSpace < SMS_MINIMUM_SPACE && pMsgType->mainType == MSG_SMS_TYPE)
+                       err = MSG_ERR_MESSAGE_COUNT_FULL;
+               else if(freeSpace < MMS_MINIMUM_SPACE && pMsgType->mainType == MSG_MMS_TYPE)
+                       err = MSG_ERR_MESSAGE_COUNT_FULL;
        }
 
-       unsigned long freeSpace = (buf.f_bfree * buf.f_bsize);
-
-       MSG_DEBUG("f_bfree [%d] f_bsize [%d]", buf.f_bfree, buf.f_bsize);
-       MSG_DEBUG("Free space of storage is [%ul] MB.", freeSpace);
-
-       if (freeSpace < SMS_MINIMUM_SPACE && pMsgType->mainType == MSG_SMS_TYPE)
-               err = MSG_ERR_MESSAGE_COUNT_FULL;
-       else if(freeSpace < MMS_MINIMUM_SPACE && pMsgType->mainType == MSG_MMS_TYPE)
-               err = MSG_ERR_MESSAGE_COUNT_FULL;
-
        MSG_END();
 
        return err;
@@ -334,6 +343,28 @@ int MsgStoCheckMsgCntLimit(const MSG_MESSAGE_TYPE_S* pMsgType, msg_folder_id_t f
 }
 
 
+msg_error_t MsgStocheckMemoryStatus()
+{
+       msg_error_t err = MSG_SUCCESS;
+       struct statvfs s;
+       double freeSpace;
+       int r;
+       r = storage_get_internal_memory_size(&s);
+       if (r < 0)
+               return MSG_ERR_STORAGE_ERROR;
+       else {
+               freeSpace = (double)s.f_bsize*s.f_bavail;
+           MSG_DEBUG("Free space of storage is [%ul] MB.", freeSpace);
+               if (freeSpace < SMS_MINIMUM_SPACE)
+                       err = MSG_ERR_MESSAGE_COUNT_FULL;
+       }
+
+       MSG_DEBUG("Memory status =[%d]", err);
+
+       return err;
+}
+
+
 msg_error_t MsgStoAddAddress(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsg, msg_thread_id_t *pConvId)
 {
        msg_error_t err = MSG_SUCCESS;
@@ -343,130 +374,116 @@ msg_error_t MsgStoAddAddress(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *
        // Check if new address or not
        if (MsgExistAddress(pDbHandle, pMsg, pConvId) == true) {
                MSG_DEBUG("The address already exists. Conversation ID : [%d]", *pConvId);
-               return err;
-       }
-
-       MSG_DEBUG("Conversation ID : [%d]", *pConvId);
-
-       /* conversation insert */
-       err = MsgStoAddConversation(pDbHandle, pConvId);
-       if (err != MSG_SUCCESS) {
-               MSG_DEBUG("MsgStoAddConversation() fail [%d]", err);
-               return err;
-       }
-
-       /* insert address in loop */
-       for (int i=0; i<pMsg->nAddressCnt; i++) {
+               MsgStoUpdateAddress(pDbHandle, pMsg, *pConvId);
+       } else {
 
-               unsigned int addrId;
-               MSG_CONTACT_INFO_S contactInfo = {0};
+               *pConvId = 0;
 
-               // Get Contact Info
-               err = MsgGetContactInfo(&(pMsg->addressList[i]), &contactInfo);
+               if(pMsg->threadId)
+                       *pConvId = pMsg->threadId;
 
+               /* conversation insert */
+               err = MsgStoAddConversation(pDbHandle, pConvId);
                if (err != MSG_SUCCESS) {
-                       MSG_DEBUG("MsgGetContactInfo() fail [%d]", err);
+                       MSG_DEBUG("MsgStoAddConversation() fail [%d]", err);
                        return err;
                }
 
-               if (pDbHandle->getRowId(MSGFW_ADDRESS_TABLE_NAME, &addrId) != MSG_SUCCESS) {
-                       return err;
-               }
+               /* insert address in loop */
+               for (int i=0; i<pMsg->nAddressCnt; i++) {
 
-               // Add Address
-               memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, '%s', %d, ?, ?, ?, '%s', 0);",
-                                       MSGFW_ADDRESS_TABLE_NAME, addrId, *pConvId, pMsg->addressList[i].addressType, pMsg->addressList[i].recipientType, pMsg->addressList[i].addressVal,
-                                       contactInfo.contactId, contactInfo.imagePath);
+                       unsigned int addrId;
+                       MSG_CONTACT_INFO_S contactInfo;
+                       memset(&contactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
 
-               MSG_DEBUG("Add Address Info. [%s]", sqlQuery);
+                       // Get Contact Info
+//                     if (MsgGetContactInfo(&(pMsg->addressList[i]), &contactInfo) != MSG_SUCCESS) {
+//                             MSG_DEBUG("MsgGetContactInfo() fail.");
+//                     }
 
-               if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
-                       return MSG_ERR_DB_PREPARE;
+                       err = pDbHandle->getRowId(MSGFW_ADDRESS_TABLE_NAME, &addrId);
+                       if (err != MSG_SUCCESS) {
+                               MSG_DEBUG("pDbHandle->getRowId fail. [%d]", err);
+                               return err;
+                       }
 
-               pDbHandle->bindText(contactInfo.displayName, 1);
-               pDbHandle->bindText(contactInfo.firstName, 2);
-               pDbHandle->bindText(contactInfo.lastName, 3);
+                       // Add Address
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, '%s', %d, %d, ?, ?, ?, ?, ?, '%s', 0);",
+                                               MSGFW_ADDRESS_TABLE_NAME, addrId, *pConvId, pMsg->addressList[i].addressType, pMsg->addressList[i].recipientType, pMsg->addressList[i].addressVal,
+                                               contactInfo.contactId, contactInfo.addrbookId, contactInfo.imagePath);
 
-               if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
-                       pDbHandle->finalizeQuery();
-                       return MSG_ERR_DB_STEP;
-               }
+                       MSG_SEC_DEBUG("Add Address Info. [%s]", sqlQuery);
 
-               pDbHandle->finalizeQuery();
+                       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+                               return MSG_ERR_DB_PREPARE;
 
-               // set conversation display name by conv id
-               MsgStoSetConversationDisplayName(pDbHandle, *pConvId);
+                       pDbHandle->bindText(contactInfo.firstName, 1);
+                       pDbHandle->bindText(contactInfo.lastName, 2);
+                       pDbHandle->bindText(contactInfo.middleName, 3);
+                       pDbHandle->bindText(contactInfo.prefix, 4);
+                       pDbHandle->bindText(contactInfo.suffix, 5);
+
+                       if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                               pDbHandle->finalizeQuery();
+                               return MSG_ERR_DB_STEP;
+                       }
 
+                       pDbHandle->finalizeQuery();
+               }
        }
 
+       // set conversation display name by conv id
+       MsgStoSetConversationDisplayName(pDbHandle, *pConvId);
+
        return err;
 }
 
-msg_error_t MsgStoGetAddressByMsgId(MsgDbHandler *pDbHandle, msg_message_id_t msgId, int contactNameOrder, int *nAddressCnt, MSG_ADDRESS_INFO_S *pAddress)
+msg_error_t MsgStoGetAddressByMsgId(MsgDbHandler *pDbHandle, msg_message_id_t msgId, int contactNameOrder, int *nAddressCnt, MSG_ADDRESS_INFO_S **pAddress)
 {
        char sqlQuery[MAX_QUERY_LEN+1];
-       char firstName[MAX_DISPLAY_NAME_LEN+1];
-       char lastName[MAX_DISPLAY_NAME_LEN+1];
+       int rowCnt = 0, index = 0;
 
        *nAddressCnt = 0;
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.ADDRESS_TYPE, A.RECIPIENT_TYPE, \
-                               A.CONTACT_ID, A.ADDRESS_VAL, A.DISPLAY_NAME, A.FIRST_NAME, A.LAST_NAME \
-                               FROM %s A, %s B WHERE A.CONV_ID = B.CONV_ID AND B.MSG_ID = %d;",
-                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, msgId);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                       "A.ADDRESS_TYPE, "
+                       "A.RECIPIENT_TYPE, "
+                       "A.ADDRESS_VAL "
+                       "FROM %s A, %s B "
+                       "WHERE A.CONV_ID = B.CONV_ID "
+                       "AND B.MSG_ID = %d;",
+                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                       msgId);
+
+       msg_error_t err = pDbHandle->getTable(sqlQuery, &rowCnt, &index);
 
-       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
-               MSG_DEBUG("Query Failed [%s]", sqlQuery);
-               return MSG_ERR_DB_PREPARE;
+       if (err == MSG_ERR_DB_NORECORD) {
+               pDbHandle->freeTable();
+               return MSG_SUCCESS;
+       } else if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               pDbHandle->freeTable();
+               return err;
        }
 
-       while (pDbHandle->stepQuery() == MSG_ERR_DB_ROW) {
-               memset(firstName, 0x00, sizeof(firstName));
-               memset(lastName, 0x00, sizeof(lastName));
-
-               pAddress[*nAddressCnt].addressType = pDbHandle->columnInt(0);
-               pAddress[*nAddressCnt].recipientType = pDbHandle->columnInt(1);
-               pAddress[*nAddressCnt].contactId = pDbHandle->columnInt(2);
-
-               if (pDbHandle->columnText(3) != NULL)
-                       strncpy(pAddress[*nAddressCnt].addressVal, (char *)pDbHandle->columnText(3), MAX_ADDRESS_VAL_LEN);
-
-               if (pDbHandle->columnText(4) != NULL && ((char *)pDbHandle->columnText(4))[0]!='\0') {
-                       MSG_DEBUG("displayName  : [%s]", pDbHandle->columnText(4));
-                       strncpy(pAddress[*nAddressCnt].displayName, (char *)pDbHandle->columnText(4), MAX_DISPLAY_NAME_LEN);
-               } else {
-                       if (pDbHandle->columnText(5) != NULL)
-                                       strncpy(firstName, (char *)pDbHandle->columnText(5), MAX_DISPLAY_NAME_LEN);
+       *nAddressCnt = rowCnt;
 
-                       if (pDbHandle->columnText(6) != NULL)
-                                       strncpy(lastName, (char *)pDbHandle->columnText(6), MAX_DISPLAY_NAME_LEN);
+       MSG_DEBUG("*nAddressCnt [%d]", *nAddressCnt);
 
-                       if (contactNameOrder == 0) {
-                               if (strlen(firstName) > 0) {
-                                       strncpy(pAddress[*nAddressCnt].displayName, firstName, MAX_DISPLAY_NAME_LEN);
-                               }
-                               if (strlen(lastName) > 0) {
-                                       strncat(pAddress[*nAddressCnt].displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(pAddress[*nAddressCnt].displayName));
-                                       strncat(pAddress[*nAddressCnt].displayName, lastName, MAX_DISPLAY_NAME_LEN-strlen(pAddress[*nAddressCnt].displayName));
-                               }
-                       } else if (contactNameOrder == 1) {
-                               if (strlen(lastName) > 0) {
-                                       strncpy(pAddress[*nAddressCnt].displayName, lastName, MAX_DISPLAY_NAME_LEN);
-                                       strncat(pAddress[*nAddressCnt].displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(pAddress[*nAddressCnt].displayName));
-                               }
+       MSG_ADDRESS_INFO_S *tmpAddressList = (MSG_ADDRESS_INFO_S *)new char[sizeof(MSG_ADDRESS_INFO_S) * rowCnt];
+       memset(tmpAddressList, 0x00, sizeof(MSG_ADDRESS_INFO_S) * rowCnt);
+       *pAddress = tmpAddressList;
 
-                               if (strlen(firstName) > 0) {
-                                       strncat(pAddress[*nAddressCnt].displayName, firstName, MAX_DISPLAY_NAME_LEN-strlen(pAddress[*nAddressCnt].displayName));
-                               }
-                       }
-               }
+       for (int i = 0; i < rowCnt; i++) {
+               tmpAddressList[i].addressType = pDbHandle->getColumnToInt(index++);
+               tmpAddressList[i].recipientType = pDbHandle->getColumnToInt(index++);
+               pDbHandle->getColumnToString(index++, MAX_ADDRESS_VAL_LEN, tmpAddressList[i].addressVal);
 
-               (*nAddressCnt)++;
+               strncpy(tmpAddressList[i].displayName, tmpAddressList[i].addressVal, MAX_DISPLAY_NAME_LEN);
        }
-
-       pDbHandle->finalizeQuery();
+       pDbHandle->freeTable();
 
        return MSG_SUCCESS;
 }
@@ -474,86 +491,65 @@ msg_error_t MsgStoGetAddressByMsgId(MsgDbHandler *pDbHandle, msg_message_id_t ms
 msg_error_t MsgStoGetAddressByMsgId(MsgDbHandler *pDbHandle, msg_message_id_t msgId, int contactNameOrder, msg_struct_list_s *pAddress)
 {
        char sqlQuery[MAX_QUERY_LEN+1];
-       char firstName[MAX_DISPLAY_NAME_LEN+1];
-       char lastName[MAX_DISPLAY_NAME_LEN+1];
-
-       pAddress->nCount = 0;
-       pAddress->nCount = NULL;
 
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.ADDRESS_TYPE, A.RECIPIENT_TYPE, \
-                       A.CONTACT_ID, A.ADDRESS_VAL, A.DISPLAY_NAME, A.FIRST_NAME, A.LAST_NAME \
-                       FROM %s A, %s B WHERE A.CONV_ID = B.CONV_ID AND B.MSG_ID = %d;",
-                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, msgId);
+       int rowCnt = 0, index = 0;
 
-       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
-               MSG_DEBUG("Query Failed [%s]", sqlQuery);
-               return MSG_ERR_DB_PREPARE;
-       }
+       pAddress->nCount = 0;
+       pAddress->msg_struct_info = NULL;
 
        msg_struct_s *pTmp = NULL;
        MSG_ADDRESS_INFO_S *pAddr = NULL;
 
-       pAddress->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t) * MAX_TO_ADDRESS_CNT];
+       pAddress->msg_struct_info = (msg_struct_t *)calloc(MAX_TO_ADDRESS_CNT, sizeof(msg_struct_t));
+       if (pAddress->msg_struct_info == NULL)
+               return MSG_ERR_MEMORY_ERROR;
 
        for (int i = 0; i < MAX_TO_ADDRESS_CNT; i++) {
-               pAddress->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];
+               pAddress->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
                pTmp = (msg_struct_s *)pAddress->msg_struct_info[i];
                pTmp->type = MSG_STRUCT_ADDRESS_INFO;
-               pTmp->data = new char[sizeof(MSG_ADDRESS_INFO_S)];
+               pTmp->data = new MSG_ADDRESS_INFO_S;
                memset(pTmp->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
        }
 
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                       "A.ADDRESS_TYPE, "
+                       "A.RECIPIENT_TYPE, "
+                       "A.ADDRESS_VAL "
+                       "FROM %s A, %s B "
+                       "WHERE A.CONV_ID = B.CONV_ID "
+                       "AND B.MSG_ID = %d;",
+                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                       msgId);
+
+       msg_error_t err = pDbHandle->getTable(sqlQuery, &rowCnt, &index);
 
-       while (pDbHandle->stepQuery() == MSG_ERR_DB_ROW) {
-               memset(firstName, 0x00, sizeof(firstName));
-               memset(lastName, 0x00, sizeof(lastName));
-
-               pTmp = (msg_struct_s *)pAddress->msg_struct_info[pAddress->nCount];
-               pAddr = (MSG_ADDRESS_INFO_S *)pTmp->data;
-
-               pAddr->addressType = pDbHandle->columnInt(0);
-               pAddr->recipientType = pDbHandle->columnInt(1);
-               pAddr->contactId = pDbHandle->columnInt(2);
-
-               if (pDbHandle->columnText(3) != NULL)
-                                       strncpy(pAddr->addressVal, (char *)pDbHandle->columnText(3), MAX_ADDRESS_VAL_LEN);
-
-               if (pDbHandle->columnText(4) != NULL && ((char *)pDbHandle->columnText(4))[0]!='\0') {
-                                       MSG_DEBUG("displayName  : [%s]", pDbHandle->columnText(4));
-                                       strncpy(pAddr->displayName, (char *)pDbHandle->columnText(4), MAX_DISPLAY_NAME_LEN);
-               } else {
-                       if (pDbHandle->columnText(5) != NULL)
-                               strncpy(firstName, (char *)pDbHandle->columnText(5), MAX_DISPLAY_NAME_LEN);
+       if (err == MSG_ERR_DB_NORECORD) {
+               pDbHandle->freeTable();
+               return MSG_SUCCESS;
+       } else if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               pDbHandle->freeTable();
+               return err;
+       }
 
-                       if (pDbHandle->columnText(6) != NULL)
-                               strncpy(lastName, (char *)pDbHandle->columnText(6), MAX_DISPLAY_NAME_LEN);
+       rowCnt = (rowCnt > 10)? MAX_TO_ADDRESS_CNT: rowCnt;
+       pAddress->nCount = rowCnt;
 
-                       if (contactNameOrder == 0) {
-                               if (strlen(firstName) > 0) {
-                                       strncpy(pAddr->displayName, firstName, MAX_DISPLAY_NAME_LEN);
-                               }
+       for (int i = 0; i < rowCnt; i++) {
+               pTmp = (msg_struct_s *)pAddress->msg_struct_info[i];
+               pAddr = (MSG_ADDRESS_INFO_S *)pTmp->data;
 
-                               if (strlen(lastName) > 0) {
-                                       strncat(pAddr->displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(pAddr->displayName));
-                                       strncat(pAddr->displayName, lastName, MAX_DISPLAY_NAME_LEN-strlen(pAddr->displayName));
-                               }
-                       } else if (contactNameOrder == 1) {
-                               if (strlen(lastName) > 0) {
-                                       strncpy(pAddr->displayName, lastName, MAX_DISPLAY_NAME_LEN);
-                                       strncat(pAddr->displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(pAddr->displayName));
-                               }
+               pAddr->addressType = pDbHandle->getColumnToInt(index++);
+               pAddr->recipientType = pDbHandle->getColumnToInt(index++);
 
-                               if (strlen(firstName) > 0) {
-                                       strncat(pAddr->displayName, firstName, MAX_DISPLAY_NAME_LEN-strlen(pAddr->displayName));
-                               }
-                       }
-               }
+               pDbHandle->getColumnToString(index++, MAX_ADDRESS_VAL_LEN, pAddr->addressVal);
 
-               pAddress->nCount++;
+               strncpy(pAddr->displayName, pAddr->addressVal, MAX_DISPLAY_NAME_LEN);
        }
 
-       pDbHandle->finalizeQuery();
+       pDbHandle->freeTable();
 
        return MSG_SUCCESS;
 }
@@ -562,27 +558,27 @@ msg_error_t MsgStoGetAddressByMsgId(MsgDbHandler *pDbHandle, msg_message_id_t ms
 msg_error_t MsgStoGetAddressByConvId(MsgDbHandler *pDbHandle, msg_thread_id_t convId, int contactNameOrder, msg_struct_list_s *pAddrlist)
 {
        char sqlQuery[MAX_QUERY_LEN+1];
-       char firstName[MAX_DISPLAY_NAME_LEN+1];
-       char lastName[MAX_DISPLAY_NAME_LEN+1];
-       int index = 7;
-       int rowCnt = 0;
+
+       int rowCnt = 0, index = 0;
 
        pAddrlist->nCount = 0;
        pAddrlist->msg_struct_info = NULL;
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT ADDRESS_TYPE, RECIPIENT_TYPE, \
-                       CONTACT_ID, ADDRESS_VAL, DISPLAY_NAME, FIRST_NAME, LAST_NAME \
-                       FROM %s WHERE CONV_ID  = %d;",
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                       "ADDRESS_TYPE, "
+                       "RECIPIENT_TYPE, "
+                       "ADDRESS_VAL "
+                       "FROM %s WHERE CONV_ID  = %d;",
                        MSGFW_ADDRESS_TABLE_NAME, convId);
 
-       msg_error_t  err = pDbHandle->getTable(sqlQuery, &rowCnt);
+       msg_error_t err = pDbHandle->getTable(sqlQuery, &rowCnt, &index);
 
        if (err == MSG_ERR_DB_NORECORD) {
                pDbHandle->freeTable();
                return MSG_SUCCESS;
        } else if (err != MSG_SUCCESS) {
-               MSG_DEBUG("sqlQuery is - %s", sqlQuery);
+               MSG_DEBUG("Fail to getTable().");
                pDbHandle->freeTable();
                return err;
        }
@@ -594,50 +590,27 @@ msg_error_t MsgStoGetAddressByConvId(MsgDbHandler *pDbHandle, msg_thread_id_t co
        msg_struct_s *pTmp = NULL;
        MSG_ADDRESS_INFO_S *pAddr = NULL;
 
-       pAddrlist->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t) * MAX_TO_ADDRESS_CNT];
+       pAddrlist->msg_struct_info = (msg_struct_t *)calloc(rowCnt, sizeof(msg_struct_t));
 
-       for (int i = 0; i < MAX_TO_ADDRESS_CNT; i++) {
-               pAddrlist->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];
+       for (int i = 0; i < rowCnt; i++) {
+               pAddrlist->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
                pTmp = (msg_struct_s *)pAddrlist->msg_struct_info[i];
                pTmp->type = MSG_STRUCT_ADDRESS_INFO;
-               pTmp->data = new char[sizeof(MSG_ADDRESS_INFO_S)];
+               pTmp->data = new MSG_ADDRESS_INFO_S;
                memset(pTmp->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
        }
 
+//     rowCnt = (rowCnt > 10)? MAX_TO_ADDRESS_CNT: rowCnt;
+
        for (int i = 0; i < rowCnt; i++) {
                pTmp = (msg_struct_s *)pAddrlist->msg_struct_info[i];
                pAddr = (MSG_ADDRESS_INFO_S *)pTmp->data;
 
                pAddr->addressType = pDbHandle->getColumnToInt(index++);
                pAddr->recipientType = pDbHandle->getColumnToInt(index++);
-               pAddr->contactId = pDbHandle->getColumnToInt(index++);
                pDbHandle->getColumnToString(index++, MAX_ADDRESS_VAL_LEN, pAddr->addressVal);
-               pDbHandle->getColumnToString(index++, MAX_DISPLAY_NAME_LEN, pAddr->displayName);
-               if(!strlen(pAddr->displayName))
-               {
-                       pDbHandle->getColumnToString(index++,MAX_DISPLAY_NAME_LEN, firstName);
-                       pDbHandle->getColumnToString(index++,MAX_DISPLAY_NAME_LEN, lastName);
-
-                       if (contactNameOrder == 0) {
-                               if (strlen(firstName) > 0) {
-                                       strncpy(pAddr->displayName, firstName, MAX_DISPLAY_NAME_LEN);
-                               }
-
-                               if (strlen(lastName) > 0) {
-                                       strncat(pAddr->displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(pAddr->displayName));
-                                       strncat(pAddr->displayName, lastName, MAX_DISPLAY_NAME_LEN-strlen(pAddr->displayName));
-                               }
-                       } else if (contactNameOrder == 1) {
-                               if (strlen(lastName) > 0) {
-                                       strncpy(pAddr->displayName, lastName, MAX_DISPLAY_NAME_LEN);
-                                       strncat(pAddr->displayName, " ", MAX_DISPLAY_NAME_LEN-strlen(pAddr->displayName));
-                               }
 
-                               if (strlen(firstName) > 0) {
-                                       strncat(pAddr->displayName, firstName, MAX_DISPLAY_NAME_LEN-strlen(pAddr->displayName));
-                               }
-                       }
-               }
+               strncpy(pAddr->displayName, pAddr->addressVal, MAX_DISPLAY_NAME_LEN);
 
        }
        pDbHandle->freeTable();
@@ -645,147 +618,158 @@ msg_error_t MsgStoGetAddressByConvId(MsgDbHandler *pDbHandle, msg_thread_id_t co
        return MSG_SUCCESS;
 }
 
-
 /* Have to use trigger for this function. */
 msg_error_t MsgStoUpdateConversation(MsgDbHandler *pDbHandle, msg_thread_id_t convId)
 {
        MSG_BEGIN();
 
-       msg_error_t err = MSG_SUCCESS;
-
-       int unreadCnt = 0;
-       int smsCnt = 0;
-       int mmsCnt = 0;
-
-       char msgText[MAX_THREAD_DATA_LEN+1];
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       // Get Unread Count
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND FOLDER_ID = %d AND READ_STATUS = 0;",
-                       MSGFW_MESSAGE_TABLE_NAME, convId, MSG_INBOX_ID);
-
-       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
-
-       err = pDbHandle->stepQuery();
-
-       if (err == MSG_ERR_DB_ROW) {
-               unreadCnt = pDbHandle->columnInt(0);
-       } else if (err != MSG_ERR_DB_DONE) {
-               pDbHandle->finalizeQuery();
-               return MSG_ERR_DB_STEP;
-       }
-
-       pDbHandle->finalizeQuery();
-
-       // Get SMS Count
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND MAIN_TYPE = %d AND FOLDER_ID > 0 AND FOLDER_ID < %d;",
-                       MSGFW_MESSAGE_TABLE_NAME, convId, MSG_SMS_TYPE, MSG_SPAMBOX_ID);
-
-       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
-
-       err = pDbHandle->stepQuery();
-
-       if (err == MSG_ERR_DB_ROW) {
-               smsCnt = pDbHandle->columnInt(0);
-       }
-       else if (err != MSG_ERR_DB_DONE) {
-               pDbHandle->finalizeQuery();
-               return MSG_ERR_DB_STEP;
-       }
-
-       pDbHandle->finalizeQuery();
-
-       // Get MMS Count
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s \
-                       WHERE CONV_ID = %d AND MAIN_TYPE = %d AND SUB_TYPE NOT IN (%d, %d, %d) AND FOLDER_ID > 0 AND FOLDER_ID < %d;",
-                       MSGFW_MESSAGE_TABLE_NAME, convId, MSG_MMS_TYPE, MSG_DELIVERYIND_MMS, MSG_READRECIND_MMS, MSG_READORGIND_MMS, MSG_SPAMBOX_ID);
-
-       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
-
-       err = pDbHandle->stepQuery();
-
-       if (err == MSG_ERR_DB_ROW) {
-               mmsCnt = pDbHandle->columnInt(0);
-       } else if (err != MSG_ERR_DB_DONE) {
-               pDbHandle->finalizeQuery();
-               return MSG_ERR_DB_STEP;
+       char sqlQuery[MAX_QUERY_LEN];
+       unsigned int tmpSize = 0;
+
+#ifdef MSG_NOTI_INTEGRATION
+       memset(sqlQuery, 0x00, MAX_QUERY_LEN);
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "SELECT * "
+                       "FROM %s "
+                       "WHERE CONV_ID = %d "
+                       "AND FOLDER_ID > %d AND FOLDER_ID < %d "
+                       "AND STORAGE_ID = %d;",
+                       MSGFW_MESSAGE_TABLE_NAME,
+                       convId,
+                       MSG_ALLBOX_ID, MSG_SPAMBOX_ID,
+                       MSG_STORAGE_PHONE);
+#else
+       memset(sqlQuery, 0x00, MAX_QUERY_LEN);
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "SELECT * "
+                       "FROM %s "
+                       "WHERE CONV_ID = %d "
+                       "AND FOLDER_ID > %d AND FOLDER_ID < %d "
+                       "AND STORAGE_ID = %d;",
+                       MSGFW_MESSAGE_TABLE_NAME,
+                       convId,
+                       MSG_ALLBOX_ID, MSG_CBMSGBOX_ID,
+                       MSG_STORAGE_PHONE);
+#endif
+
+       msg_error_t err = pDbHandle->prepareQuery(sqlQuery);
+       if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("Fail to prepareQuery().");
+                       pDbHandle->finalizeQuery();
+                       return err;
        }
 
-       pDbHandle->finalizeQuery();
-
-       // Get Latest Msg Data
-       MSG_MAIN_TYPE_T mainType = MSG_UNKNOWN_TYPE;
-       MSG_SUB_TYPE_T subType = MSG_NORMAL_SMS;
-       msg_direction_type_t direction = MSG_DIRECTION_TYPE_MO;
-       time_t msgTime = 0;
-
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MAIN_TYPE, SUB_TYPE, MSG_DIRECTION, DISPLAY_TIME, SUBJECT, MSG_TEXT FROM %s \
-                       WHERE CONV_ID = %d AND FOLDER_ID > 0 AND FOLDER_ID < %d ORDER BY DISPLAY_TIME DESC;",
-                       MSGFW_MESSAGE_TABLE_NAME, convId, MSG_SPAMBOX_ID);
-
-       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
-               return MSG_ERR_DB_PREPARE;
-
-       err = pDbHandle->stepQuery();
-
-       if (err == MSG_ERR_DB_ROW) {
-               mainType = pDbHandle->columnInt(0);
-               subType = pDbHandle->columnInt(1);
-               direction = pDbHandle->columnInt(2);
-
-               msgTime = (time_t)pDbHandle->columnInt(3);
-
-               memset(msgText, 0x00, sizeof(msgText));
-
-               if (mainType == MSG_SMS_TYPE) {
-                       if (pDbHandle->columnText(5) != NULL)
-                               strncpy(msgText, (char*)pDbHandle->columnText(5), MAX_THREAD_DATA_LEN);
-               } else if (mainType == MSG_MMS_TYPE) {
-                       if (pDbHandle->columnText(4) != NULL) {
-                               strncpy(msgText, (char*)pDbHandle->columnText(4), MAX_THREAD_DATA_LEN);
-                       }
-
-                       if ((strlen(msgText) <= 0) && (pDbHandle->columnText(5) != NULL) && (subType != MSG_NOTIFICATIONIND_MMS)) {
-                               memset(msgText, 0x00, sizeof(msgText));
-                               strncpy(msgText, (char*)pDbHandle->columnText(5), MAX_THREAD_DATA_LEN);
-                       }
-               }
-       } else if (err != MSG_ERR_DB_DONE) {
-               pDbHandle->finalizeQuery();
-               return MSG_ERR_DB_STEP;
+       if (pDbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               memset(sqlQuery, 0x00, MAX_QUERY_LEN);
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "UPDATE %s SET ",
+                               MSGFW_CONVERSATION_TABLE_NAME);
+
+               tmpSize = strlen(sqlQuery);
+#ifdef MSG_NOTI_INTEGRATION
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "UNREAD_CNT = (SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND (FOLDER_ID = %d OR FOLDER_ID = %d) AND STORAGE_ID = %d AND READ_STATUS = 0), ",
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_INBOX_ID, MSG_CBMSGBOX_ID, MSG_STORAGE_PHONE);
+#else
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "UNREAD_CNT = (SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND FOLDER_ID = %d AND STORAGE_ID = %d AND READ_STATUS = 0), ",
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_INBOX_ID, MSG_STORAGE_PHONE);
+#endif
+
+               tmpSize = strlen(sqlQuery);
+#ifdef MSG_NOTI_INTEGRATION
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "SMS_CNT = (SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND MAIN_TYPE = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d), ",
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_SMS_TYPE, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE);
+#else
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "SMS_CNT = (SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND MAIN_TYPE = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d), ",
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_SMS_TYPE, MSG_ALLBOX_ID, MSG_CBMSGBOX_ID, MSG_STORAGE_PHONE);
+#endif
+
+               tmpSize = strlen(sqlQuery);
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "MMS_CNT = (SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND MAIN_TYPE = %d AND SUB_TYPE NOT IN (%d, %d, %d) AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d), ",
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_MMS_TYPE, MSG_DELIVERYIND_MMS, MSG_READRECIND_MMS, MSG_READORGIND_MMS, MSG_ALLBOX_ID, MSG_CBMSGBOX_ID, MSG_STORAGE_PHONE);
+
+               tmpSize = strlen(sqlQuery);
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "MAIN_TYPE = (SELECT MAIN_TYPE FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d ORDER BY DISPLAY_TIME DESC), ",
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE);
+
+               tmpSize = strlen(sqlQuery);
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "SUB_TYPE = (SELECT SUB_TYPE FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d ORDER BY DISPLAY_TIME DESC), ",
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE);
+
+               tmpSize = strlen(sqlQuery);
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "MSG_DIRECTION = (SELECT MSG_DIRECTION FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d ORDER BY DISPLAY_TIME DESC), ",
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE);
+
+               tmpSize = strlen(sqlQuery);
+#if 1
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "DISPLAY_TIME = CASE "
+                               "WHEN (SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND SCHEDULED_TIME = 0 ORDER BY DISPLAY_TIME DESC) > 0 "
+                               "THEN (SELECT DISPLAY_TIME FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND SCHEDULED_TIME = 0 ORDER BY DISPLAY_TIME DESC) "
+                               "ELSE 0 "
+                               "END, ",
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE,
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE);
+#else
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "DISPLAY_TIME = CASE "
+                               "WHEN (SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND FOLDER_ID = %d AND STORAGE_ID = %d AND READ_STATUS = 0) > 0 "
+                               "THEN (SELECT DISPLAY_TIME FROM %s WHERE CONV_ID = %d AND FOLDER_ID = %d AND STORAGE_ID = %d AND READ_STATUS = 0 ORDER BY DISPLAY_TIME DESC) "
+                               "WHEN (SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND FOLDER_ID = %d AND STORAGE_ID = %d) > 0 "
+                               "THEN (SELECT DISPLAY_TIME FROM %s WHERE CONV_ID = %d AND FOLDER_ID = %d AND STORAGE_ID = %d ORDER BY DISPLAY_TIME DESC) "
+                               "WHEN (SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND FOLDER_ID = %d AND STORAGE_ID = %d AND NETWORK_STATUS = %d) > 0 "
+                               "THEN (SELECT DISPLAY_TIME FROM %s WHERE CONV_ID = %d AND FOLDER_ID = %d AND STORAGE_ID = %d AND NETWORK_STATUS = %d ORDER BY DISPLAY_TIME DESC) "
+                               "ELSE (SELECT DISPLAY_TIME FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d ORDER BY DISPLAY_TIME DESC) "
+                               "END, ",
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_INBOX_ID, MSG_STORAGE_PHONE,
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_INBOX_ID, MSG_STORAGE_PHONE,
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_DRAFT_ID, MSG_STORAGE_PHONE,
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_DRAFT_ID, MSG_STORAGE_PHONE,
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_OUTBOX_ID, MSG_STORAGE_PHONE, MSG_NETWORK_SEND_FAIL,
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_OUTBOX_ID, MSG_STORAGE_PHONE, MSG_NETWORK_SEND_FAIL,
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE);
+#endif
+
+               tmpSize = strlen(sqlQuery);
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "MSG_TEXT = CASE "
+                               "WHEN (SELECT COUNT(MSG_ID) FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND SCHEDULED_TIME = 0 ORDER BY DISPLAY_TIME DESC) > 0 "
+                               "THEN CASE "
+                               "WHEN (SELECT LENGTH(SUBJECT) FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND SCHEDULED_TIME = 0 ORDER BY DISPLAY_TIME DESC) > 0 "
+                               "THEN (SELECT SUBJECT FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND SCHEDULED_TIME = 0 ORDER BY DISPLAY_TIME DESC) "
+                               "ELSE (SELECT MSG_TEXT FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d AND SCHEDULED_TIME = 0 ORDER BY DISPLAY_TIME DESC) "
+                               "END ELSE '' "
+                               "END ",
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE,
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE,
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE,
+                               MSGFW_MESSAGE_TABLE_NAME, convId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE);
+
+               tmpSize = strlen(sqlQuery);
+               snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                               "WHERE CONV_ID = %d;",
+                               convId);
+       } else {
+               memset(sqlQuery, 0x00, MAX_QUERY_LEN);
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "UPDATE %s SET UNREAD_CNT = 0, SMS_CNT = 0, MMS_CNT = 0, MAIN_TYPE = 0, SUB_TYPE = 0, MSG_DIRECTION = 0, DISPLAY_TIME = 0, MSG_TEXT = '' "
+                               "WHERE CONV_ID = %d;",
+                               MSGFW_CONVERSATION_TABLE_NAME, convId);
        }
 
        pDbHandle->finalizeQuery();
 
-       // Update Address Table
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET \
-                       UNREAD_CNT = %d, SMS_CNT = %d, MMS_CNT = %d, MAIN_TYPE = %d, SUB_TYPE = %d, MSG_DIRECTION = %d, DISPLAY_TIME = %ld, MSG_TEXT = ? \
-                       WHERE CONV_ID = %d;", MSGFW_CONVERSATION_TABLE_NAME, unreadCnt, smsCnt, mmsCnt, mainType, subType, direction, msgTime, convId);
-
-       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+       if (pDbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
                MSG_DEBUG("Query Failed [%s]", sqlQuery);
-               return MSG_ERR_DB_PREPARE;
-       }
-
-       pDbHandle->bindText(msgText, 1);
-
-       if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
                pDbHandle->finalizeQuery();
-               MSG_DEBUG("Update Address Info. Fail [%d] [%s]", err, sqlQuery);
-               return MSG_ERR_DB_STEP;
+               return MSG_ERR_DB_EXEC;
        }
 
        pDbHandle->finalizeQuery();
@@ -820,187 +804,119 @@ msg_error_t MsgStoClearConversationTable(MsgDbHandler *pDbHandle)
 }
 
 
-void MsgConvertNumber(const char* pSrcNum, char* pDestNum)
-{
-       int overLen = 0;
-       int i = 0;
-
-       overLen = strlen(pSrcNum) - MAX_PRECONFIG_NUM;
-
-       for (i = 0; i < MAX_PRECONFIG_NUM; i++)
-               pDestNum[i] = pSrcNum[i+overLen];
-
-       pDestNum[i] = '\0';
-}
-
 /* Change the function name to conversation related. */
 bool MsgExistAddress(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsg, msg_thread_id_t *pConvId)
 {
        msg_error_t err = MSG_SUCCESS;
 
        char sqlQuery[MAX_QUERY_LEN+1];
+       unsigned int tmpSize = 0;
 
        *pConvId = 0;
 
-       if(pMsg->nAddressCnt == 1) {
-               if (strlen(pMsg->addressList[0].addressVal) > MAX_PRECONFIG_NUM) {
-                       char newPhoneNum[MAX_PRECONFIG_NUM+1];
-
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "SELECT CONV_ID FROM ( SELECT CONV_ID FROM %s WHERE ( ",
+                       MSGFW_ADDRESS_TABLE_NAME);
+
+       for (int i = 0; i < pMsg->nAddressCnt; i++) {
+               if (strlen(pMsg->addressList[i].addressVal) >= (unsigned int)MsgContactGetMinMatchDigit()
+                               && pMsg->addressList[i].addressType != MSG_ADDRESS_TYPE_EMAIL
+                               && MsgIsNumber(pMsg->addressList[i].addressVal)) {
+                       int addrSize = strlen(pMsg->addressList[i].addressVal);
+                       char newPhoneNum[addrSize+1];
                        memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
+                       MsgConvertNumber(pMsg->addressList[i].addressVal, newPhoneNum, addrSize);
 
-                       MsgConvertNumber(pMsg->addressList[0].addressVal, newPhoneNum);
-
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
-
-                       snprintf(sqlQuery, sizeof(sqlQuery),
-                                       "SELECT CONV_ID FROM (SELECT B.CONV_ID FROM %s A, %s B WHERE A.ADDRESS_VAL LIKE '%%%%%s' AND A.CONV_ID=B.CONV_ID) GROUP BY CONV_ID HAVING COUNT(CONV_ID)=1;",
-                                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, newPhoneNum);
-               } else {
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       tmpSize = strlen(sqlQuery);
+                       snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                                       "ADDRESS_VAL LIKE '%%%%%s' ",
+                                       newPhoneNum);
 
-                       snprintf(sqlQuery, sizeof(sqlQuery),
-                                       "SELECT CONV_ID FROM (SELECT B.CONV_ID FROM %s A, %s B WHERE A.ADDRESS_VAL = '%s' AND A.CONV_ID=B.CONV_ID) GROUP BY CONV_ID HAVING COUNT(CONV_ID)=1;",
-                                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, pMsg->addressList[0].addressVal);
-               }
+                       if ((pMsg->nAddressCnt-1) == i) break;
 
-               int rowCnt = 0;
-               msg_thread_id_t convId = 0;
-               err = pDbHandle->getTable(sqlQuery, &rowCnt);
+                       tmpSize = strlen(sqlQuery);
+                       snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize, " OR ");
 
-               /* No record or other error */
-               if (err != MSG_SUCCESS) {
-                       MSG_DEBUG("Query Failed [%s]", sqlQuery);
-                       pDbHandle->freeTable();
-                       return false;
-               }
+               } else {
 
-               if(rowCnt > 0) {
-                       convId = pDbHandle->getColumnToInt(1);
+                       tmpSize = strlen(sqlQuery);
+                       snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                                       "ADDRESS_VAL LIKE '%s' ",
+                                       pMsg->addressList[i].addressVal);
 
-                       MSG_DEBUG("CONV_ID : [%d]", convId);
+                       if ((pMsg->nAddressCnt-1) == i) break;
 
-                       if (convId > 0) {
-                               *pConvId = convId;
-                               pDbHandle->freeTable();
-                               return true;
-                       } else {
-                               pDbHandle->freeTable();
-                               return false;
-                       }
+                       tmpSize = strlen(sqlQuery);
+                       snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize, " OR ");
 
-                       pDbHandle->freeTable();
                }
+       }
 
-       } else { /* multiple address */
-               if (strlen(pMsg->addressList[0].addressVal) > MAX_PRECONFIG_NUM) {
-                       char newPhoneNum[MAX_PRECONFIG_NUM+1];
-
-                       memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
-
-                       MsgConvertNumber(pMsg->addressList[0].addressVal, newPhoneNum);
+       tmpSize = strlen(sqlQuery);
+       snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                       ") AND CONV_ID IN (SELECT CONV_ID FROM %s GROUP BY CONV_ID HAVING COUNT(CONV_ID)=%d) ",
+                       MSGFW_ADDRESS_TABLE_NAME, pMsg->nAddressCnt);
 
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-                       snprintf(sqlQuery, sizeof(sqlQuery),
-                                       "SELECT CONV_ID FROM (SELECT B.CONV_ID FROM %s A, %s B WHERE A.ADDRESS_VAL LIKE '%%%%%s' AND A.CONV_ID=B.CONV_ID) GROUP BY CONV_ID HAVING COUNT(CONV_ID)=%d;",
-                                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, newPhoneNum, pMsg->nAddressCnt);
-               } else {
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       tmpSize = strlen(sqlQuery);
+       snprintf(sqlQuery+tmpSize, MAX_QUERY_LEN-tmpSize,
+                       ") GROUP BY CONV_ID HAVING COUNT(CONV_ID)=%d;",
+                       pMsg->nAddressCnt);
 
-                       snprintf(sqlQuery, sizeof(sqlQuery),
-                                       "SELECT CONV_ID FROM (SELECT B.CONV_ID FROM %s A, %s B WHERE A.ADDRESS_VAL = '%s' AND A.CONV_ID=B.CONV_ID) GROUP BY CONV_ID HAVING COUNT(CONV_ID)=%d;",
-                                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, pMsg->addressList[0].addressVal, pMsg->nAddressCnt);
-               }
+       int rowCnt = 0;
+       int convId = 0;
 
-               int rowCnt = 0;
-               int convId = 0;
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
-               MSG_DEBUG("Query [%s]", sqlQuery);
+       /* No record or other error */
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               pDbHandle->freeTable();
+               return false;
+       }
 
-               err = pDbHandle->getTable(sqlQuery, &rowCnt);
+       convId = pDbHandle->getColumnToInt(1);
 
-               /* No record or other error */
-               if (err != MSG_SUCCESS) {
-                       MSG_DEBUG("Query Failed [%s]", sqlQuery);
-                       pDbHandle->freeTable();
-                       return false;
-               }
+       if (convId > 0) {
+               MSG_DEBUG("Success  to get convId [%d]", convId);
+               *pConvId = convId;
+               pDbHandle->freeTable();
+               return true;
+       }
 
-               for (int i = 1; i <= rowCnt; i++) {
-                       convId = pDbHandle->getColumnToInt(i);
+       pDbHandle->freeTable();
 
-                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       return false;
+}
 
-                       snprintf(sqlQuery, sizeof(sqlQuery),
-                                       "SELECT COUNT(*) FROM %s WHERE CONV_ID=%d AND (",
-                                       MSGFW_ADDRESS_TABLE_NAME, convId);
 
-                       for (int j = 0; j<(pMsg->nAddressCnt); j++ ) {
+int MsgStoGetUnreadCnt(MsgDbHandler *pDbHandle, MSG_MAIN_TYPE_T msgType)
+{
+       int msgCnt = 0;
 
-                               if (j!=0)
-                                       strncat(sqlQuery, "OR ", MAX_QUERY_LEN-strlen(sqlQuery));
+       char sqlQuery[MAX_QUERY_LEN+1];
 
-                               if (strlen(pMsg->addressList[j].addressVal) > MAX_PRECONFIG_NUM) {
-
-                                       strncat(sqlQuery, "ADDRESS_VAL LIKE '%%%%", MAX_QUERY_LEN-strlen(sqlQuery));
-
-                                       char newPhoneNum[MAX_PRECONFIG_NUM+1];
-                                       memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
-                                       MsgConvertNumber(pMsg->addressList[j].addressVal, newPhoneNum);
-
-                                       strncat(sqlQuery, newPhoneNum, MAX_QUERY_LEN-strlen(sqlQuery));
-
-                                       strncat(sqlQuery, "' ", MAX_QUERY_LEN-strlen(sqlQuery));
-                               } else {
-                                       strncat(sqlQuery, "ADDRESS_VAL = '", MAX_QUERY_LEN-strlen(sqlQuery));
-
-                                       strncat(sqlQuery, pMsg->addressList[j].addressVal, MAX_QUERY_LEN-strlen(sqlQuery));
-
-                                       strncat(sqlQuery, "' ", MAX_QUERY_LEN-strlen(sqlQuery));
-                               }
-                       }
-                       strncat(sqlQuery, ");", MAX_QUERY_LEN-strlen(sqlQuery));
-                       MSG_DEBUG("Query [%s]", sqlQuery);
-                       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
-                               MSG_DEBUG("Query Failed [%s]", sqlQuery);
-                               pDbHandle->freeTable();
-                               pDbHandle->finalizeQuery();
-                               return false;
-                       }
-
-                       if (pDbHandle->stepQuery() == MSG_ERR_DB_ROW) {
-                               if (pMsg->nAddressCnt == pDbHandle->columnInt(0)) {
-                                       *pConvId = convId;
-                                       pDbHandle->finalizeQuery();
-                                       pDbHandle->freeTable();
-                                       return true;
-                               }
-                       }
-                       pDbHandle->finalizeQuery();
-               }
-               pDbHandle->freeTable();
-       }
-
-       return false;
-}
-
-
-int MsgStoGetUnreadCnt(MsgDbHandler *pDbHandle, MSG_MAIN_TYPE_T msgType)
-{
-       int msgCnt = 0;
-
-       char sqlQuery[MAX_QUERY_LEN+1];
-
-       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
        if (msgType == MSG_SMS_TYPE) {
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s \
-                               WHERE MAIN_TYPE = %d AND SUB_TYPE IN (%d, %d, %d, %d, %d, %d, %d) AND FOLDER_ID = %d AND READ_STATUS = 0;",
-                               MSGFW_MESSAGE_TABLE_NAME, MSG_SMS_TYPE, MSG_NORMAL_SMS, MSG_STATUS_REPORT_SMS, MSG_CONCAT_SIM_SMS, MSG_WAP_SI_SMS, MSG_WAP_SL_SMS, MSG_MWI_VOICE_SMS, MSG_SYNCML_CP, MSG_INBOX_ID);
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s "
+                               "WHERE MAIN_TYPE = %d "
+                               "AND (SUB_TYPE IN (%d, %d, %d, %d, %d, %d, %d) OR (SUB_TYPE >= %d AND SUB_TYPE <= %d)) "
+                               "AND FOLDER_ID = %d AND READ_STATUS = 0 AND STORAGE_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               MSG_SMS_TYPE,
+                               MSG_NORMAL_SMS, MSG_STATUS_REPORT_SMS, MSG_CONCAT_SIM_SMS, MSG_WAP_SI_SMS, MSG_WAP_SL_SMS, MSG_MWI_VOICE_SMS, MSG_SYNCML_CP,
+                               MSG_REPLACE_TYPE1_SMS, MSG_REPLACE_TYPE7_SMS,
+                               MSG_INBOX_ID, MSG_STORAGE_PHONE);
        } else if (msgType == MSG_MMS_TYPE) {
-               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s \
-                               WHERE MAIN_TYPE = %d AND SUB_TYPE IN (%d, %d, %d) AND FOLDER_ID = %d AND READ_STATUS = 0;",
-                               MSGFW_MESSAGE_TABLE_NAME, MSG_MMS_TYPE, MSG_RETRIEVE_AUTOCONF_MMS, MSG_RETRIEVE_MANUALCONF_MMS, MSG_NOTIFICATIONIND_MMS, MSG_INBOX_ID);
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s "
+                               "WHERE MAIN_TYPE = %d AND SUB_TYPE IN (%d, %d, %d) "
+                               "AND FOLDER_ID = %d AND READ_STATUS = 0 AND STORAGE_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               MSG_MMS_TYPE,
+                               MSG_RETRIEVE_AUTOCONF_MMS, MSG_RETRIEVE_MANUALCONF_MMS, MSG_NOTIFICATIONIND_MMS,
+                               MSG_INBOX_ID, MSG_STORAGE_PHONE);
        }
 
        if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
@@ -1021,36 +937,61 @@ int MsgStoGetUnreadCnt(MsgDbHandler *pDbHandle, MSG_MAIN_TYPE_T msgType)
 
 msg_error_t MsgStoAddContactInfo(MsgDbHandler *pDbHandle, MSG_CONTACT_INFO_S *pContactInfo, const char *pNumber)
 {
-       char newPhoneNum[MAX_PRECONFIG_NUM+1];
+
+       if (pDbHandle == NULL || pContactInfo == NULL || pNumber == NULL) {
+               MSG_DEBUG("pDbHandle == NULL || pContactInfo == NULL || pNumber == NULL");
+               return  MSG_ERR_NULL_POINTER;
+       }
+
        char sqlQuery[MAX_QUERY_LEN+1];
+       char displayName[MAX_DISPLAY_NAME_LEN+1];
+       memset(displayName, 0x00, sizeof(displayName));
 
-       if (strlen(pNumber) > MAX_PRECONFIG_NUM) {
+       if (strlen(pNumber) > (unsigned int)MsgContactGetMinMatchDigit()) {
+               int addrSize = strlen(pNumber);
+               char newPhoneNum[addrSize+1];
                memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
-               MsgConvertNumber(pNumber, newPhoneNum);
+               MsgConvertNumber(pNumber, newPhoneNum, addrSize);
 
-               MSG_DEBUG("Phone Number to Compare : [%s]", newPhoneNum);
+               MSG_SEC_DEBUG("Phone Number to Compare : [%s]", newPhoneNum);
 
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET \
-                               CONTACT_ID = %d, DISPLAY_NAME = ?, FIRST_NAME = ?, LAST_NAME = ?, IMAGE_PATH = '%s' \
-                               WHERE ADDRESS_VAL LIKE '%%%%%s';",
-                               MSGFW_ADDRESS_TABLE_NAME, pContactInfo->contactId, pContactInfo->imagePath, newPhoneNum);
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET "
+                               "CONTACT_ID = %d, "
+                               "ADDR_BOOK_ID = %d, "
+                               "FIRST_NAME = ?, "
+                               "LAST_NAME = ?, "
+                               "MIDDLE_NAME = ?, "
+                               "PREFIX = ?, "
+                               "SUFFIX = ?, "
+                               "IMAGE_PATH = '%s' "
+                               "WHERE ADDRESS_VAL LIKE '%%%%%s';",
+                               MSGFW_ADDRESS_TABLE_NAME, pContactInfo->contactId, pContactInfo->addrbookId, pContactInfo->imagePath, newPhoneNum);
        } else {
                memset(sqlQuery, 0x00, sizeof(sqlQuery));
-               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET \
-                               CONTACT_ID = %d, DISPLAY_NAME = ?, FIRST_NAME = ?, LAST_NAME = ?, IMAGE_PATH = '%s' \
-                               WHERE ADDRESS_VAL = '%s';",
-                               MSGFW_ADDRESS_TABLE_NAME, pContactInfo->contactId, pContactInfo->imagePath, pNumber);
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET "
+                               "CONTACT_ID = %d, "
+                               "ADDR_BOOK_ID = %d, "
+                               "FIRST_NAME = ?, "
+                               "LAST_NAME = ?, "
+                               "MIDDLE_NAME = ?, "
+                               "PREFIX = ?, "
+                               "SUFFIX = ?, "
+                               "IMAGE_PATH = '%s' "
+                               "WHERE ADDRESS_VAL = '%s';",
+                               MSGFW_ADDRESS_TABLE_NAME, pContactInfo->contactId, pContactInfo->addrbookId, pContactInfo->imagePath, pNumber);
        }
 
-       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
                return MSG_ERR_DB_PREPARE;
+       }
 
-       pDbHandle->bindText(pContactInfo->displayName, 1);
-
-       pDbHandle->bindText(pContactInfo->firstName, 2);
-
-       pDbHandle->bindText(pContactInfo->lastName, 3);
+       pDbHandle->bindText(pContactInfo->firstName, 1);
+       pDbHandle->bindText(pContactInfo->lastName, 2);
+       pDbHandle->bindText(pContactInfo->middleName, 3);
+       pDbHandle->bindText(pContactInfo->prefix, 4);
+       pDbHandle->bindText(pContactInfo->suffix, 5);
 
        if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
                pDbHandle->finalizeQuery();
@@ -1064,6 +1005,41 @@ msg_error_t MsgStoAddContactInfo(MsgDbHandler *pDbHandle, MSG_CONTACT_INFO_S *pC
 }
 
 
+msg_error_t MsgStoClearContactInfoByAddrbookIdList(MsgDbHandler *pDbHandle, int* addrbookList, int addrbookCnt)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       int rowCnt = 0;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT(CONTACT_ID) FROM %s WHERE ADDR_BOOK_ID NOT IN ( ", MSGFW_ADDRESS_TABLE_NAME);
+
+       for (int i=0; i<(addrbookCnt-1); i++) {
+               snprintf(sqlQuery+strlen(sqlQuery), sizeof(sqlQuery)-strlen(sqlQuery), "%d, ", addrbookList[i]);
+       }
+
+       snprintf(sqlQuery+strlen(sqlQuery), sizeof(sqlQuery)-strlen(sqlQuery), "%d );", addrbookList[addrbookCnt-1]);
+
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+       if (err != MSG_SUCCESS) {
+               pDbHandle->freeTable();
+               MSG_DEBUG("Fail to getTable().");
+               return err;
+       }
+
+       MsgDbHandler tmpDbHandle;
+       for (int i=1; i<=rowCnt; i++)
+               MsgStoClearContactInfo(&tmpDbHandle, pDbHandle->getColumnToInt(i));
+
+       pDbHandle->freeTable();
+
+       return err;
+}
+
+
 msg_error_t MsgStoClearContactInfo(MsgDbHandler *pDbHandle, int contactId)
 {
        msg_error_t err = MSG_SUCCESS;
@@ -1076,7 +1052,7 @@ msg_error_t MsgStoClearContactInfo(MsgDbHandler *pDbHandle, int contactId)
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT(CONV_ID) FROM %s WHERE CONTACT_ID = %d;",
                        MSGFW_ADDRESS_TABLE_NAME, contactId);
 
-       err = pDbHandle->getTable(sqlQuery, &rowCnt);
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
        if (err != MSG_SUCCESS) {
                pDbHandle->freeTable();
@@ -1085,12 +1061,21 @@ msg_error_t MsgStoClearContactInfo(MsgDbHandler *pDbHandle, int contactId)
        }
 
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
-       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET \
-                       CONTACT_ID = 0, DISPLAY_NAME = '', FIRST_NAME = '', LAST_NAME = '', IMAGE_PATH = '' \
-                       WHERE CONTACT_ID = %d;",
-                       MSGFW_ADDRESS_TABLE_NAME, contactId);
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET "
+                       "CONTACT_ID = 0, "
+                       "ADDR_BOOK_ID = 0, "
+                       "FIRST_NAME = '', "
+                       "LAST_NAME = '', "
+                       "MIDDLE_NAME = '', "
+                       "PREFIX = '', "
+                       "SUFFIX = '', "
+                       "IMAGE_PATH = '' "
+                       "WHERE CONTACT_ID = %d;",
+                       MSGFW_ADDRESS_TABLE_NAME,
+                       contactId);
 
        if (pDbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               pDbHandle->freeTable();
                MSG_DEBUG("Fail to execute query");
                return MSG_ERR_DB_EXEC;
        }
@@ -1105,36 +1090,73 @@ msg_error_t MsgStoClearContactInfo(MsgDbHandler *pDbHandle, int contactId)
 }
 
 
-msg_error_t MsgStoClearContactInfo(MsgDbHandler *pDbHandle, int contactId, const char *pNumber)
+msg_error_t MsgStoResetContactInfo(MsgDbHandler *pDbHandle, int contactId)
 {
-       char newPhoneNum[MAX_PRECONFIG_NUM+1];
+       msg_error_t err = MSG_SUCCESS;
+
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
+       int rowCnt = 0, index = 0;
+
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
 
-       if (strlen(pNumber) > MAX_PRECONFIG_NUM) {
-               MsgConvertNumber(pNumber, newPhoneNum);
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT ADDRESS_VAL, CONV_ID FROM %s WHERE CONTACT_ID = %d;",
+                       MSGFW_ADDRESS_TABLE_NAME, contactId);
 
-               MSG_DEBUG("Phone Number to Compare : [%s]", newPhoneNum);
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, &index);
 
-               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET \
-                               CONTACT_ID = 0, DISPLAY_NAME = '', FIRST_NAME = '', LAST_NAME = '', IMAGE_PATH = '' \
-                               WHERE CONTACT_ID = %d AND ADDRESS_VAL NOT LIKE '%%%s';",
-                               MSGFW_ADDRESS_TABLE_NAME, contactId, newPhoneNum);
-       } else {
-               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET \
-                               CONTACT_ID = 0, DISPLAY_NAME = '', FIRST_NAME = '', LAST_NAME = '', IMAGE_PATH = '' \
-                               WHERE CONTACT_ID = %d AND ADDRESS_VAL <> '%s';",
-                               MSGFW_ADDRESS_TABLE_NAME, contactId, pNumber);
+       if (err != MSG_SUCCESS) {
+               pDbHandle->freeTable();
+               MSG_DEBUG("[Error]Failed to Get Table");
+               return err;
        }
 
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET "
+                       "CONTACT_ID = 0, "
+                       "ADDR_BOOK_ID = 0, "
+                       "FIRST_NAME = '', "
+                       "LAST_NAME = '', "
+                       "MIDDLE_NAME = '', "
+                       "PREFIX = '', "
+                       "SUFFIX = '', "
+                       "IMAGE_PATH = '' "
+                       "WHERE CONTACT_ID = %d;",
+                       MSGFW_ADDRESS_TABLE_NAME,
+                       contactId);
+
        if (pDbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               pDbHandle->freeTable();
                MSG_DEBUG("Fail to execute query");
                return MSG_ERR_DB_EXEC;
        }
 
-       return MSG_SUCCESS;
+       MsgDbHandler tmpDbHandle;
+       for (int i=0; i<rowCnt; i++) {
+
+               char *strNumber = pDbHandle->getColumnToString(index++);
+               MSG_CONTACT_INFO_S contactInfo;
+               memset(&contactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+               if (strNumber != NULL) {
+                       MSG_SEC_DEBUG("Number [%s]", strNumber);
+
+                       MSG_ADDRESS_INFO_S addrInfo;
+                       memset(&addrInfo, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+                       strncpy(addrInfo.addressVal, strNumber, MAX_ADDRESS_VAL_LEN);
+
+                       if(MsgGetContactInfo(&addrInfo, &contactInfo) == MSG_SUCCESS) {
+                               if (!MsgInsertContact(&contactInfo, strNumber))
+                                       MSG_DEBUG("MsgInsertContact fail.");
+                       }
+               }
+
+               MsgStoSetConversationDisplayName(&tmpDbHandle, (msg_thread_id_t)pDbHandle->getColumnToInt(index++));
+       }
+
+       pDbHandle->freeTable();
+
+       return err;
 }
 
 
@@ -1179,7 +1201,7 @@ bool MsgStoCheckReadReportRequested(MsgDbHandler *pDbHandle, msg_message_id_t ms
                        WHERE A.MSG_ID = B.MSG_ID AND B.MSG_ID = %d;",
                        MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, msgId);
 
-       err = pDbHandle->getTable(sqlQuery, &rowCnt);
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
        if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
                pDbHandle->freeTable();
@@ -1216,7 +1238,7 @@ bool MsgStoCheckReadReportIsSent(MsgDbHandler *pDbHandle, msg_message_id_t msgId
                        WHERE A.MSG_ID = B.MSG_ID AND B.MSG_ID = %d;",
                        MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, msgId);
 
-       err = pDbHandle->getTable(sqlQuery, &rowCnt);
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
        if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
                pDbHandle->freeTable();
@@ -1242,10 +1264,11 @@ msg_error_t MsgStoAddConversation(MsgDbHandler *pDbHandle, msg_thread_id_t *pCon
 {
        char sqlQuery[MAX_QUERY_LEN+1];
 
-       if (pDbHandle->getRowId(MSGFW_CONVERSATION_TABLE_NAME, pConvId) != MSG_SUCCESS) {
-               return MSG_ERR_DB_EXEC;
+       if(*pConvId == 0) {
+               if (pDbHandle->getRowId(MSGFW_CONVERSATION_TABLE_NAME, pConvId) != MSG_SUCCESS) {
+                       return MSG_ERR_DB_EXEC;
+               }
        }
-
        // Add Conversation
        memset(sqlQuery, 0x00, sizeof(sqlQuery));
        snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, 0, 0, 0, 0, 0, 0, 0, '', '');",
@@ -1273,11 +1296,11 @@ msg_error_t MsgStoSetConversationDisplayName(MsgDbHandler *pDbHandle, int contac
        snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT(CONV_ID) FROM %s WHERE CONTACT_ID = %d;",
                        MSGFW_ADDRESS_TABLE_NAME, contactId);
 
-       err = pDbHandle->getTable(sqlQuery, &rowCnt);
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
 
        if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
                pDbHandle->freeTable();
-               MSG_DEBUG("Query Failed [%s]", sqlQuery);
+               MSG_DEBUG("Fail to getTable().");
                return err;
        }
 
@@ -1311,6 +1334,7 @@ msg_error_t MsgStoSetConversationDisplayName(MsgDbHandler *pDbHandle, int contac
                                MSGFW_CONVERSATION_TABLE_NAME, pDbHandle->getColumnToInt(i));
 
                if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       pDbHandle->freeTable();
                        MSG_DEBUG("Query Failed [%s]", sqlQuery);
                        return MSG_ERR_DB_PREPARE;
                }
@@ -1318,18 +1342,23 @@ msg_error_t MsgStoSetConversationDisplayName(MsgDbHandler *pDbHandle, int contac
                pDbHandle->bindText(displayName, 1);
 
                if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                       pDbHandle->freeTable();
                        pDbHandle->finalizeQuery();
-                       MSG_DEBUG("Update Conversation disply name. Fail [%s]", sqlQuery);
+                       MSG_SEC_DEBUG("Update Conversation disply name. Fail [%s]", sqlQuery);
                        return MSG_ERR_DB_STEP;
                }
 
                pDbHandle->finalizeQuery();
 
                // free address list
-               for(int j = 0; j < MAX_TO_ADDRESS_CNT; j++){
+               for (int j = 0; j < addressList.nCount; j++) {
                        msg_struct_s *pStruct = (msg_struct_s *)addressList.msg_struct_info[j];
-                       delete [] (MSG_ADDRESS_INFO_S *)pStruct->data;
-                       delete [] (msg_struct_s *)pStruct;
+                       delete (MSG_ADDRESS_INFO_S *)pStruct->data;
+                       delete (msg_struct_s *)pStruct;
+               }
+
+               if (addressList.msg_struct_info != NULL) {
+                       g_free((msg_struct_t *)addressList.msg_struct_info);
                }
        }
 
@@ -1383,65 +1412,1944 @@ msg_error_t MsgStoSetConversationDisplayName(MsgDbHandler *pDbHandle, msg_thread
 
        if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
                pDbHandle->finalizeQuery();
-               MSG_DEBUG("Update Conversation disply name. Fail [%s]", sqlQuery);
+               MSG_SEC_DEBUG("Update Conversation disply name. Fail [%s]", sqlQuery);
                return MSG_ERR_DB_STEP;
        }
 
        pDbHandle->finalizeQuery();
 
-       for(int j = 0; j < MAX_TO_ADDRESS_CNT; j++){
+       for (int j = 0; j < addressList.nCount; j++) {
                msg_struct_s *pStruct = (msg_struct_s *)addressList.msg_struct_info[j];
-               delete [] (MSG_ADDRESS_INFO_S *)pStruct->data;
-               delete [] (msg_struct_s *)pStruct;
+               delete (MSG_ADDRESS_INFO_S *)pStruct->data;
+               delete (msg_struct_s *)pStruct;
+       }
+
+       if (addressList.msg_struct_info != NULL) {
+               g_free((msg_struct_t *)addressList.msg_struct_info);
        }
 
        return err;
 }
 
+msg_error_t MsgStoUpdateNetworkStatus(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S *pMsgInfo, msg_network_status_t status)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET NETWORK_STATUS = %d WHERE MSG_ID = %d;",
+                       MSGFW_MESSAGE_TABLE_NAME, status, pMsgInfo->msgId);
+
+       if (pDbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+               err = MSG_ERR_DB_EXEC;
+
+       pDbHandle->finalizeQuery();
+
+       return err;
+}
 
-char *MsgStoReplaceString(const char *origStr, const char *oldStr, const char *newStr)
+bool MsgExistConversation(MsgDbHandler *pDbHandle, msg_thread_id_t convId)
 {
-       if (origStr == NULL)
-               return NULL;
-
-       char *replaceStr = NULL;
-       char *pTemp = NULL;
-       int i = 0;
-       int matchedCnt = 0;
-       int oldStrLen = 0;
-       int newStrLen = 0;
-
-       if (g_strcmp0(oldStr, newStr) != 0) {
-               oldStrLen = strlen(oldStr);
-               newStrLen = strlen(newStr);
-
-               for (i = 0; origStr[i] != '\0';) {
-                       if (memcmp(&origStr[i], oldStr, oldStrLen) == 0) {
-                               matchedCnt++;
-                               i += oldStrLen;
-                       } else {
-                               i++;
-                       }
-               }
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       int rowCnt = 0;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CONV_ID FROM %s WHERE CONV_ID = %d;",
+                       MSGFW_CONVERSATION_TABLE_NAME, convId);
+
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               pDbHandle->freeTable();
+               return false;
+       }
+       else if ( err != MSG_SUCCESS) {
+               pDbHandle->freeTable();
+               return false;
+       }
+       pDbHandle->freeTable();
+
+       return true;
+}
+
+bool MsgExistMessage(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S *pMsg)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+
+       int rowCnt = 0;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE CONV_ID = %ud AND DISPLAY_TIME = %ud;",
+                       MSGFW_MESSAGE_TABLE_NAME, pMsg->threadId, (int)pMsg->displayTime);
+
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+
+       if ( err != MSG_SUCCESS) {
+               pDbHandle->freeTable();
+               return false;
+       }
+
+       if(rowCnt > 0) {
+               pMsg->msgId = pDbHandle->getColumnToInt(1);
+       }
+       pDbHandle->freeTable();
+
+       return true;
+}
+
+
+bool MsgExistAddress(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S *pMsg,  msg_thread_id_t convId, int index)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+
+       int rowCnt = 0;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       if (strlen(pMsg->addressList[index].addressVal) > (unsigned int)MsgContactGetMinMatchDigit()) {
+               int addrSize = strlen(pMsg->addressList[index].addressVal);
+               char newPhoneNum[addrSize+1];
+               memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
+               MsgConvertNumber(pMsg->addressList[index].addressVal, newPhoneNum, addrSize);
+
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT ADDRESS_ID FROM %s WHERE ADDRESS_VAL LIKE '%%%%%s' AND CONV_ID= %d;",
+                               MSGFW_ADDRESS_TABLE_NAME, newPhoneNum, convId);
        } else {
-               return g_strdup(origStr);
+
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT ADDRESS_ID FROM %s WHERE ADDRESS_VAL = '%s' AND CONV_ID= %d;",
+                               MSGFW_ADDRESS_TABLE_NAME, pMsg->addressList[index].addressVal, convId);
+       }
+
+       err = pDbHandle->getTable(sqlQuery, &rowCnt, NULL);
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               pDbHandle->freeTable();
+               return false;
+       }
+       else if ( err != MSG_SUCCESS) {
+               pDbHandle->freeTable();
+               return false;
        }
+       pDbHandle->freeTable();
 
-       replaceStr = (char *)calloc(1, i + sizeof(char) * (matchedCnt * (newStrLen - oldStrLen) + 1));
-       if (replaceStr == NULL)
-               return NULL;
+       return true;
+}
 
-       pTemp = replaceStr;
 
-       while (*origStr) {
-               if (memcmp(origStr, oldStr, oldStrLen) == 0) {
-                       memcpy(pTemp, newStr, newStrLen);
-                       pTemp += newStrLen;
-                       origStr += oldStrLen;
-               } else {
-                       *pTemp++ = *origStr++;
+void MsgStoUpdateAddress(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsg, msg_thread_id_t convId)
+{
+       MSG_BEGIN();
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       for (int i = 0; i < pMsg->nAddressCnt; i++) {
+                       if (strlen(pMsg->addressList[i].addressVal) > (unsigned int)MsgContactGetMinMatchDigit() && pMsg->addressList[i].addressType == MSG_ADDRESS_TYPE_PLMN) {
+                               int addrSize = strlen(pMsg->addressList[i].addressVal);
+                               char newPhoneNum[addrSize+1];
+                               memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
+                               MsgConvertNumber(pMsg->addressList[i].addressVal, newPhoneNum, addrSize);
+
+                               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                               snprintf(sqlQuery, sizeof(sqlQuery),
+                                               "UPDATE %s SET "
+                                               "ADDRESS_VAL = '%s' "
+                                               "WHERE CONV_ID = %d "
+                                               "AND ADDRESS_VAL LIKE '%%%%%s';",
+                                               MSGFW_ADDRESS_TABLE_NAME, pMsg->addressList[i].addressVal, convId, newPhoneNum);
+
+                               err = pDbHandle->execQuery(sqlQuery);
+                               if (err != MSG_SUCCESS) MSG_DEBUG("Fail to execQuery(). [%s]", sqlQuery);
+
+                               pDbHandle->finalizeQuery();
+                       }
+       }
+
+       MSG_END();
+}
+
+#ifndef FEATURE_SMS_CDMA
+msg_error_t MsgStoAddCBChannelInfo(MsgDbHandler *pDbHandle, MSG_CB_CHANNEL_S *pCBChannel, msg_sim_slot_id_t simIndex)
+{
+       MSG_BEGIN();
+
+       char sqlQuery[MAX_QUERY_LEN] = {0,};
+
+       pDbHandle->beginTrans();
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE SIM_INDEX = %d;", MSGFW_CB_CHANNEL_INFO_TABLE_NAME, simIndex);
+
+       if (pDbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               pDbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       for (int i = 0; i < pCBChannel->channelCnt; i++) {
+               int index = 1;
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s(CHANNEL_ACTIVATION, CHANNEL_FROM, CHANNEL_TO, CHANNEL_NAME, SIM_INDEX) VALUES (?, ?, ?, ?, ?);",
+                               MSGFW_CB_CHANNEL_INFO_TABLE_NAME);
+
+               if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       pDbHandle->endTrans(false);
+                       return MSG_ERR_DB_PREPARE;
+               }
+               pDbHandle->bindInt(pCBChannel->channelInfo[i].bActivate, index++);
+               pDbHandle->bindInt(pCBChannel->channelInfo[i].from, index++);
+               pDbHandle->bindInt(pCBChannel->channelInfo[i].to, index++);
+               pDbHandle->bindText(pCBChannel->channelInfo[i].name, index++);
+               pDbHandle->bindInt(simIndex, index++);
+
+               if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                       pDbHandle->finalizeQuery();
+                       pDbHandle->endTrans(false);
+                       return MSG_ERR_DB_STEP;
                }
+
+               pDbHandle->finalizeQuery();
+       }
+
+       pDbHandle->endTrans(true);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetCBChannelInfo(MsgDbHandler *pDbHandle, MSG_CB_CHANNEL_S *pCBChannel, msg_sim_slot_id_t simIndex)
+{
+       MSG_BEGIN();
+
+       int rowCnt = 0, index = 0;
+
+       char sqlQuery[MAX_QUERY_LEN] = {0,};
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CHANNEL_ACTIVATION, CHANNEL_FROM, CHANNEL_TO, CHANNEL_NAME FROM %s WHERE SIM_INDEX = %d;", MSGFW_CB_CHANNEL_INFO_TABLE_NAME, simIndex);
+
+       msg_error_t err = pDbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+       pCBChannel->channelCnt = rowCnt;
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               pDbHandle->freeTable();
+               return MSG_ERR_DB_NORECORD;
+       } else if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               pDbHandle->freeTable();
+               return MSG_ERR_DB_GETTABLE;
        }
 
-       return replaceStr;
+       for (int i = 0; i < rowCnt; i++) {
+               pCBChannel->channelInfo[i].bActivate = pDbHandle->getColumnToInt(index++);
+               pCBChannel->channelInfo[i].from  = pDbHandle->getColumnToInt(index++);
+               pCBChannel->channelInfo[i].to = pDbHandle->getColumnToInt(index++);
+               pDbHandle->getColumnToString(index++, CB_CHANNEL_NAME_MAX, pCBChannel->channelInfo[i].name);
+
+               MSG_DEBUG("CH_ACT = %d", pCBChannel->channelInfo[i].bActivate);
+               MSG_DEBUG("CH_FROM = %d", pCBChannel->channelInfo[i].from);
+               MSG_DEBUG("CH_TO = %d", pCBChannel->channelInfo[i].to);
+               MSG_DEBUG("CH_NAME = %s", pCBChannel->channelInfo[i].name);
+       }
+
+       pDbHandle->freeTable();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+#else
+
+msg_error_t MsgStoAddCBChannelInfo(MsgDbHandler *pDbHandle, MSG_CB_CHANNEL_S *pCBChannel)
+{
+       MSG_BEGIN();
+
+       char sqlQuery[MAX_QUERY_LEN] = {0,};
+
+       pDbHandle->beginTrans();
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s;", MSGFW_CDMA_CB_CHANNEL_INFO_TABLE_NAME);
+
+       if (pDbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               pDbHandle->endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       for (int i = 0; i < pCBChannel->channelCnt; i++) {
+               int index = 1;
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d, '%s');", MSGFW_CDMA_CB_CHANNEL_INFO_TABLE_NAME,
+                               i, pCBChannel->channelInfo[i].bActivate, pCBChannel->channelInfo[i].ctg,
+                               pCBChannel->channelInfo[i].lang, pCBChannel->channelInfo[i].name);
+
+               if (pDbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+                       pDbHandle->endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
+       }
+
+       pDbHandle->endTrans(true);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetCBChannelInfo(MsgDbHandler *pDbHandle, MSG_CB_CHANNEL_S *pCBChannel)
+{
+       MSG_BEGIN();
+
+       int rowCnt = 0, index = 0;
+
+       char sqlQuery[MAX_QUERY_LEN] = {0,};
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT CHANNEL_ACTIVATION, CHANNEL_CATEGORY, CHANNEL_LANGUAGE, CHANNEL_NAME FROM %s;", MSGFW_CDMA_CB_CHANNEL_INFO_TABLE_NAME);
+
+       msg_error_t err = pDbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+       pCBChannel->channelCnt = rowCnt;
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               pDbHandle->freeTable();
+               return MSG_ERR_DB_NORECORD;
+       } else if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               pDbHandle->freeTable();
+               return MSG_ERR_DB_GETTABLE;
+       }
+
+       for (int i = 0; i < rowCnt; i++) {
+               pCBChannel->channelInfo[i].bActivate = pDbHandle->getColumnToInt(index++);
+               pCBChannel->channelInfo[i].ctg  = pDbHandle->getColumnToInt(index++);
+               pCBChannel->channelInfo[i].lang = pDbHandle->getColumnToInt(index++);
+               pDbHandle->getColumnToString(index++, CB_CHANNEL_NAME_MAX, pCBChannel->channelInfo[i].name);
+
+               MSG_DEBUG("CH_ACT = %d", pCBChannel->channelInfo[i].bActivate);
+               MSG_DEBUG("CH_CTG = %d", pCBChannel->channelInfo[i].ctg);
+               MSG_DEBUG("CH_LANG = %d", pCBChannel->channelInfo[i].lang);
+               MSG_DEBUG("CH_NAME = %s", pCBChannel->channelInfo[i].name);
+       }
+
+       pDbHandle->freeTable();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+#endif
+
+// Lists
+msg_error_t MsgStoGetFolderViewList(msg_folder_id_t folderId, const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pMsgFolderViewList)
+{
+       if (pMsgFolderViewList == NULL) {
+               MSG_DEBUG("pMsgFolderViewList is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       int rowCnt = 0, index = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       char sqlSort[64];
+
+       // Get Name Order
+       int order = MsgGetContactNameOrder();
+
+       // Get Message In Folder
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       if (folderId == MSG_ALLBOX_ID) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID, CONV_ID, FOLDER_ID, STORAGE_ID, MAIN_TYPE, SUB_TYPE, \
+                               DISPLAY_TIME, DATA_SIZE, NETWORK_STATUS, READ_STATUS, PROTECTED, BACKUP, PRIORITY, \
+                               MSG_DIRECTION, SCHEDULED_TIME, SUBJECT, MSG_TEXT, ATTACHMENT_COUNT, THUMB_PATH \
+                               FROM %s WHERE FOLDER_ID < %d ",
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_SPAMBOX_ID);
+       } else {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID, CONV_ID, FOLDER_ID, STORAGE_ID, MAIN_TYPE, SUB_TYPE, \
+                               DISPLAY_TIME, DATA_SIZE, NETWORK_STATUS, READ_STATUS, PROTECTED, BACKUP, PRIORITY, \
+                               MSG_DIRECTION, SCHEDULED_TIME, SUBJECT, MSG_TEXT, ATTACHMENT_COUNT, THUMB_PATH \
+                               FROM %s WHERE FOLDER_ID = %d ",
+                               MSGFW_MESSAGE_TABLE_NAME, folderId);
+       }
+
+       memset(sqlSort, 0x00, sizeof(sqlSort));
+       MsgMakeSortRule(pSortRule, sqlSort);
+       strncat(sqlQuery, sqlSort, strlen(sqlSort));
+
+       msg_error_t err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               pMsgFolderViewList->nCount = 0;
+               pMsgFolderViewList->msg_struct_info = NULL;
+
+               dbHandle->freeTable();
+
+               return MSG_SUCCESS;
+       } else if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
+               return err;
+       }
+
+       pMsgFolderViewList->nCount = rowCnt;
+
+       MSG_DEBUG("pMsgCommInfoList->nCount [%d]", pMsgFolderViewList->nCount);
+
+       pMsgFolderViewList->msg_struct_info = (msg_struct_t *)calloc(rowCnt, sizeof(msg_struct_t));
+
+       msg_struct_s *msg = NULL;
+       MSG_MESSAGE_HIDDEN_S *pTmp = NULL;
+
+       for (int i = 0; i < rowCnt; i++) {
+               pMsgFolderViewList->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
+
+               msg = (msg_struct_s *)pMsgFolderViewList->msg_struct_info[i];
+
+               msg->type = MSG_STRUCT_MESSAGE_INFO;
+               msg->data = new MSG_MESSAGE_HIDDEN_S;
+
+               pTmp = (MSG_MESSAGE_HIDDEN_S *)msg->data;
+
+               pTmp->pData = NULL;
+               pTmp->pMmsData = NULL;
+               pTmp->addressList = NULL;
+
+               pTmp->msgId = dbHandle->getColumnToInt(index++);
+               pTmp->threadId = dbHandle->getColumnToInt(index++);
+               pTmp->folderId = dbHandle->getColumnToInt(index++);
+               pTmp->storageId = dbHandle->getColumnToInt(index++);
+               pTmp->mainType = dbHandle->getColumnToInt(index++);
+               pTmp->subType = dbHandle->getColumnToInt(index++);
+               pTmp->displayTime = (time_t)dbHandle->getColumnToInt(index++);
+               pTmp->dataSize = dbHandle->getColumnToInt(index++);
+               pTmp->networkStatus = dbHandle->getColumnToInt(index++);
+               pTmp->bRead = dbHandle->getColumnToInt(index++);
+               pTmp->bProtected = dbHandle->getColumnToInt(index++);
+               pTmp->bBackup = dbHandle->getColumnToInt(index++);
+               pTmp->priority = dbHandle->getColumnToInt(index++);
+               pTmp->direction= dbHandle->getColumnToInt(index++);
+
+               index++; // This field is reserved.
+
+               dbHandle->getColumnToString(index++, MAX_SUBJECT_LEN, pTmp->subject);
+
+               if (pTmp->mainType == MSG_MMS_TYPE &&
+                       (pTmp->networkStatus == MSG_NETWORK_RETRIEVING || pTmp->networkStatus == MSG_NETWORK_RETRIEVE_FAIL || pTmp->subType == MSG_NOTIFICATIONIND_MMS)) {
+                       pTmp->pData = NULL;
+                       index++;
+               } else {
+                       pTmp->pData = (void *)new char[pTmp->dataSize + 2];
+                       memset(pTmp->pData, 0x00, pTmp->dataSize + 2);
+
+                       dbHandle->getColumnToString(index++, pTmp->dataSize+1, (char *)pTmp->pData);
+               }
+
+               // get address information from db.
+               msg_struct_list_s *addr_list = (msg_struct_list_s *)new msg_struct_list_s;
+
+               MsgDbHandler db;
+               MsgStoGetAddressByMsgId(&db, pTmp->msgId, order, addr_list);
+
+               pTmp->addr_list = addr_list;
+
+               // For GList *addressList
+               int nAddressCnt = 0;
+               MSG_ADDRESS_INFO_S *addressList = NULL;
+               MsgStoGetAddressByMsgId(&db, pTmp->msgId, order, &nAddressCnt, &addressList);
+
+               for (int i = 0; i < nAddressCnt; i++) {
+                       msg_struct_s *addr_info_s = NULL;
+                       MSG_ADDRESS_INFO_S *addr_info = NULL;
+
+                       addr_info_s = new msg_struct_s;
+                       memset(addr_info_s, 0x00, sizeof(msg_struct_s));
+
+                       addr_info_s->type = MSG_STRUCT_ADDRESS_INFO;
+                       addr_info_s->data = new MSG_ADDRESS_INFO_S;
+                       memset(addr_info_s->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+                       addr_info = (MSG_ADDRESS_INFO_S *)addr_info_s->data;
+
+                       addr_info->addressType = addressList[i].addressType;
+                       addr_info->recipientType = addressList[i].recipientType;
+                       addr_info->contactId = addressList[i].contactId;
+                       strncpy(addr_info->addressVal, addressList[i].addressVal, MAX_ADDRESS_VAL_LEN);
+                       strncpy(addr_info->displayName, addressList[i].displayName, MAX_DISPLAY_NAME_LEN);
+                       addr_info->displayName[MAX_DISPLAY_NAME_LEN] = '\0';
+
+                       pTmp->addressList = g_list_append(pTmp->addressList, addr_info_s);
+               }
+
+               delete [] addressList;
+
+               pTmp->attachCount = dbHandle->getColumnToInt(index++);
+
+               dbHandle->getColumnToString(index++, MSG_FILEPATH_LEN_MAX, pTmp->thumbPath);
+       }
+
+       dbHandle->freeTable();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetThreadViewList(const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pThreadViewList)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       pThreadViewList->nCount = 0;
+       pThreadViewList->msg_struct_info = NULL;
+
+       int rowCnt = 0, index = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.CONV_ID, A.UNREAD_CNT, A.SMS_CNT, A.MMS_CNT, A.MAIN_TYPE, A.SUB_TYPE, "
+                       "A.MSG_DIRECTION, A.DISPLAY_TIME, A.DISPLAY_NAME, A.MSG_TEXT, "
+                       "(COUNT(CASE WHEN B.PROTECTED = 1 THEN 1 END)) AS PROTECTED, "
+                       "(COUNT(CASE WHEN B.FOLDER_ID = %d THEN 1 END)) AS DRAFT, "
+                       "(COUNT(CASE WHEN B.NETWORK_STATUS = %d THEN 1 END)) AS FAILED, "
+                       "(COUNT(CASE WHEN B.NETWORK_STATUS = %d THEN 1 END)) AS SENDING "
+                       "FROM %s A, %s B ON A.SMS_CNT + A.MMS_CNT > 0 AND B.CONV_ID = A.CONV_ID "
+                       "GROUP BY A.CONV_ID ORDER BY A.DISPLAY_TIME DESC;",
+                       MSG_DRAFT_ID,
+                       MSG_NETWORK_SEND_FAIL,
+                       MSG_NETWORK_SENDING,
+                       MSGFW_CONVERSATION_TABLE_NAME,
+                       MSGFW_MESSAGE_TABLE_NAME);
+
+       msg_error_t err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               dbHandle->freeTable();
+               return MSG_SUCCESS;
+       } else if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
+               return err;
+       }
+
+       if (rowCnt < 1) {
+               MSG_DEBUG("rowCnt is %d", rowCnt);
+               dbHandle->freeTable();
+               return err;
+       }
+
+       pThreadViewList->nCount = rowCnt;
+
+       MSG_DEBUG("pThreadViewList->nCount [%d]", pThreadViewList->nCount);
+
+       pThreadViewList->msg_struct_info = (msg_struct_t *)calloc(rowCnt, sizeof(msg_struct_t));
+
+       MSG_THREAD_VIEW_S *pTmp = NULL;
+       msg_struct_s *thread_t = NULL;
+
+       for (int i = 0; i < rowCnt; i++) {
+               thread_t = (msg_struct_s *)new msg_struct_s;
+               pThreadViewList->msg_struct_info[i] = (msg_struct_t)thread_t;
+
+               thread_t->type = MSG_STRUCT_THREAD_INFO;
+               thread_t->data = new MSG_THREAD_VIEW_S;
+
+               pTmp = (MSG_THREAD_VIEW_S *)thread_t->data;
+               memset(pTmp, 0x00, sizeof(MSG_THREAD_VIEW_S));
+
+               pTmp->threadId = dbHandle->getColumnToInt(index++);
+
+               pTmp->unreadCnt = dbHandle->getColumnToInt(index++);
+               pTmp->smsCnt = dbHandle->getColumnToInt(index++);
+               pTmp->mmsCnt = dbHandle->getColumnToInt(index++);
+
+               pTmp->mainType = dbHandle->getColumnToInt(index++);
+               pTmp->subType = dbHandle->getColumnToInt(index++);
+
+               pTmp->direction = dbHandle->getColumnToInt(index++);
+               pTmp->threadTime = (time_t)dbHandle->getColumnToInt(index++);
+
+               memset(pTmp->threadName, 0x00, sizeof(pTmp->threadName));
+               dbHandle->getColumnToString(index++, MAX_THREAD_NAME_LEN, pTmp->threadName);
+
+               memset(pTmp->threadData, 0x00, sizeof(pTmp->threadData));
+               dbHandle->getColumnToString(index++, MAX_THREAD_DATA_LEN, pTmp->threadData);
+
+               int protectedCnt = dbHandle->getColumnToInt(index++);
+               if (protectedCnt > 0)
+                       pTmp->bProtected = true;
+
+               int draftCnt = dbHandle->getColumnToInt(index++);
+               if (draftCnt > 0)
+                       pTmp->bDraft = true;
+
+               int failedCnt = dbHandle->getColumnToInt(index++);
+               if (failedCnt > 0)
+                       pTmp->bSendFailed = true;
+
+               int sendingCnt = dbHandle->getColumnToInt(index++);
+               if (sendingCnt > 0)
+                       pTmp->bSending = true;
+       }
+
+       dbHandle->freeTable();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetConversationPreview(MSG_CONVERSATION_VIEW_S *pConv)
+{
+       MsgDbHandler dbHandleForInner;
+
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       int rowCnt = 0, index = 0;
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       if (pConv == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       pConv->tcs_bc_level = -1; //init
+
+       //(MSG_ID INTEGER, TYPE INTEGER, VALUE TEXT, COUNT INTEGER)
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "SELECT TYPE, VALUE, COUNT "
+                       "FROM %s WHERE MSG_ID=%d;",
+                       MSGFW_MMS_PREVIEW_TABLE_NAME, pConv->msgId);
+
+       msg_error_t err = dbHandleForInner.getTable(sqlQuery, &rowCnt, &index);
+       if (err == MSG_SUCCESS) {
+               for (int i = 0; i < rowCnt; i++) {
+                       int type = dbHandleForInner.getColumnToInt(index++);
+                       if (type == MSG_MMS_ITEM_TYPE_IMG) {
+                               dbHandleForInner.getColumnToString(index++, MSG_FILEPATH_LEN_MAX, pConv->imageThumbPath);
+                               dbHandleForInner.getColumnToInt(index++);
+                       } else if (type == MSG_MMS_ITEM_TYPE_VIDEO) {
+                               dbHandleForInner.getColumnToString(index++, MSG_FILEPATH_LEN_MAX, pConv->videoThumbPath);
+                               dbHandleForInner.getColumnToInt(index++);
+                       } else if (type == MSG_MMS_ITEM_TYPE_AUDIO) {
+                               dbHandleForInner.getColumnToString(index++, MSG_FILENAME_LEN_MAX, pConv->audioFileName);
+                               dbHandleForInner.getColumnToInt(index++);
+                       } else if (type == MSG_MMS_ITEM_TYPE_ATTACH) {
+                               dbHandleForInner.getColumnToString(index++, MSG_FILENAME_LEN_MAX, pConv->attachFileName);
+                               pConv->attachCount = dbHandleForInner.getColumnToInt(index++);
+                       } else if (type == MSG_MMS_ITEM_TYPE_PAGE) {
+                               index++;
+                               pConv->pageCount = dbHandleForInner.getColumnToInt(index++);
+                       } else if (type == MSG_MMS_ITEM_TYPE_MALWARE) {
+                               index++;
+                               pConv->tcs_bc_level = dbHandleForInner.getColumnToInt(index++);
+                       } else if (type == MSG_MMS_ITEM_TYPE_1ST_MEDIA) {
+                               dbHandleForInner.getColumnToString(index++, MSG_FILEPATH_LEN_MAX, pConv->firstMediaPath);
+                               dbHandleForInner.getColumnToInt(index++);
+                       } else {
+                               MSG_DEBUG("Unknown item type [%d]", type);
+                               index+=2;
+                       }
+               }
+       }
+
+       dbHandleForInner.freeTable();
+       return MSG_SUCCESS;
+}
+
+msg_error_t MsgStoGetConversationMultipart(MSG_CONVERSATION_VIEW_S *pConv)
+{
+       MsgDbHandler dbHandleForInner;
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       int rowCnt = 0, index = 0;
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       if (pConv == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "SELECT CONTENT_TYPE, NAME, FILE_PATH, CONTENT_ID, CONTENT_LOCATION, TCS_LEVEL, MALWARE_ALLOW, THUMB_FILE_PATH "
+                       "FROM %s WHERE MSG_ID=%d;",
+                       MSGFW_MMS_MULTIPART_TABLE_NAME, pConv->msgId);
+
+       msg_error_t err = dbHandleForInner.getTable(sqlQuery, &rowCnt, &index);
+       if (err == MSG_SUCCESS) {
+               GList *multipart_list = NULL;
+               for (int i = 0; i < rowCnt; i++) {
+
+                       msg_struct_s *multipart_struct_s = new msg_struct_s;
+                       multipart_struct_s->type = MSG_STRUCT_MULTIPART_INFO;
+                       multipart_struct_s->data = new MMS_MULTIPART_DATA_S;
+                       memset(multipart_struct_s->data, 0x00, sizeof(MMS_MULTIPART_DATA_S));
+
+                       MMS_MULTIPART_DATA_S *multipart = (MMS_MULTIPART_DATA_S *)multipart_struct_s->data;
+
+                       dbHandleForInner.getColumnToString(index++, sizeof(multipart->szContentType), multipart->szContentType);
+                       dbHandleForInner.getColumnToString(index++, sizeof(multipart->szFileName), multipart->szFileName);
+                       dbHandleForInner.getColumnToString(index++, sizeof(multipart->szFilePath), multipart->szFilePath);
+                       dbHandleForInner.getColumnToString(index++, sizeof(multipart->szContentID), multipart->szContentID);
+                       dbHandleForInner.getColumnToString(index++, sizeof(multipart->szContentLocation), multipart->szContentLocation);
+
+                       multipart->tcs_bc_level = dbHandleForInner.getColumnToInt(index++);
+                       multipart->malware_allow = dbHandleForInner.getColumnToInt(index++);
+                       dbHandleForInner.getColumnToString(index++, sizeof(multipart->szThumbFilePath), multipart->szThumbFilePath);
+
+                       multipart_list = g_list_append(multipart_list, multipart_struct_s);
+               }
+               pConv->multipart_list = (msg_list_handle_t)multipart_list;
+       }
+
+       dbHandleForInner.freeTable();
+       return MSG_SUCCESS;
+}
+
+msg_error_t MsgStoGetConversationViewItem(msg_message_id_t msgId, MSG_CONVERSATION_VIEW_S *pConv)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       int rowCnt = 0, index = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID, CONV_ID, FOLDER_ID, STORAGE_ID, MAIN_TYPE, SUB_TYPE, \
+                       DISPLAY_TIME, DATA_SIZE, NETWORK_STATUS, READ_STATUS, PROTECTED, \
+                       MSG_DIRECTION, SCHEDULED_TIME, SUBJECT, MSG_TEXT, ATTACHMENT_COUNT, SIM_INDEX\
+                       FROM %s WHERE MSG_ID=%d;",
+                       MSGFW_MESSAGE_TABLE_NAME, msgId);
+
+       msg_error_t err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               dbHandle->freeTable();
+               return MSG_SUCCESS;
+       } else if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
+               return err;
+       }
+
+       memset(pConv, 0x00, sizeof(MSG_CONVERSATION_VIEW_S));
+       pConv->pText = NULL;
+
+       pConv->msgId = dbHandle->getColumnToInt(index++);
+       pConv->threadId = dbHandle->getColumnToInt(index++);
+       pConv->folderId = dbHandle->getColumnToInt(index++);
+       pConv->storageId = dbHandle->getColumnToInt(index++);
+       pConv->mainType = dbHandle->getColumnToInt(index++);
+       pConv->subType = dbHandle->getColumnToInt(index++);
+       pConv->displayTime = (time_t)dbHandle->getColumnToInt(index++);
+       pConv->textSize = dbHandle->getColumnToInt(index++);
+       pConv->networkStatus = dbHandle->getColumnToInt(index++);
+       pConv->bRead = dbHandle->getColumnToInt(index++);
+       pConv->bProtected = dbHandle->getColumnToInt(index++);
+       pConv->direction = dbHandle->getColumnToInt(index++);
+       pConv->scheduledTime = (time_t)dbHandle->getColumnToInt(index++);
+
+       dbHandle->getColumnToString(index++, MAX_SUBJECT_LEN, pConv->subject);
+
+       if (pConv->mainType == MSG_MMS_TYPE &&
+               (pConv->networkStatus == MSG_NETWORK_RETRIEVING || pConv->networkStatus == MSG_NETWORK_RETRIEVE_FAIL || pConv->subType == MSG_NOTIFICATIONIND_MMS)) {
+               pConv->pText = NULL;
+               pConv->textSize = 0;
+               index++;
+       } else {
+               if (pConv->mainType == MSG_SMS_TYPE) {
+                       pConv->pText = new char[pConv->textSize+2];
+                       memset(pConv->pText, 0x00, pConv->textSize+2);
+                       dbHandle->getColumnToString(index++, pConv->textSize+1, pConv->pText);
+               } else {
+                       char *tmpMmsText = dbHandle->getColumnToString(index++);
+
+                       pConv->textSize = strlen(tmpMmsText);
+
+                       pConv->pText = new char[pConv->textSize+1];
+                       memset(pConv->pText, 0x00, pConv->textSize+1);
+
+                       strncpy(pConv->pText, tmpMmsText, pConv->textSize);
+
+                       MsgStoGetConversationPreview(pConv);
+                       MsgStoGetConversationMultipart(pConv);
+               }
+       }
+
+       //It does Not need to Get attach count in MSG_MESSAGE_TABLE. see MsgStoGetConversationPreview
+       //pConv->attachCount = dbHandle->getColumnToInt(index++);
+       index++;
+       pConv->simIndex = dbHandle->getColumnToInt(index++);
+
+       dbHandle->freeTable();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetConversationViewList(msg_thread_id_t threadId, msg_struct_list_s *pConvViewList)
+{
+       MSG_BEGIN();
+
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       pConvViewList->nCount = 0;
+       pConvViewList->msg_struct_info = NULL;
+
+       int rowCnt = 0, index = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+#ifdef MSG_NOTI_INTEGRATION
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID, CONV_ID, FOLDER_ID, STORAGE_ID, MAIN_TYPE, SUB_TYPE, \
+                       DISPLAY_TIME, DATA_SIZE, NETWORK_STATUS, READ_STATUS, PROTECTED, \
+                       MSG_DIRECTION, SCHEDULED_TIME, SUBJECT, MSG_TEXT, ATTACHMENT_COUNT, SIM_INDEX  \
+                       FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d ORDER BY DISPLAY_TIME, MSG_ID ASC;",
+                       MSGFW_MESSAGE_TABLE_NAME, threadId, MSG_ALLBOX_ID, MSG_SPAMBOX_ID, MSG_STORAGE_PHONE);
+#else
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID, CONV_ID, FOLDER_ID, STORAGE_ID, MAIN_TYPE, SUB_TYPE, \
+                       DISPLAY_TIME, DATA_SIZE, NETWORK_STATUS, READ_STATUS, PROTECTED, \
+                       MSG_DIRECTION, SCHEDULED_TIME, SUBJECT, MSG_TEXT, ATTACHMENT_COUNT \
+                       FROM %s WHERE CONV_ID = %d AND FOLDER_ID > %d AND FOLDER_ID < %d AND STORAGE_ID = %d ORDER BY DISPLAY_TIME, MSG_ID ASC;",
+                       MSGFW_MESSAGE_TABLE_NAME, threadId, MSG_ALLBOX_ID, MSG_CBMSGBOX_ID, MSG_STORAGE_PHONE);
+#endif
+
+       msg_error_t err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               dbHandle->freeTable();
+               return MSG_SUCCESS;
+       } else if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
+               return err;
+       }
+
+       pConvViewList->nCount = rowCnt;
+
+       MSG_DEBUG("pConvViewList->nCount [%d]", pConvViewList->nCount);
+
+       pConvViewList->msg_struct_info = (msg_struct_t *)calloc(rowCnt, sizeof(msg_struct_t));
+       memset(pConvViewList->msg_struct_info, 0x00, sizeof(msg_struct_t) * rowCnt);
+
+       msg_struct_s *conv = NULL;
+       MSG_CONVERSATION_VIEW_S *pTmp = NULL;
+
+       for (int i = 0; i < rowCnt; i++) {
+               pConvViewList->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
+               memset(pConvViewList->msg_struct_info[i], 0x00, sizeof(msg_struct_s));
+
+               conv = (msg_struct_s *)pConvViewList->msg_struct_info[i];
+
+               conv->type = MSG_STRUCT_CONV_INFO;
+               conv->data = new MSG_CONVERSATION_VIEW_S;
+               memset(conv->data, 0x00, sizeof(MSG_CONVERSATION_VIEW_S));
+
+               pTmp = (MSG_CONVERSATION_VIEW_S *)conv->data;
+
+               pTmp->pText = NULL;
+
+               pTmp->msgId = dbHandle->getColumnToInt(index++);
+               pTmp->threadId = dbHandle->getColumnToInt(index++);
+               pTmp->folderId = dbHandle->getColumnToInt(index++);
+               pTmp->storageId = dbHandle->getColumnToInt(index++);
+               pTmp->mainType = dbHandle->getColumnToInt(index++);
+               pTmp->subType = dbHandle->getColumnToInt(index++);
+               pTmp->displayTime = (time_t)dbHandle->getColumnToInt(index++);
+               pTmp->textSize = dbHandle->getColumnToInt(index++);
+               pTmp->networkStatus = dbHandle->getColumnToInt(index++);
+               pTmp->bRead = dbHandle->getColumnToInt(index++);
+               pTmp->bProtected = dbHandle->getColumnToInt(index++);
+               pTmp->direction = dbHandle->getColumnToInt(index++);
+               index++; // This field is reserved.
+
+               dbHandle->getColumnToString(index++, MAX_SUBJECT_LEN, pTmp->subject);
+
+               if (pTmp->mainType == MSG_MMS_TYPE &&
+                       (pTmp->networkStatus == MSG_NETWORK_RETRIEVING || pTmp->networkStatus == MSG_NETWORK_RETRIEVE_FAIL || pTmp->subType == MSG_NOTIFICATIONIND_MMS)) {
+                       pTmp->pText = NULL;
+                       pTmp->textSize = 0;
+                       index++;
+               } else {
+                       if (pTmp->mainType == MSG_SMS_TYPE) {
+                               pTmp->pText = new char[pTmp->textSize+2];
+                               memset(pTmp->pText, 0x00, pTmp->textSize+2);
+                               dbHandle->getColumnToString(index++, pTmp->textSize+1, pTmp->pText);
+                       } else {
+                               char *tmpMmsText = dbHandle->getColumnToString(index++);
+
+                               if (tmpMmsText) {
+                                       pTmp->textSize = strlen(tmpMmsText);
+
+                                       pTmp->pText = new char[pTmp->textSize+1];
+                                       memset(pTmp->pText, 0x00, pTmp->textSize+1);
+
+                                       strncpy(pTmp->pText, tmpMmsText, pTmp->textSize);
+                               }
+
+                               MsgStoGetConversationPreview(pTmp);
+                               MsgStoGetConversationMultipart(pTmp);
+                       }
+               }
+               //It does Not need to Get attach count in MSG_MESSAGE_TABLE. see MsgStoGetConversationPreview
+               //pTmp->attachCount = dbHandle->getColumnToInt(index++);
+               index++;
+               pTmp->simIndex = dbHandle->getColumnToInt(index++);
+       }
+
+       dbHandle->freeTable();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoSearchMessage(const char *pSearchString, msg_struct_list_s *pThreadViewList)
+{
+       if (!pSearchString)
+               return MSG_ERR_NULL_POINTER;
+
+       MsgDbHandler *dbHandle = getDbHandle();
+       char *escapeAddressStr = NULL;
+
+       // Clear Out Parameter
+       pThreadViewList->nCount = 0;
+       pThreadViewList->msg_struct_info = NULL;
+
+       tr1::unordered_set<msg_thread_id_t> IdList;
+       queue<MSG_THREAD_VIEW_S> searchList;
+
+       MSG_THREAD_VIEW_S threadView;
+
+       MSG_ADDRESS_INFO_S *pAddrInfo = NULL;
+       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> buf(&pAddrInfo, unique_ptr_deleter);
+       int count = 0;
+
+       // get contact search list
+       if (MsgGetContactSearchList(pSearchString, &pAddrInfo, &count) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgGetContactSearchList fail.");
+               count = 0;
+       }
+       int iteration = (count / ITERATION_SIZE) + 1;
+       int remaining = count;
+
+       for (int itr = 0; itr < iteration ; ++ itr) {
+               int cnt = 0;
+               (remaining > ITERATION_SIZE) ? (cnt = ITERATION_SIZE) : (cnt = remaining);
+
+               unsigned int maxlength = MAX_QUERY_LEN + (MAX_ADDRESS_VAL_LEN * cnt) +1;
+               char sqlQuery[maxlength];
+
+               // Search - Address, Name
+               memset(sqlQuery, 0x00, maxlength);
+               snprintf(sqlQuery, maxlength, "SELECT A.CONV_ID, A.UNREAD_CNT, A.SMS_CNT, A.MMS_CNT, A.DISPLAY_NAME, "
+                               "A.MAIN_TYPE, A.SUB_TYPE, A.MSG_DIRECTION, A.DISPLAY_TIME, A.MSG_TEXT, "
+                               "(SELECT COUNT(*) FROM %s B WHERE B.CONV_ID = A.CONV_ID AND B.PROTECTED = 1) AS PROTECTED, "
+                               "(SELECT COUNT(*) FROM %s B WHERE B.CONV_ID = A.CONV_ID AND B.FOLDER_ID = %d) AS DRAFT, "
+                               "(SELECT COUNT(*) FROM %s B WHERE B.CONV_ID = A.CONV_ID AND B.NETWORK_STATUS = %d) AS FAILED, "
+                               "(SELECT COUNT(*) FROM %s B WHERE B.CONV_ID = A.CONV_ID AND B.NETWORK_STATUS = %d) AS SENDING "
+                               "FROM %s A WHERE (A.SMS_CNT > 0 OR A.MMS_CNT > 0) "
+                               "AND A.CONV_ID IN "
+                               "(SELECT DISTINCT(CONV_ID) FROM %s WHERE "
+                               "ADDRESS_VAL LIKE ? ESCAPE '%c' ",
+                               MSGFW_MESSAGE_TABLE_NAME,
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_DRAFT_ID,
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_NETWORK_SEND_FAIL,
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_NETWORK_SENDING,
+                               MSGFW_CONVERSATION_TABLE_NAME,
+                               MSGFW_ADDRESS_TABLE_NAME,
+                               MSGFW_DB_ESCAPE_CHAR);
+
+               unsigned int tmpSize = 0;
+
+               for (int i = 0; i < cnt; i++) {
+                       int addrSize = strlen(pAddrInfo[itr * ITERATION_SIZE + i].addressVal);
+                       char newPhoneNum[addrSize+1];
+                       memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
+
+                       if (addrSize > MsgContactGetMinMatchDigit())
+                               MsgConvertNumber(pAddrInfo[itr * ITERATION_SIZE + i].addressVal, newPhoneNum, addrSize);
+                       else
+                               strncpy(newPhoneNum, pAddrInfo[itr * ITERATION_SIZE + i].addressVal, addrSize);
+
+                       tmpSize = strlen(sqlQuery);
+                       snprintf(sqlQuery+tmpSize, maxlength-tmpSize,
+                                       "OR ADDRESS_VAL LIKE '%%%s' ",
+                                       newPhoneNum);
+
+               }
+               remaining -= cnt;
+               tmpSize = strlen(sqlQuery);
+               snprintf(sqlQuery+tmpSize, maxlength-tmpSize,
+                               ") ORDER BY A.DISPLAY_TIME DESC;");
+               MSG_DEBUG("maxlength: [%d], Query Length: [%d]", maxlength, strlen(sqlQuery));
+               MSG_DEBUG("[%s]", sqlQuery);
+
+               if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Prepare query fail.");
+                       return MSG_ERR_DB_PREPARE;
+               }
+
+               MsgConvertStrWithEscape(pSearchString, &escapeAddressStr);
+               MSG_DEBUG("escapeAddressStr [%s]", escapeAddressStr);
+               dbHandle->bindText(escapeAddressStr, 1);
+               //dbHandle->bindText(escapeAddressStr, 2);
+               //dbHandle->bindText(escapeAddressStr, 3);
+               //dbHandle->bindText(escapeAddressStr, 4);
+
+               while (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+                       memset(&threadView, 0x00, sizeof(threadView));
+
+                       threadView.threadId = dbHandle->columnInt(0);
+                       threadView.unreadCnt = dbHandle->columnInt(1);
+                       threadView.smsCnt = dbHandle->columnInt(2);
+                       threadView.mmsCnt = dbHandle->columnInt(3);
+
+                       if (dbHandle->columnText(4))
+                               strncpy(threadView.threadName, (char *)dbHandle->columnText(4), MAX_THREAD_NAME_LEN);
+
+                       threadView.mainType = dbHandle->columnInt(5);
+                       threadView.subType = dbHandle->columnInt(6);
+
+                       threadView.direction = dbHandle->columnInt(7);
+                       threadView.threadTime = (time_t)dbHandle->columnInt(8);
+
+                       if (dbHandle->columnText(9))
+                               strncpy(threadView.threadData, (char *)dbHandle->columnText(9), MAX_THREAD_DATA_LEN);
+
+                       int protectedCnt = dbHandle->columnInt(10);
+                       if (protectedCnt > 0)
+                               threadView.bProtected = true;
+
+                       int draftCnt = dbHandle->columnInt(11);
+                       if (draftCnt > 0)
+                               threadView.bDraft = true;
+
+                       int failedCnt = dbHandle->columnInt(12);
+                       if (failedCnt > 0)
+                               threadView.bSendFailed = true;
+
+                       int sendingCnt = dbHandle->columnInt(13);
+                       if (sendingCnt > 0)
+                               threadView.bSending = true;
+
+                       tr1::unordered_set<msg_thread_id_t>::iterator it;
+
+                       it = IdList.find(threadView.threadId);
+
+                       if (it == IdList.end()) {
+                               IdList.insert(threadView.threadId);
+                               searchList.push(threadView);
+                       }
+
+               }
+
+               dbHandle->finalizeQuery();
+
+               if (escapeAddressStr) {
+                       free(escapeAddressStr);
+                       escapeAddressStr = NULL;
+               }
+       }
+
+
+       // Add data to Out Parameter
+       pThreadViewList->nCount = searchList.size();
+       pThreadViewList->msg_struct_info = (msg_struct_t *)calloc(searchList.size(), sizeof(msg_struct_t));
+       if (pThreadViewList->msg_struct_info == NULL)
+               return MSG_ERR_MEMORY_ERROR;
+
+       MSG_THREAD_VIEW_S *pTmp = NULL;
+       msg_struct_s *thread_t = NULL;
+
+       int index = 0;
+
+       while (!searchList.empty()) {
+               thread_t = (msg_struct_s *)new msg_struct_s;
+               pThreadViewList->msg_struct_info[index] = (msg_struct_t)thread_t;
+
+               thread_t->type = MSG_STRUCT_THREAD_INFO;
+               thread_t->data = new MSG_THREAD_VIEW_S;
+
+               pTmp = (MSG_THREAD_VIEW_S *)thread_t->data;
+               memset(pTmp, 0x00, sizeof(MSG_THREAD_VIEW_S));
+
+               memcpy(pTmp, &(searchList.front()), sizeof(MSG_THREAD_VIEW_S));
+
+               searchList.pop();
+
+               index++;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetRejectMsgList(const char *pNumber, msg_struct_list_s *pRejectMsgList)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       // Clear Out Parameter
+       pRejectMsgList->nCount = 0;
+       pRejectMsgList->msg_struct_info = NULL;
+
+       int rowCnt = 0, index = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       // Search Reject Msg
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       if (pNumber != NULL) {
+               int addrSize = strlen(pNumber);
+               char phoneNumber[addrSize+1];
+               memset(phoneNumber, 0x00, sizeof(phoneNumber));
+
+               if (addrSize > MsgContactGetMinMatchDigit())
+                       MsgConvertNumber(pNumber, phoneNumber, addrSize);
+               else
+                       strncpy(phoneNumber, pNumber, addrSize);
+
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                               "B.MSG_ID, "
+                               "B.MSG_TEXT, "
+                               "B.DISPLAY_TIME "
+                               "FROM %s A, %s B "
+                               "WHERE A.CONV_ID = B.CONV_ID "
+                               "AND B.MAIN_TYPE = %d "
+                               "AND B.SUB_TYPE = %d "
+                               "AND A.ADDRESS_VAL LIKE '%%%s' "
+                               "ORDER BY B.DISPLAY_TIME DESC;",
+                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                               MSG_SMS_TYPE,
+                               MSG_REJECT_SMS,
+                               phoneNumber);
+       } else {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT "
+                               "B.MSG_ID, "
+                               "B.MSG_TEXT, "
+                               "B.DISPLAY_TIME "
+                               "FROM %s A, %s B "
+                               "WHERE A.CONV_ID = B.CONV_ID "
+                               "AND B.MAIN_TYPE = %d "
+                               "AND B.SUB_TYPE = %d "
+                               "ORDER BY B.DISPLAY_TIME DESC;",
+                               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME,
+                               MSG_SMS_TYPE,
+                               MSG_REJECT_SMS);
+       }
+
+       msg_error_t err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to getTable().");
+               dbHandle->freeTable();
+               return err;
+       }
+
+       pRejectMsgList->nCount = rowCnt;
+
+       MSG_DEBUG("pRejectMsgList->nCount [%d]", pRejectMsgList->nCount);
+
+       pRejectMsgList->msg_struct_info = (msg_struct_t *)calloc(rowCnt, sizeof(MSG_REJECT_MSG_INFO_S *));
+
+       msg_struct_s* pTmp = NULL;
+
+       for (int i = 0; i < rowCnt; i++) {
+               pRejectMsgList->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
+
+               pTmp = (msg_struct_s *)pRejectMsgList->msg_struct_info[i];
+               pTmp->type = MSG_STRUCT_REJECT_MSG_INFO;
+               pTmp->data = new MSG_REJECT_MSG_INFO_S;
+               MSG_REJECT_MSG_INFO_S * pMsg = (MSG_REJECT_MSG_INFO_S *)pTmp->data;
+               memset(pMsg, 0x00, sizeof(MSG_REJECT_MSG_INFO_S));
+
+               pMsg->msgId = dbHandle->getColumnToInt(index++);
+               memset(pMsg->msgText, 0x00, sizeof(pMsg->msgText));
+               dbHandle->getColumnToString(index++, MAX_MSG_TEXT_LEN, pMsg->msgText);
+
+               pMsg->displayTime = (time_t)dbHandle->getColumnToInt(index++);
+       }
+
+       dbHandle->freeTable();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetAddressList(const msg_thread_id_t threadId, msg_struct_list_s *pAddrList)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       int order = MsgGetContactNameOrder();
+
+       err = MsgStoGetAddressByConvId(dbHandle, threadId, order, pAddrList);
+
+       return err;
+}
+
+
+msg_error_t MsgStoGetMessageList(const MSG_LIST_CONDITION_S *pListCond, msg_struct_list_s *pMsgList)
+{
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       // Clear Out Parameter
+       pMsgList->nCount = 0;
+       pMsgList->msg_struct_info = NULL;
+
+       int index = 0;
+       int multipartCnt = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       char sqlQuerySubset[(MAX_QUERY_LEN/5)+1];
+       char tmpsqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*) FROM %s;", MSGFW_MMS_MULTIPART_TABLE_NAME);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               multipartCnt = dbHandle->columnInt(0);
+       } else {
+               dbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle->finalizeQuery();
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT "
+                       "A.MSG_ID, "
+                       "A.CONV_ID, "
+                       "A.FOLDER_ID, "
+                       "A.STORAGE_ID, "
+                       "A.MAIN_TYPE, "
+                       "A.SUB_TYPE, "
+                       "A.DISPLAY_TIME, "
+                       "A.DATA_SIZE, "
+                       "A.NETWORK_STATUS, "
+                       "A.READ_STATUS, "
+                       "A.PROTECTED, "
+                       "A.BACKUP, "
+                       "A.PRIORITY, "
+                       "A.MSG_DIRECTION, "
+                       "A.SCHEDULED_TIME, "
+                       "A.SUBJECT, "
+                       "A.MSG_TEXT, "
+                       "A.ATTACHMENT_COUNT, "
+                       "A.THUMB_PATH, "
+                       "A.SIM_INDEX, "
+                       "B.ADDRESS_TYPE, "
+                       "B.RECIPIENT_TYPE, "
+                       "B.ADDRESS_VAL ");
+
+       if (pListCond->pTextVal != NULL && multipartCnt > 0) {
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset),        "FROM %s C, %s B, %s A WHERE A.CONV_ID > 0 AND A.CONV_ID = B.CONV_ID AND "
+                       ,MSGFW_MMS_MULTIPART_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME);
+       }
+       else {
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset),        "FROM %s B, %s A WHERE A.CONV_ID > 0 AND A.CONV_ID = B.CONV_ID AND ",
+               MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME);
+       }
+
+       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+       //// folder
+       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+
+       if (pListCond->folderId == MSG_ALLBOX_ID)
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "A.FOLDER_ID > 0 AND A.FOLDER_ID < %d ", MSG_SPAMBOX_ID);
+       else if (pListCond->folderId == MSG_IOSBOX_ID)
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "A.FOLDER_ID > 0 AND A.FOLDER_ID < %d ", MSG_DRAFT_ID);
+       else
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "A.FOLDER_ID = %d ", pListCond->folderId);
+
+       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+
+       //// thread
+       if (pListCond->threadId > 0) {
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.CONV_ID = %d ", pListCond->threadId);
+               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+       }
+
+
+       //// msg type
+       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+
+       switch (pListCond->msgType) {
+               case MSG_TYPE_SMS:
+                       if (pListCond->pAddressVal == NULL)
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.MAIN_TYPE = %d ", MSG_SMS_TYPE);
+                       else
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.MAIN_TYPE = %d AND A.SUB_TYPE = %d ", MSG_SMS_TYPE, MSG_NORMAL_SMS);
+                       break;
+
+               case MSG_TYPE_MMS:
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.MAIN_TYPE = %d ", MSG_MMS_TYPE);
+                       break;
+
+               case MSG_TYPE_MMS_JAVA:
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.MAIN_TYPE = %d AND A.SUB_TYPE = %d ", MSG_MMS_TYPE, MSG_SENDREQ_JAVA_MMS);
+                       break;
+
+               case MSG_TYPE_SMS_SYNCML:
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.MAIN_TYPE = %d AND A.SUB_TYPE = %d ", MSG_SMS_TYPE, MSG_SYNCML_CP);
+                       break;
+               case MSG_TYPE_SMS_REJECT:
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.MAIN_TYPE = %d AND A.SUB_TYPE = %d ", MSG_SMS_TYPE, MSG_REJECT_SMS);
+                       break;
+
+               default:
+                       MSG_DEBUG("msg type is not set.");
+                       break;
+       }
+
+       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+
+       //// storage
+       if (pListCond->storageId > MSG_STORAGE_UNKNOWN) {
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.STORAGE_ID = %d ", pListCond->storageId);
+               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+       }
+
+
+       //// protected
+       if (pListCond->bProtected) {
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.PROTECTED = %d ", pListCond->bProtected);
+               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+       }
+
+
+       //// scheduled
+       if (pListCond->bScheduled) {
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.SCHEDULED_TIME > 0 ");
+               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+       }
+
+
+       //// sim index
+       if (pListCond->simIndex > 0) {
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.SIM_INDEX = %d ", pListCond->simIndex);
+               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+       }
+
+
+       //// time range
+       if (pListCond->fromTime > 0) {
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.DISPLAY_TIME >= %u ", (unsigned int)pListCond->fromTime);
+               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+       }
+
+       if (pListCond->toTime > 0) {
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND A.DISPLAY_TIME <= %u ", (unsigned int)pListCond->toTime);
+               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+       }
+
+       if (pListCond->pAddressVal == NULL) {
+               /// Text
+               if (pListCond->pTextVal != NULL) {
+
+                       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                       if (multipartCnt > 0) {
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset),
+                                               "AND ((A.MSG_TEXT LIKE ? ESCAPE '%c' OR A.SUBJECT LIKE ? ESCAPE '%c' OR (C.NAME LIKE ? ESCAPE '%c' AND A.MSG_ID = C.MSG_ID AND C.CONTENT_TYPE <> 'application/smil'))) ",
+                                               MSGFW_DB_ESCAPE_CHAR, MSGFW_DB_ESCAPE_CHAR, MSGFW_DB_ESCAPE_CHAR);
+                       }
+                       else {
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset),
+                                               "AND ((A.MSG_TEXT LIKE ? ESCAPE '%c' OR A.SUBJECT LIKE ? ESCAPE '%c')) ",
+                                               MSGFW_DB_ESCAPE_CHAR, MSGFW_DB_ESCAPE_CHAR);
+                       }
+                       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+               }
+       } else {
+               /// Text
+               if (pListCond->pTextVal != NULL) {
+
+                       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                       if (multipartCnt > 0) {
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset),
+                                               "AND ((A.MSG_TEXT LIKE ? ESCAPE '%c' OR A.SUBJECT LIKE ? ESCAPE '%c' OR (C.NAME LIKE ? ESCAPE '%c' AND A.MSG_ID = C.MSG_ID AND C.CONTENT_TYPE <> 'application/smil')) ",
+                                               MSGFW_DB_ESCAPE_CHAR, MSGFW_DB_ESCAPE_CHAR, MSGFW_DB_ESCAPE_CHAR);
+                       }
+                       else {
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset),
+                                               "AND ((A.MSG_TEXT LIKE ? ESCAPE '%c' OR A.SUBJECT LIKE ? ESCAPE '%c') ",
+                                               MSGFW_DB_ESCAPE_CHAR, MSGFW_DB_ESCAPE_CHAR);
+                       }
+                       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+                       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                       if (pListCond->bAnd) {
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND ");
+                       } else {
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "OR ");
+                       }
+                       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+                       // Address
+                       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset),
+                                       "(B.ADDRESS_VAL LIKE ? ESCAPE '%c' ", MSGFW_DB_ESCAPE_CHAR);
+                       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+                       MSG_ADDRESS_INFO_S *pAddrInfo = NULL;
+                       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> buf(&pAddrInfo, unique_ptr_deleter);
+                       int count = 0;
+
+                       // get contact search list
+                       if (MsgGetContactSearchList(pListCond->pAddressVal, &pAddrInfo, &count) != MSG_SUCCESS) {
+                               MSG_DEBUG("MsgGetContactSearchList fail.");
+                               count = 0;
+                       }
+
+                       if (count > 0) {
+                               dbHandle->beginTrans();
+                               // reset address temp table
+                               memset(tmpsqlQuery, 0x00, sizeof(tmpsqlQuery));
+                               snprintf(tmpsqlQuery, sizeof(tmpsqlQuery), "DELETE FROM %s;", MSGFW_ADDRESS_TEMP_TABLE_NAME);
+                               MSG_DEBUG("[%s]", tmpsqlQuery);
+
+                               if (dbHandle->prepareQuery(tmpsqlQuery) != MSG_SUCCESS)
+                                       return MSG_ERR_DB_EXEC;
+
+                               if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                                       dbHandle->finalizeQuery();
+                                       dbHandle->endTrans(false);
+                                       return MSG_ERR_DB_EXEC;
+                               }
+
+                               dbHandle->finalizeQuery();
+
+                               memset(tmpsqlQuery, 0x00, sizeof(tmpsqlQuery));
+                               snprintf(tmpsqlQuery, sizeof(tmpsqlQuery), "INSERT INTO %s VALUES ('%%%%?');", MSGFW_ADDRESS_TEMP_TABLE_NAME);
+                               if (dbHandle->prepareQuery(tmpsqlQuery) != MSG_SUCCESS) {
+                                       dbHandle->endTrans(false);
+                                       return MSG_ERR_DB_PREPARE;
+                               }
+
+                               for (int i = 0; i < count; i++) {
+                                       int addrSize = strlen(pAddrInfo[i].addressVal);
+                                       char newPhoneNum[addrSize+1];
+                                       memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
+                                       MsgConvertNumber(pAddrInfo[i].addressVal, newPhoneNum, addrSize);
+
+                                       dbHandle->resetQuery();
+                                       dbHandle->bindText(newPhoneNum, 1);
+                                       if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                                               dbHandle->finalizeQuery();
+                                               dbHandle->endTrans(false);
+                                               return MSG_ERR_DB_EXEC;
+                                       }
+                               }
+
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(true);
+
+                               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset),
+                                               "OR B.ADDRESS_VAL IN (SELECT D.ADDRESS_VAL FROM %s D JOIN %s E ON (D.ADDRESS_VAL LIKE E.ADDRESS_VAL)) "
+                                               , MSGFW_ADDRESS_TABLE_NAME, MSGFW_ADDRESS_TEMP_TABLE_NAME);
+                               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+                       }
+
+                       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), ")) ");
+                       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+               } else {
+                       // Address
+                       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset),
+                                       "AND (B.ADDRESS_VAL LIKE ? ESCAPE '%c' ", MSGFW_DB_ESCAPE_CHAR);
+                       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+                       MSG_ADDRESS_INFO_S *pAddrInfo = NULL;
+                       unique_ptr<MSG_ADDRESS_INFO_S*, void(*)(MSG_ADDRESS_INFO_S**)> buf(&pAddrInfo, unique_ptr_deleter);
+                       int count = 0;
+
+                       // get contact search list
+                       if (MsgGetContactSearchList(pListCond->pAddressVal, &pAddrInfo, &count) != MSG_SUCCESS) {
+                               MSG_DEBUG("MsgGetContactSearchList fail.");
+                               count = 0;
+                       }
+
+                       if (count > 0) {
+                               dbHandle->beginTrans();
+                               // reset address temp table
+                               memset(tmpsqlQuery, 0x00, sizeof(tmpsqlQuery));
+                               snprintf(tmpsqlQuery, sizeof(tmpsqlQuery), "DELETE FROM %s;", MSGFW_ADDRESS_TEMP_TABLE_NAME);
+                               MSG_DEBUG("[%s]", tmpsqlQuery);
+
+                               if (dbHandle->prepareQuery(tmpsqlQuery) != MSG_SUCCESS) {
+                                       dbHandle->endTrans(false);
+                                       return MSG_ERR_DB_EXEC;
+                               }
+
+                               if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                                       dbHandle->finalizeQuery();
+                                       return MSG_ERR_DB_EXEC;
+                               }
+
+                               dbHandle->finalizeQuery();
+
+                               memset(tmpsqlQuery, 0x00, sizeof(tmpsqlQuery));
+                               snprintf(tmpsqlQuery, sizeof(tmpsqlQuery), "INSERT INTO %s VALUES ('%%%%?');", MSGFW_ADDRESS_TEMP_TABLE_NAME);
+                               if (dbHandle->prepareQuery(tmpsqlQuery) != MSG_SUCCESS) {
+                                       dbHandle->endTrans(false);
+                                       return MSG_ERR_DB_PREPARE;
+                               }
+
+                               for (int i = 0; i < count; i++) {
+                                       int addrSize = strlen(pAddrInfo[i].addressVal);
+                                       char newPhoneNum[addrSize+1];
+                                       memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
+                                       MsgConvertNumber(pAddrInfo[i].addressVal, newPhoneNum, addrSize);
+
+                                       dbHandle->resetQuery();
+                                       dbHandle->bindText(newPhoneNum, 1);
+                                       if (dbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                                               dbHandle->finalizeQuery();
+                                               dbHandle->endTrans(false);
+                                               return MSG_ERR_DB_EXEC;
+                                       }
+                               }
+
+                               dbHandle->finalizeQuery();
+                               dbHandle->endTrans(true);
+
+                               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset),
+                                               "OR B.ADDRESS_VAL IN (SELECT D.ADDRESS_VAL FROM %s D JOIN %s E ON (D.ADDRESS_VAL LIKE E.ADDRESS_VAL)) "
+                                               , MSGFW_ADDRESS_TABLE_NAME, MSGFW_ADDRESS_TEMP_TABLE_NAME);
+                               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+                       }
+
+                       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), ") ");
+                       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+               }
+       }
+
+       msg_struct_s *pSortRule = (msg_struct_s *)pListCond->sortRule;
+
+       if (pSortRule->type != MSG_STRUCT_SORT_RULE) {
+               /// Order
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "ORDER BY A.DISPLAY_TIME ");
+
+               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+               /// Sorting type
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "DESC ");
+
+               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+       } else {
+               MSG_SORT_RULE_S *pTmp = (MSG_SORT_RULE_S *)pSortRule->data;
+               /// order // TODO: have to finish this
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               switch (pTmp->sortType)
+               {
+               case MSG_SORT_BY_MSG_TYPE :
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "ORDER BY A.MAIN_TYPE ");
+                       break;
+               case MSG_SORT_BY_READ_STATUS :
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "ORDER BY A.READ_STATUS ");
+                       break;
+               case MSG_SORT_BY_STORAGE_TYPE :
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "ORDER BY A.STORAGE_ID ");
+                       break;
+               default:
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "ORDER BY A.DISPLAY_TIME ");
+                       break;
+               }
+               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+               // Sorting type
+               memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+               if (pTmp->bAscending)
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "ASC ");
+               else
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "DESC ");
+
+               strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+       }
+
+       // offset & limit
+       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+       if (pListCond->offset >= 0 && pListCond->limit > 0)
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "LIMIT %d OFFSET %d;", pListCond->limit, pListCond->offset);
+       else
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), ";");
+
+       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+
+       //////// 'til here sqlQuery is complete.
+
+       queue<MSG_MESSAGE_HIDDEN_S*> searchList;
+
+       MSG_DEBUG("[%s]", sqlQuery);
+
+       if (dbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Prepare query fail.");
+               return MSG_ERR_DB_PREPARE;
+       }
+
+       char *escapeTextStr = NULL;
+       char *escapeAddressStr = NULL;
+
+       if (pListCond->pAddressVal == NULL) {
+               /// Text
+               if (pListCond->pTextVal != NULL) {
+
+                       MsgConvertStrWithEscape(pListCond->pTextVal, &escapeTextStr);
+                       MSG_DEBUG("escapeTextStr [%s]", escapeTextStr);
+                       dbHandle->bindText(escapeTextStr, 1);
+                       dbHandle->bindText(escapeTextStr, 2);
+                       if (multipartCnt > 0) dbHandle->bindText(escapeTextStr, 3);
+
+               }
+       } else {
+               /// Text
+               if (pListCond->pTextVal != NULL) {
+
+                       MsgConvertStrWithEscape(pListCond->pTextVal, &escapeTextStr);
+                       MSG_DEBUG("escapeTestStr [%s]", escapeTextStr);
+
+                       // Address
+                       MsgConvertStrWithEscape(pListCond->pAddressVal, &escapeAddressStr);
+                       MSG_DEBUG("escapeAddressStr [%s]", escapeAddressStr);
+
+                       dbHandle->bindText(escapeTextStr, 1);
+                       dbHandle->bindText(escapeTextStr, 2);
+                       if (multipartCnt > 0) {
+                               dbHandle->bindText(escapeTextStr, 3);
+                               dbHandle->bindText(escapeAddressStr, 4);
+                       } else {
+                               dbHandle->bindText(escapeAddressStr, 3);
+                       }
+
+               } else {
+                       // Address
+                       MsgConvertStrWithEscape(pListCond->pAddressVal, &escapeAddressStr);
+                       MSG_DEBUG("escapeAddressStr [%s]", escapeAddressStr);
+                       dbHandle->bindText(escapeAddressStr, 1);
+               }
+       }
+
+
+       MSG_MESSAGE_HIDDEN_S *pTmp = NULL;
+       int lastMsgId = 0;  // for comparing same msg id.
+
+       while (dbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+
+               index = 0;
+
+               int msgid = dbHandle->columnInt(index++);
+               MSG_DEBUG("msgid [%d]", msgid);
+
+               if (lastMsgId != msgid) {
+                       MSG_DEBUG("lastMsgId != msgid");
+
+                       lastMsgId = msgid;
+
+                       pTmp = new MSG_MESSAGE_HIDDEN_S;
+
+                       if(pTmp)
+                       {
+                               memset(pTmp, 0x00, sizeof(MSG_MESSAGE_HIDDEN_S));
+
+                               pTmp->pData = NULL;
+                               pTmp->pMmsData = NULL;
+                               pTmp->addressList = NULL;
+
+                               pTmp->msgId = msgid;
+
+                               pTmp->threadId = dbHandle->columnInt(index++);
+                               pTmp->folderId = dbHandle->columnInt(index++);
+                               pTmp->storageId = dbHandle->columnInt(index++);
+                               pTmp->mainType = dbHandle->columnInt(index++);
+                               pTmp->subType = dbHandle->columnInt(index++);
+                               pTmp->displayTime = (time_t)dbHandle->columnInt(index++);
+                               pTmp->dataSize = dbHandle->columnInt(index++);
+                               pTmp->networkStatus = dbHandle->columnInt(index++);
+                               pTmp->bRead = dbHandle->columnInt(index++);
+                               pTmp->bProtected = dbHandle->columnInt(index++);
+                               pTmp->bBackup = dbHandle->columnInt(index++);
+                               pTmp->priority = dbHandle->columnInt(index++);
+                               pTmp->direction = dbHandle->columnInt(index++);
+                               index++; // This field is reserved.
+
+                               strncpy(pTmp->subject, (char *)dbHandle->columnText(index++), MAX_SUBJECT_LEN);
+
+                               if (pTmp->mainType == MSG_MMS_TYPE &&
+                                       (pTmp->networkStatus == MSG_NETWORK_RETRIEVING || pTmp->networkStatus == MSG_NETWORK_RETRIEVE_FAIL || pTmp->subType == MSG_NOTIFICATIONIND_MMS)) {
+                                       pTmp->pData = NULL;
+                                       index++;
+                               } else {
+                                       pTmp->pData = (void *)new char[pTmp->dataSize+2];
+                                       memset(pTmp->pData, 0x00, pTmp->dataSize+2);
+
+                                       strncpy((char *)pTmp->pData, (char *)dbHandle->columnText(index++), pTmp->dataSize+1);
+                               }
+
+                               pTmp->attachCount = dbHandle->columnInt(index++);
+
+                               strncpy(pTmp->thumbPath, (char *)dbHandle->columnText(index++), MSG_FILEPATH_LEN_MAX);
+
+                               pTmp->simIndex = dbHandle->columnInt(index++);
+
+                               pTmp->addr_list = (msg_struct_list_s *)new msg_struct_list_s;
+                               pTmp->addr_list->nCount = 0;
+                               pTmp->addr_list->msg_struct_info = (msg_struct_t *)calloc(MAX_TO_ADDRESS_CNT, sizeof(msg_struct_t));
+                               for (int i = 0; i < MAX_TO_ADDRESS_CNT; i++) {
+                                       pTmp->addr_list->msg_struct_info[i] = (msg_struct_t)new msg_struct_s;
+                                       memset(pTmp->addr_list->msg_struct_info[i], 0x00, sizeof(msg_struct_s));
+                               }
+
+                               searchList.push(pTmp);
+                       }
+
+               } else {
+                       MSG_DEBUG("lastMsgId == msgid");
+                       index += 19;
+               }
+
+               if(pTmp) {
+                       MSG_ADDRESS_INFO_S *pAddr = new MSG_ADDRESS_INFO_S;
+                       memset(pAddr, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+                       pAddr->addressType = dbHandle->columnInt(index++);
+                       pAddr->recipientType = dbHandle->columnInt(index++);
+
+                       strncpy(pAddr->addressVal, (char *)dbHandle->columnText(index++), MAX_ADDRESS_VAL_LEN);
+
+                       strncpy(pAddr->displayName, pAddr->addressVal, MAX_DISPLAY_NAME_LEN);
+
+                       // For GList *addressList
+                       msg_struct_s *addr_info_s = new msg_struct_s;
+                       memset(addr_info_s, 0x00, sizeof(msg_struct_s));
+                       addr_info_s->type = MSG_STRUCT_ADDRESS_INFO;
+                       addr_info_s->data = new MSG_ADDRESS_INFO_S;
+                       memset(addr_info_s->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+                       MSG_ADDRESS_INFO_S *addr_info = (MSG_ADDRESS_INFO_S *)addr_info_s->data;
+                       addr_info->addressType = pAddr->addressType;
+                       addr_info->recipientType = pAddr->recipientType;
+                       addr_info->contactId = pAddr->contactId;
+                       strncpy(addr_info->addressVal, pAddr->addressVal, MAX_ADDRESS_VAL_LEN);
+                       strncpy(addr_info->displayName, pAddr->displayName, MAX_DISPLAY_NAME_LEN);
+                       addr_info->displayName[MAX_DISPLAY_NAME_LEN] = '\0';
+
+                       pTmp->addressList = g_list_append(pTmp->addressList, addr_info_s);
+
+                       if (pTmp->addr_list->nCount >= MAX_TO_ADDRESS_CNT) {
+
+                               delete pAddr;
+
+                       } else {
+                               msg_struct_s *pStruct = (msg_struct_s *)pTmp->addr_list->msg_struct_info[pTmp->addr_list->nCount];
+                               pTmp->addr_list->nCount++;
+                               pStruct->type = MSG_STRUCT_ADDRESS_INFO;
+                               pStruct->data = pAddr;
+                       }
+               }
+       }
+
+       dbHandle->finalizeQuery();
+
+       pMsgList->nCount = searchList.size();
+       MSG_DEBUG("pMsgList->nCount [%d]", pMsgList->nCount);
+
+       pMsgList->msg_struct_info = (msg_struct_t *)calloc(pMsgList->nCount, sizeof(msg_struct_t));
+       if (pMsgList->msg_struct_info == NULL)
+               return MSG_ERR_MEMORY_ERROR;
+
+       int offset = 0;
+       while (!searchList.empty()) {
+
+               msg_struct_s *msg = new msg_struct_s;
+
+               pMsgList->msg_struct_info[offset++] = (msg_struct_t)msg;
+
+               msg->type = MSG_STRUCT_MESSAGE_INFO;
+               msg->data = searchList.front();
+
+               searchList.pop();
+       }
+
+
+       if (escapeTextStr)
+               free(escapeTextStr);
+
+       if (escapeAddressStr)
+               free(escapeAddressStr);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetMediaList(const msg_thread_id_t threadId, msg_list_handle_t *pMediaList)
+{
+       MSG_BEGIN();
+       msg_error_t err = MSG_SUCCESS;
+       MsgDbHandler *dbHandle = getDbHandle();
+       char sqlQuery[MAX_QUERY_LEN+1];
+       int msgIdCnt = 0;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE MAIN_TYPE = %d AND CONV_ID = %d;",
+                       MSGFW_MESSAGE_TABLE_NAME, MSG_MMS_TYPE, threadId);
+
+       MSG_DEBUG("sqlQuery = [%s]", sqlQuery);
+
+       err = dbHandle->getTable(sqlQuery, &msgIdCnt, NULL);
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               dbHandle->freeTable();
+               return err;
+       } else if (err == MSG_ERR_DB_NORECORD) {
+               dbHandle->freeTable();
+               return MSG_SUCCESS;
+       }
+
+       msg_message_id_t *msgIds = new msg_message_id_t[msgIdCnt];
+
+       for (int i = 1; i <= msgIdCnt; i++) {
+               msgIds[i-1] = dbHandle->getColumnToInt(i);
+       }
+
+       dbHandle->freeTable();
+
+       int main_type = 0;
+       GList *media_list = NULL;
+
+       for (int i = 0; i < msgIdCnt; i++) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MAIN_TYPE FROM %s WHERE MSG_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, msgIds[i]);
+
+               err = dbHandle->prepareQuery(sqlQuery);
+               if (err != MSG_SUCCESS)
+                       return err;
+
+               err = dbHandle->stepQuery();
+               if (err != MSG_ERR_DB_ROW) {
+                       dbHandle->finalizeQuery();
+                       return err;
+               }
+
+               main_type = dbHandle->columnInt(0);
+
+               dbHandle->finalizeQuery();
+
+               if (main_type == MSG_MMS_TYPE) {
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID, CONTENT_TYPE, FILE_PATH, THUMB_FILE_PATH "
+                                       "FROM %s WHERE MSG_ID = %d AND SEQ <> -1;",
+                                       MSGFW_MMS_MULTIPART_TABLE_NAME, msgIds[i]);
+               }
+
+               int rowCnt = 0, msg_id = 0, index = 0;
+
+               err = dbHandle->getTable(sqlQuery, &rowCnt, &index);
+
+               if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+                       dbHandle->freeTable();
+                       return err;
+               }
+
+               MSG_MEDIA_INFO_S *pMedia = NULL;
+               char mime_type[MAX_MIME_TYPE_LEN+1], media_item[MSG_FILEPATH_LEN_MAX+1], thumb_path[MSG_FILEPATH_LEN_MAX+1];
+
+               for (int j = 0; j < rowCnt; j++) {
+                       msg_id = dbHandle->getColumnToInt(index++);
+                       memset(mime_type, 0x00, sizeof(mime_type));
+                       dbHandle->getColumnToString(index++, MAX_MIME_TYPE_LEN, mime_type);
+                       memset(media_item, 0x00, sizeof(media_item));
+                       dbHandle->getColumnToString(index++, MSG_FILEPATH_LEN_MAX, media_item);
+                       memset(thumb_path, 0x00, sizeof(thumb_path));
+                       dbHandle->getColumnToString(index++, MSG_FILEPATH_LEN_MAX, thumb_path);
+
+                       if (strstr(mime_type, "image") || strstr(mime_type, "video")) {
+                               msg_struct_s *media_struct_s = new msg_struct_s;
+                               media_struct_s->type = MSG_STRUCT_MEDIA_INFO;
+                               media_struct_s->data = new MSG_MEDIA_INFO_S;
+                               memset(media_struct_s->data, 0x00, sizeof(MSG_MEDIA_INFO_S));
+
+                               pMedia = (MSG_MEDIA_INFO_S *)media_struct_s->data;
+
+                               pMedia->msg_id = msg_id;
+                               snprintf(pMedia->mime_type, MAX_MIME_TYPE_LEN, "%s", mime_type);
+                               snprintf(pMedia->media_item, MSG_FILEPATH_LEN_MAX, "%s", media_item);
+                               snprintf(pMedia->thumb_path, MSG_FILEPATH_LEN_MAX, "%s", thumb_path);
+
+                               media_list = g_list_append(media_list, media_struct_s);
+                       }
+               }
+
+               dbHandle->freeTable();
+
+               *pMediaList = (msg_list_handle_t)media_list;
+       }
+
+       if (msgIds)
+               delete [] msgIds;
+
+       MSG_END();
+       return err;
+}
+
+#ifdef FEATURE_SMS_CDMA
+msg_error_t MsgStoClearUniquenessTable()
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       MsgDbHandler *dbHandle = getDbHandle();
+
+       char sqlQuery[MAX_QUERY_LEN+1] = {0,};
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID = 0", MSGFW_UNIQUENESS_INFO_TABLE_NAME);
+
+       err = dbHandle->execQuery(sqlQuery);
+
+       MSG_END();
+
+       return err;
 }
+#endif
diff --git a/utils/MsgVMessage.cpp b/utils/MsgVMessage.cpp
new file mode 100755 (executable)
index 0000000..c0db4b4
--- /dev/null
@@ -0,0 +1,667 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include <VMessage.h>
+#include <VCard.h>
+#include <time.h>
+
+#include "MsgMmsTypes.h"
+
+#include "MsgDebug.h"
+#include "MsgUtilFile.h"
+#include "MsgCppTypes.h"
+#include "MsgVMessage.h"
+#include "MsgMmsMessage.h"
+#include "MsgSerialize.h"
+
+/*==================================================================================================
+                                     DEFINES
+==================================================================================================*/
+#define INSERT_VMSG_OBJ pObject = (VObject*)calloc(1, sizeof(VObject));        \
+                                      if ( !pObject )\
+{\
+   vmsg_free_vtree_memory( pMessage );\
+   return false;\
+}\
+if (pMessage->pTop == NULL)\
+{\
+   pMessage->pTop = pObject;\
+}\
+else\
+{\
+   pMessage->pCur->pSibling = pObject;\
+}\
+pMessage->pCur = pObject;
+
+
+#define INSERT_VBODY_OBJ pObject = (VObject*)calloc(1, sizeof(VObject));       \
+                                      if ( !pObject )\
+{\
+   vmsg_free_vtree_memory( pMessage );\
+   return false;\
+}\
+if (pBody->pTop == NULL)\
+{\
+   pBody->pTop = pObject;\
+}\
+else\
+{\
+   pBody->pCur->pSibling = pObject;\
+}\
+pBody->pCur = pObject;
+
+
+#define INSERT_VCARD_OBJ pObject = (VObject*)calloc(1, sizeof(VObject));       \
+                                      if ( !pObject )\
+{\
+   vmsg_free_vtree_memory( pMessage );\
+   return false;\
+}\
+if (pCard->pTop == NULL)\
+{\
+   pCard->pTop = pObject;\
+}\
+else\
+{\
+   pCard->pCur->pSibling = pObject;\
+}\
+pCard->pCur = pObject;
+
+
+#define INSERT_PARAM  param = (VParam*)calloc(1, sizeof(VParam));\
+                             if (!param)\
+{\
+   vmsg_free_vtree_memory( pMessage );\
+   if (pObject != NULL)\
+   {\
+      free(pObject);\
+      pObject = NULL;\
+   }\
+   return false;\
+}
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+char* MsgVMessageAddRecord(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S* pMsg)
+{
+       MSG_BEGIN();
+
+       VObject*                pObject = NULL;
+       VParam*         param = NULL;
+       VTree *         pBody = NULL;
+       VTree *         pCard = NULL;
+       VTree *         pCurrent= NULL;
+       struct tm       display_time;
+       char*           encoded_data = NULL;
+
+       VTree* pMessage = NULL;
+       if (pMessage == NULL) {
+               pMessage = (VTree *)malloc(sizeof(VTree));
+               if (!pMessage) {
+                       return NULL;
+               }
+               pMessage->treeType = VMESSAGE;
+               pMessage->pTop = NULL;
+               pMessage->pCur = NULL;
+               pMessage->pNext = NULL;
+
+       }
+               pCurrent = pMessage;
+
+       //Insert VObject (X-MESSAGE-TYPE) to VMessage tree
+       INSERT_VMSG_OBJ;
+
+       pObject->property = VMSG_TYPE_MSGTYPE;
+
+       if(pMsg->msgType.subType == MSG_NORMAL_SMS)
+               pObject->pszValue[0] = strdup("SMS");
+#if 0
+       else if(pMsg->msgType.mainType == MSG_MMS_TYPE && pMsg->msgType.subType == MSG_NOTIFICATIONIND_MMS)
+               pObject->pszValue[0] = strdup("MMS NOTIFICATION");
+#endif
+
+       else if(pMsg->msgType.mainType == MSG_MMS_TYPE && (pMsg->msgType.subType == MSG_SENDREQ_MMS || pMsg->msgType.subType == MSG_SENDCONF_MMS))
+               pObject->pszValue[0] = strdup("MMS SEND");
+
+       else if(pMsg->msgType.mainType == MSG_MMS_TYPE && (pMsg->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || pMsg->msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS))
+               pObject->pszValue[0] = strdup("MMS RETRIEVED");
+
+       else
+               goto __CATCH_FAIL__;
+
+       pObject->valueCount = 1;
+
+
+       //Insert VObject (X-IRMC-BOX) to VMessate tree
+       INSERT_VMSG_OBJ;
+
+       pObject->property = VMSG_TYPE_MSGBOX;
+
+       switch(pMsg->folderId)
+       {
+               case MSG_INBOX_ID:
+                       pObject->pszValue[0] = strdup("INBOX");
+                       break;
+               case MSG_OUTBOX_ID:
+                       pObject->pszValue[0] = strdup("OUTBOX");
+                       break;
+               case MSG_SENTBOX_ID:
+                       pObject->pszValue[0] = strdup("SENTBOX");
+                       break;
+               case MSG_DRAFT_ID:
+                       pObject->pszValue[0] = strdup("DRAFTBOX");
+                       break;
+               default:
+                       // Discard User Defined or Spam folder's messages.
+                       goto __CATCH_FAIL__;
+       }
+       pObject->valueCount = 1;
+
+
+       //Insert VObject (X-SS-DT) to VMessage tree
+       INSERT_VMSG_OBJ;
+
+       pObject->property = VMSG_TYPE_DATE;
+       tzset();
+       localtime_r(&(pMsg->displayTime), &display_time);
+       pObject->pszValue[0] = _convert_tm_to_vdata_str(&display_time);
+       pObject->valueCount = 1;
+
+
+       //Insert Vobject read status to VMessage tree
+       INSERT_VMSG_OBJ;
+
+       pObject->property = VMSG_TYPE_STATUS;
+
+       if(pMsg->bRead)
+               pObject->pszValue[0] = strdup("READ");
+       else
+               pObject->pszValue[0] = strdup("UNREAD");
+
+       pObject->valueCount = 1;
+
+
+       //Insert VBody  tree for message body;
+       pBody = (VTree*)calloc(1, sizeof(VTree));
+       if ( !pBody )
+               goto __CATCH_FAIL__;
+       pBody->treeType = VBODY;
+       pBody->pTop = NULL;
+       pBody->pCur = NULL;
+       pBody->pNext = NULL;
+       pCurrent->pNext = pBody;
+       pCurrent = pBody;
+
+if(strlen(pMsg->subject) > 0)
+{
+       //Insert Subject object
+       INSERT_VBODY_OBJ;
+       pObject->property = VMSG_TYPE_SUBJECT;
+       pObject->pszValue[0] = strdup(pMsg->subject);
+       pObject->valueCount = 1;
+}
+       //Insert VBody object
+       INSERT_VBODY_OBJ;
+       pObject->property = VMSG_TYPE_BODY;
+
+       if(pMsg->msgType.mainType == MSG_SMS_TYPE)
+       {
+               if(pMsg->msgType.subType == MSG_NORMAL_SMS)
+               {
+                       if (pMsg->bTextSms == false)
+                       {
+                               char* pFileData = NULL;
+                               unique_ptr<char*, void(*)(char**)> buf(&pFileData, unique_ptr_deleter);
+
+                               int             fileSize = 0;
+                               char*   msgText = NULL;
+
+                               if (MsgOpenAndReadFile(pMsg->msgData, &pFileData, &fileSize) == false)
+                                       goto __CATCH_FAIL__;
+
+                               msgText = (char *)calloc(1, fileSize);
+                               memcpy(msgText, pFileData, fileSize);
+                               pObject->numOfBiData = fileSize;
+                               pObject->pszValue[0] = msgText;
+                       }
+                       else
+                       {
+                               pObject->numOfBiData = pMsg->dataSize;
+                               pObject->pszValue[0] = strdup(pMsg->msgText);
+                       }
+                       pObject->valueCount = 1;
+               }
+               else
+                       goto __CATCH_FAIL__;
+       }
+
+       else if(pMsg->msgType.mainType == MSG_MMS_TYPE)
+       {
+               //Insert VBody for mms raw data;
+               char* pFileData = NULL;
+               MMS_DATA_S *pMmsData = NULL;
+               int             fileSize = 0;
+               char*   msgText = NULL;
+#if 0
+               char            filePath[MSG_FILEPATH_LEN_MAX] = {0, };
+               if(pMsg->msgType.subType == MSG_NOTIFICATIONIND_MMS)
+                       pFileData = MsgOpenAndReadMmsFile(pMsg->msgData, 0, -1, &fileSize);
+
+               else
+               {
+                       err = MsgStoGetMmsRawFilePath(pDbHandle, pMsg->msgId, filePath);
+
+                       if (err != MSG_SUCCESS)
+                               goto __CATCH_FAIL__;
+
+                       pFileData = MsgOpenAndReadMmsFile(filePath, 0, -1, &fileSize);
+               }
+#else
+
+               if (pMsg->bTextSms == false) {
+                       if (MsgOpenAndReadFile(pMsg->msgData, &pFileData, &fileSize) == false) {
+                               //CID 16205: Memory leak in case of failure
+                               if (pFileData) {
+                                       free(pFileData);
+                                       pFileData = NULL;
+                               }
+                               goto __CATCH_FAIL__;
+                       }
+               } else {
+                       fileSize = strlen(pMsg->msgData);
+                       pFileData = (char *)calloc(1, fileSize+1);
+                       snprintf(pFileData, fileSize, "%s", pMsg->msgData);
+               }
+
+               //CID 46178: Pulling up the null check
+               if (pFileData) {
+                       if (MsgDeserializeMmsData(pFileData, fileSize, &pMmsData) != 0) {
+                               MSG_DEBUG("Fail to Deserialize Message Data");
+                               goto __CATCH_FAIL__;
+                       }
+
+                       free(pFileData);
+                       pFileData = NULL;
+               }
+
+               int serializedDataSize = 0;
+
+               if (pMmsData) {
+                       MsgMmsSetMultipartListData(pMmsData);//app file -> data
+                       serializedDataSize = MsgSerializeMms(pMmsData, &pFileData);
+               }
+
+               if (pFileData) {
+                       fileSize = serializedDataSize;
+               }
+
+               MsgMmsRelease(&pMmsData);
+
+#endif
+               MSG_DEBUG("FILE SIZE IS %d, %s", fileSize, pFileData);
+               msgText = (char *)calloc(1, fileSize);
+               if(pFileData && msgText)
+                       memcpy(msgText, pFileData, fileSize);
+
+               pObject->numOfBiData = fileSize;
+               pObject->pszValue[0] = msgText;
+               pObject->valueCount = 1;
+
+               if (pFileData) {
+                       free(pFileData);
+                       pFileData = NULL;
+               }
+       }
+
+       // Insert parameter for base64 encoding
+       MSG_DEBUG("before to start INSERT_PARAM");
+       INSERT_PARAM;
+       pObject->pParam = param;
+       param->parameter = VMSG_PARAM_ENCODING;
+       param->paramValue = VMSG_ENC_PARAM_BASE64;
+
+       // Add VCard tree for recipient address information.
+       for(int i = 0; i < pMsg->nAddressCnt; ++i)
+       {
+               pCard = (VTree*)calloc(1, sizeof(VTree));
+               if ( !pCard )
+                       goto __CATCH_FAIL__;
+
+               pCard->treeType = VCARD;
+               pCard->pTop = NULL;
+               pCard->pCur = NULL;
+               pCard->pNext = NULL;
+               pCurrent->pNext = pCard;
+               pCurrent = pCard;
+
+               INSERT_VCARD_OBJ;
+               pObject->property = VCARD_TYPE_TEL;
+               pObject->pszValue       [0] = strdup(pMsg->addressList[i].addressVal);
+               pObject->valueCount = 1;
+       }
+       MSG_DEBUG("before to start vmsg_encode");
+       encoded_data = vmsg_encode(pMessage);
+
+       vmsg_free_vtree_memory(pMessage);
+       MSG_END();
+       return encoded_data;
+
+__CATCH_FAIL__ :
+       vmsg_free_vtree_memory( pMessage );
+
+       return NULL;
+}
+
+
+char* _convert_tm_to_vdata_str(const struct tm * tm)
+{
+       char str[17] = {0, };
+
+       snprintf(str, 17, "%04d%02d%02dT%02d%02d%02dZ",
+               tm->tm_year + 1900,
+               tm->tm_mon +1,
+               tm->tm_mday,
+               tm->tm_hour,
+               tm->tm_min,
+               tm->tm_sec);
+
+       return strdup(str);
+}
+
+
+bool _convert_vdata_str_to_tm(const char* szText, struct tm * tm)
+{
+
+   if (szText == NULL) return false;
+   if (strlen(szText) < 15) return false;
+   if (szText[8] != 'T') return false;
+
+   char szBuff[8]={0};
+   memset(tm, 0, sizeof(struct tm));
+
+   // year, month, day
+   memcpy(szBuff, &(szText[0]), 4);
+   szBuff[4] = '\0';
+   tm->tm_year = atol(szBuff) - 1900;
+   if ((tm->tm_year > 137) || (tm->tm_year < 0))
+      tm->tm_year = 0;
+
+   memcpy(szBuff, &(szText[4]), 2);
+   szBuff[2] = '\0';
+   tm->tm_mon = atol(szBuff)-1;
+   if ((tm->tm_mon > 11) || (tm->tm_mon < 0))
+      tm->tm_mon = 11;
+
+   memcpy(szBuff, &(szText[6]), 2);
+   szBuff[2] = '\0';
+   tm->tm_mday = atol(szBuff);
+   if ((tm->tm_mday > 31) || (tm->tm_mday < 1))
+      tm->tm_mday = 31;
+
+   // hour, minute, second
+   memcpy(szBuff, &(szText[9]), 2);
+   szBuff[2] = '\0';
+   tm->tm_hour = atol(szBuff);
+   if ((tm->tm_hour > 23) || (tm->tm_hour < 0))
+      tm->tm_hour = 23;
+
+   memcpy(szBuff, &(szText[11]), 2);
+   szBuff[2] = '\0';
+   tm->tm_min = atol(szBuff);
+   if ((tm->tm_min > 59) || (tm->tm_min < 0))
+      tm->tm_min = 59;
+
+   memcpy(szBuff, &(szText[13]), 2);
+   szBuff[2] = '\0';
+   tm->tm_sec = atol(szBuff);
+   if ((tm->tm_sec > 59) || (tm->tm_sec < 0))
+      tm->tm_sec = 59;
+
+   return true;
+}
+
+char *MsgVMessageEncode(MSG_MESSAGE_INFO_S *pMsg)
+{
+       MSG_BEGIN();
+
+       MsgDbHandler dbHandle;
+       VObject *pObject = NULL;
+       VParam *param = NULL;
+       VTree *pBody = NULL;
+       VTree *pCard = NULL;
+       VTree *pCurrent= NULL;
+       VTree *pMessage = NULL;
+
+       struct tm       display_time;
+       char *encoded_data = NULL;
+       int err = MSG_SUCCESS;
+
+       if (pMessage == NULL) {
+               pMessage = (VTree *)malloc(sizeof(VTree));
+               if (!pMessage) {
+                       return NULL;
+               }
+               pMessage->treeType = VMESSAGE;
+               pMessage->pTop = NULL;
+               pMessage->pCur = NULL;
+               pMessage->pNext = NULL;
+
+       }
+               pCurrent = pMessage;
+
+       //Insert VObject (X-MESSAGE-TYPE) to VMessage tree
+       INSERT_VMSG_OBJ;
+
+       pObject->property = VMSG_TYPE_MSGTYPE;
+
+       if(pMsg->msgType.subType == MSG_NORMAL_SMS)
+               pObject->pszValue[0] = strdup("SMS");
+#if 0
+       else if(pMsg->msgType.mainType == MSG_MMS_TYPE && pMsg->msgType.subType == MSG_NOTIFICATIONIND_MMS)
+               pObject->pszValue[0] = strdup("MMS NOTIFICATION");
+#endif
+
+       else if(pMsg->msgType.mainType == MSG_MMS_TYPE && (pMsg->msgType.subType == MSG_SENDREQ_MMS || pMsg->msgType.subType == MSG_SENDCONF_MMS))
+               pObject->pszValue[0] = strdup("MMS SEND");
+
+       else if(pMsg->msgType.mainType == MSG_MMS_TYPE && (pMsg->msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || pMsg->msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS))
+               pObject->pszValue[0] = strdup("MMS RETRIEVED");
+
+       else
+               goto __CATCH_FAIL__;
+
+       pObject->valueCount = 1;
+
+
+       //Insert VObject (X-IRMC-BOX) to VMessate tree
+       INSERT_VMSG_OBJ;
+
+       pObject->property = VMSG_TYPE_MSGBOX;
+
+       switch(pMsg->folderId)
+       {
+               case MSG_INBOX_ID:
+                       pObject->pszValue[0] = strdup("INBOX");
+                       break;
+               case MSG_OUTBOX_ID:
+                       pObject->pszValue[0] = strdup("OUTBOX");
+                       break;
+               case MSG_SENTBOX_ID:
+                       pObject->pszValue[0] = strdup("SENTBOX");
+                       break;
+               case MSG_DRAFT_ID:
+                       pObject->pszValue[0] = strdup("DRAFTBOX");
+                       break;
+               default:
+                       // Discard User Defined or Spam folder's messages.
+                       goto __CATCH_FAIL__;
+       }
+       pObject->valueCount = 1;
+
+
+       //Insert VObject (X-SS-DT) to VMessage tree
+       INSERT_VMSG_OBJ;
+
+       pObject->property = VMSG_TYPE_DATE;
+       tzset();
+       localtime_r(&(pMsg->displayTime), &display_time);
+       pObject->pszValue[0] = _convert_tm_to_vdata_str(&display_time);
+       pObject->valueCount = 1;
+
+
+       //Insert Vobject read status to VMessage tree
+       INSERT_VMSG_OBJ;
+
+       pObject->property = VMSG_TYPE_STATUS;
+
+       if(pMsg->bRead)
+               pObject->pszValue[0] = strdup("READ");
+       else
+               pObject->pszValue[0] = strdup("UNREAD");
+
+       pObject->valueCount = 1;
+
+
+       //Insert VBody  tree for message body;
+       pBody = (VTree*)calloc(1, sizeof(VTree));
+       if ( !pBody )
+               goto __CATCH_FAIL__;
+       pBody->treeType = VBODY;
+       pBody->pTop = NULL;
+       pBody->pCur = NULL;
+       pBody->pNext = NULL;
+       pCurrent->pNext = pBody;
+       pCurrent = pBody;
+
+if(strlen(pMsg->subject) > 0)
+{
+       //Insert Subject object
+       INSERT_VBODY_OBJ;
+       pObject->property = VMSG_TYPE_SUBJECT;
+       pObject->pszValue[0] = strdup(pMsg->subject);
+       pObject->valueCount = 1;
+}
+       //Insert VBody object
+       INSERT_VBODY_OBJ;
+       pObject->property = VMSG_TYPE_BODY;
+
+       if(pMsg->msgType.mainType == MSG_SMS_TYPE)
+       {
+               if(pMsg->msgType.subType == MSG_NORMAL_SMS)
+               {
+                       if (pMsg->bTextSms == false)
+                       {
+                               char* pFileData = NULL;
+                               unique_ptr<char*, void(*)(char**)> buf(&pFileData, unique_ptr_deleter);
+
+                               int             fileSize = 0;
+                               char*   msgText = NULL;
+
+                               if (MsgOpenAndReadFile(pMsg->msgData, &pFileData, &fileSize) == false)
+                                       goto __CATCH_FAIL__;
+
+                               msgText = (char *)calloc(1, fileSize);
+                               if (pFileData && msgText)
+                                       memcpy(msgText, pFileData, fileSize);
+                               pObject->numOfBiData = fileSize;
+                               pObject->pszValue[0] = msgText;
+                       }
+                       else
+                       {
+                               pObject->numOfBiData = pMsg->dataSize;
+                               pObject->pszValue[0] = strdup(pMsg->msgText);
+                       }
+                       pObject->valueCount = 1;
+               }
+               else
+                       goto __CATCH_FAIL__;
+       }
+
+       else if(pMsg->msgType.mainType == MSG_MMS_TYPE)
+       {
+               //Insert VBody for mms raw data;
+               char* pFileData = NULL;
+
+               int             fileSize = 0;
+               char*   msgText = NULL;
+               char            filePath[MSG_FILEPATH_LEN_MAX] = {0, };
+
+               if(pMsg->msgType.subType == MSG_NOTIFICATIONIND_MMS)
+                       pFileData = MsgOpenAndReadMmsFile(pMsg->msgData, 0, -1, &fileSize);
+
+               else
+               {
+                       err = MsgStoGetMmsRawFilePath(&dbHandle, pMsg->msgId, filePath);
+
+                       if (err != MSG_SUCCESS)
+                               goto __CATCH_FAIL__;
+
+                       pFileData = MsgOpenAndReadMmsFile(filePath, 0, -1, &fileSize);
+               }
+               MSG_DEBUG("FILE SIZE IS %d", fileSize);
+               msgText = (char *)calloc(1, fileSize);
+               if(pFileData && msgText)
+                       memcpy(msgText, pFileData, fileSize);
+               pObject->numOfBiData = fileSize;
+               pObject->pszValue[0] = msgText;
+               pObject->valueCount = 1;
+
+               if (pFileData) {
+                       free(pFileData);
+                       pFileData = NULL;
+               }
+       }
+
+       // Insert parameter for base64 encoding
+       MSG_DEBUG("before to start INSERT_PARAM");
+       INSERT_PARAM;
+       pObject->pParam = param;
+       param->parameter = VMSG_PARAM_ENCODING;
+       param->paramValue = VMSG_ENC_PARAM_BASE64;
+
+       // Add VCard tree for recipient address information.
+       for(int i = 0; i < pMsg->nAddressCnt; ++i)
+       {
+               pCard = (VTree*)calloc(1, sizeof(VTree));
+               if ( !pCard )
+                       goto __CATCH_FAIL__;
+
+               pCard->treeType = VCARD;
+               pCard->pTop = NULL;
+               pCard->pCur = NULL;
+               pCard->pNext = NULL;
+               pCurrent->pNext = pCard;
+               pCurrent = pCard;
+
+               INSERT_VCARD_OBJ;
+               pObject->property = VCARD_TYPE_TEL;
+               pObject->pszValue       [0] = strdup(pMsg->addressList[i].addressVal);
+               pObject->valueCount = 1;
+       }
+       MSG_DEBUG("before to start vmsg_encode");
+       encoded_data = vmsg_encode(pMessage);
+
+       vmsg_free_vtree_memory(pMessage);
+       MSG_END();
+       return encoded_data;
+
+__CATCH_FAIL__ :
+       vmsg_free_vtree_memory( pMessage );
+
+       return NULL;
+}
diff --git a/vobject-engine/CMakeLists.txt b/vobject-engine/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..08cec7b
--- /dev/null
@@ -0,0 +1,40 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT(msg-server CXX)
+
+SET(CMAKE_SKIP_BUILD_RPATH TRUE)
+
+IF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+       SET(CMAKE_BUILD_TYPE "Debug")
+ENDIF("${CMAKE_BUILD_TYPE}" STREQUAL "")
+MESSAGE("Build type: ${CMAKE_BUILD_TYPE}")
+
+#SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
+SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
+
+SET(VOBJECT-SRCS
+               ${CMAKE_SOURCE_DIR}/vobject-engine/VCard.c
+               ${CMAKE_SOURCE_DIR}/vobject-engine/VCardCalUtil.c
+               ${CMAKE_SOURCE_DIR}/vobject-engine/VMessage.c
+)
+
+INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/include)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(vobject_pkgs REQUIRED dlog glib-2.0)
+
+SET(EXTRA_CFLAGS "")
+FOREACH(flag ${vobject_pkgs_CFLAGS})
+        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+#SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS}")
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+ADD_LIBRARY(${VOBJECT-LIB} SHARED ${VOBJECT-SRCS})
+TARGET_LINK_LIBRARIES(${VOBJECT-LIB} ${vobject_pkgs_LDFLAGS})
+
+INSTALL(TARGETS ${VOBJECT-LIB} DESTINATION lib)
diff --git a/vobject-engine/VCard.c b/vobject-engine/VCard.c
new file mode 100755 (executable)
index 0000000..9835886
--- /dev/null
@@ -0,0 +1,1547 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include "VTypes.h"
+#include "VCard.h"
+#include "vobject.h"
+
+#define MAX_TYPE_NAME_LEN 50
+#define MAX_PARAM_NAME_LEN 50
+#define CHECK_START 1
+#define CHECK_END 2
+
+#define VFREE(obj) if(obj != NULL) { /*VDATA_TRACE("%p",obj);*/ free(obj); \
+       obj = NULL; \
+}
+
+#define TRIM(obj) if(obj != NULL) {\
+       _VRLSpace(obj);\
+       _VRTSpace(obj);\
+}
+
+#define UPPER(obj,start,end) if(obj != NULL) {\
+       for(start = 0; start < end; start++)\
+               obj[start] = toupper(obj[start]);\
+}
+
+#define GO_NEXT_CHAR(current, rowData, addedCnt) {\
+       current = *rowData;\
+       rowData++;\
+       (*addedCnt)++;\
+}
+
+#define SET_PARAM_VALUE(PARAM, SZVALUE, LIST, LISTCNT, PARAMOBJ, PTYPE, ENC) {\
+       PARAM = 0;\
+       PARAM |= __VCardGetValue(SZVALUE, LIST, LISTCNT);\
+       if ( PARAM != UNKNOWN_NAME ) {\
+               PARAMOBJ->parameter = PTYPE;\
+               if(PTYPE == VCARD_PARAM_ENCODING)\
+                       ENC = PARAM;\
+               break;\
+       }\
+}
+
+#define LENGTH_TYPE_LIST(obj, len) for(len =0; obj[len] != NULL; len++);
+
+extern char* _VUnfoldingNoSpecNew( char *string );
+
+/** GLOBAL VARIABLE DECLARATION AND INITIALIZATION */
+/** vCard Types. */
+char* pszCardTypeList[] =
+{
+       "ADR",                  /* Delivery Address -> address*/
+       "AGENT",                        /* Agent -> assistant name, assistant number*/
+       "BDAY",                 /* Birthday -> birthday */
+       "BEGIN",                        /* BEGIN VCARD DELIMITER*/
+       "CATEGORIES",   /* Categories is a multivalued attribute */
+       "CLASS",                        /* */
+       "EMAIL",                        /* Email -> email */
+       "END",                  /* END VCARD DELIMITER*/
+       "FN",                   /* Formatted Name -> display_name */
+       "GEO",                  /* Geographic Positioning*/
+       "KEY",                  /* Public Key*/
+       "LABEL",                        /* Label Address -> address*/
+       "LOGO",                 /* Logo*/
+       "MAILER",               /* Email Program (Optional)*/
+       "N",                            /* Name -> name */
+       "NAME",                 /* Name -> name */
+       "NICKNAME",             /* Nickname -> nickname */
+       "NOTE",                 /* Note -> note */
+       "ORG",                  /* Organization Name or Organizational unit -> department*/
+       "PHOTO",                        /* Photograph -> caller id*/
+       "PRODID",               /* */
+       "PROFILE",              /* */
+       "REV",                  /* Last Revision(combination of calendar date & time)*/
+       "ROLE",                 /* Role or occupation */
+       "SORT-STRING",  /* */
+       "SOUND",                        /* Sound*/
+       "SOURCE",               /* */
+       "TEL",                  /* Telephone -> phone number */
+       "TITLE",                        /* Job Title -> job title */
+       "TZ",                   /* Time Zone*/
+       "UID",                  /* Unique Identifier*/
+       "URL",                  /* URL -> web address */
+       "VERSION",              /* Version*/
+       "X-IRMC-LUID",  /* */
+       NULL
+};
+
+/** Parameter */
+char* pszCardParamList[] =
+{
+       "CHARSET",
+       "CONTEXT",
+       "ENCODING",
+       "LANGUAGE",
+       "TYPE",
+       "VALUE"
+};
+
+/** Encoding value */
+ValueObj pEncList[] =
+{
+       {"B",                   0x00000001},
+       {"BASE64",      0x00000002},
+       {"QUOTED-PRINTABLE", 0x00000004},
+       {"7BIT",                0x00000008},
+       {"8BIT",                0x00000010}
+};
+
+/** Character set value */
+ValueObj pCharsetList[] =
+{
+       {"UTF-8",                       0x00000001},
+       {"UTF-16",              0x00000002},
+       {"ISO-8859-1",  0x00000004}
+};
+
+/** Value value */
+ValueObj pValueList[] =
+{
+       {"BINARY",                      0x00000001},
+       {"BOOLEAN",                     0x00000002},
+       {"DATE",                                0x00000004},
+       {"DATE-TIME",           0x00000008},
+       {"FLOAT",                               0x00000010},
+       {"INTEGER",                     0x00000020},
+       {"PHONE-NUMBER",        0x00000040},
+       {"TEXT",                                0x00000080},
+       {"TIME",                                0x00000100},
+       {"URI",                                 0x00000200},
+       {"URL",                                 0x00000400},
+       {"UTC-OFFSET",          0x00000800},
+       {"VCARD",                               0x00001000}
+};
+
+/** Type value */
+ValueObj pTypeList[] =
+{
+       {"AIFF",                0x00000001},
+       {"BBS",                 0x00000002},
+       {"CAR",                 0x00000004},
+       {"CELL",                0x00000008},
+       {"DOM",                 0x00000010},
+       {"WORK",                0x00000020},
+       {"FAX",                 0x00000040},
+       {"GIF",                 0x00000080},
+       {"HOME",                0x00000100},
+       {"INTL",                0x00000200},
+       {"INTERNET",    0x00000400},
+       {"ISDN",                0x00000800},
+       {"JPEG",                0x00001000},
+       {"MOBILE",      0x00002000},
+       {"MODEM",               0x00004000},
+       {"MSG",                 0x00008000},
+       {"PAGER",               0x00010000},
+       {"PARCEL",      0x00020000},
+       {"PCM",                 0x00040000},
+       {"PCS",                 0x00080000},
+       {"PNG",                 0x00100000},
+       {"POSTAL",      0x00200000},
+       {"PREF",                0x00400000},
+       {"VIDEO",               0x00800000},
+       {"VOICE",               0x01000000},
+       {"WAVE",                0x02000000},
+       {"WBMP",                0x04000000},
+       {"ETC",                 0x08000000},
+       {"X400",                0x10000000}
+};
+
+/** FUNCTION DECLARATION       */
+int __VCardGetName(char*, char**, int);
+int __VCardGetValue(char*, const ValueObj*, int);
+int __VCardGetTypeName(char*, int*, int*);
+int __VCardGetParamName(char*, int*, int*);
+int __VIsVcardFile(char*, int);
+char* __VCardGetParamVal(char*,int*, int*);
+char* __VCardGetTypeVal(char*, int*, int*, int, VObject*);
+char* __VCardTypeEncode(VObject*, char*);
+char* __VCardParamEncode(VObject*, int*);
+
+#ifdef VDATA_GROUPNAME_SUPPORTED
+char*  gszGroupName;
+#endif // VDATA_GROUPNAME_SUPPORTED
+
+
+/**
+ * __VCardGetName() compares the string and vCard type, parameter name.
+ *
+ * @param      szString        Name which will compare
+ * @param              pszList[]               Name list of vCard type and param
+ * @param              size                            Number of total element of list
+ *
+ * @return     index           The index in the list
+ */
+int
+__VCardGetName(char* szString, char* pszList[], int size)
+{
+       VDATA_TRACE_BEGINE
+       int high, low, i, diff;
+
+       low = 0;
+       high = size - 1;
+
+       for(; high >= low; diff<0 ? (low = i+1):(high = i-1)) {
+               i = ( low + high ) / 2;
+               if((diff = strcmp( pszList[i], szString )) == 0) /* success: found it */
+                       return i;
+       }
+       VDATA_TRACE_END
+       return UNKNOWN_NAME;
+}
+
+/**
+ * __VCardGetValue() compares the string and vCard type, parameter value.
+ *
+ * @param      szString        Value which will compare
+ * @param              list[]          Value list of vCard param
+ * @param              size                    Number of total element of list
+ *
+ * @return     flag      The value's flag.
+ */
+int
+__VCardGetValue( char* szString, const ValueObj list[], int size)
+{
+       VDATA_TRACE_BEGINE
+       int i = 0, diff = -1;
+       char* szTemp = szString;
+
+       SysRequireEx(szString, UNKNOWN_NAME);
+       SysRequireEx(size > 0, UNKNOWN_NAME);
+
+       UPPER(szTemp,i,strlen(szTemp));
+
+       for(i = 0; i < size-1; i++)
+       {
+               VDATA_TRACE(" i : %d",i);
+               VDATA_TRACE(" for loop %d < %d, list[%d] : %p, list[%d].szName : %p",i,size,i,list[i],i,list[i].szName);
+               VDATA_TRACE(" i : %d",i);
+               if(list[i].szName != NULL)
+               {
+                       VDATA_TRACE(" list[%d].szName != NULL",i);
+                       VDATA_TRACE(" before strcmp %s %s",list[i].szName,szTemp);
+                       VDATA_TRACE(" before strcmp %d",strcmp(list[i].szName, szTemp));
+                       if((diff = strcmp(list[i].szName, szTemp)) == 0) /* success: found it */
+                       {
+                               VDATA_TRACE(" return %d",list[i].flag);
+                               VDATA_TRACE_END
+                               return list[i].flag;
+                       }
+                       VDATA_TRACE(" after strcmp %s %s",list[i].szName,szTemp);
+               }
+       }
+       VDATA_TRACE(" return UNKNOWN_NAME");
+       VDATA_TRACE_END
+       return UNKNOWN_NAME;
+}
+
+/**
+ * __VCardGetTypeName() fine the type name and returns the index number
+ *
+ * @param              pVCardRaw       The raw data
+ * @param              pStatus         Decoder status
+ * @param              pDLen           retrived length
+ *
+ * @return     res                     The index in type list
+ */
+int
+__VCardGetTypeName(char* pVCardRaw, int* pStatus, int* pDLen)
+{
+       VDATA_TRACE_BEGINE
+       int     i, index, res;
+       char    c;
+       char    name[MAX_TYPE_NAME_LEN+1]={0,};
+
+#ifdef VDATA_GROUPNAME_SUPPORTED
+       char*   szGroupName = NULL;
+#endif // VDATA_GROUPNAME_SUPPORTED
+
+       SysRequireEx(pVCardRaw, UNKNOWN_NAME);
+
+       i = index = 0;
+       res = UNKNOWN_NAME;
+
+       while(true) {
+
+               GO_NEXT_CHAR(c, pVCardRaw, pDLen);
+
+               /**
+                * TYPE NAME's length is must be less than MAX_TYPE_NAME_LEN.
+                * If TYPE NAME's value is over MAX_TYPE_NAME_LEN, return UNKNOWN_NAME.
+                * And then Decoding Step shoud not be changed.
+                */
+               if(index >= MAX_TYPE_NAME_LEN) {
+                       *pStatus = VCARD_TYPE_NAME_STATUS;
+                       res = UNKNOWN_NAME;
+                       break;
+               }
+
+               /**
+                * There is a delimeter between TYPE NAME and next element(=Param, or Type Value).
+                * If VTYPE_TOKEN_SEMICOLON or VTYPE_TOKEN_COLON is faced with,
+                * find TYPE NAME's value in pszCardTypeList, and then return searched result.
+                */
+               if ((c == VTYPE_TOKEN_SEMICOLON ) || ( c == VTYPE_TOKEN_COLON)) {
+                       name[index] = 0x00;
+                       TRIM(name);
+                       UPPER(name,i,index);
+                       res = __VCardGetName( name, (char**)pszCardTypeList, VCARD_TYPE_NUM );
+                       break;
+               }
+               /** current version not support grouping vcard type */
+               else if ( c == VTYPE_TOKEN_DOT ) {
+#ifdef VDATA_GROUPNAME_SUPPORTED
+                       name[index] = '\0';
+                       szGroupName = ( char* ) calloc(1,  index+1 );
+                       if(szGroupName != NULL){
+                               strncpy( szGroupName, name, index );
+                               gszGroupName = szGroupName;
+                       }
+                       index = 0;
+#endif
+               }
+               /**
+                * There is no new line in TYPE NAME.
+                * If new line character is faced with, return UNKNOWN_NAME;
+                */
+               else if ( ( c == '\r' ) || ( c == '\n' ) )
+               {
+                       (*pDLen)++;
+                       *pStatus = VCARD_TYPE_NAME_STATUS;
+                       res = UNKNOWN_NAME;
+                       return res;
+               }
+               else if(_VIsSpace(c));
+               else    name[index++] = c;
+       }
+
+       /**
+        *      Set Next Step.
+        *
+        */
+       if ( c == VTYPE_TOKEN_SEMICOLON )
+               /**
+                * This case next token is parameter. So set VCARD_PARAM_NAME_STATUS step.
+                */
+               *pStatus = VCARD_PARAM_NAME_STATUS;
+       else {
+               if(res != UNKNOWN_NAME)
+                       /**
+                        * This case next string is value. So set VCARD_TYPE_VALUE_STATUS step.
+                        */
+                       *pStatus = VCARD_TYPE_VALUE_STATUS;
+               else
+                       /**
+                        * In current step, TYPE NAME is invalid. So Try to get TYPE NAME again from next position.
+                        */
+                       *pStatus = VCARD_TYPE_NAME_STATUS;
+       }
+       VDATA_TRACE_END
+       return res;
+}
+
+/**
+ * __VCardGetParamName() fine the param name and returns the index number
+ *
+ * @param              pVCardRaw       The raw data
+ * @param              pStatus         Decoder status
+ * @param              pDLen           retrived length
+ *
+ * @return     res                     The index in type list
+ */
+int
+__VCardGetParamName( char* pVCardRaw, int* pStatus, int* pDLen )
+{
+       VDATA_TRACE_BEGINE
+       int     i, index, res;
+
+       char    c;
+       char    name[MAX_PARAM_NAME_LEN+1]={0,};
+       char* pTemp = pVCardRaw;
+
+       SysRequireEx( pVCardRaw, UNKNOWN_NAME );
+
+       i = index = 0;
+       res = UNKNOWN_NAME;
+
+       while ( true )
+       {
+               GO_NEXT_CHAR(c, pVCardRaw, pDLen);
+
+               /**
+                * PARAM NAME's length is must be less than MAX_PARAM_NAME_LEN.
+                * If PARAM NAME's value is over MAX_PARAM_NAME_LEN, return UNKNOWN_NAME.
+                * And then Decoding Step shoud not be changed.
+                */
+               if(index >= MAX_PARAM_NAME_LEN) {
+                       *pStatus = VCARD_TYPE_NAME_STATUS;
+                       res = UNKNOWN_NAME;
+                       break;
+               }
+
+               /**
+                * There is a delimeter between PARAM NAME and next element(=Param, or Param Value).
+                * If VTYPE_TOKEN_EQUAL is faced with,
+                * find PARAM NAME's value in pszCardParamList, and then return searched result.
+                */
+               if(c == VTYPE_TOKEN_EQUAL) {
+                       name[index] = '\0';
+                       TRIM(name);
+                       UPPER(name, i, index);
+                       res = __VCardGetName( name, ( char** )pszCardParamList, VCARD_PARAM_NUM );
+                       if(res==UNKNOWN_NAME){
+                               (*pDLen) = 0;
+                       }
+                       *pStatus = VCARD_PARAM_VALUE_STATUS;
+                       break;
+               }
+               /**
+                * This case, There is no parameter type. Only Parameter Value.
+                * In VCARD_PARAM_NAME_STATUS status, VTYPE_TOKEN_COLON means that anything parameter is no more.
+                * so set next step to VCARD_PARAM_VALUE_STATUS.
+                *
+                * Ex) TEL;WORK:+12341234
+                *        ------ ":" next is TEL TYPE's value.
+                *
+                * VCARD_PARAM_NAME_STATUS(current) -> VCARD_PARAM_VALUE_STATUS
+                * -> VCARD_TYPE_VALUE_STATUS -> MOVE TO NEXT TYPE
+                */
+               else if(c == VTYPE_TOKEN_COLON) {
+                       *pStatus = VCARD_PARAM_VALUE_STATUS;
+                       pVCardRaw = pTemp;
+                       (*pDLen) = 0;
+                       res = UNKNOWN_NAME;
+                       break;
+               }
+               /**
+                * This case, There is no parameter type. Only Parameter Value.
+                * In VCARD_PARAM_NAME_STATUS status, VTYPE_TOKEN_SEMICOLON means that there is a next parameter.
+                * so set next step to VCARD_PARAM_NAME_STATUS.
+                *
+                * Ex) TEL;WORK;PREF:+12341234
+                *        ------ ":" next is TEL TYPE's value.
+                *
+                * VCARD_PARAM_NAME_STATUS(current) -> VCARD_PARAM_NAME_STATUS
+                * -> VCARD_PARAM_VALUE_STATUS -> VCARD_TYPE_VALUE_STATUS -> MOVE TO NEXT TYPE
+                */
+               else if(c == VTYPE_TOKEN_SEMICOLON) {
+                       *pStatus = VCARD_PARAM_NAME_STATUS;
+                       pVCardRaw = pTemp;
+                       (*pDLen) = 0;
+                       res = UNKNOWN_NAME;
+                       break;
+               }
+               else if((c == '\r') || (c == '\n') || (_VIsSpace(c)));
+               else
+                       name[index++] = c;
+       }
+       VDATA_TRACE_END
+       return res;
+}
+
+bool
+__VCardFreeVTreeMemory(VTree * pTree)
+{
+       VDATA_TRACE_BEGINE
+       VObject*                pCurObj = NULL;
+       VObject*                pNextObj = NULL;
+
+       VTree*                  pCurTree = NULL;
+       VTree*                  pNextTree = NULL;
+
+       VParam* pCurParam = NULL;
+       VParam* pNextParam = NULL;
+
+       int count = 0;
+       int i = 0;
+
+       SysRequireEx( pTree->treeType == VCARD, false );
+       SysRequireEx( pTree != NULL, false );
+       VDATA_TRACE("vcard_free_vtree_memory() entered.");
+
+       if (pTree->treeType != VCARD)
+       {
+               VDATA_TRACE_END
+               return true;
+       }
+
+       pCurTree = pTree;
+
+       while(pCurTree)
+       {
+               pNextTree = pCurTree->pNext;
+               pCurObj = pCurTree->pTop;
+
+               while ( pCurObj )
+               {
+
+                       pNextObj = pCurObj->pSibling;
+                       count = pCurObj->valueCount;
+
+                       for ( i = 0; i < count; i++ ) {
+                               VFREE( pCurObj->pszValue[i]);
+                       }
+
+#ifdef VDATA_GROUPNAME_SUPPORTED
+                       if ( pCurObj->pszGroupName )
+                               VFREE( pCurObj->pszGroupName );
+#endif
+
+                       if ( pCurObj->pParam )
+                       {
+
+                               pCurParam = pCurObj->pParam;
+
+                               while(pCurParam != NULL)
+                               {
+                                       pNextParam = pCurParam->pNext;
+                                       VDATA_TRACE("pNEXT ==> %p", pCurParam->pNext);
+                                       VDATA_TRACE("pPARAM ==> %p", pCurParam->parameter);
+                                       VDATA_TRACE("pVALUE ==> %p", pCurParam->paramValue);
+                                       VDATA_TRACE("pCurParam : %p", pCurParam);
+                                       VDATA_TRACE("pCurParam->parameter : %d", pCurParam->parameter);
+                                       VDATA_TRACE("pCurParam->paramValue : %d", pCurParam->paramValue);
+                                       if(pNextParam != NULL) {
+                                               VDATA_TRACE("pNextParam : %p", pNextParam);
+                                               VDATA_TRACE("pNextParam->parameter : %d", pNextParam->parameter);
+                                               VDATA_TRACE("pNextParam->paramValue : %d", pNextParam->paramValue);
+                                       }
+                                       VFREE(pCurParam);
+                                       pCurParam = pNextParam;
+                               }
+                       }
+
+                       VFREE( pCurObj );
+                       pCurObj = pNextObj;
+               }
+
+               VFREE( pCurTree );
+               pCurTree = pNextTree;
+       }
+
+       VDATA_TRACE("exit vcard_free_vtree_memory");
+       VDATA_TRACE_END
+       return true;
+}
+
+/**
+ * __VCardGetParamVal() fine the param value and returns value.
+ *
+ * @param              pVCardRaw       The raw data
+ * @param              pStatus         Decoder status
+ * @param              pDLen           retrived length
+ *
+ * @return     buffer          The result value
+ */
+char*
+__VCardGetParamVal( char* pVCardRaw, int* pStatus, int* pDLen )
+{
+       VDATA_TRACE_BEGINE
+       int len = 0;
+       char    c;
+       char* pBuf = NULL;
+       char* pTemp = pVCardRaw;
+
+       SysRequireEx( pVCardRaw, NULL );
+
+       while(true) {
+               GO_NEXT_CHAR(c, pVCardRaw, pDLen);
+               len++;
+               switch(c) {
+                       case VTYPE_TOKEN_SEMICOLON :
+                               *pStatus = VCARD_PARAM_NAME_STATUS;
+                               break;
+                       case VTYPE_TOKEN_COLON :
+                               *pStatus = VCARD_TYPE_VALUE_STATUS;
+                               break;
+                       case VTYPE_TOKEN_COMMA :
+                               *pStatus = VCARD_PARAM_VALUE_STATUS;
+                               break;
+               }
+               if( c == VTYPE_TOKEN_SEMICOLON
+                               || c == VTYPE_TOKEN_COLON
+                               || c == VTYPE_TOKEN_COMMA
+                               || c == 0x00)
+                       break;
+       }
+
+       //if (len < 1)
+               //return NULL;
+
+       pBuf = (char *)calloc(1, len);
+       if(pBuf  == NULL)
+               return NULL;
+
+       memset(pBuf, 0x00, len);
+       memcpy(pBuf, pTemp, len-1);
+       TRIM(pBuf);
+       VDATA_TRACE_END
+       return pBuf;
+}
+
+
+/**
+ * __VCardGetTypeVal() fine the type value and returns value.
+ *
+ * @param      pVCardRaw       The raw data
+ * @param              status                  Decoder status
+ * @return     buffer          The result value
+ */
+char*
+__VCardGetTypeVal( char* pVCardRaw, int* pStatus, int* pDLen, int enc, VObject* pType)
+{
+       VDATA_TRACE_BEGINE
+       int num = 0;
+       int len = 0;
+       int bufferCount = 0;
+
+       bool bEscape = false;
+
+       char    c, c1, c2;
+       char* pBuf = NULL;
+       char* pTemp = pVCardRaw;
+       char* pTmpBuf = NULL;
+       int Status = 0;
+       int Len = 0;
+
+       SysRequireEx( pVCardRaw, NULL );
+
+       while(true)
+       {
+               GO_NEXT_CHAR(c, pVCardRaw, pDLen);
+
+               if( c == 0x00) break;
+
+               len++;
+
+               /** This case means that there are more type's value. */
+               if ( c == VTYPE_TOKEN_SEMICOLON && bEscape == false ) {
+
+                       if((pBuf = (char *)calloc(1, len)) == NULL) return NULL;
+
+                       memset(pBuf, 0x00, len);
+                       memcpy(pBuf,pTemp,len-1);
+
+                       TRIM(pBuf);
+                       _VUnescape(pBuf);
+
+                       *pStatus = VCARD_TYPE_VALUE_STATUS;
+
+                       /** Base 64 Decoding */
+                       if((enc & pEncList[1].flag) || (enc & pEncList[0].flag)) {
+
+                               bufferCount = (len * 6 / 8) + 2;
+
+                               if((pTmpBuf = (char *)calloc(1, bufferCount)) == NULL) {
+                                       VFREE(pBuf);
+                                       return NULL;
+                               }
+
+                               memset(pTmpBuf, 0x00, bufferCount);
+                               num = _VB64Decode(pTmpBuf, pBuf);
+
+                               if(pType != NULL) pType->numOfBiData = num;
+
+                               VFREE(pBuf);
+                               pBuf = pTmpBuf;
+                               pTmpBuf = NULL;
+                               break;
+                       }
+
+                       /** Quoted Printable Decoding */
+                       if(enc & pEncList[2].flag) {
+
+                               int i = 0, j = 0;
+
+                               while(pBuf[i]) {
+                                       if(pBuf[i] == '\n' || pBuf[i] == '\r'){
+                                               i++;
+                                               if(pBuf[i] == '\n'|| pBuf[i] == '\r')
+                                                       i++;
+
+                                               if(pBuf[j-1] == '=') j--;
+                                       }
+                                       else
+                                               pBuf[j++] = pBuf[i++];
+                               }
+                               pBuf[j] = '\0';
+
+                               _VQPDecode(pBuf);
+                               TRIM(pBuf);
+                               break;
+                       }
+                       break;
+               }
+
+               if(c == '\\')
+                       bEscape = true;
+               else if(bEscape == true && c != VTYPE_TOKEN_SEMICOLON )
+                       bEscape = false;
+               else if((c == '\r') || (c == '\n'))
+               {
+                       c2 = *(pVCardRaw-2);
+
+                       if(c2 == '=' && (enc & pEncList[2].flag))
+                       {
+                               c1 = *pVCardRaw;
+                               if((c1 == '\r') || (c1 == '\n'))
+                               {
+                                       pVCardRaw += 1;
+                                       (*pDLen) += 1;
+                                       len++;
+                               }
+                       }
+                       else if(__VCardGetTypeName(pVCardRaw, &Status, &Len) != UNKNOWN_NAME)
+                       {
+                               --len;
+                               if((pBuf = (char *)calloc(1, len)) == NULL) return NULL;
+
+                               memset(pBuf, 0x00, len);
+                               memcpy(pBuf,pTemp,len-1);
+
+                               TRIM(pBuf);
+                               _VUnescape(pBuf);
+
+                               *pStatus = VCARD_TYPE_NAME_STATUS;
+
+                               c1 = *pVCardRaw;
+
+                               if((c1 == '\r') || (c1 == '\n')) {
+                                       pVCardRaw += 1;
+                                       (*pDLen) += 1;
+                               }
+
+                               if((enc & pEncList[1].flag) || (enc & pEncList[0].flag)) {
+
+                                       bufferCount = (len * 6 / 8) + 5;
+
+                                       if((pTmpBuf = (char *)calloc(1, bufferCount)) == NULL) {
+                                               VFREE(pBuf);
+                                               return NULL;
+                                       }
+
+                                       memset(pTmpBuf, 0x00, bufferCount);
+                                       num = _VB64Decode(pTmpBuf, pBuf);
+
+                                       if(pType != NULL)
+                                               pType->numOfBiData = num;
+
+                                       VFREE(pBuf);
+                                       pBuf = pTmpBuf;
+                                       pTmpBuf = NULL;
+                                       break;
+                               }
+
+                               if(enc & pEncList[2].flag) {
+
+                                       int i = 0, j = 0;
+
+                                       while(pBuf[i])
+                                       {
+                                               if(pBuf[i] == '\n' || pBuf[i] == '\r')
+                                               {
+                                                       i++;
+                                                       if(pBuf[i] == '\n' || pBuf[i] == '\r')
+                                                               i++;
+
+                                                       if(pBuf[j-1] == '=') j--;
+                                               }
+                                               else
+                                                       pBuf[j++] = pBuf[i++];
+                                       }
+                                       pBuf[j] = '\0';
+
+                                       _VQPDecode(pBuf);
+                                       TRIM(pBuf);
+                                       break;
+                               }
+                               break;
+                       }
+               }
+       }
+       VDATA_TRACE_END
+       return pBuf;
+}
+
+
+int
+VCardGetTypeValue( int index )
+{
+       VDATA_TRACE_BEGINE
+       VDATA_TRACE("VCardGetTypeValue() enter..\n");
+       VDATA_TRACE_END
+       return pTypeList[index].flag;
+}
+
+int
+VCardGetValValue( int index )
+{
+       VDATA_TRACE_BEGINE
+       VDATA_TRACE("VCardGetValValue() enter..\n");
+       VDATA_TRACE_END
+       return pValueList[index].flag;
+}
+
+int
+VCardGetEncValue( int index )
+{
+       VDATA_TRACE_BEGINE
+       VDATA_TRACE("VCardGetEncValue() enter..\n");
+       VDATA_TRACE_END
+       return pEncList[index].flag;
+}
+
+int
+VCardGetCharsetValue( int index )
+{
+       VDATA_TRACE_BEGINE
+       VDATA_TRACE("VCardGetCharsetValue() enter..\n");
+       VDATA_TRACE_END
+       return pCharsetList[index].flag;
+}
+
+/*
+ * vcard_decode() decode the vCard data and returns vObject struct
+ *
+ * @param       pVCardRaw            The raw data
+ * @return      vObject             The result value
+ */
+SLPAPI VTree*
+vcard_decode( char *pCardRaw )
+{
+       VDATA_TRACE_BEGINE;
+       char* szValue = NULL;
+       char* szCardBegin = NULL;
+       char* pCardRawTmp = NULL;
+       VTree* pVCard = NULL;
+       VParam* pTmpParam = NULL;
+       VObject* pTemp = NULL;
+
+       char    c;
+
+       int type, param;
+       int status = VCARD_TYPE_NAME_STATUS;
+       int done = false;
+       int valueCount = 0;
+       int len;
+       int dLen = 0;
+       int param_status = false;
+       int numberedParam = 0;
+       int enc = 0;
+       //int start_status = 0;
+       char* temp = NULL;
+
+       bool vcard_ended = false;
+
+       SysRequireEx(pCardRaw != NULL, NULL);
+       len = strlen(pCardRaw);
+       VDATA_TRACE("length of pCardRaw = %d", len);
+
+       pCardRaw = _VUnfoldingNoSpecNew(pCardRaw);
+       if (pCardRaw == NULL) {
+               return NULL;
+       }
+       pCardRawTmp = pCardRaw;
+       len = _VManySpace2Space( pCardRaw );
+
+       VDATA_TRACE("ret value of _VManySpace2Space = %d", len);
+
+       if(!__VIsVcardFile(pCardRaw, CHECK_START)) {
+               VFREE(pCardRawTmp);
+               VDATA_TRACE_END
+               return NULL;
+       }
+
+
+       while(true && !done)
+       {
+               c = *pCardRaw;
+
+               if((c == '\0') || done)
+                       break;
+
+               switch(status) {
+                       case VCARD_TYPE_NAME_STATUS:
+                               dLen = 0;
+                               type = __VCardGetTypeName(pCardRaw, &status, &dLen);
+                               pCardRaw += dLen;
+
+                               if(type == -1)
+                                       break;
+
+                               switch ( type )
+                               {
+                                       case VCARD_TYPE_BEGIN:
+                                               if (pVCard) {
+                                                       free(pVCard);
+                                                       pVCard = NULL;
+                                               }
+
+                                               if ( ( pVCard = ( VTree* )calloc(1,  sizeof( VTree ) ) ) == NULL ) {
+                                                       //start_status = 1;
+                                                       goto CATCH;
+                                               }
+
+                                               memset(pVCard,0x00, sizeof(VTree));
+
+                                               dLen = 0;
+                                               szCardBegin = __VCardGetTypeVal(pCardRaw, &status, &dLen, enc, NULL);
+                                               pCardRaw += dLen;
+                                               VFREE(szCardBegin);
+
+                                               pVCard->treeType = VCARD;
+                                               pVCard->pTop = NULL;
+                                               pVCard->pCur = NULL;
+                                               pVCard->pNext = NULL;
+                                               break;
+
+                                       case VCARD_TYPE_END:
+                                               enc = 0;
+                                               if(strstr(pCardRaw,"VCARD") != NULL) {
+                                                       pCardRaw += dLen;
+                                                       done = true;
+                                               vcard_ended = true;
+                                               }
+                                               else    {
+                                                       status = VCARD_TYPE_NAME_STATUS;
+                                                       pCardRaw += dLen;
+                                                       //VFREE(etemp);
+                                               }
+                                               break;
+
+                                       case UNKNOWN_NAME :
+                                               break;
+
+                                       default:
+                                               if(UNKNOWN_NAME == type || type < 0) {
+                                                       status = VCARD_TYPE_NAME_STATUS;
+                                                       break;
+                                               }
+
+                                               if ( ( pTemp = ( VObject* )calloc(1,  sizeof( VObject ) ) ) == NULL ) {
+                                                       goto CATCH;
+                                               }
+
+                                               memset( pTemp, 0, sizeof( VObject ) );
+                                               pTemp->property = type;
+
+                                               if ( pVCard->pTop == NULL ) {
+                                                       pVCard->pTop = pTemp;
+                                                       pVCard->pCur = pTemp;
+                                               }
+                                               else {
+                                                       pVCard->pCur->pSibling = pTemp;
+                                                       pVCard->pCur = pTemp;
+                                               }
+
+                                               break;
+                               }
+
+                               numberedParam = 0;
+                               param_status = false;
+                               valueCount = 0;
+
+#ifdef VDATA_GROUPNAME_SUPPORTED
+                               if ( gszGroupName != NULL )
+                                       pVCard->pCur->pszGroupName = gszGroupName;
+#endif
+                               break;
+
+                       case VCARD_PARAM_NAME_STATUS:
+                       {
+                               dLen = 0;
+                               param = __VCardGetParamName( pCardRaw, &status, &dLen );
+                               pCardRaw += dLen;
+
+                               if ( param_status != true ) {
+
+                                       if ( ( pTmpParam = ( VParam* )calloc(1,  sizeof( VParam ) ) ) == NULL )
+                                                       goto CATCH;
+
+                                       param_status = true;
+                                       pVCard->pCur->pParam = pTmpParam;
+                                       memset( pTmpParam, 0x00, sizeof( VParam ) );
+                                       VDATA_TRACE("pTmpParam : %p", pTmpParam);
+                               }
+                               else
+                               {
+                                       if ( ( pTmpParam->pNext = ( VParam* )calloc(1,  sizeof( VParam ) ) ) == NULL )
+                                                       goto CATCH;
+
+                                       pTmpParam = pTmpParam->pNext;
+                                       memset( pTmpParam, 0x00, sizeof(VParam));
+                                       VDATA_TRACE("pTmpParam : %p", pTmpParam);
+                               }
+
+                               pTmpParam->parameter = param;
+                               break;
+                       }
+                       case VCARD_PARAM_VALUE_STATUS:
+                               dLen = 0;
+                               numberedParam = 0;
+                               switch ( pTmpParam->parameter )
+                               {
+                                       case VCARD_PARAM_TYPE:
+                                               szValue = __VCardGetParamVal( pCardRaw, &status, &dLen );
+                                               numberedParam |= __VCardGetValue( szValue, pTypeList, VCARD_TYPE_PARAM_NUM );
+                                               break;
+                                       case VCARD_PARAM_VALUE:
+                                               szValue = __VCardGetParamVal( pCardRaw, &status, &dLen );
+                                               numberedParam |= __VCardGetValue( szValue, pValueList, VCARD_VALUE_PARAM_NUM );
+                                               break;
+                                       case VCARD_PARAM_ENCODING:
+                                               szValue = __VCardGetParamVal( pCardRaw, &status, &dLen );
+                                               numberedParam |= __VCardGetValue( szValue, pEncList, VCARD_ENCODE_PARAM_NUM );
+                                               enc = numberedParam;
+                                               break;
+                                       case VCARD_PARAM_CHARSET:
+                                               szValue = __VCardGetParamVal( pCardRaw, &status, &dLen );
+                                               numberedParam |= __VCardGetValue( szValue, pCharsetList, VCARD_CHARSET_PARAM_NUM );
+                                               break;
+                                       case VCARD_PARAM_CONTEXT:
+                                       case VCARD_PARAM_LANGUAGE:
+                                               // prevent 7605 08.03.13
+                                               szValue = __VCardGetParamVal( pCardRaw, &status, &dLen );
+                                               numberedParam = 0;
+                                               break;
+                                       default:
+                                               szValue = __VCardGetParamVal( pCardRaw, &status, &dLen );
+
+                                               SET_PARAM_VALUE(numberedParam, szValue, pTypeList, VCARD_TYPE_PARAM_NUM, pTmpParam, VCARD_PARAM_TYPE, enc);
+                                               SET_PARAM_VALUE(numberedParam, szValue, pValueList, VCARD_VALUE_PARAM_NUM, pTmpParam, VCARD_PARAM_VALUE, enc);
+                                               SET_PARAM_VALUE(numberedParam, szValue, pEncList, VCARD_ENCODE_PARAM_NUM, pTmpParam, VCARD_PARAM_ENCODING, enc);
+                                               SET_PARAM_VALUE(numberedParam, szValue, pCharsetList, VCARD_CHARSET_PARAM_NUM, pTmpParam, VCARD_PARAM_CHARSET, enc);
+
+                                               numberedParam = 0;
+                                               pCardRaw += dLen;
+                                               dLen = 0;
+
+                                               break;
+                               }
+
+                               VDATA_TRACE("%d, %s, %p",numberedParam, szValue, pTmpParam);
+                               pTmpParam->paramValue = numberedParam;
+                               pTmpParam->pNext = NULL;
+                               VFREE(szValue);
+                               pCardRaw += dLen;
+                               break;
+                       case VCARD_TYPE_VALUE_STATUS:
+                               dLen = 0;
+                               temp = __VCardGetTypeVal( pCardRaw, &status, &dLen, enc, pVCard->pCur);
+
+                               if(valueCount <= VDATA_VALUE_COUNT_MAX) {
+                                       pVCard->pCur->pszValue[valueCount] = temp;
+                                       valueCount++;
+                                       pVCard->pCur->valueCount = valueCount;
+                               }
+                               else
+                                       VFREE(temp);
+
+                               pCardRaw += dLen;
+                               break;
+               }
+       }
+
+       VFREE(pCardRawTmp);
+
+       if(pVCard->pTop == NULL)
+               goto CATCH;
+
+       if(!vcard_ended) {
+               goto CATCH1;
+       }
+       VDATA_TRACE_END
+       return pVCard;
+
+CATCH :
+       VFREE(pTemp);
+CATCH1 :
+       VFREE(pCardRawTmp);
+       __VCardFreeVTreeMemory(pVCard);
+       VDATA_TRACE_END
+       return NULL;
+}
+
+/*
+ * vcard_encode() compares the string and vCard type, parameter value.
+ *
+ * @param       pVCardRaw            Data which will be encoded
+ * @return      char *              Encoded result
+ */
+SLPAPI char*
+vcard_encode( VTree *pVCardRaw )
+{
+       VDATA_TRACE_BEGINE
+       char*           pVCardRes = NULL;
+       VObject *       pTmpObj =  NULL;
+       char*           pTemp = NULL;
+       int                     len;
+       int                     total = 0;
+       int             cnt = 0;
+       int             lenTypeList = 0;
+
+       LENGTH_TYPE_LIST(pszCardTypeList, lenTypeList);
+
+       SysRequireEx(pVCardRaw != NULL, NULL);
+       SysRequireEx(pVCardRaw->pTop != NULL, NULL);
+       SysRequireEx(pVCardRaw->pTop->property >= 0, NULL);
+       SysRequireEx(pVCardRaw->pTop->property < lenTypeList, NULL);
+       SysRequireEx(pVCardRaw->treeType == VCARD, NULL);
+       SysRequireEx(pVCardRaw->pTop->valueCount > 0, NULL);
+
+       //VDATA_TRACE("START %d %d", pVCardRaw->pTop->property, lenTypeList);
+
+       for(;cnt < pVCardRaw->pTop->valueCount;cnt++) {
+
+               if(pVCardRaw->pTop->pszValue[cnt] == NULL)  {
+                       VDATA_TRACE("pVCardRaw->pTop->valueCount : %d",pVCardRaw->pTop->valueCount);
+                       VDATA_TRACE("pVCardRaw->pTop->pszValue[%d] : %s", cnt, pVCardRaw->pTop->pszValue[cnt]);
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+       }
+       total += sizeof(char) * (14 + 14);
+       if ( ( pVCardRes = ( char * )calloc(1,  total ) ) == NULL )
+       {
+               VDATA_TRACE(  "vcard_encode:calloc failed\n" );
+               VDATA_TRACE_END
+               return NULL;
+       }
+
+       memcpy( pVCardRes, "BEGIN:VCARD\r\n", 14 );
+       g_strlcat( pVCardRes, "VERSION:2.1\r\n", total - strlen(pVCardRes));
+
+       pTmpObj = pVCardRaw->pTop;
+
+       while ( true )
+       {
+               if(pTmpObj == NULL)
+                       break;
+
+               if ( ( pTemp = __VCardTypeEncode( pTmpObj, pszCardTypeList[pTmpObj->property] ) ) != NULL )
+               {
+                       len = strlen( pTemp );
+                       total += len + sizeof(char) * 10;
+                       if ( ( pVCardRes = ( char* )realloc( pVCardRes, total ) ) == NULL )
+                       {
+                               VDATA_TRACE(  "vcard_encode():realloc failed\n");
+                               VFREE( pTemp );
+                               pTemp = NULL;
+                               VDATA_TRACE_END
+                               return NULL;
+                       }
+
+                       if( strncmp(pTemp,"VERSION", strlen("VERSION")) != 0)
+                               g_strlcat(pVCardRes, pTemp, total - strlen(pVCardRes));
+
+                       VDATA_TRACE("pTemp : %s", pTemp);
+
+                       VFREE( pTemp );
+                       pTemp = NULL;
+               }
+
+               if ( pTmpObj->pSibling != NULL )
+                       pTmpObj = pTmpObj->pSibling;
+               else
+                       break;
+       }
+
+       total += sizeof(char) * 12;
+       if ( ( pVCardRes = ( char * )realloc( pVCardRes, total ) ) == NULL )
+       {
+               VDATA_TRACE(  "vcard_encode:realloc failed\n");
+               VDATA_TRACE_END
+               return NULL;
+       }
+       g_strlcat( pVCardRes, "END:VCARD\r\n", total - strlen(pVCardRes));
+
+       VDATA_TRACE_END
+       return pVCardRes;
+}
+
+
+/*
+ * VIsVcardFile() verify VCard file.
+ *
+ * @param       pVCardRaw           Data which will be encoded
+ * @return      int                 result (true or false)
+ */
+int
+__VIsVcardFile(char *pCardRaw, int mode)
+{
+       int i=0;
+       bool rtnValue = true;
+       char *pszVcardBegin = "BEGIN:VCARD";
+
+       switch(mode)
+       {
+               case CHECK_START :
+                       for(i=0; i < 11; i++)
+               if(*pszVcardBegin++ != *pCardRaw++)
+                                       rtnValue = false;
+                       break;
+
+               default :
+                       rtnValue = false;
+       }
+       VDATA_TRACE_END
+       return rtnValue;
+}
+
+
+/*
+ * vCardTypeEncoder() compares the string and vCard type, parameter value.
+ *
+ * @param              typeObj                         Data which will be encoded
+ * @param              type                            Name of the type
+ * @return      char *              Encoded result
+ */
+char*
+__VCardTypeEncode( VObject *pTypeObj, char *pType )
+{
+       VDATA_TRACE_BEGINE
+       int                     len;
+       char*           pTemp = NULL;
+       char*           szTypeValue = NULL;
+       int                     i;
+       int                     enc = 0;
+       char*           pEncode = NULL;
+       char*           pRes = NULL;
+       int                     total = 0;
+       int                     biLen = 0;
+
+       len = strlen( pType );
+       biLen = pTypeObj->numOfBiData;
+
+#ifdef VDATA_GROUPNAME_SUPPORTED
+       if ( pTypeObj->pszGroupName != NULL )
+       {
+               len += strlen( pTypeObj->pszGroupName ) + 1;
+       }
+#endif // VDATA_GROUPNAME_SUPPORTED
+       if ( ( szTypeValue = ( char * )calloc(1,  total += ( len+1 ) ) ) == NULL )
+       {
+               VDATA_TRACE(  "__VCardTypeEncode():calloc failed\n");
+               VDATA_TRACE_END
+               return NULL;
+       }
+       memset( szTypeValue, '\0', ( len+1 ) );
+#ifdef VDATA_GROUPNAME_SUPPORTED
+       if ( pTypeObj->pszGroupName != NULL )
+       {
+               g_strlcat( szTypeValue, pTypeObj->pszGroupName, total - strlen(szTypeValue));
+               g_strlcat( szTypeValue, ".", total - strlen(szTypeValue));
+       }
+#endif // VDATA_GROUPNAME_SUPPORTED
+       g_strlcat( szTypeValue, pType, total - strlen(szTypeValue));
+
+       pTemp = __VCardParamEncode( pTypeObj, &enc );
+       if ( pTemp != NULL )
+       {
+               len = strlen( pTemp );
+               if ( ( szTypeValue = ( char * )realloc( szTypeValue, ( total += len ) ) ) == NULL )
+               {
+                       VDATA_TRACE(  "__VCardTypeEncode():realloc failed\n");
+                       VFREE( pTemp );
+                       pTemp = NULL
+                       VDATA_TRACE_END;
+                       return NULL;
+               }
+               g_strlcat( szTypeValue, pTemp, total - strlen(szTypeValue));
+               VFREE( pTemp );
+               pTemp = NULL;
+       }
+
+       if ( ( szTypeValue = ( char * )realloc( szTypeValue, ( total += 2 ) ) ) == NULL )
+       {
+               VDATA_TRACE_END
+               return NULL;
+       }
+
+       g_strlcat( szTypeValue, ":", total - strlen(szTypeValue));
+
+       len = 0;
+
+       if(strcmp(pType, pszCardTypeList[19]) != 0)     {
+               for ( i = 0; i < pTypeObj->valueCount; i++ ) {
+
+                       if(pTypeObj->pszValue[i] != NULL)
+                       len += strlen( pTypeObj->pszValue[i] );
+               }
+       }
+       else {
+               len += biLen;
+       }
+
+       for ( i = 0; i < pTypeObj->valueCount; i++ ) {
+
+               if ( i == 0 ) {
+                       if ( ( pEncode = ( char * )calloc(1,  len+20 ) ) == NULL ) {
+                               VFREE(szTypeValue);
+                               VDATA_TRACE_END
+                               return NULL;
+                       }
+
+                       memset( pEncode, '\0', len+20 );
+
+                       if(strcmp(pType, pszCardTypeList[19]) != 0)     {
+                               g_strlcat( pEncode, pTypeObj->pszValue[i], len+20 - strlen(pEncode));
+                               _VEscape(pEncode);
+                       }
+                       else
+                               memcpy(pEncode, pTypeObj->pszValue[i], biLen);
+                       }
+               else {
+                       char    buf[1000];
+                       strncpy( buf, pTypeObj->pszValue[i], 999 );
+                       _VEscape( buf );
+                       g_strlcat( pEncode, ";", len+20 - strlen(pEncode));
+                       g_strlcat( pEncode, buf, len+20 - strlen(pEncode));
+               }
+       }
+
+       if(strcmp(pType, pszCardTypeList[19]) != 0)     {
+               if (pEncode) {
+                       g_strlcat( pEncode, "\0\0", len+20 - strlen(pEncode) );
+                       len = strlen( pEncode );
+               }
+       }
+       else {
+               len = biLen;
+       }
+
+       if ( enc & pEncList[2].flag ) {
+               if((pRes = (char *)calloc(1, len * 6 + 10)) == NULL) {
+                       VFREE(pEncode);
+                       VFREE(szTypeValue);
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+               if(pEncode)
+                       _VQPEncode( pRes, pEncode );
+               VFREE(pEncode);
+                       }
+       else if(enc & pEncList[1].flag ) {
+               if((pRes = (char *)calloc(1, (len * 8 / 6) + 4)) == NULL){
+                       VFREE(pEncode);
+                       VFREE(szTypeValue);
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+
+               memset( pRes, '\0', ( ( len * 8 / 6 ) + 4 ) );
+               _VB64Encode( pRes, pEncode, biLen );
+               VFREE(pEncode);
+                       }
+       else {
+               if((pRes = (char *)calloc(1, len+30)) == NULL) {
+                       VFREE(pEncode);
+                       VFREE(szTypeValue);
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+               memset( pRes, '\0', ( len + 30 ) );
+               if(pEncode)
+               {
+                       memcpy( pRes, pEncode, len );
+                       VFREE(pEncode);
+               }
+       }
+
+       if((pRes = (char *)realloc(pRes, strlen(pRes) + 3)) == NULL)
+       {
+               VFREE(pEncode);
+               VFREE(szTypeValue);
+               VDATA_TRACE_END
+               return NULL;
+       }
+       g_strlcat( pRes, "\r\n", 2);
+
+       len = strlen( pRes );
+
+       if ((szTypeValue = (char *)realloc(szTypeValue, (total += (len+3)))) == NULL) {
+               VFREE(pEncode);
+               VFREE(pRes);
+               VDATA_TRACE_END
+               return NULL;
+       }
+
+       g_strlcat(szTypeValue, pRes, total - strlen(szTypeValue));
+
+       if(strcmp(pType, pszCardTypeList[19]) != 0) {
+               _VRLSpace( szTypeValue );
+               _VRTSpace( szTypeValue );
+       }
+
+       VFREE(pRes);
+       VDATA_TRACE_END
+       return szTypeValue;
+}
+
+/**
+ * __VCardParamEncode() Parameter Encoding.
+ *
+ * @param              pTypeObj                Data which will be encoded
+ * @param              pEnc                            Name of the type
+ */
+char *
+__VCardParamEncode(VObject* pTypeObj, int* pEnc)
+{
+       VDATA_TRACE_BEGINE
+       int i = 0;
+       int len = 0;
+       int sNum = 0;
+       int shift = 0;
+       bool bSupported;
+       char* szParam = NULL;
+       VParam* pTemp = NULL;
+       ValueObj*       pList = NULL;
+
+       /** Paramter initialize. */
+       pTemp = pTypeObj->pParam;
+
+       /** Momory Allocation for parameter string. */
+       if(pTemp != NULL) {
+               if ((szParam = (char*)calloc(1, len+=2)) == NULL)
+               {
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+               memset(szParam, 0x00, 2);
+       }
+
+       /** appending pamaters. */
+       while(true) {
+
+               if(pTemp == NULL) break;
+
+               bSupported = false;
+
+               /** Expand szParam string. For appending.*/
+               if((szParam = (char *)realloc(szParam, len += 15)) == NULL)
+               {
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+
+               /** appending paramter name. */
+               g_strlcat( szParam, ";", len - strlen(szParam) );
+
+               if(pTemp->parameter != VCARD_PARAM_TYPE) {
+                       g_strlcat( szParam, pszCardParamList[pTemp->parameter], len - strlen(szParam));
+                       g_strlcat( szParam, "=", len - strlen(szParam));
+               }
+
+               /** Set Parameter Value name. */
+               switch ( pTemp->parameter )
+               {
+                       case VCARD_PARAM_ENCODING:
+                               *pEnc = pTemp->paramValue;
+                               shift = VCARD_ENCODE_PARAM_NUM;
+                               pList = pEncList; bSupported = true;
+                               break;
+                       case VCARD_PARAM_TYPE:
+                               shift = VCARD_TYPE_PARAM_NUM;
+                               pList = pTypeList; bSupported = true;
+                               break;
+                       case VCARD_PARAM_VALUE:
+                               shift = VCARD_VALUE_PARAM_NUM;
+                               pList = pValueList; bSupported = true;
+                               break;
+                       case VCARD_PARAM_CHARSET:
+                               shift = VCARD_CHARSET_PARAM_NUM;
+                               pList = pCharsetList; bSupported = true;
+                               break;
+                       default:
+                               if ( ( szParam = ( char* )realloc( szParam, 5 ) ) == NULL )
+                               {
+                                       VDATA_TRACE_END
+                                       return NULL;
+                               }
+                               g_strlcat( szParam, "NONE", 5 - strlen(szParam) );
+               }
+
+               /** exchage parameter value's to string.*/
+               if(bSupported == true) {
+
+                       for(i = 0, sNum = 0x00000001; i < shift; i++) {
+
+                               if(pTemp->paramValue & sNum) {
+                                       if((szParam = (char *)realloc(szParam, ( len += (strlen(pList[i].szName) + 2)))) == NULL)
+                                       {
+                                               VDATA_TRACE_END
+                                               return NULL;
+                                       }
+
+                                       g_strlcat( szParam, pList[i].szName, len - strlen(szParam));
+                                       g_strlcat( szParam, "; ", len - strlen(szParam));
+                               }
+
+                               sNum <<= 1;
+                       }
+               }
+
+               /** remove semicolon from tail. */
+               for(i = strlen( szParam ); i > 0 ; i--) {
+
+                       if ( szParam[i] == ' ' && szParam[i-1] == ';' ) {
+                               szParam[i-1] = '\0';
+                               break;
+                       }
+               }
+
+               if ( pTemp->pNext != NULL )
+                       pTemp = pTemp->pNext;
+               else
+                       break;
+       }
+       VDATA_TRACE_END
+       return szParam;
+}
+
+SLPAPI bool
+vcard_free_vtree_memory(VTree * pTree)
+{
+       VDATA_TRACE_BEGINE
+       if(pTree == NULL)
+       {
+               VDATA_TRACE_END
+               return false;
+       }
+       VDATA_TRACE_END
+       return __VCardFreeVTreeMemory(pTree);
+}
+
diff --git a/vobject-engine/VCardCalUtil.c b/vobject-engine/VCardCalUtil.c
new file mode 100755 (executable)
index 0000000..1fa815a
--- /dev/null
@@ -0,0 +1,1236 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+
+#include "VTypes.h"
+#include "vobject.h"
+
+#define VCARD_TYPE_NUM 34
+#define VCAL_TYPE_NUM  66
+#define VMSG_TYPE_NUM 12
+extern char *pszCardTypeList[];
+
+/* BASE64 TABLE */
+char Base64Table[65] = {                                                                                                       'A',
+       'B',    'C',    'D',    'E',    'F',    'G',    'H',    'I',    'J',    'K',
+       'L',    'M',    'N',    'O',    'P',    'Q',    'R',    'S',    'T',    'U',
+       'V',    'W',    'X',    'Y',    'Z',    'a',    'b',    'c',    'd',    'e',
+       'f',    'g',    'h',    'i',    'j',    'k',    'l',    'm',    'n',    'o',
+       'p',    'q',    'r',    's',    't',    'u',    'v',    'w',    'x',    'y',
+       'z',    '0',    '1',    '2',    '3',    '4',    '5',    '6',    '7',    '8',
+       '9',    '+',    '/',    '='
+};
+
+/* Function Declaration */
+int            __VFindBase64( char );
+int            __VBase64Check( char * );
+int            __VRepChar2Space( char *, char );
+char   __VHexaDecoder( char * );
+void   __VHexaEncoder( char * );
+int            __VIsPrintable( char );
+
+
+/**
+ * vCardIsSpace() returns one if char is either a space, tab, or newline.
+ *
+ * @param      s1                [in] pointer to first string.
+ * @param      s2                [in] pointer to second string.
+ * @return     1                 'in' is a space character.
+ * @return     0                 'in' is not a space.
+ */
+int
+_VIsSpace( char in )
+{
+    if ( ( in == TAB ) || ( in == WSP ) )
+       {
+               return 1;
+    }
+       else
+       {
+               return 0;
+    }
+}
+
+
+/*
+ * vRemLeadSpace() removes leading space in string 'in'.
+ *
+ * @param      in                 [inout] pointer to string.
+ * @return     0                  if success.
+ */
+int
+_VRLSpace( char *in )
+{
+    int                        i, j;
+    short int  done;
+
+    i = 0;
+    done = 0;
+
+    while ( !done && in[i] )
+       {
+               if ( _VIsSpace( in[i] ) )
+               {
+                       i++;
+               }
+               else
+               {
+                       done = 1;
+               }
+    }
+
+    j = 0;
+    while ( in[i] )
+       {
+               in[j++] = in[i++];
+    }
+
+    in[j] = '\0';
+
+    return 0;
+}
+
+
+/*
+ * vRemTermSpace() removes terminating space.
+ *
+ * @param      in                 [inout] pointer to string.
+ * @return     0                  if success.
+ */
+int
+_VRTSpace( char *in )
+{
+    int                        i;
+    short int  done;
+
+    i = strlen(in) - 1;
+    done = 0;
+
+    while ( !done && !( i < 0 ) )
+       {
+               if ( _VIsSpace( in[i] ) )
+               {
+                       in[i--] = '\0';
+               }
+               else
+               {
+                       done = 1;
+               }
+    }
+
+    return(0);
+}
+
+
+/*
+ * VUnescape() unescapes escaped character.
+ *
+ * @param      in                 [inout] pointer to string.
+ * @return     0                  if success.
+ */
+int
+_VUnescape( char *in )
+{
+    int                        i;
+    int                        index;
+       int                     len;
+       char c1;
+       char c2;
+
+    len = strlen(in);
+
+    for ( i = 0, index = 0; i < len; i++ )
+       {
+               c1 = in[i];
+
+               if ( c1 == '\\' )
+               {
+                       c2 = in[i+1];
+                       if ( c2 == ';' ) continue;
+               }
+               in[index++] = c1;
+       }
+
+       in[index] = '\0';
+
+    return(0);
+}
+
+/*
+ * VEscape() escapes character.
+ *
+ * @param      in                 [inout] pointer to string.
+ * @return     0                  if success.
+ */
+int
+_VEscape( char *in )
+{
+       int i;
+       int index;
+       int len;
+       char *buf = NULL;
+       char c;
+
+       len = strlen(in);
+       buf = (char*) calloc(1, len*2+1);
+       if (buf) {
+               for ( i = 0, index = 0; i < len; i++ ){
+                       c = in[i];
+                       if ( c == ';' ) {
+                               buf[index++] = '\\';
+                       }
+                       buf[index++] = c;
+               }
+
+               strncpy( in, buf, len*2+1 );
+               free(buf);
+       }
+
+    return(0);
+}
+
+
+
+/*
+ * vManySpace2Space() converts multiple spaces to single space in 'in'.
+ *
+ * @param      in                 [inout] pointer to string.
+ * @return     int                length of converted string.
+ */
+int
+_VManySpace2Space( char *in )
+{
+    int                i, j;
+    int                spaced = 0;
+
+    j = 0;
+    for ( i = 0; in[i]; i++ )
+       {
+               if ( _VIsSpace( in[i] ) )
+               {
+                       if ( !spaced )
+                       {
+                               in[j] = WSP;
+                               spaced = 1;
+                               j++;
+                       }
+               }
+               else
+               {
+                       spaced = 0;
+                       in[j] = in[i];
+                       j++;
+               }
+    }
+
+
+    in[j] = '\0';
+
+    return j;
+}
+
+
+/**
+ * vFindBase64() returns the integer repesentation of the location in base64 table.
+ *
+ * @param      in                a character
+ * @return     int               The base64 table location of input character
+ */
+int
+__VFindBase64( char in )
+{
+    int                i;
+
+    for ( i = 0; i < 65; i++ )
+       {
+               if ( Base64Table[i] == in )
+                       return i;
+    }
+    return -1;
+}
+
+
+
+/**
+ * vBase64Check() returns the total length of input except non-base64 value.
+ *
+ * @param      in               char values which are base64 or non-base64
+ * @return     int              the total length of input except non-base64
+ */
+int
+__VBase64Check( char *in )
+{
+       int             i = 0, j = 0;
+       int             base;
+
+       while ( in[i] )
+       {
+               base = __VFindBase64( in[i] );
+               if ( base < 0 )
+               {
+                       i++;
+               }
+               else
+               {
+                       in[j] = in[i];
+                       j++; i++;
+               }
+       }
+
+       in[j] = '\0';
+
+       return j;
+}
+
+/**
+ * vBase64Decoder() decodes the base64 encoded input.
+ *
+ * @param      Src                Base64 encoded input
+ * @param      Dest               The destination buffer of decoded value
+ * @return     int                The total length decoded value
+ */
+int
+_VB64Decode( char *Dest, char *Src )
+{
+       char*           Encoded = Src;
+       int                     i, j = 0;
+       int                     res;
+       char            Base = 0;
+       char            DecodeTemp;
+       char            Debuffer[4] = {0x00, 0x00, 0x00, '\0'};
+       int                     index = 0;
+       int                     len;
+
+       len = __VBase64Check( Src );
+
+       VDATA_TRACE("total length of Src except non-base64 value = %d", len);
+
+       while ( *Encoded )
+       {
+               for ( i = 0; i < 3; i++ )
+                       Debuffer[i] = 0x00;
+
+               for ( i = 0; i < 4; i++, Encoded++, j++ )
+               {
+                       if(*Encoded == 0x00) break;
+                       if((res = __VFindBase64(*Encoded)) < 0) continue;
+
+                       Base = ( char )res;
+                       DecodeTemp = 0x00;
+
+                       if(Base == 64)  {
+                               Encoded++;
+                               break;
+                       }
+
+                       switch ( i )
+                       {
+                       case 0:
+                               DecodeTemp = Base << 2;
+                               Debuffer[0] |= DecodeTemp;
+                               break;
+                       case 1:
+                               DecodeTemp = Base >> 4;
+                               Debuffer[0] |= DecodeTemp;
+                               DecodeTemp = Base << 4;
+                               Debuffer[1] |= DecodeTemp;
+                               break;
+                       case 2:
+                               DecodeTemp = Base >> 2;
+                               Debuffer[1] |= DecodeTemp;
+                               DecodeTemp = Base << 6;
+                               Debuffer[2] |= DecodeTemp;
+                               break;
+                       case 3:
+                               DecodeTemp = Base;
+                               Debuffer[2] |= DecodeTemp;
+                               break;
+                       }
+               }
+
+               if ( Base == 64 )
+               {
+                       switch ( i )
+                       {
+                       case 0: break;
+                       case 1:
+                       case 2:
+                               Dest[index] = Debuffer[0];
+                               index++;
+                               break;
+                       case 3:
+                               Dest[index++] = Debuffer[0];
+                               Dest[index++] = Debuffer[1];
+                               break;
+                       }
+               }
+               else
+               {
+                       Dest[index++] = Debuffer[0];
+                       Dest[index++] = Debuffer[1];
+                       Dest[index++] = Debuffer[2];
+               }
+       }
+
+       return index;
+}
+
+
+/**
+ * vBase64Encoder() encode the input to base64.
+ *
+ * @param      Src                non-base64 char input
+ * @param      Dest               The destination buffer of encoded value
+ * @return     0
+ */
+int
+_VB64Encode( char *Dest, char *Src, int len )
+{
+       char*   Encoded = Dest;
+       char*   Decoded = Src;
+       int             i, j;
+       int             index;
+       int             res = 0;
+       int             base1 = 0, base2 = 0;
+       char    Enbuffer[4];
+       char    Debuffer[3];
+       int             length = 0;
+
+       for ( i = 0; i < 4; i++ )
+               Enbuffer[i] = 0x00;
+
+       for ( i = 0; i < len; i++ )
+       {
+               res = i%3;
+
+               switch ( res )
+               {
+               case 0:
+                       Debuffer[0] = *Decoded;
+                       break;
+               case 1:
+                       Debuffer[1] = *Decoded;
+                       break;
+               case 2:
+                       Debuffer[2] = *Decoded;
+                       index = ( int )( ( Debuffer[0] & 0xFC ) >> 2 );
+                       Enbuffer[0] = Base64Table[index];
+                       base1 = ( int )( ( Debuffer[0] & 0x03 ) << 4 );
+                       base2 = ( int )( ( Debuffer[1] & 0xF0 ) >> 4 );
+                       index = ( int )( base1 | base2 );
+                       Enbuffer[1] = Base64Table[index];
+                       base1 = ( int )( ( Debuffer[1] & 0x0F ) << 2 );
+                       base2 = ( int )( ( Debuffer[2] & 0xC0 ) >> 6 );
+                       index = ( int )( base1 | base2 );
+                       Enbuffer[2] = Base64Table[index];
+                       index = ( int )( Debuffer[2] & 0x3F );
+                       Enbuffer[3] = Base64Table[index];
+
+                       Encoded[length++] = Enbuffer[0];
+                       Encoded[length++] = Enbuffer[1];
+                       Encoded[length++] = Enbuffer[2];
+                       Encoded[length++] = Enbuffer[3];
+
+                       for ( j = 0; j < 3; j++ )
+                               Debuffer[j] = 0x00;
+
+                       break;
+               }
+
+               Decoded++;
+       }
+
+       res = i % 3;
+
+       switch ( res )
+       {
+       case 0:
+               break;
+       case 1:
+               index = ( int )( ( Debuffer[0] & 0xFC ) >> 2 );
+               Enbuffer[0] = Base64Table[index];
+               base1 = ( int )( ( Debuffer[0] & 0x03 ) << 4 );
+               base2 = ( int )( ( Debuffer[1] & 0xF0 ) >> 4 );
+               index = ( int )( base1 | base2 );
+               Enbuffer[1] = Base64Table[index];
+               Enbuffer[2] = Base64Table[64];
+               Enbuffer[3] = Base64Table[64];
+
+               Encoded[length++] = Enbuffer[0];
+               Encoded[length++] = Enbuffer[1];
+               Encoded[length++] = Enbuffer[2];
+               Encoded[length++] = Enbuffer[3];
+
+               break;
+       case 2:
+               index = ( int )( ( Debuffer[0] & 0xFC ) >> 2 );
+               Enbuffer[0] = Base64Table[index];
+               base1 = ( int )( ( Debuffer[0] & 0x03 ) << 4 );
+               base2 = ( int )( ( Debuffer[1] & 0xF0 ) >> 4 );
+               index = ( int )( base1 | base2 );
+               Enbuffer[1] = Base64Table[index];
+               base1 = ( int )( ( Debuffer[1] & 0x0F ) << 2 );
+               base2 = ( int )( ( Debuffer[2] & 0xC0 ) >> 6 );
+               index = ( int )( base1 | base2 );
+               Enbuffer[2] = Base64Table[index];
+               Enbuffer[3] = Base64Table[64];
+
+               Encoded[length++] = Enbuffer[0];
+               Encoded[length++] = Enbuffer[1];
+               Encoded[length++] = Enbuffer[2];
+               Encoded[length++] = Enbuffer[3];
+
+               break;
+       }
+
+       Encoded[length] = '\0';
+
+       return 0;
+}
+
+
+
+int
+__VRepChar2Space( char *vRaw, char replaced )
+{
+       int length = 0;
+
+       while ( *vRaw )
+       {
+               if ( *vRaw == replaced )
+                       *vRaw = WSP;
+
+               vRaw++;
+               length++;
+       }
+
+       return length;
+}
+
+
+/**
+ * vUnfolding() unfold the folded line.
+ *
+ * @param      string             The folded line input
+ * @return     int                Total length of unfolded output
+ */
+int
+_VUnfolding( char *string )
+{
+       unsigned int i, j;
+       unsigned int len;
+
+       len = strlen( string );
+
+       for ( i = 0, j = 0; i < len; i++, j++ )
+       {
+               string[j] = string[i];
+
+               // 12.03.2004 Process garbage character at the end of vcard/vcal
+               if ( _VIsSpace( string[i] ) &&  ( i < len-5 ) )
+               {
+                       if ( string[i-1] == LF || string[i-1] == CR )
+                       {
+                               if (j < 2)
+                                       j = 0;
+                               else
+                                       j -= 2;
+
+                               string[i-1] = 0;
+                       }
+                       if ( string[i-2] == LF || string[i-2] == CR )
+                       {
+                               if (j < 1)
+                                       j = 0;
+                               else
+                                       j -= 1;
+
+                               string[i-2] = 0;
+                       }
+               }
+       }
+
+       string[j] = '\0';
+
+       return j;
+}
+
+
+int
+__VIsNewType( char *pCardRaw )
+{
+       int count=0, i = 0, low=0, high=0, diff=0;
+       char strTypeName[50]={0};
+
+       while(1)
+       {
+               if(*pCardRaw == CR || *pCardRaw == LF)
+                       pCardRaw++;
+               else
+               {
+                       if(*pCardRaw == ';' || *pCardRaw == ':' || count >= 50)
+                       {
+                               break;
+                       }
+                       else
+                               strTypeName[count++] = *pCardRaw++;
+               }
+
+       }
+
+
+    for ( low = 0, high = VCARD_TYPE_NUM - 1; high >= low; diff < 0 ? ( low = i+1 ) : ( high = i-1 ) )
+       {
+               i = ( low + high ) / 2;
+               diff = strcmp( pszCardTypeList[i], strTypeName );
+               if ( diff == 0 )        /* success: found it */
+                       return true;
+    }
+
+
+
+    return false;
+       //res = __VCardGetName( strTypeName, (char**)pszCardTypeList, VCARD_TYPE_NUM );
+}
+
+
+int
+__VIsNewTypeforOrg( char *pCardRaw, int vType )
+{
+       int count=0, i = 0, low=0, high=0, diff=0,vTypeNum;
+       char strTypeName[50]={0};
+       extern char* pszCardTypeList[];
+       extern char* pszMsgTypeList[];
+
+       while(1)
+       {
+               if(*pCardRaw == CR || *pCardRaw == LF)
+                       pCardRaw++;
+               else
+               {
+                       if(*pCardRaw == ';' || *pCardRaw == ':' || count >= 50)
+                       {
+                               break;
+                       }
+                       else
+                               strTypeName[count++] = *pCardRaw++;
+               }
+       }
+
+       if(vType == VCARD)
+               vTypeNum = VCARD_TYPE_NUM;
+       else if(vType == VMESSAGE)
+               vTypeNum = VMSG_TYPE_NUM;
+       else
+                return false;
+
+       for ( low = 0, high = vTypeNum - 1; high >= low; diff < 0 ? ( low = i+1 ) : ( high = i-1 ) )
+       {
+               i = ( low + high ) / 2;
+
+               if(vType == VCARD)
+                       diff = strcmp( pszCardTypeList[i], strTypeName );
+               else if(vType == VMESSAGE)
+                       diff = strcmp( pszMsgTypeList[i], strTypeName );
+
+               if ( diff == 0 )        /* success: found it */
+                       return true;
+               else if( !strncmp( strTypeName, "X-", 2 ))
+                       return true;
+       }
+
+       //if(count <= 50) return TRUE;
+
+    return false;
+
+       //res = __VCardGetName( strTypeName, (char**)pszCardTypeList, VCARD_TYPE_NUM );
+}
+
+char*
+_VUnfoldingNoSpecNew(char *string)
+{
+       unsigned int i, j;
+       unsigned int len;
+
+       char* newString;
+
+       len = strlen( string );
+
+       if( !(newString = (char*) calloc(1, len+1) )) {
+               return NULL;
+       }
+
+
+       for ( i = 0, j = 0; i < len; i++, j++ ) {
+
+               newString[j] = string[i];
+
+               if( i < len-5 ) {
+
+                       if ( string[i] == '=' ) {
+
+                               if(string[i+1] == CR && string[i+2] == LF) {
+
+                                       if(__VIsNewType(string) == false){
+                                               j -= 2;
+                                       i += 2;
+                               }
+                               }
+                               else if(string[i+1] == CR || string[i+1] == LF) {
+                                       if(__VIsNewType(string) == false){
+                                       j -= 1;
+                                       i += 1;
+                               }
+                       }
+                       }
+                       else if(string[i] == ' ') {
+
+                               if(string[i-2] == CR && string[i-1] == LF) {
+                                       if(__VIsNewType(string) == false)
+                                       j -= 3;
+                                       else
+                                               j -= 1;
+                               }
+                               else if(string[i-1] == CR || string[i-1] == LF) {
+                                       j -= 2;
+                               }
+                       }
+
+                       else if((string[i] == CR || string[i] == LF) && __VIsNewType(string) == false) {
+
+                               if(string[i+1] == LF) {
+                                       j -= 1;
+                                       i += 1;
+                               }
+                       }
+               }
+       }
+
+       newString[j] = '\0';
+
+       return newString;
+}
+
+/**
+ * vUnfolding() unfold the folded line.
+ *
+ * @param      string             The folded line input
+ * @return     int                Total length of unfolded output
+ */
+int
+_VUnfoldingNoSpec( char *string, int vType )
+{
+       unsigned int i, j;
+       unsigned int len;
+
+       len = strlen( string );
+
+       for ( i = 0, j = 0; i < len; i++, j++ )
+       {
+               string[j] = string[i];
+
+               if ( ( i < len-5 ) )
+               {
+                       if ( string[i] == '=' )
+                       {
+                               if(string[i+1] == CR && string[i+2] == LF && string[i+3] =='=' )
+                               {
+                                       string[i] = 0;
+                                       string[i+1] = 0;
+                                       string[i+2] = 0;
+                                       if (j > 0)
+                                                j -= 1;
+                                       i += 2;
+                               }
+                               else if(string[i+1] == CR && string[i+2] == LF &&  __VIsNewTypeforOrg(&string[i+3], vType) == false)
+                               {
+                                       string[i] = 0;
+                                       string[i+1] = 0;
+                                       string[i+2] = 0;
+                                       if (j > 0)
+                                               j -= 1;
+                                       i += 2;
+                               }
+                       }
+                       else if(string[i] ==WSP
+                               ||string[i]==TAB)
+                       {
+                               if(string[i-2] == CR && string[i-1] == LF)
+                               {
+                                       string[i] = 0;
+                                       string[i-1] = 0;
+                                       string[i-2] = 0;
+                                       if (j >= 3)
+                                               j -= 3;
+                                       else
+                                               j = 0;
+                               }
+                               else if(string[i-1] == CR || string[i-1] == LF)
+                               {
+                                       string[i] = 0;
+                                       string[i-1] = 0;
+
+                                       if (j >=2)
+                                               j -= 2;
+                                       else
+                                               j = 0;
+                               }
+                       }
+
+               }
+       }
+
+       string[j] = '\0';
+
+       return j;
+}
+
+/**
+ * vFolding() decodes the base64 encoded input.
+ *
+ * @param      contentline        Original line (unfolded)
+ * @param      Dest               The destination buffer of folded result
+ */
+void
+_VFolding( char *result, char *contentline )
+{
+       int             i = 0;
+
+       while ( *contentline )
+       {
+               if ( i == 75 )
+               {
+                       i = 0;
+                       *result++ = '\r';
+                       *result++ = '\n';
+                       *result++ = ' ';
+               }
+
+               *result++ = *contentline++;
+               i++;
+       }
+
+       *result++ = '\0';
+}
+
+
+/**
+ * vFolding() decodes the base64 encoded input.
+ *
+ * @param      contentline        Original line (unfolded)
+ * @param      Dest               The destination buffer of folded result
+ */
+void
+_VFoldingQP( char *result, char *contentline )
+{
+       int             i = 0;
+
+       while ( *contentline )
+       {
+               if ( i == 74 )
+               {
+                       i = 0;
+                       *result++= '=';
+                       *result++ = '\r';
+                       *result++ = '\n';
+               }
+
+               *result++ = *contentline++;
+               i++;
+       }
+
+       *result++ = '\0';
+}
+
+
+/**
+ * vFolding() decodes the base64 encoded input.
+ *
+ * @param      contentline        Original line (unfolded)
+ * @param      Dest               The destination buffer of folded result
+ */
+void
+_VFoldingNoSpace( char *result, char *contentline )
+{
+       int             i = 0;
+
+       while ( *contentline )
+       {
+               if ( i == 75 )
+               {
+                       i = 0;
+                       *result++ = '\r';
+                       *result++ = '\n';
+               }
+
+               *result++ = *contentline++;
+               i++;
+       }
+
+       *result++ = '\0';
+}
+
+
+/**
+ * vQuotedPrintalbeDecoder() decodes the quoted-printable encoded input.
+ *
+ * @param      Src                Quoted-printable encoded input
+ * @return     int                The total length decoded value
+ */
+int
+_VQPDecode( char *src )
+{
+       int             i = 0, j = 0;
+       char    qp[2];
+       char    decodedNum;
+
+       while ( src[i] )
+       {
+               if ( src[i] == '=' )
+               {
+                       if ( !( _VIsSpace( src[i + 1] ) || ( src[i + 1] == '\r' ) || ( src[i+1] == '\n' ) ) )
+                       {
+                               if ( src[i + 1] == '0' && ( src[i + 2] == 'D' || src[i +2] == 'd' ) && src[i + 3] == '='
+                                       && src[i + 4] == '0' && ( src[i + 5] == 'A' || src[i + 5] == 'a' ) )
+                               {
+                                       src[j] = '\n';
+                                       j++;
+                                       i += 6;
+                               }
+                               else
+                               {
+                                       qp[0] = src[i + 1];
+                                       qp[1] = src[i + 2];
+                                       decodedNum = __VHexaDecoder( qp );
+                                       src[j] = decodedNum;
+                                       i += 3; j++;
+                               }
+                       }
+                       else
+                       {
+                               i += 3;
+                       }
+               }
+               else
+               {
+                       src[j] = src[i];
+                       i++; j++;
+               }
+       }
+
+       src[j] = '\0';
+
+       j =     _VManySpace2Space( src );
+
+       return j;
+}
+
+
+
+/**
+ * vQuotedPrintableEncoder() decodes the quoted-printalbe encoded input.
+ *
+ * @param      Src                Quoted-printable encoded input
+ * @param      Dest               The destination buffer of decoded value
+ * @return     int                The total length decoded value
+ */
+int
+_VQPEncode( char *dest, char *src )
+{
+       int             i = 0, j = 0, k = 0;
+       char    encoded[2] = {0x0f, 0x0f};
+
+       while ( src[i] /*&& ( src[i] > 0 )*/ )
+       {
+               if ( k == 73 && _VIsSpace( src[i] ) )
+               {
+                       if( src[i] == WSP )
+                       {
+                               dest[j++] = '='; dest[j++] = '2'; dest[j++] = '0';
+                               k += 3;
+                       }
+                       else if ( src[i] == TAB )
+                       {
+                               dest[j++] = '='; dest[j++] = '0'; dest[j++] = '9';
+                               k += 3;
+                       }
+               }
+       /*      else if ( k == 76 )
+               {
+                       dest[j++] = '='; dest[j++] = WSP;
+                       k = 0;
+               } */
+               else if ( !__VIsPrintable( src[i] ) )
+               {
+                       dest[j++] = '=';
+                       encoded[0] &= (src[i] >> 4);
+                       encoded[1] &= (src[i]);
+                       __VHexaEncoder( encoded );
+                       dest[j++] = encoded[0]; encoded[0] = 0x0f;
+                       dest[j++] = encoded[1]; encoded[1] = 0x0f;
+                       k += 3;
+               }
+               else if ( src[i] == '\r' || src[i] == '\n' )
+               {
+                       dest[j++] = '='; dest[j++] = '0'; dest[j++] = 'D'; k += 3;
+                       dest[j++] = '='; dest[j++] = '0'; dest[j++] = 'A'; k += 3;
+               }
+               else
+               {
+                       dest[j++] = src[i]; k++;
+               }
+               i++;
+       }
+
+       dest[j] = '\0';
+
+       return j;
+}
+
+
+/**
+ * vIsPrintable() check whether the input is printable.
+ *
+ * @param      in
+ * @return     true/false            if input is printable :true else : false
+ */
+int
+__VIsPrintable( char in )
+{
+       if ( in >= 33 && in <= 60 ) return true;
+       else if ( in >= 62 && in <= 126 ) return true;
+       else if ( in == WSP || in == TAB ) return true;
+       else if ( in == '\r' || in == '\n' ) return true;
+       else return false;
+}
+
+
+
+/**
+ * vHexaDecoder() output the character value of inputed hexadecimal value.
+ *
+ * @param      qp               Hexadecimal input value
+ * @return     char             Character representation of input hexadecimal value
+ */
+char
+__VHexaDecoder( char *qp )
+{
+       int             i;
+       char    decoded[2] = {0x00, 0x00};
+       char    res;
+
+       for ( i = 0; i < 2; i++ )
+       {
+               switch ( qp[i] )
+               {
+               case '0':
+                       decoded[i] = 0x00;
+                       break;
+               case '1':
+                       decoded[i] = 0x01;
+                       break;
+               case '2':
+                       decoded[i] = 0x02;
+                       break;
+               case '3':
+                       decoded[i] = 0x03;
+                       break;
+               case '4':
+                       decoded[i] = 0x04;
+                       break;
+               case '5':
+                       decoded[i] = 0x05;
+                       break;
+               case '6':
+                       decoded[i] = 0x06;
+                       break;
+               case '7':
+                       decoded[i] = 0x07;
+                       break;
+               case '8':
+                       decoded[i] = 0x08;
+                       break;
+               case '9':
+                       decoded[i] = 0x09;
+                       break;
+               case 'a':
+               case 'A':
+                       decoded[i] = 0x0a;
+                       break;
+               case 'b':
+               case 'B':
+                       decoded[i] = 0x0b;
+                       break;
+               case 'c':
+               case 'C':
+                       decoded[i] = 0x0c;
+                       break;
+               case 'd':
+               case 'D':
+                       decoded[i] = 0x0d;
+                       break;
+               case 'e':
+               case 'E':
+                       decoded[i] = 0x0e;
+                       break;
+               case 'f':
+               case 'F':
+                       decoded[i] = 0x0f;
+                       break;
+               }
+       }
+
+       res = ( char )( ( decoded[0] << 4 ) + decoded[1] );
+
+       return res;
+}
+
+
+
+/**
+ * vHexaEncoder() output the hexadecimal value of input character value.
+ *
+ * @return     qp               Character representation of input hexadecimal value
+ */
+void
+__VHexaEncoder( char *qp )
+{
+       int             i;
+
+       for ( i = 0; i < 2; i++ )
+       {
+               switch ( qp[i] )
+               {
+               case 0:
+                       qp[i] = '0';
+                       break;
+               case 1:
+                       qp[i] = '1';
+                       break;
+               case 2:
+                       qp[i] = '2';
+                       break;
+               case 3:
+                       qp[i] = '3';
+                       break;
+               case 4:
+                       qp[i] = '4';
+                       break;
+               case 5:
+                       qp[i] = '5';
+                       break;
+               case 6:
+                       qp[i] = '6';
+                       break;
+               case 7:
+                       qp[i] = '7';
+                       break;
+               case 8:
+                       qp[i] = '8';
+                       break;
+               case 9:
+                       qp[i] = '9';
+                       break;
+               case 10:
+                       qp[i] = 'A';
+                       break;
+               case 11:
+                       qp[i] = 'B';
+                       break;
+               case 12:
+                       qp[i] = 'C';
+                       break;
+               case 13:
+                       qp[i] = 'D';
+                       break;
+               case 14:
+                       qp[i] = 'E';
+                       break;
+               case 15:
+                       qp[i] = 'F';
+                       break;
+               }
+       }
+
+}
+
+/**
+ * _VIsCrLf() returns one if char is either a space, tab, or newline.
+ *
+ * @param      s1                [in] pointer to first string.
+ * @param      s2                [in] pointer to second string.
+ * @return     1                 'in' is a space character.
+ * @return     0                 'in' is not a space.
+ */
+int
+_VIsCrLf(char in)
+{
+       if ( ( in == CR ) || ( in == LF ) )
+       {
+               return 1;
+       }
+       else
+       {
+               return 0;
+       }
+}
+
+/*
+ * vManySpace2Space() converts multiple spaces to single space in 'in'.
+ *
+ * @param      in                 [inout] pointer to string.
+ * @return     int                length of converted string.
+ */
+int
+_VManyCRLF2CRLF(char *pIn)
+{
+       int             i, j;
+       bool    bCrLf = false, bFirstCrLf = true;
+
+       j = 0;
+       for ( i = 0; pIn[i]; i++ )
+       {
+               if ( _VIsCrLf( pIn[i] ) && _VIsCrLf( pIn[i+1] ))
+               {
+                       if( bFirstCrLf && !bCrLf)
+                       {
+                               bCrLf = 1;
+                       }
+                       else if( !bFirstCrLf )
+                       {
+                               if ( !bCrLf )
+                               {
+                                       pIn[j] = CR;
+                                       pIn[++j] = LF;
+                                       bCrLf = true;
+                                       j++;
+                               }
+                       }
+                       i++;
+               }
+               else
+               {
+                       bCrLf = false;
+                       bFirstCrLf = false;
+                       pIn[j] = pIn[i];
+                       j++;
+               }
+       }
+
+       pIn[j] = '\0';
+
+       return j;
+}
diff --git a/vobject-engine/VMessage.c b/vobject-engine/VMessage.c
new file mode 100755 (executable)
index 0000000..8f069ee
--- /dev/null
@@ -0,0 +1,1639 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#include "VTypes.h"
+#include "VMessage.h"
+#include "VCard.h"
+#include "vobject.h"
+
+#define MAX_TYPE_NAME_LEN 50
+#define MAX_PARAM_NAME_LEN 50
+#define CHECK_START 1
+#define CHECK_END 2
+
+#define VFREE(obj) if(obj != NULL) { /*VDATA_TRACE("%p",obj);*/ free(obj); \
+       obj = NULL; \
+}
+
+#define TRIM(obj) if(obj != NULL) {\
+       _VRLSpace(obj);\
+       _VRTSpace(obj);\
+}
+
+#define UPPER(obj,start,end) if(obj != NULL) {\
+       for(start = 0; start < end; start++)\
+               obj[start] = toupper(obj[start]);\
+}
+
+#define GO_NEXT_CHAR(current, rowData, addedCnt) {\
+       current = *rowData;\
+       rowData++;\
+       (*addedCnt)++;\
+}
+
+#define SET_PARAM_VALUE(PARAM, SZVALUE, LIST, LISTCNT, PARAMOBJ, PTYPE, ENC) {\
+       PARAM = 0;\
+       PARAM |= __VMsgGetValue(SZVALUE, LIST, LISTCNT);\
+       if ( PARAM != UNKNOWN_NAME ) {\
+               PARAMOBJ->parameter = PTYPE;\
+               if(PTYPE == VMSG_PARAM_ENCODING)\
+                       ENC = PARAM;\
+               break;\
+       }\
+}
+
+#define LENGTH_TYPE_LIST(obj, len) for(len =0; obj[len] != NULL; len++);
+
+extern char* _VUnfoldingNoSpecNew( char *string );
+
+/** GLOBAL VARIABLE DECLARATION AND INITIALIZATION */
+/** vMsg Types. */
+char* pszMsgTypeList[] =
+{
+       "BEGIN",
+       "END",
+       "TEL",
+       "VBODY",
+       "VCARD",
+       "VMSG",
+       "X-BODY-CONTENTS",
+       "X-BODY-SUBJECT",
+       "X-IRMC-BOX",
+       "X-IRMC-STATUS",
+       "X-MESSAGE-TYPE",
+       "X-SS-DT",
+};
+
+/** Parameter */
+char* pszMsgParamList[] =
+{
+       "CHARSET",
+       "CONTEXT",
+       "ENCODING",
+       "LANGUAGE",
+       "TYPE",
+       "VALUE"
+};
+
+/** Encoding value */
+ValueObj pMsgEncList[] =
+{
+       {"B",                   0x00000001},
+       {"BASE64",      0x00000002},
+       {"QUOTED-PRINTABLE", 0x00000004},
+       {"7BIT",                0x00000008},
+       {"8BIT",                0x00000010}
+};
+
+/** Character set value */
+ValueObj pMsgCharsetList[] =
+{
+       {"UTF-8",                       0x00000001},
+       {"UTF-16",              0x00000002},
+       {"ISO-8859-1",  0x00000004}
+};
+
+/** Value value */
+ValueObj pMsgValueList[] =
+{
+       {"BINARY",                      0x00000001},
+       {"BOOLEAN",                     0x00000002},
+       {"DATE",                                0x00000004},
+       {"DATE-TIME",           0x00000008},
+       {"FLOAT",                               0x00000010},
+       {"INTEGER",                     0x00000020},
+       {"PHONE-NUMBER",        0x00000040},
+       {"TEXT",                                0x00000080},
+       {"TIME",                                0x00000100},
+       {"URI",                                 0x00000200},
+       {"URL",                                 0x00000400},
+       {"UTC-OFFSET",          0x00000800},
+       {"VMSG",                                0x00001000}
+};
+
+/** Type value */
+ValueObj pMsgTypeList[] =
+{
+       {"AIFF",                0x00000001},
+       {"BBS",                 0x00000002},
+       {"CAR",                 0x00000004},
+       {"CELL",                0x00000008},
+       {"DOM",                 0x00000010},
+       {"WORK",                0x00000020},
+       {"FAX",                 0x00000040},
+       {"GIF",                 0x00000080},
+       {"HOME",                0x00000100},
+       {"INTL",                0x00000200},
+       {"INTERNET",    0x00000400},
+       {"ISDN",                0x00000800},
+       {"JPEG",                0x00001000},
+       {"MOBILE",      0x00002000},
+       {"MODEM",               0x00004000},
+       {"MSG",                 0x00008000},
+       {"PAGER",               0x00010000},
+       {"PARCEL",      0x00020000},
+       {"PCM",                 0x00040000},
+       {"PCS",                 0x00080000},
+       {"PNG",                 0x00100000},
+       {"POSTAL",      0x00200000},
+       {"PREF",                0x00400000},
+       {"VIDEO",               0x00800000},
+       {"VOICE",               0x01000000},
+       {"WAVE",                0x02000000},
+       {"WBMP",                0x04000000},
+       {"ETC",                 0x08000000},
+       {"X400",                0x10000000}
+};
+
+/** FUNCTION DECLARATION       */
+int __VMsgGetName(char*, char**, int);
+int __VMsgGetValue(char*, const ValueObj*, int);
+int __VMsgGetTypeName(char*, int*, int*);
+int __VMsgGetParamName(char*, int*, int*);
+int __VIsVmsgFile(char*, int);
+char* __VMsgGetParamVal(char*,int*, int*);
+char* __VMsgGetTypeVal(char*, int*, int*, int, VObject*);
+char* __VMsgTypeEncode(VObject*, char*);
+char* __VMsgParamEncode(VObject*, int*);
+
+
+/**
+ * __VMsgGetName() compares the string and vMsg type, parameter name.
+ *
+ * @param      szString        Name which will compare
+ * @param              pszList[]               Name list of vMsg type and param
+ * @param              size                            Number of total element of list
+ *
+ * @return     index           The index in the list
+ */
+int
+__VMsgGetName(char* szString, char* pszList[], int size)
+{
+       VDATA_TRACE_BEGINE
+       int high, low, i, diff = 0;
+
+       low = 0;
+       high = size - 1;
+
+       for(; high >= low; diff<0 ? (low = i+1):(high = i-1)) {
+               i = ( low + high ) / 2;
+               if((diff = strcmp( pszList[i], szString )) == 0) /* success: found it */
+                       return i;
+       }
+       VDATA_TRACE_END
+       return UNKNOWN_NAME;
+}
+
+/**
+ * __VMsgGetValue() compares the string and vMsg type, parameter value.
+ *
+ * @param      szString        Value which will compare
+ * @param              list[]          Value list of vMsg param
+ * @param              size                    Number of total element of list
+ *
+ * @return     flag      The value's flag.
+ */
+int
+__VMsgGetValue( char* szString, const ValueObj list[], int size)
+{
+       VDATA_TRACE_BEGINE
+       int i = 0, diff = -1;
+       char* szTemp = szString;
+
+       SysRequireEx(szString, UNKNOWN_NAME);
+       SysRequireEx(size > 0, UNKNOWN_NAME);
+
+       UPPER(szTemp,i,strlen(szTemp));
+
+       for(i = 0; i < size-1; i++)
+       {
+               VDATA_TRACE(" i : %d",i);
+               VDATA_TRACE(" for loop %d < %d, list[%d] : %p, list[%d].szName : %p",i,size,i,list[i],i,list[i].szName);
+               VDATA_TRACE(" i : %d",i);
+               if(list[i].szName != NULL)
+               {
+                       VDATA_TRACE(" list[%d].szName != NULL",i);
+                       VDATA_TRACE(" before strcmp %s %s",list[i].szName,szTemp);
+                       VDATA_TRACE(" before strcmp %d",strcmp(list[i].szName, szTemp));
+                       if((diff = strcmp(list[i].szName, szTemp)) == 0) /* success: found it */
+                       {
+                               VDATA_TRACE(" return %d",list[i].flag);
+                               VDATA_TRACE_END
+                               return list[i].flag;
+                       }
+                       VDATA_TRACE(" after strcmp %s %s",list[i].szName,szTemp);
+               }
+       }
+       VDATA_TRACE(" return UNKNOWN_NAME");
+       VDATA_TRACE_END
+       return UNKNOWN_NAME;
+}
+
+/**
+ * __VMsgGetTypeName() fine the type name and returns the index number
+ *
+ * @param              pVMsgRaw        The raw data
+ * @param              pStatus         Decoder status
+ * @param              pDLen           retrived length
+ *
+ * @return     res                     The index in type list
+ */
+int
+__VMsgGetTypeName(char* pVMsgRaw, int* pStatus, int* pDLen)
+{
+       VDATA_TRACE_BEGINE
+       int     i, index, res;
+       char    c;
+       char    name[MAX_TYPE_NAME_LEN+1]={0,};
+
+       SysRequireEx(pVMsgRaw, UNKNOWN_NAME);
+
+       i = index = 0;
+       res = UNKNOWN_NAME;
+
+       while(true) {
+
+               GO_NEXT_CHAR(c, pVMsgRaw, pDLen);
+
+               /**
+                * TYPE NAME's length is must be less than MAX_TYPE_NAME_LEN.
+                * If TYPE NAME's value is over MAX_TYPE_NAME_LEN, return UNKNOWN_NAME.
+                * And then Decoding Step shoud not be changed.
+                */
+               if(index >= MAX_TYPE_NAME_LEN) {
+                       *pStatus = VMSG_TYPE_NAME_STATUS;
+                       res = UNKNOWN_NAME;
+                       break;
+               }
+
+               /**
+                * There is a delimeter between TYPE NAME and next element(=Param, or Type Value).
+                * If VTYPE_TOKEN_SEMICOLON or VTYPE_TOKEN_COLON is faced with,
+                * find TYPE NAME's value in pszMsgTypeList, and then return searched result.
+                */
+               if ((c == VTYPE_TOKEN_SEMICOLON ) || ( c == VTYPE_TOKEN_COLON)) {
+                       name[index] = 0x00;
+                       TRIM(name);
+                       UPPER(name,i,index);
+                       res = __VMsgGetName( name, (char**)pszMsgTypeList, VMSG_TYPE_NUM );
+                       break;
+               }
+               /**
+                * There is no new line in TYPE NAME.
+                * If new line character is faced with, return UNKNOWN_NAME;
+                */
+               else if ( ( c == '\r' ) || ( c == '\n' ) )
+               {
+                       (*pDLen)++;
+                       *pStatus = VMSG_TYPE_NAME_STATUS;
+                       res = UNKNOWN_NAME;
+                       return res;
+               }
+               else if(_VIsSpace(c));
+               else    name[index++] = c;
+       }
+
+       /**
+        *      Set Next Step.
+        *
+        */
+       if ( c == VTYPE_TOKEN_SEMICOLON )
+               /**
+                * This case next token is parameter. So set VMSG_PARAM_NAME_STATUS step.
+                */
+               *pStatus = VMSG_PARAM_NAME_STATUS;
+       else
+       {
+               if(res != UNKNOWN_NAME)
+                       /**
+                        * This case next string is value. So set VMSG_TYPE_VALUE_STATUS step.
+                        */
+                       *pStatus = VMSG_TYPE_VALUE_STATUS;
+               else
+                       /**
+                        * In current step, TYPE NAME is invalid. So Try to get TYPE NAME again from next position.
+                        */
+                       *pStatus = VMSG_TYPE_NAME_STATUS;
+       }
+       VDATA_TRACE_END
+       return res;
+}
+
+/**
+ * __VMsgGetParamName() fine the param name and returns the index number
+ *
+ * @param              pVMsgRaw        The raw data
+ * @param              pStatus         Decoder status
+ * @param              pDLen           retrived length
+ *
+ * @return     res                     The index in type list
+ */
+int
+__VMsgGetParamName( char* pVMsgRaw, int* pStatus, int* pDLen )
+{
+       VDATA_TRACE_BEGINE
+       int     i, index, res;
+
+       char    c;
+       char    name[MAX_PARAM_NAME_LEN+1]={0,};
+       char* pTemp = pVMsgRaw;
+
+       SysRequireEx( pVMsgRaw, UNKNOWN_NAME );
+
+       i = index = 0;
+       res = UNKNOWN_NAME;
+
+       while ( true )
+       {
+               GO_NEXT_CHAR(c, pVMsgRaw, pDLen);
+
+               /**
+                * PARAM NAME's length is must be less than MAX_PARAM_NAME_LEN.
+                * If PARAM NAME's value is over MAX_PARAM_NAME_LEN, return UNKNOWN_NAME.
+                * And then Decoding Step shoud not be changed.
+                */
+               if(index >= MAX_PARAM_NAME_LEN) {
+                       *pStatus = VMSG_TYPE_NAME_STATUS;
+                       res = UNKNOWN_NAME;
+                       break;
+               }
+
+               /**
+                * There is a delimeter between PARAM NAME and next element(=Param, or Param Value).
+                * If VTYPE_TOKEN_EQUAL is faced with,
+                * find PARAM NAME's value in pszMsgParamList, and then return searched result.
+                */
+               if(c == VTYPE_TOKEN_EQUAL) {
+                       name[index] = '\0';
+                       TRIM(name);
+                       UPPER(name, i, index);
+                       res = __VMsgGetName( name, ( char** )pszMsgParamList, VMSG_PARAM_NUM );
+                       if(res==UNKNOWN_NAME){
+                               (*pDLen) = 0;
+                       }
+                       *pStatus = VMSG_PARAM_VALUE_STATUS;
+                       break;
+               }
+               /**
+                * This case, There is no parameter type. Only Parameter Value.
+                * In VMSG_PARAM_NAME_STATUS status, VTYPE_TOKEN_COLON means that anything parameter is no more.
+                * so set next step to VMSG_PARAM_VALUE_STATUS.
+                *
+                * Ex) TEL;WORK:+12341234
+                *        ------ ":" next is TEL TYPE's value.
+                *
+                * VMSG_PARAM_NAME_STATUS(current) -> VMSG_PARAM_VALUE_STATUS
+                * -> VMSG_TYPE_VALUE_STATUS -> MOVE TO NEXT TYPE
+                */
+               else if(c == VTYPE_TOKEN_COLON) {
+                       *pStatus = VMSG_PARAM_VALUE_STATUS;
+                       pVMsgRaw = pTemp;
+                       (*pDLen) = 0;
+                       res = UNKNOWN_NAME;
+                       break;
+               }
+               /**
+                * This case, There is no parameter type. Only Parameter Value.
+                * In VMSG_PARAM_NAME_STATUS status, VTYPE_TOKEN_SEMICOLON means that there is a next parameter.
+                * so set next step to VMSG_PARAM_NAME_STATUS.
+                *
+                * Ex) TEL;WORK;PREF:+12341234
+                *        ------ ":" next is TEL TYPE's value.
+                *
+                * VMSG_PARAM_NAME_STATUS(current) -> VMSG_PARAM_NAME_STATUS
+                * -> VMSG_PARAM_VALUE_STATUS -> VMSG_TYPE_VALUE_STATUS -> MOVE TO NEXT TYPE
+                */
+               else if(c == VTYPE_TOKEN_SEMICOLON) {
+                       *pStatus = VMSG_PARAM_NAME_STATUS;
+                       pVMsgRaw = pTemp;
+                       (*pDLen) = 0;
+                       res = UNKNOWN_NAME;
+                       break;
+               }
+               else if((c == '\r') || (c == '\n') || (_VIsSpace(c)));
+               else
+                       name[index++] = c;
+       }
+       VDATA_TRACE_END
+       return res;
+}
+
+bool
+__VMsgFreeVTreeMemory(VTree * pTree)
+{
+       VDATA_TRACE_BEGINE
+       VObject*                pCurObj = NULL;
+       VObject*                pNextObj = NULL;
+
+       VTree*                  pCurTree = NULL;
+       VTree*                  pNextTree = NULL;
+
+       VParam* pCurParam = NULL;
+       VParam* pNextParam = NULL;
+
+       int count = 0;
+       int i = 0;
+
+       SysRequireEx( pTree->treeType == VMESSAGE, false );
+       SysRequireEx( pTree != NULL, false );
+       VDATA_TRACE("vmsg_free_vtree_memory() entered.");
+
+       if (pTree->treeType != VMESSAGE)
+       {
+               VDATA_TRACE_END
+               return true;
+       }
+
+       pCurTree = pTree;
+
+       while(pCurTree)
+       {
+               pNextTree = pCurTree->pNext;
+               pCurObj = pCurTree->pTop;
+
+               while ( pCurObj )
+               {
+
+                       pNextObj = pCurObj->pSibling;
+                       count = pCurObj->valueCount;
+
+                       for ( i = 0; i < count; i++ ) {
+                               VFREE( pCurObj->pszValue[i]);
+                       }
+
+                       if ( pCurObj->pParam )
+                       {
+
+                               pCurParam = pCurObj->pParam;
+
+                               while(pCurParam != NULL)
+                               {
+                                       pNextParam = pCurParam->pNext;
+                                       VDATA_TRACE("pNEXT ==> %p", pCurParam->pNext);
+                                       VDATA_TRACE("pPARAM ==> %p", pCurParam->parameter);
+                                       VDATA_TRACE("pVALUE ==> %p", pCurParam->paramValue);
+                                       VDATA_TRACE("pCurParam : %p", pCurParam);
+                                       VDATA_TRACE("pCurParam->parameter : %d", pCurParam->parameter);
+                                       VDATA_TRACE("pCurParam->paramValue : %d", pCurParam->paramValue);
+                                       if(pNextParam != NULL) {
+                                               VDATA_TRACE("pNextParam : %p", pNextParam);
+                                               VDATA_TRACE("pNextParam->parameter : %d", pNextParam->parameter);
+                                               VDATA_TRACE("pNextParam->paramValue : %d", pNextParam->paramValue);
+                                       }
+                                       VFREE(pCurParam);
+                                       pCurParam = pNextParam;
+                               }
+                       }
+
+                       VFREE( pCurObj );
+                       pCurObj = pNextObj;
+               }
+
+               VFREE( pCurTree );
+               pCurTree = pNextTree;
+       }
+
+       VDATA_TRACE("exit vmsg_free_vtree_memory");
+       VDATA_TRACE_END
+       return true;
+}
+
+/**
+ * __VMsgGetParamVal() fine the param value and returns value.
+ *
+ * @param              pVMsgRaw        The raw data
+ * @param              pStatus         Decoder status
+ * @param              pDLen           retrived length
+ *
+ * @return     buffer          The result value
+ */
+char*
+__VMsgGetParamVal( char* pVMsgRaw, int* pStatus, int* pDLen )
+{
+       VDATA_TRACE_BEGINE
+       int len = 0;
+       char    c;
+       char* pBuf = NULL;
+       char* pTemp = pVMsgRaw;
+
+       SysRequireEx( pVMsgRaw, NULL );
+
+       while(true) {
+               GO_NEXT_CHAR(c, pVMsgRaw, pDLen);
+               len++;
+               switch(c) {
+                       case VTYPE_TOKEN_SEMICOLON :
+                               *pStatus = VMSG_PARAM_NAME_STATUS;
+                               break;
+                       case VTYPE_TOKEN_COLON :
+                               *pStatus = VMSG_TYPE_VALUE_STATUS;
+                               break;
+                       case VTYPE_TOKEN_COMMA :
+                               *pStatus = VMSG_PARAM_VALUE_STATUS;
+                               break;
+               }
+               if( c == VTYPE_TOKEN_SEMICOLON
+                               || c == VTYPE_TOKEN_COLON
+                               || c == VTYPE_TOKEN_COMMA
+                               || c == 0x00)
+                       break;
+       }
+
+       if(len < 1 || (pBuf = (char *)calloc(1, len)) == NULL)
+               return NULL;
+       memset(pBuf, 0x00, len);
+       memcpy( pBuf, pTemp, len-1 );
+       TRIM(pBuf);
+       VDATA_TRACE_END
+       return pBuf;
+}
+
+
+/**
+ * __VMsgGetTypeVal() fine the type value and returns value.
+ *
+ * @param      pVMsgRaw        The raw data
+ * @param              status                  Decoder status
+ * @return     buffer          The result value
+ */
+char*
+__VMsgGetTypeVal( char* pVMsgRaw, int* pStatus, int* pDLen, int enc, VObject* pType)
+{
+       VDATA_TRACE_BEGINE
+       int num = 0;
+       int len = 0;
+       int bufferCount = 0;
+
+       bool bEscape = false;
+
+       char    c, c1, c2;
+       char* pBuf = NULL;
+       char* pTemp = pVMsgRaw;
+       char* pTmpBuf = NULL;
+       int Status = 0;
+       int Len = 0;
+
+       SysRequireEx( pVMsgRaw, NULL );
+       VDATA_TRACE("pVMsgRaw: %s", pVMsgRaw);
+       while(true)
+       {
+               GO_NEXT_CHAR(c, pVMsgRaw, pDLen);
+
+               if( c == 0x00)
+                       break;
+
+               len++;
+
+               /** This case means that there are more type's value. */
+               if ( c == VTYPE_TOKEN_SEMICOLON && bEscape == false )
+               {
+                       if((pBuf = (char *)calloc(1, len)) == NULL)
+                               return NULL;
+
+                       memset(pBuf, 0x00, len);
+                       memcpy(pBuf,pTemp,len-1);
+
+                       TRIM(pBuf);
+                       _VUnescape(pBuf);
+
+                       *pStatus = VMSG_TYPE_VALUE_STATUS;
+
+                       /** Base 64 Decoding */
+                       if((enc & pMsgEncList[1].flag) || (enc & pMsgEncList[0].flag))
+                       {
+
+                               bufferCount = (len * 6 / 8) + 2;
+
+                               if((pTmpBuf = (char *)calloc(1, bufferCount)) == NULL)
+                               {
+                                       VFREE(pBuf);
+                                       return NULL;
+                               }
+
+                               memset(pTmpBuf, 0x00, bufferCount);
+                               num = _VB64Decode(pTmpBuf, pBuf);
+
+                               if(pType != NULL)
+                                       pType->numOfBiData = num;
+
+                               VFREE(pBuf);
+                               pBuf = pTmpBuf;
+                               pTmpBuf = NULL;
+                               break;
+                       }
+
+                       /** Quoted Printable Decoding */
+                       if(enc & pMsgEncList[2].flag)
+                       {
+
+                               int i = 0, j = 0;
+
+                               while(pBuf[i])
+                               {
+                                       if(pBuf[i] == '\n' || pBuf[i] == '\r')
+                                       {
+                                               i++;
+                                               if(pBuf[i] == '\n'|| pBuf[i] == '\r')
+                                                       i++;
+
+                                               if(pBuf[j-1] == '=')
+                                                       j--;
+                                       }
+                                       else
+                                               pBuf[j++] = pBuf[i++];
+                               }
+                               pBuf[j] = '\0';
+
+                               _VQPDecode(pBuf);
+                               TRIM(pBuf);
+                               break;
+                       }
+                       break;
+               }
+
+               if(c == '\\')
+                       bEscape = true;
+               else if(bEscape == true && c != VTYPE_TOKEN_SEMICOLON )
+                       bEscape = false;
+               else if((c == '\r') || (c == '\n'))
+               {
+                       c2 = *(pVMsgRaw-2);
+
+                       if(c2 == '=' && (enc & pMsgEncList[2].flag))
+                       {
+                               c1 = *pVMsgRaw;
+                               if((c1 == '\r') || (c1 == '\n'))
+                               {
+                                       pVMsgRaw += 1;
+                                       (*pDLen) += 1;
+                                       len++;
+                               }
+                       }
+                       else if(__VMsgGetTypeName(pVMsgRaw, &Status, &Len) != UNKNOWN_NAME)
+                       {
+                               if((pBuf = (char *)calloc(1, len)) == NULL)
+                                       return NULL;
+
+                               memset(pBuf, 0x00, len);
+                               memcpy(pBuf, pTemp, len-1);
+
+                               TRIM(pBuf);
+                               _VUnescape(pBuf);
+                               VDATA_TRACE("pVMsgRaw: %s", pVMsgRaw);
+                               *pStatus = VMSG_TYPE_NAME_STATUS;
+
+                               c1 = *pVMsgRaw;
+
+                               if((c1 == '\r') || (c1 == '\n'))
+                               {
+                                       pVMsgRaw += 1;
+                                       (*pDLen) += 1;
+                               }
+
+                               if((enc & pMsgEncList[1].flag) || (enc & pMsgEncList[0].flag))
+                               {
+
+                                       bufferCount = (len * 6 / 8) + 5;
+
+                                       if((pTmpBuf = (char *)calloc(1, bufferCount)) == NULL)
+                                       {
+                                               VFREE(pBuf);
+                                               return NULL;
+                                       }
+
+                                       memset(pTmpBuf, 0x00, bufferCount);
+                                       num = _VB64Decode(pTmpBuf, pBuf);
+
+                                       if(pType != NULL)
+                                               pType->numOfBiData = num;
+
+                                       VFREE(pBuf);
+                                       pBuf = pTmpBuf;
+                                       pTmpBuf = NULL;
+                                       break;
+                               }
+
+                               if(enc & pMsgEncList[2].flag)
+                               {
+
+                                       int i = 0, j = 0;
+
+                                       while(pBuf[i])
+                                       {
+                                               if(pBuf[i] == '\n' || pBuf[i] == '\r')
+                                               {
+                                                       i++;
+                                                       if(pBuf[i] == '\n' || pBuf[i] == '\r')
+                                                               i++;
+
+                                                       if(pBuf[j-1] == '=') j--;
+                                               }
+                                               else
+                                                       pBuf[j++] = pBuf[i++];
+                                       }
+                                       pBuf[j] = '\0';
+
+                                       _VQPDecode(pBuf);
+                                       TRIM(pBuf);
+                                       break;
+                               }
+                               break;
+                       }
+               }
+       }
+
+       VDATA_TRACE_END
+       return pBuf;
+}
+
+
+int
+VMsgGetTypeValue( int index )
+{
+       VDATA_TRACE_BEGINE
+       VDATA_TRACE("VMsgGetTypeValue() enter..\n");
+       VDATA_TRACE_END
+       return pMsgTypeList[index].flag;
+}
+
+int
+VMsgGetValValue( int index )
+{
+       VDATA_TRACE_BEGINE
+       VDATA_TRACE("VMsgGetValValue() enter..\n");
+       VDATA_TRACE_END
+       return pMsgValueList[index].flag;
+}
+
+int
+VMsgGetEncValue( int index )
+{
+       VDATA_TRACE_BEGINE
+       VDATA_TRACE("VMsgGetEncValue() enter..\n");
+       VDATA_TRACE_END
+       return pMsgEncList[index].flag;
+}
+
+int
+VMsgGetCharsetValue( int index )
+{
+       VDATA_TRACE_BEGINE
+       VDATA_TRACE("VMsgGetCharsetValue() enter..\n");
+       VDATA_TRACE_END
+       return pMsgCharsetList[index].flag;
+}
+
+/*
+ * vmsg_decode() decode the vMsg data and returns vObject struct
+ *
+ * @param       pVMsgRaw            The raw data
+ * @return      vObject             The result value
+ */
+SLPAPI VTree*
+vmsg_decode( char *pMsgRaw )
+{
+       VDATA_TRACE_BEGINE;
+
+       char* szValue = NULL;
+       char* szMsgBegin = NULL;
+       char* pMsgRawTmp = NULL;
+       VTree* pVMsg = NULL;
+       VTree* pVBody = NULL;
+       VTree* pCurrent = NULL;
+       VTree* pVCard = NULL;
+       VParam* pTmpParam = NULL;
+       VObject* pTemp = NULL;
+
+       char    c;
+
+       int type, param;
+       int status = VMSG_TYPE_NAME_STATUS;
+       int done = false;
+       int valueCount = 0;
+       int len;
+       int dLen = 0;
+       int param_status = false;
+       int numberedParam = 0;
+       int enc = 0;
+       int start_status = 0;
+       char* temp = NULL;
+       char* pVTree = NULL;
+       bool vmsg_ended = false;
+
+       SysRequireEx(pMsgRaw != NULL, NULL);
+       len = strlen(pMsgRaw);
+       VDATA_TRACE("length of pCardRaw = %d", len);
+
+       len = _VUnfoldingNoSpec(pMsgRaw, VMESSAGE);
+       pMsgRawTmp = pMsgRaw;
+       len = _VManySpace2Space( pMsgRaw );
+
+       VDATA_TRACE("ret value of _VManySpace2Space = %d", len);
+
+       if(!__VIsVmsgFile(pMsgRaw, CHECK_START)) {
+               VFREE(pMsgRawTmp);
+               VDATA_TRACE_END
+               return NULL;
+       }
+
+       while(true && !done)
+       {
+               c = *pMsgRaw;
+
+               if((c == '\0') || done)
+                       break;
+
+               switch(status) {
+                       case VMSG_TYPE_NAME_STATUS:
+                               dLen = 0;
+                               type = __VMsgGetTypeName(pMsgRaw, &status, &dLen);
+
+                               if(type == VMSG_TYPE_BEGIN)
+                                       pVTree = pMsgRaw;
+
+                               pMsgRaw += dLen;
+
+                               if(type == -1)
+                                       break;
+
+                               switch ( type )
+                               {
+                                       case VMSG_TYPE_BEGIN:
+                                               dLen = 0;
+                                               enc = 0;
+                                               szMsgBegin = __VMsgGetTypeVal(pMsgRaw, &status, &dLen, enc, NULL);
+                                               pMsgRaw += dLen;
+
+                                               if(szMsgBegin == NULL)
+                                                       goto CATCH;
+
+                                               if(!strncmp(szMsgBegin, "VCARD", strlen("VCARD")))
+                                               {
+                                                       VDATA_TRACE("pVTree: %s", pVTree);
+                                                       pVCard = vcard_decode(pVTree);
+                                                       pCurrent->pNext = pVCard;
+                                                       pCurrent = pVCard;
+
+                                                       dLen = ((strstr(pMsgRaw,"END:VCARD") + 9) - pMsgRaw);
+                                                       pMsgRaw += dLen;
+                                               }
+
+                                               else
+                                               {
+
+                                                       if(start_status == 1)
+                                                               goto CATCH;
+
+
+
+
+                                                       if(!strncmp(szMsgBegin, "VMSG", strlen("VMSG")))
+                                                       {
+                                                               if ( ( pVMsg = ( VTree* )calloc( 1, sizeof( VTree ) ) ) == NULL )
+                                                               {
+                                                                       start_status = 1;
+                                                                       goto CATCH;
+                                                               }
+                                                               memset(pVMsg,0x00, sizeof(VTree));
+
+                                                               pVMsg->treeType = VMESSAGE;
+                                                               pVMsg->pTop = NULL;
+                                                               pVMsg->pCur = NULL;
+                                                               pVMsg->pNext = NULL;
+                                                               pCurrent = pVMsg;
+                                                       }
+
+                                                       else if(!strncmp(szMsgBegin, "VBODY", strlen("VBODY")))
+                                                       {
+                                                               if ( ( pVBody = ( VTree* )calloc( 1, sizeof( VTree ) ) ) == NULL )
+                                                               {
+                                                                       start_status = 1;
+                                                                       goto CATCH;
+                                                               }
+
+                                                               memset(pVBody,0x00, sizeof(VTree));
+                                                               pVBody->treeType = VBODY;
+                                                               pVBody->pTop = NULL;
+                                                               pVBody->pCur = NULL;
+                                                               pVBody->pNext = NULL;
+                                                               pCurrent->pNext = pVBody;
+                                                               pCurrent = pVBody;
+                                                       }
+                                               }
+
+                                               VFREE(szMsgBegin);
+                                               break;
+
+                                       case VMSG_TYPE_END:
+                                               dLen = 0;
+                                               enc = 0;
+                                               //szMsgBegin = __VMsgGetTypeVal(pMsgRaw, &status, &dLen, enc, NULL);
+
+                                               if(!strncmp(pMsgRaw,"VMSG", strlen("VMSG")))
+                                               {
+                                                       done = true;
+                                                       vmsg_ended = true;
+                                               }
+                                               else
+                                               {
+                                                       status = VMSG_TYPE_NAME_STATUS;
+                                                       //pMsgRaw += dLen;
+                                               }
+                                               VDATA_TRACE("pMsgRaw:%s", pMsgRaw);
+                                               pMsgRaw += dLen;
+                                               break;
+
+                                       case UNKNOWN_NAME :
+                                               break;
+
+                                       default:
+                                               if(UNKNOWN_NAME == type || type < 0) {
+                                                       status = VMSG_TYPE_NAME_STATUS;
+                                                       break;
+                                               }
+
+                                               if ( ( pTemp = ( VObject* )calloc( 1, sizeof( VObject ) ) ) == NULL )
+                                               {
+                                                       goto CATCH;
+                                               }
+
+                                               memset( pTemp, 0, sizeof( VObject ) );
+                                               pTemp->property = type;
+
+                                               if ( pCurrent->pTop == NULL ) {
+                                                       pCurrent->pTop = pTemp;
+                                                       pCurrent->pCur = pTemp;
+                                               }
+                                               else {
+                                                       pCurrent->pCur->pSibling = pTemp;
+                                                       pCurrent->pCur = pTemp;
+                                               }
+
+                                               break;
+                               }
+
+                               numberedParam = 0;
+                               param_status = false;
+                               valueCount = 0;
+                               break;
+
+                       case VMSG_PARAM_NAME_STATUS:
+                       {
+                               dLen = 0;
+                               param = __VMsgGetParamName( pMsgRaw, &status, &dLen );
+                               pMsgRaw += dLen;
+
+                               if ( param_status != true ) {
+
+                                       if ( ( pTmpParam = ( VParam* )calloc( 1, sizeof( VParam ) ) ) == NULL )
+                                                       goto CATCH;
+
+                                       param_status = true;
+                                       pCurrent->pCur->pParam = pTmpParam;
+                                       memset( pTmpParam, 0x00, sizeof( VParam ) );
+                                       VDATA_TRACE("pTmpParam : %p", pTmpParam);
+                               }
+                               else
+                               {
+                                       if ( ( pTmpParam->pNext = ( VParam* )calloc( 1, sizeof( VParam ) ) ) == NULL )
+                                                       goto CATCH;
+
+                                       pTmpParam = pTmpParam->pNext;
+                                       memset( pTmpParam, 0x00, sizeof(VParam));
+                                       VDATA_TRACE("pTmpParam : %p", pTmpParam);
+                               }
+
+                               pTmpParam->parameter = param;
+                               break;
+                       }
+                       case VMSG_PARAM_VALUE_STATUS:
+                               dLen = 0;
+                               numberedParam = 0;
+                               switch ( pTmpParam->parameter )
+                               {
+                                       case VMSG_PARAM_TYPE:
+                                               szValue = __VMsgGetParamVal( pMsgRaw, &status, &dLen );
+                                               numberedParam |= __VMsgGetValue( szValue, pMsgTypeList, VMSG_TYPE_PARAM_NUM );
+                                               break;
+                                       case VMSG_PARAM_VALUE:
+                                               szValue = __VMsgGetParamVal( pMsgRaw, &status, &dLen );
+                                               numberedParam |= __VMsgGetValue( szValue, pMsgValueList, VMSG_VALUE_PARAM_NUM );
+                                               break;
+                                       case VMSG_PARAM_ENCODING:
+                                               szValue = __VMsgGetParamVal( pMsgRaw, &status, &dLen );
+                                               numberedParam |= __VMsgGetValue( szValue, pMsgEncList, VMSG_ENCODE_PARAM_NUM );
+                                               enc = numberedParam;
+                                               break;
+                                       case VMSG_PARAM_CHARSET:
+                                               szValue = __VMsgGetParamVal( pMsgRaw, &status, &dLen );
+                                               numberedParam |= __VMsgGetValue( szValue, pMsgCharsetList, VMSG_CHARSET_PARAM_NUM );
+                                               break;
+                                       case VMSG_PARAM_CONTEXT:
+                                       case VMSG_PARAM_LANGUAGE:
+                                               // prevent 7605 08.03.13
+                                               szValue = __VMsgGetParamVal( pMsgRaw, &status, &dLen );
+                                               numberedParam = 0;
+                                               break;
+                                       default:
+                                               szValue = __VMsgGetParamVal( pMsgRaw, &status, &dLen );
+
+                                               SET_PARAM_VALUE(numberedParam, szValue, pMsgTypeList, VMSG_TYPE_PARAM_NUM, pTmpParam, VMSG_PARAM_TYPE, enc);
+                                               SET_PARAM_VALUE(numberedParam, szValue, pMsgValueList, VMSG_VALUE_PARAM_NUM, pTmpParam, VMSG_PARAM_VALUE, enc);
+                                               SET_PARAM_VALUE(numberedParam, szValue, pMsgEncList, VMSG_ENCODE_PARAM_NUM, pTmpParam, VMSG_PARAM_ENCODING, enc);
+                                               SET_PARAM_VALUE(numberedParam, szValue, pMsgCharsetList, VMSG_CHARSET_PARAM_NUM, pTmpParam, VMSG_PARAM_CHARSET, enc);
+
+                                               numberedParam = 0;
+                                               pMsgRaw += dLen;
+                                               dLen = 0;
+
+                                               break;
+                               }
+
+                               VDATA_TRACE("%d, %s, %p",numberedParam, szValue, pTmpParam);
+                               pTmpParam->paramValue = numberedParam;
+                               pTmpParam->pNext = NULL;
+                               VFREE(szValue);
+                               pMsgRaw += dLen;
+                               break;
+                       case VMSG_TYPE_VALUE_STATUS:
+                               dLen = 0;
+                               temp = __VMsgGetTypeVal( pMsgRaw, &status, &dLen, enc, pCurrent->pCur);
+
+                               if(valueCount <= VDATA_VALUE_COUNT_MAX) {
+                                       pCurrent->pCur->pszValue[valueCount] = temp;
+                                       valueCount++;
+                                       pCurrent->pCur->valueCount = valueCount;
+                                       VDATA_TRACE("object property: %d, value: %s", pCurrent->pCur->property, pCurrent->pCur->pszValue[valueCount - 1]);
+                               }
+                               else
+                                       VFREE(temp);
+
+                               pMsgRaw += dLen;
+                               break;
+               }
+       }
+       VDATA_TRACE("pMsgRawTmp: %s", pMsgRawTmp);
+       //VFREE(pMsgRawTmp);
+
+       if(pVMsg->pTop == NULL)
+       {
+               VDATA_TRACE("pVMsg->Top: NULL");
+               goto CATCH;
+       }
+
+       if(!vmsg_ended) {
+               VDATA_TRACE("vmsg_ended: false");
+               goto CATCH1;
+       }
+       VDATA_TRACE_END
+       return pVMsg;
+
+CATCH :
+       VFREE(pTemp);
+CATCH1 :
+       VFREE(szMsgBegin);
+       VFREE(pMsgRawTmp);
+       __VMsgFreeVTreeMemory(pVMsg);
+       VDATA_TRACE_END
+       return NULL;
+}
+
+/*
+ * vmsg_encode() compares the string and vMsg type, parameter value.
+ *
+ * @param       pVMsgRaw            Data which will be encoded
+ * @return      char *              Encoded result
+ */
+SLPAPI char*
+vmsg_encode( VTree *pVMsgRaw )
+{
+       VDATA_TRACE_BEGINE
+       char*           pVMsgRes = NULL;
+       char*           pTmpVMsgRes = NULL;
+       VTree*          pTmpTree = NULL;
+       VObject *       pTmpObj =  NULL;
+       char*           pTemp = NULL;
+       int                     len;
+       int                     total = 0;
+       int             cnt = 0;
+
+       for(;cnt < pVMsgRaw->pTop->valueCount;cnt++) {
+
+               if(pVMsgRaw->pTop->pszValue[cnt] == NULL)  {
+                       VDATA_TRACE("pVMsgRaw->pTop->valueCount : %d",pVMsgRaw->pTop->valueCount);
+                       VDATA_TRACE("pVMsgRaw->pTop->pszValue[%d] : %s", cnt, pVMsgRaw->pTop->pszValue[cnt]);
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+       }
+
+       pTmpTree = pVMsgRaw;
+       pTmpObj = pVMsgRaw->pTop;
+
+       while(true)
+       {
+               switch(pTmpTree->treeType)
+               {
+                       case VMESSAGE:
+                               if (pVMsgRes) {
+                                       free(pVMsgRes);
+                                       pVMsgRes = NULL;
+                               }
+
+                               if ( ( pVMsgRes = ( char * )calloc( 1, sizeof( char ) * ( total += 13 ) ) ) == NULL )
+                               {
+                                       VDATA_TRACE(  "vmsg_encode:calloc failed\n" );
+                                       VDATA_TRACE_END
+                                       return NULL;
+                               }
+                               memcpy( pVMsgRes, "BEGIN:VMSG\r\n", 13 );
+                               break;
+
+                       case VBODY:
+                               if ( ( pTmpVMsgRes = ( char * )realloc( pVMsgRes,  sizeof( char ) * ( total += 14 ) ) ) == NULL )
+                               {
+                                       VDATA_TRACE(  "vmsg_encode:realloc failed\n" );
+                                       VFREE(pVMsgRes);
+                                       VDATA_TRACE_END
+                                       return NULL;
+                               }
+
+                               pVMsgRes = pTmpVMsgRes;
+                               g_strlcat( pVMsgRes, "BEGIN:VBODY\r\n", 13);
+                               break;
+
+                       case VCARD:
+                               break;
+               }
+
+               while ( true )
+               {
+                       if(pTmpObj == NULL)
+                               break;
+
+                       if ( ( pTemp = __VMsgTypeEncode( pTmpObj, pTmpObj->property == VCARD_TYPE_TEL ? "TEL" : pszMsgTypeList[pTmpObj->property] ) ) != NULL )
+                       {
+                               if(pTmpTree->treeType == VCARD)
+                               {
+                                       char* encoded  = NULL;
+
+                                       encoded = vcard_encode(pTmpTree);
+                                       if (encoded == NULL) {
+                                               VDATA_TRACE(  "vcard_encode() failed\n");
+                                               VFREE(pTemp);
+                                               VFREE(pVMsgRes);
+                                               VDATA_TRACE_END
+                                               return NULL;
+                                       }
+
+                                       len= strlen(encoded);
+
+                                       if ( ( pTmpVMsgRes = ( char* )realloc( pVMsgRes, ( total += len+10 ) ) ) == NULL )
+                                       {
+                                               VDATA_TRACE(  "vmsg_encode():realloc failed\n");
+                                               VFREE( pTemp );
+                                               VFREE( encoded );
+                                               VFREE(pVMsgRes);
+                                               VDATA_TRACE_END
+                                               return NULL;
+                                       }
+
+                                       pVMsgRes = pTmpVMsgRes;
+                                       g_strlcat(pVMsgRes, encoded, len+10);
+                                       VDATA_TRACE("pTemp : %s", encoded);
+                                       VFREE( pTemp );
+                                       VFREE( encoded );
+                                       break;
+                               }
+                               else
+                               {
+                                       len = strlen( pTemp );
+
+                                       if ( ( pTmpVMsgRes = ( char* )realloc( pVMsgRes, ( total += len+10 ) ) ) == NULL )
+                                       {
+                                               VDATA_TRACE(  "vmsg_encode():realloc failed\n");
+                                               VFREE( pTemp );
+                                               VFREE(pVMsgRes);
+                                               VDATA_TRACE_END
+                                               return NULL;
+                                       }
+                                       pVMsgRes = pTmpVMsgRes;
+                                       g_strlcat(pVMsgRes, pTemp, len+10);
+                                       VDATA_TRACE("pTemp : %s", pTemp);
+                                       VFREE( pTemp );
+
+                                       if ( pTmpObj->pSibling != NULL )
+                                               pTmpObj = pTmpObj->pSibling;
+                                       else
+                                               break;
+                               }
+                       }
+
+
+               }
+
+               switch(pTmpTree->treeType)
+               {
+                       case VBODY:
+                               if ( ( pTmpVMsgRes = ( char * )realloc( pVMsgRes, ( total += 12 ) ) ) == NULL )
+                               {
+                                       VFREE(pVMsgRes);
+                                       VDATA_TRACE(  "vcal_encode():realloc failed\n");
+                                       return NULL;
+                               }
+
+                               pVMsgRes = pTmpVMsgRes;
+                               g_strlcat( pVMsgRes, "END:VBODY\r\n", 12);
+                               break;
+
+                       case VCARD:
+                               break;
+
+                       case VMESSAGE:
+                               break;
+
+               }
+
+               if ( pTmpTree->pNext != NULL )
+                       pTmpTree = pTmpTree->pNext;
+               else
+                       break;
+               pTmpObj = pTmpTree->pTop;
+       }
+
+       if ( ( pTmpVMsgRes = ( char * )realloc( pVMsgRes, ( total += 11 ) ) ) == NULL )
+       {
+               VDATA_TRACE(  "vmsg_encode:realloc failed\n");
+               VFREE(pVMsgRes);
+               VDATA_TRACE_END
+               return NULL;
+       }
+
+       pVMsgRes = pTmpVMsgRes;
+       g_strlcat( pVMsgRes, "END:VMSG\r\n", 11);
+       VDATA_TRACE_END
+       return pVMsgRes;
+}
+
+
+/*
+ * VIsVmsgFile() verify VMsg file.
+ *
+ * @param       pVMsgRaw           Data which will be encoded
+ * @return      int                 result (true or false)
+ */
+int
+__VIsVmsgFile(char *pMsgRaw, int mode)
+{
+       int i=0;
+       bool rtnValue = true;
+       char *pszVmsgBegin = "BEGIN:VMSG";
+
+       switch(mode)
+       {
+               case CHECK_START :
+                       for(i=0; i < 10; i++)
+               if(*pszVmsgBegin++ != *pMsgRaw++)
+                                       rtnValue = false;
+                       break;
+
+               default :
+                       rtnValue = false;
+       }
+       VDATA_TRACE_END
+       return rtnValue;
+}
+
+
+/*
+ * vMsgTypeEncoder() compares the string and vMsg type, parameter value.
+ *
+ * @param              typeObj                         Data which will be encoded
+ * @param              type                            Name of the type
+ * @return      char *              Encoded result
+ */
+char*
+__VMsgTypeEncode( VObject *pTypeObj, char *pType )
+{
+       VDATA_TRACE_BEGINE
+       int                     len;
+       char*           pTemp = NULL;
+       char*           szTypeValue = NULL;
+       int                     i;
+       int                     enc = 0;
+       char*           pEncode = NULL;
+       char*           pRes = NULL;
+       int                     total = 0;
+       int                     biLen = 0;
+
+       len = strlen( pType );
+       biLen = pTypeObj->numOfBiData;
+
+       if ( ( szTypeValue = ( char * )calloc( 1, total += ( len+1 ) ) ) == NULL )
+       {
+               VDATA_TRACE(  "__VMsgTypeEncode():calloc failed\n");
+               VDATA_TRACE_END
+               return NULL;
+       }
+       memset( szTypeValue, '\0', ( len+1 ) );
+       g_strlcat( szTypeValue, pType, len+1);
+
+       pTemp = __VMsgParamEncode( pTypeObj, &enc );
+       if ( pTemp != NULL )
+       {
+               len = strlen( pTemp );
+               if ( ( szTypeValue = ( char * )realloc( szTypeValue, ( total += len ) ) ) == NULL )
+               {
+                       VDATA_TRACE(  "__VMsgTypeEncode():realloc failed\n");
+                       VFREE( pTemp );
+                       pTemp = NULL
+                       VDATA_TRACE_END;
+                       return NULL;
+               }
+               g_strlcat( szTypeValue, pTemp, len);
+               VFREE( pTemp );
+               pTemp = NULL;
+       }
+
+       if ( ( szTypeValue = ( char * )realloc( szTypeValue, ( total += 2 ) ) ) == NULL )
+       {
+               VDATA_TRACE_END
+               return NULL;
+       }
+
+       g_strlcat( szTypeValue, ":", 2 );
+
+       len = 0;
+
+       if(strcmp(pType, pszMsgTypeList[6]) != 0)       {
+               for ( i = 0; i < pTypeObj->valueCount; i++ ) {
+
+                       if(pTypeObj->pszValue[i] != NULL)
+                       len += strlen( pTypeObj->pszValue[i] );
+               }
+       }
+       else
+               len += biLen;
+
+
+       for ( i = 0; i < pTypeObj->valueCount; i++ ) {
+
+               if ( i == 0 )
+               {
+                       if ( ( pEncode = ( char * )calloc( 1, len+20 ) ) == NULL )
+                       {
+                               VFREE(szTypeValue);
+                               VDATA_TRACE_END
+                               return NULL;
+                       }
+
+                       memset( pEncode, '\0', len+20 );
+
+                       if(strcmp(pType, pszMsgTypeList[6]) != 0)
+                       {
+                               g_strlcat( pEncode, pTypeObj->pszValue[i], 20 );
+                               _VEscape(pEncode);
+                       }
+                       else
+                               memcpy(pEncode, pTypeObj->pszValue[i], biLen);
+               }
+               else
+               {
+                       char    buf[1000];
+                       strncpy( buf, pTypeObj->pszValue[i], 999 );
+                       _VEscape( buf );
+                       g_strlcat( pEncode, ";" , len+20);
+                       g_strlcat( pEncode, buf , len+20);
+               }
+       }
+
+       if(strcmp(pType, pszMsgTypeList[6]) != 0)       {
+               if (pEncode) {
+                       g_strlcat( pEncode, "\0\0", 2);
+                       len = strlen( pEncode );
+               }
+       }
+       else {
+               len = biLen;
+       }
+
+       if ( enc & pMsgEncList[2].flag ) {
+               if((pRes = (char *)calloc(1, len * 6 + 10)) == NULL) {
+                       VFREE(pEncode);
+                       VFREE(szTypeValue);
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+               if(pEncode)
+                       _VQPEncode( pRes, pEncode );
+               VFREE(pEncode);
+                       }
+       else if(enc & pMsgEncList[1].flag )
+       {
+               if((pRes = (char *)calloc(1, (len * 8 / 6) + 48)) == NULL)
+               {
+                       VFREE(pEncode);
+                       VFREE(szTypeValue);
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+
+               memset( pRes, '\0', ( ( len * 8 / 6 ) + 48 ) );
+               _VB64Encode( pRes, pEncode, biLen );
+               VDATA_TRACE(  "Origin Size: %d, Allocated Size %d, Coverted Size: %d\n", biLen, ( len * 8 / 6 ) + 48, strlen(pRes));
+               VFREE(pEncode);
+       }
+       else
+       {
+               if((pRes = (char *)calloc(1, len+30)) == NULL)
+               {
+                       VFREE(pEncode);
+                       VFREE(szTypeValue);
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+               memset( pRes, '\0', ( len + 30 ) );
+               if(pEncode)
+               {
+                       memcpy( pRes, pEncode, len );
+                       VFREE(pEncode);
+               }
+       }
+
+       if((pRes = (char *)realloc(pRes, strlen(pRes) + 3)) == NULL)
+       {
+               VFREE(pEncode);
+               VFREE(szTypeValue);
+               VDATA_TRACE_END
+               return NULL;
+       }
+       g_strlcat( pRes, "\r\n", strlen(pRes) + 2);
+
+       len = strlen( pRes );
+
+       if ((szTypeValue = (char *)realloc(szTypeValue, (total += (len+3)))) == NULL) {
+               VFREE(pEncode);
+               VFREE(pRes);
+               VDATA_TRACE_END
+               return NULL;
+       }
+
+       g_strlcat(szTypeValue, pRes, total - 1);
+
+       if(strcmp(pType, pszMsgTypeList[6]) != 0) {
+               _VRLSpace( szTypeValue );
+               _VRTSpace( szTypeValue );
+       }
+
+       VFREE(pRes);
+
+       VDATA_TRACE_END
+       return szTypeValue;
+}
+
+/**
+ * __VMsgParamEncode() Parameter Encoding.
+ *
+ * @param              pTypeObj                Data which will be encoded
+ * @param              pEnc                            Name of the type
+ */
+char *
+__VMsgParamEncode(VObject* pTypeObj, int* pEnc)
+{
+       VDATA_TRACE_BEGINE
+       int i = 0;
+       int len = 0;
+       int sNum = 0;
+       int shift = 0;
+       bool bSupported;
+       char* szParam = NULL;
+       VParam* pTemp = NULL;
+       ValueObj*       pList = NULL;
+
+       /** Paramter initialize. */
+       pTemp = pTypeObj->pParam;
+
+       /** Momory Allocation for parameter string. */
+       if(pTemp != NULL) {
+               if ((szParam = (char*)calloc(1, len+=2)) == NULL)
+               {
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+               memset(szParam, 0x00, 2);
+       }
+
+       /** appending pamaters. */
+       while(true) {
+
+               if(pTemp == NULL) break;
+
+               bSupported = false;
+
+               /** Expand szParam string. For appending.*/
+               if((szParam = (char *)realloc(szParam, len += 15)) == NULL)
+               {
+                       VDATA_TRACE_END
+                       return NULL;
+               }
+
+               /** appending paramter name. */
+               g_strlcat( szParam, ";" , len);
+               if(pTemp->parameter != VMSG_PARAM_TYPE) {
+                       g_strlcat( szParam, pszMsgParamList[pTemp->parameter], len);
+                       g_strlcat( szParam, "=", len);
+               }
+
+               /** Set Parameter Value name. */
+               switch ( pTemp->parameter )
+               {
+                       case VMSG_PARAM_ENCODING:
+                               *pEnc = pMsgEncList[pTemp->paramValue].flag;
+                               shift = VMSG_ENCODE_PARAM_NUM;
+                               pList = pMsgEncList; bSupported = true;
+                               break;
+                       case VMSG_PARAM_TYPE:
+                               shift = VMSG_TYPE_PARAM_NUM;
+                               pList = pMsgTypeList; bSupported = true;
+                               break;
+                       case VMSG_PARAM_VALUE:
+                               shift = VMSG_VALUE_PARAM_NUM;
+                               pList = pMsgValueList; bSupported = true;
+                               break;
+                       case VMSG_PARAM_CHARSET:
+                               shift = VMSG_CHARSET_PARAM_NUM;
+                               pList = pMsgCharsetList; bSupported = true;
+                               break;
+                       default:
+                               if ( ( szParam = ( char* )realloc( szParam, 5 ) ) == NULL )
+                               {
+                                       VDATA_TRACE_END
+                                       return NULL;
+                               }
+                               g_strlcat( szParam, "NONE", strlen("NONE"));
+
+               }
+
+               /** exchage parameter value's to string.*/
+               if(bSupported == true) {
+
+                       for(i = 0, sNum = 0x00000001; i < shift; i++) {
+
+                               if(pList[pTemp->paramValue].flag & sNum) {
+                                       if((szParam = (char *)realloc(szParam, ( len += (strlen(pList[i].szName) + 2)))) == NULL)
+                                       {
+                                               VDATA_TRACE_END
+                                               return NULL;
+                                       }
+
+                                       g_strlcat( szParam, pList[i].szName, len);
+                                       g_strlcat( szParam, "; ", len);
+                               }
+
+                               sNum <<= 1;
+                       }
+               }
+
+               /** remove semicolon from tail. */
+               for(i = strlen( szParam ); i > 0 ; i--) {
+
+                       if ( szParam[i] == ' ' && szParam[i-1] == ';' ) {
+                               szParam[i-1] = '\0';
+                               break;
+                       }
+               }
+
+               if ( pTemp->pNext != NULL )
+                       pTemp = pTemp->pNext;
+               else
+                       break;
+       }
+       VDATA_TRACE_END
+       return szParam;
+}
+
+SLPAPI bool
+vmsg_free_vtree_memory(VTree * pTree)
+{
+       VDATA_TRACE_BEGINE
+       if(pTree == NULL)
+       {
+               VDATA_TRACE_END
+               return false;
+       }
+       VDATA_TRACE_END
+       return __VMsgFreeVTreeMemory(pTree);
+}
diff --git a/vobject-engine/include/VCard.h b/vobject-engine/include/VCard.h
new file mode 100755 (executable)
index 0000000..4079e2c
--- /dev/null
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef _VCARD_H
+#define _VCARD_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#include "VTypes.h"
+
+/****************************************************************************************************/
+/*                                                                                     ENUMERATION DECLARATION                                                                 */
+/****************************************************************************************************/
+
+/**
+* @enum vCardType
+* This enumeration defines the property of vcard.
+*/
+typedef enum
+{
+       VCARD_TYPE_ADR,                 /**<This is address of vcard. */
+       VCARD_TYPE_AGENT,                       /**<This is agent of vcard. */
+       VCARD_TYPE_BDAY,                        /**<This is bday of vcard. */
+       VCARD_TYPE_BEGIN,                       /**<This is begin of vcard. */
+       VCARD_TYPE_CATEGORIES,  /**<This is categories of vcard. */
+       VCARD_TYPE_CLASS,                       /**<This is class of vcard. */
+       VCARD_TYPE_EMAIL,                       /**<This is email of vcard. */
+       VCARD_TYPE_END,                 /**<This is end of vcard. */
+       VCARD_TYPE_FN,                          /**<This is FN  of vcard. */
+       VCARD_TYPE_GEO,                 /**<This is GEO of vcard. */
+       VCARD_TYPE_KEY,                 /**<This is key of vcard. */
+       VCARD_TYPE_LABEL,                       /**<This is label of vcard. */
+       VCARD_TYPE_LOGO,                        /**<This is logo of vcard. */
+       VCARD_TYPE_MAILER,              /**<This is mailer of vcar. */
+       VCARD_TYPE_N,                           /**<This is N of vcard. */
+       VCARD_TYPE_NAME,                        /**<This is name of vcard. */
+       VCARD_TYPE_NICKNAME,            /**<This is nick name of vcard. */
+       VCARD_TYPE_NOTE,                        /**<This is note of vcard. */
+       VCARD_TYPE_ORG,                 /**<This is ORG of vcard. */
+       VCARD_TYPE_PHOTO,                       /**<This is photo of vcard. */
+       VCARD_TYPE_PRODID,              /**<This is PRODID of vcard. */
+       VCARD_TYPE_PROFILE,             /**<This is profile of vcard. */
+       VCARD_TYPE_REV,                 /**<This is REV of vcard. */
+       VCARD_TYPE_ROLE,                        /**<This is ROLE of vcard. */
+       VCARD_TYPE_SORT_STRING, /**<This is sort string of vcard. */
+       VCARD_TYPE_SOUND,                       /**<This is sound of vcard. */
+       VCARD_TYPE_SOURCE,              /**<This is source of vcard. */
+       VCARD_TYPE_TEL,                 /**<This is tel of vcard. */
+       VCARD_TYPE_TITLE,                       /**<This is title of vcard. */
+       VCARD_TYPE_TZ,                          /**<This is TZ of vcard. */
+       VCARD_TYPE_UID,                 /**<This is uid of vcard. */
+       VCARD_TYPE_URL,                 /**<This is url of vcard. */
+       VCARD_TYPE_VERSION,             /**<This is version of vcard. */
+       VCARD_TYPE_XIRMCLUID            /**<This is xirmcl uid of vcard. */
+}vCardType;
+
+#define VCARD_TYPE_NUM 34              /**< number of vcard type */
+
+/**
+* @enum vCardParamName
+* This enumeration defines the name of vcard parameter.
+*/
+typedef enum
+{
+       VCARD_PARAM_CHARSET,            /**<This is charset parameter. */
+       VCARD_PARAM_CONTEXT,            /**<This is context parameter. */
+       VCARD_PARAM_ENCODING,   /**<This is encoding parameter. */
+       VCARD_PARAM_LANGUAGE,   /**<This is language parameter. */
+       VCARD_PARAM_TYPE,                       /**<This is type parameter. */
+       VCARD_PARAM_VALUE               /**<This is value parameter. */
+}vCardParamName;
+
+#define VCARD_PARAM_NUM                6       /**< number of vcard parameter */
+
+/**
+* @enum vCardParamName
+* This enumeration defines the value of encoding parameter.
+*/
+typedef enum
+{
+       VCARD_ENC_PARAM_B,                                      /**<This is b encoding parameter. */
+       VCARD_ENC_PARAM_BASE64,                         /**<This isbase64 encoding parameter. */
+       VCARD_ENC_PARAM_QUOTED_PRINTABLE,       /**<This is quoted printable encoding parameter. */
+       VCARD_ENC_PARAM_7BIT,                           /**<This is 7 bit encoding parameter. */
+       VCARD_ENC_PARAM_8BIT                                    /**<This is 8 bit encoding parameter. */
+}vCardEncVal;
+
+#define VCARD_ENCODE_PARAM_NUM 5       /**< number of vcard encoding parameter */
+
+/**
+* @enum vCardCharsetVal
+* This enumeration defines the value of charset parameter.
+*/
+typedef enum
+{
+       VCARD_CHARSET_PARAM_UTF_8,              /**<This is utf-8 charset parameter. */
+       VCARD_CHARSET_PARAM_UTF_16,             /**<This is utf-16 charset parameter. */
+       VCARD_CHARSET_PARAM_SHIFT_JIS,  /**<This is shift-jis charset parameter. */
+       VCARD_CHARSET_PARAM_ISO_8859_1  /**<This is iso-8859-1 charset parameter. */
+}vCardCharsetVal;
+
+#define VCARD_CHARSET_PARAM_NUM  4     /**< number of vcard charset parameter */
+
+/**
+* @enum vCardValVal
+* This enumeration defines the value of value parameter.
+*/
+typedef enum
+{
+       VCARD_VALUE_PARAM_BINARY,               /**<This is binary value parameter. */
+       VCARD_VALUE_PARAM_BOOLEAN,              /**<This is boolean value parameter. */
+       VCARD_VALUE_PARAM_DATE,                 /**<This is date value parameter. */
+       VCARD_VALUE_PARAM_DATE_TIME,    /**<This is date time value parameter. */
+       VCARD_VALUE_PARAM_FLOAT,                /**<This is float value parameter. */
+       VCARD_VALUE_PARAM_INTEGER,              /**<This is integer value parameter. */
+       VCARD_VALUE_PARAM_PHONE_NUMBER, /**<This is phone number value parameter. */
+       VCARD_VALUE_PARAM_TEXT,                         /**<This is text value parameter. */
+       VCARD_VALUE_PARAM_TIME,                         /**<This is time value parameter. */
+       VCARD_VALUE_PARAM_URI,                          /**<This is uri value parameter. */
+       VCARD_VALUE_PARAM_URL,                          /**<This is url value parameter. */
+       VCARD_VALUE_PARAM_UTC_OFFSET,           /**<This is utc offset value parameter. */
+       VCARD_VALUE_PARAM_VCARD                         /**<This is vcard value parameter. */
+}vCardValVal;
+
+#define VCARD_VALUE_PARAM_NUM          13              /**< number of vcard value parameter */
+
+/**
+* @enum vCardValVal
+* This enumeration defines the value of type parameter.
+*/
+typedef enum
+{
+       VCARD_TYPE_PARAM_AIFF,          /**<This is aiff type parameter. */
+       VCARD_TYPE_PARAM_BBS,           /**<This is bbs type parameter. */
+       VCARD_TYPE_PARAM_CAR,           /**<This is car type parameter. */
+       VCARD_TYPE_PARAM_CELL,          /**<This is cell type parameter. */
+       VCARD_TYPE_PARAM_DOM,           /**<This is dom type parameter. */
+       VCARD_TYPE_PARAM_WORK,          /**<This is work type parameter. */
+       VCARD_TYPE_PARAM_FAX,           /**<This is fax type parameter. */
+       VCARD_TYPE_PARAM_GIF,           /**<This is gif type parameter. */
+       VCARD_TYPE_PARAM_HOME,          /**<This is home type parameter. */
+       VCARD_TYPE_PARAM_INTL,          /**<This is intl type parameter. */
+       VCARD_TYPE_PARAM_INTERNET,      /**<This is internet type parameter. */
+       VCARD_TYPE_PARAM_ISDN,          /**<This is ISDN type parameter. */
+       VCARD_TYPE_PARAM_JPEG,          /**<This is jpeg type parameter. */
+       VCARD_TYPE_PARAM_MOBILE,                /**<This is mobile type parameter. */
+       VCARD_TYPE_PARAM_MODEM,         /**<This is mpdem type parameter. */
+       VCARD_TYPE_PARAM_MSG,           /**<This is msg type parameter. */
+       VCARD_TYPE_PARAM_PAGER,         /**<This is pager type parameter. */
+       VCARD_TYPE_PARAM_PARCEL,                /**<This is parcel type parameter. */
+       VCARD_TYPE_PARAM_PCM,           /**<This is PCM type parameter. */
+       VCARD_TYPE_PARAM_PCS,           /**<This is PCS type parameter. */
+       VCARD_TYPE_PARAM_PNG,           /**<This is png type parameter. */
+       VCARD_TYPE_PARAM_POSTAL,                /**<This is potsal type parameter. */
+       VCARD_TYPE_PARAM_PREF,          /**<This is pref type parameter. */
+       VCARD_TYPE_PARAM_VIDEO,         /**<This is video type parameter. */
+       VCARD_TYPE_PARAM_VOICE,         /**<This is voice type parameter. */
+       VCARD_TYPE_PARAM_WAVE,          /**<This is wave type parameter. */
+       VCARD_TYPE_PARAM_WBMP,          /**<This is wbmp type parameter. */
+       VCARD_TYPE_PARAM_ETC,           /**<This is etc type parameter. */
+       VCARD_TYPE_PARAM_X400,          /**<This is X400 type parameter. */
+       VCARD_TYPE_PARAM_X_IRMC_N       /**<This is X-IRMC-N type parameter. */
+}vCardTypeVal;
+
+#define VCARD_TYPE_PARAM_NUM           30              /**< number of vcard type parameter */
+
+/* VCard Encoder/Decoder status. */
+#define VCARD_TYPE_NAME_STATUS 1       /**< vcard type name status */
+#define VCARD_PARAM_NAME_STATUS        2       /**< vcard parameter name status */
+#define VCARD_TYPE_VALUE_STATUS        3       /**< vcard type value status */
+#define VCARD_PARAM_VALUE_STATUS 4     /**< vcard parameter value status */
+
+
+/*
+ * Public Function Prototypes
+ */
+
+
+/**
+* @fn VTree* vcard_decode(char* pVCardRaw);
+* This function decodes a vcard string to a vTree.
+*
+* @return      This function returns a pointer to VTree.
+* @param[in] pVCardRaw  Points to the vcard string.
+* @see vcard_encode
+*/
+SLPAPI VTree*  vcard_decode(char* pVCardRaw);
+
+/**
+* @fn char* vcard_encode(VTree* pVTree);
+* This function encodes a vTree to a string.
+*
+* @return      This function returns a pointer to a vcard string.
+* @param[in] pVTree  Points to a VTree.
+* @see vcard_decode
+*/
+SLPAPI char*   vcard_encode(VTree* pVTree);
+
+/**
+* @fn char* vcard_free_vtree_memory(VTree* pTree);
+* This function free a pTree allocated memory
+*
+* @return      This function returns value of success or fail
+* @param[in] pVTree  Points to a VTree.
+*/
+SLPAPI bool vcard_free_vtree_memory(VTree * pTree);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* _VCARD_H_ */
+
+/**
+* @}
+*/
diff --git a/vobject-engine/include/VMessage.h b/vobject-engine/include/VMessage.h
new file mode 100755 (executable)
index 0000000..ddf2f6a
--- /dev/null
@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef _VMSG_H
+#define _VMSG_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+#include "VTypes.h"
+
+/****************************************************************************************************/
+/*                                                                                     ENUMERATION DECLARATION                                                                 */
+/****************************************************************************************************/
+
+/**
+* @enum vMsgType
+* This enumeration defines the property of vcard.
+*/
+typedef enum
+{
+       VMSG_TYPE_BEGIN,
+       VMSG_TYPE_END,
+       VMSG_TYPE_TEL,
+       VMSG_TYPE_VBODY,
+       VMSG_TYPE_VCARD,
+       VMSG_TYPE_VMSG,
+       VMSG_TYPE_BODY,
+       VMSG_TYPE_SUBJECT,
+       VMSG_TYPE_MSGBOX,
+       VMSG_TYPE_STATUS,
+       VMSG_TYPE_MSGTYPE,
+       VMSG_TYPE_DATE,
+}vMsgType;
+
+#define VMSG_TYPE_NUM  12              /**< number of vcard type */
+
+/**
+* @enum vMsgParamName
+* This enumeration defines the name of vcard parameter.
+*/
+typedef enum
+{
+       VMSG_PARAM_CHARSET,             /**<This is charset parameter. */
+       VMSG_PARAM_CONTEXT,             /**<This is context parameter. */
+       VMSG_PARAM_ENCODING,    /**<This is encoding parameter. */
+       VMSG_PARAM_LANGUAGE,    /**<This is language parameter. */
+       VMSG_PARAM_TYPE,                        /**<This is type parameter. */
+       VMSG_PARAM_VALUE                /**<This is value parameter. */
+}vMsgParamName;
+
+#define VMSG_PARAM_NUM         6       /**< number of vcard parameter */
+
+/**
+* @enum vMsgParamName
+* This enumeration defines the value of encoding parameter.
+*/
+typedef enum
+{
+       VMSG_ENC_PARAM_B,                                       /**<This is b encoding parameter. */
+       VMSG_ENC_PARAM_BASE64,                          /**<This isbase64 encoding parameter. */
+       VMSG_ENC_PARAM_QUOTED_PRINTABLE,        /**<This is quoted printable encoding parameter. */
+       VMSG_ENC_PARAM_7BIT,                            /**<This is 7 bit encoding parameter. */
+       VMSG_ENC_PARAM_8BIT                                     /**<This is 8 bit encoding parameter. */
+}vMsgEncVal;
+
+#define VMSG_ENCODE_PARAM_NUM  5       /**< number of vcard encoding parameter */
+
+/**
+* @enum vMsgCharsetVal
+* This enumeration defines the value of charset parameter.
+*/
+typedef enum
+{
+       VMSG_CHARSET_PARAM_UTF_8,               /**<This is utf-8 charset parameter. */
+       VMSG_CHARSET_PARAM_UTF_16,              /**<This is utf-16 charset parameter. */
+       VMSG_CHARSET_PARAM_SHIFT_JIS,   /**<This is shift-jis charset parameter. */
+       VMSG_CHARSET_PARAM_ISO_8859_1   /**<This is iso-8859-1 charset parameter. */
+}vMsgCharsetVal;
+
+#define VMSG_CHARSET_PARAM_NUM  4      /**< number of vcard charset parameter */
+
+/**
+* @enum vMsgValVal
+* This enumeration defines the value of value parameter.
+*/
+typedef enum
+{
+       VMSG_VALUE_PARAM_BINARY,                /**<This is binary value parameter. */
+       VMSG_VALUE_PARAM_BOOLEAN,               /**<This is boolean value parameter. */
+       VMSG_VALUE_PARAM_DATE,                  /**<This is date value parameter. */
+       VMSG_VALUE_PARAM_DATE_TIME,     /**<This is date time value parameter. */
+       VMSG_VALUE_PARAM_FLOAT,         /**<This is float value parameter. */
+       VMSG_VALUE_PARAM_INTEGER,               /**<This is integer value parameter. */
+       VMSG_VALUE_PARAM_PHONE_NUMBER,  /**<This is phone number value parameter. */
+       VMSG_VALUE_PARAM_TEXT,                          /**<This is text value parameter. */
+       VMSG_VALUE_PARAM_TIME,                          /**<This is time value parameter. */
+       VMSG_VALUE_PARAM_URI,                           /**<This is uri value parameter. */
+       VMSG_VALUE_PARAM_URL,                           /**<This is url value parameter. */
+       VMSG_VALUE_PARAM_UTC_OFFSET,            /**<This is utc offset value parameter. */
+       VMSG_VALUE_PARAM_VMSG                           /**<This is vcard value parameter. */
+}vMsgValVal;
+
+#define VMSG_VALUE_PARAM_NUM           13              /**< number of vcard value parameter */
+
+/**
+* @enum vMsgValVal
+* This enumeration defines the value of type parameter.
+*/
+typedef enum
+{
+       VMSG_TYPE_PARAM_AIFF,           /**<This is aiff type parameter. */
+       VMSG_TYPE_PARAM_BBS,            /**<This is bbs type parameter. */
+       VMSG_TYPE_PARAM_CAR,            /**<This is car type parameter. */
+       VMSG_TYPE_PARAM_CELL,           /**<This is cell type parameter. */
+       VMSG_TYPE_PARAM_DOM,            /**<This is dom type parameter. */
+       VMSG_TYPE_PARAM_WORK,           /**<This is work type parameter. */
+       VMSG_TYPE_PARAM_FAX,            /**<This is fax type parameter. */
+       VMSG_TYPE_PARAM_GIF,            /**<This is gif type parameter. */
+       VMSG_TYPE_PARAM_HOME,           /**<This is home type parameter. */
+       VMSG_TYPE_PARAM_INTL,           /**<This is intl type parameter. */
+       VMSG_TYPE_PARAM_INTERNET,       /**<This is internet type parameter. */
+       VMSG_TYPE_PARAM_ISDN,           /**<This is ISDN type parameter. */
+       VMSG_TYPE_PARAM_JPEG,           /**<This is jpeg type parameter. */
+       VMSG_TYPE_PARAM_MOBILE,         /**<This is mobile type parameter. */
+       VMSG_TYPE_PARAM_MODEM,          /**<This is mpdem type parameter. */
+       VMSG_TYPE_PARAM_MSG,            /**<This is msg type parameter. */
+       VMSG_TYPE_PARAM_PAGER,          /**<This is pager type parameter. */
+       VMSG_TYPE_PARAM_PARCEL,         /**<This is parcel type parameter. */
+       VMSG_TYPE_PARAM_PCM,            /**<This is PCM type parameter. */
+       VMSG_TYPE_PARAM_PCS,            /**<This is PCS type parameter. */
+       VMSG_TYPE_PARAM_PNG,            /**<This is png type parameter. */
+       VMSG_TYPE_PARAM_POSTAL,         /**<This is potsal type parameter. */
+       VMSG_TYPE_PARAM_PREF,           /**<This is pref type parameter. */
+       VMSG_TYPE_PARAM_VIDEO,          /**<This is video type parameter. */
+       VMSG_TYPE_PARAM_VOICE,          /**<This is voice type parameter. */
+       VMSG_TYPE_PARAM_WAVE,           /**<This is wave type parameter. */
+       VMSG_TYPE_PARAM_WBMP,           /**<This is wbmp type parameter. */
+       VMSG_TYPE_PARAM_ETC,            /**<This is etc type parameter. */
+       VMSG_TYPE_PARAM_X400,           /**<This is X400 type parameter. */
+       VMSG_TYPE_PARAM_X_IRMC_N        /**<This is X-IRMC-N type parameter. */
+}vMsgTypeVal;
+
+#define VMSG_TYPE_PARAM_NUM            30              /**< number of vcard type parameter */
+
+/* VCard Encoder/Decoder status. */
+#define VMSG_TYPE_NAME_STATUS  1       /**< vcard type name status */
+#define VMSG_PARAM_NAME_STATUS 2       /**< vcard parameter name status */
+#define VMSG_TYPE_VALUE_STATUS 3       /**< vcard type value status */
+#define VMSG_PARAM_VALUE_STATUS 4      /**< vcard parameter value status */
+
+
+/*
+ * Public Function Prototypes
+ */
+
+
+/**
+* @fn VTree* vcard_decode(char* pVCardRaw);
+* This function decodes a vcard string to a vTree.
+*
+* @return      This function returns a pointer to VTree.
+* @param[in] pVCardRaw  Points to the vcard string.
+* @see vcard_encode
+*/
+SLPAPI VTree*  vmsg_decode(char* pVMsgRaw);
+
+/**
+* @fn char* vcard_encode(VTree* pVTree);
+* This function encodes a vTree to a string.
+*
+* @return      This function returns a pointer to a vcard string.
+* @param[in] pVTree  Points to a VTree.
+* @see vcard_decode
+*/
+SLPAPI char*   vmsg_encode(VTree* pVTree);
+
+/**
+* @fn char* vcard_free_vtree_memory(VTree* pTree);
+* This function free a pTree allocated memory
+*
+* @return      This function returns value of success or fail
+* @param[in] pVTree  Points to a VTree.
+*/
+SLPAPI bool vmsg_free_vtree_memory(VTree * pTree);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* _VMSG_H_ */
+
+/**
+* @}
+*/
diff --git a/vobject-engine/include/VTypes.h b/vobject-engine/include/VTypes.h
new file mode 100755 (executable)
index 0000000..655b53f
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef _VTYPES_H
+#define _VTYPES_H
+
+#include "stdio.h"
+#include "stdbool.h"
+#include "stdlib.h"
+#include "string.h"
+#include "ctype.h"
+
+#ifndef SLPAPI
+#define SLPAPI __attribute__ ((visibility("default")))
+#endif
+
+#define CR                             0x0d
+#define LF                             0x0a
+#define TAB                            0x09
+#define WSP                            0x20
+#define UNKNOWN_NAME   0x80000000
+
+#define VCARD                  0x01
+#define VCALENDAR              0x02
+#define VNOTE 0x0b
+
+#define VEVENT                 0x03
+#define VTODO                  0x04
+#define VJOURNAL               0x05
+#define VFREEBUSY              0x06
+#define VTIMEZONE              0x07
+#define VALARM                 0x08
+#define VMESSAGE               0x0c
+#define VBODY                  0X0d
+#define STANDARD               0x09
+#define DAYLIGHT               0x0a
+
+#define VTYPE_TOKEN_SEMICOLON          ';'
+#define VTYPE_TOKEN_COLON                      ':'
+#define VTYPE_TOKEN_EQUAL                      '='
+#define VTYPE_TOKEN_COMMA                      ','
+#define VTYPE_TOKEN_DOT                                '.'
+#define VTYPE_TOKEN_QUOTE                      '\''
+#define VTYPE_TOKEN_DBLQUOTE           '"'
+
+#define VDATA_VALUE_COUNT_MAX  2000
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+
+/****************************************************************************************************/
+/*                                                                      GLOBAL STRUCTURE DECLARATION                                                                   */
+/****************************************************************************************************/
+
+typedef struct _VParam VParam;
+typedef struct _VObject VObject;
+typedef struct _ValueObj ValueObj;
+typedef struct _VTree VTree;
+
+struct _VTree
+{
+       int                     treeType;
+       VObject*        pTop;
+       VObject*        pCur;
+       VTree*          pNext;
+};
+
+struct _VParam
+{
+       int                     parameter;
+       int                     paramValue;
+       VParam*         pNext;
+};
+
+struct _VObject
+{
+       int                     property;
+       VParam*         pParam;
+       int                     valueCount;
+       int                     numOfBiData;
+       char*           pszValue[VDATA_VALUE_COUNT_MAX];
+       VObject*        pSibling;
+       VObject*        pParent;
+       VObject*        pChild;
+
+       char*           pszGroupName; //VDATA_GROUPNAME_SUPPORTED
+};
+
+struct _ValueObj
+{
+       char*           szName;
+       int                     flag;
+};
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+
+#endif // _VTYPES_H
diff --git a/vobject-engine/include/vobject.h b/vobject-engine/include/vobject.h
new file mode 100755 (executable)
index 0000000..4e3cb87
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+*/
+
+#ifndef _VOBJECT_H
+#define _VOBJECT_H
+
+#include "stdio.h"
+#include "stdbool.h"
+#include "stdlib.h"
+#include "string.h"
+#include "ctype.h"
+#include <glib.h>
+#include <dlog.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+//#define ORG_ENABLE_TRACE
+#define FEATURE_SHIFT_JIS
+
+#ifdef ORG_ENABLE_TRACE
+#define USER_TAG "MSG_FW"
+#define VDATA_TRACE(fmt, arg...) \
+       do\
+       {\
+               SLOG(LOG_DEBUG, USER_TAG, "\n[calendarui] %s:%d: " fmt "\n", __FUNCTION__, __LINE__, ##arg); \
+       } while (0)
+
+
+#define VDATA_TRACE_LINE() fprintf(stderr, "\n[calendarui] %s:%d\n", __FUNCTION__, __LINE__ )
+
+#define SysRequireEx(expr, retValue) \
+       if (!(expr)) { \
+               fprintf(stderr,"INVALID_PARAM (%d lines in %s)\n", __LINE__,__FILE__); \
+               return retValue; }\
+       else {;}
+#else
+#define USER_TAG "MSG_SERVICE"
+#define VDATA_TRACE(fmt, arg...) \
+       do\
+       {\
+               SLOG(LOG_DEBUG, USER_TAG, "\n[calendarui] %s:%d: " fmt "\n", __FUNCTION__, __LINE__, ##arg); \
+       } while (0)
+
+#define VDATA_TRACE_LINE()
+#define SysRequireEx(expr, retValue)
+#endif
+
+#define VDATA_TRACE_BEGINE //VDATA_TRACE(">>>>>> start. >>>>>>"); //usleep(1000);
+#define VDATA_TRACE_END //VDATA_TRACE(">>>>>> end. >>>>>>");
+
+/****************************************************************************************************/
+/*                                                                              FUNCTION DECLARATION                                                                           */
+/****************************************************************************************************/
+int            _VIsSpace( char );
+int            _VRLSpace( char * );
+int            _VRTSpace( char * );
+int            _VUnescape( char* );
+int            _VEscape(char*);
+int            _VManySpace2Space( char * );
+int            _VB64Decode( char *, char * );
+int            _VB64Encode( char *, char *, int );
+int            _VUnfolding( char * );
+void   _VFolding( char *, char * );
+int            _VQPDecode( char * );
+int            _VQPEncode( char *, char * );
+
+void _VFoldingQP( char *result, char *contentline );
+void _VFoldingNoSpace( char *result, char *contentline );
+int _VManyCRLF2CRLF(char *pIn);
+int _VUnfoldingNoSpec( char *string, int vType );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif