Tizen 2.1 base
authorJinkun Jang <jinkun.jang@samsung.com>
Tue, 12 Mar 2013 16:48:50 +0000 (01:48 +0900)
committerJinkun Jang <jinkun.jang@samsung.com>
Tue, 12 Mar 2013 16:48:50 +0000 (01:48 +0900)
209 files changed:
AUTHORS [new file with mode: 0755]
CMakeLists.txt [new file with mode: 0755]
LICENSE.Flora [new file with mode: 0755]
NOTICE [new file with mode: 0755]
SLP_MessagingFW_PG.h [new file with mode: 0755]
config/alert_on_call.mp3 [new file with mode: 0755]
config/message_tone/Sherbet.wav [new file with mode: 0755]
config/plugin.cfg [new file with mode: 0755]
framework/CMakeLists.txt [new file with mode: 0755]
framework/deliver-handler/MsgDeliverHandler.cpp [new file with mode: 0755]
framework/main.cpp [new file with mode: 0755]
framework/plugin-manager/MsgPluginConfig.cpp [new file with mode: 0755]
framework/plugin-manager/MsgPluginManager.cpp [new file with mode: 0755]
framework/setting-handler/MsgSettingHandler.cpp [new file with mode: 0755]
framework/storage-handler/MsgStorageFilter.cpp [new file with mode: 0755]
framework/storage-handler/MsgStorageFolder.cpp [new file with mode: 0755]
framework/storage-handler/MsgStorageManager.cpp [new file with mode: 0755]
framework/storage-handler/MsgStorageMessage.cpp [new file with mode: 0755]
framework/storage-handler/MsgStorageMms.cpp [new file with mode: 0755]
framework/storage-handler/MsgStorageSim.cpp [new file with mode: 0755]
framework/storage-handler/MsgStorageUtil.cpp [new file with mode: 0755]
framework/submit-handler/MsgSubmitHandler.cpp [new file with mode: 0755]
framework/transaction-manager/MsgCmdHandlerFilter.cpp [new file with mode: 0755]
framework/transaction-manager/MsgCmdHandlerSetting.cpp [new file with mode: 0755]
framework/transaction-manager/MsgCmdHandlerStorage.cpp [new file with mode: 0755]
framework/transaction-manager/MsgCmdHandlerTransport.cpp [new file with mode: 0755]
framework/transaction-manager/MsgTransManager.cpp [new file with mode: 0755]
image/messaging_image001.png [new file with mode: 0755]
include/common/MsgCmdTypes.h [new file with mode: 0755]
include/common/MsgCppTypes.h [new file with mode: 0755]
include/common/MsgFilterTypes.h [new file with mode: 0755]
include/common/MsgInternalTypes.h [new file with mode: 0755]
include/common/MsgMmsTypes.h [new file with mode: 0755]
include/common/MsgPluginInterface.h [new file with mode: 0755]
include/common/MsgQueue.h [new file with mode: 0755]
include/common/MsgSettingTypes.h [new file with mode: 0755]
include/common/MsgStorageTypes.h [new file with mode: 0755]
include/common/MsgThread.h [new file with mode: 0755]
include/common/MsgTransportTypes.h [new file with mode: 0755]
include/common/MsgTypes.h [new file with mode: 0755]
include/framework/MsgCmdHandler.h [new file with mode: 0755]
include/framework/MsgDeliverHandler.h [new file with mode: 0755]
include/framework/MsgPluginConfig.h [new file with mode: 0755]
include/framework/MsgPluginManager.h [new file with mode: 0755]
include/framework/MsgSettingHandler.h [new file with mode: 0755]
include/framework/MsgStorageHandler.h [new file with mode: 0755]
include/framework/MsgSubmitHandler.h [new file with mode: 0755]
include/framework/MsgTransManager.h [new file with mode: 0755]
include/mapi/msg.h [new file with mode: 0755]
include/mapi/msg_private.h [new file with mode: 0755]
include/mapi/msg_storage.h [new file with mode: 0755]
include/mapi/msg_storage_types.h [new file with mode: 0755]
include/mapi/msg_transport.h [new file with mode: 0755]
include/mapi/msg_transport_types.h [new file with mode: 0755]
include/mapi/msg_types.h [new file with mode: 0755]
include/msg_helper/MsgHelper.h [new file with mode: 0755]
include/proxy/MsgHandle.h [new file with mode: 0755]
include/proxy/MsgProxyListener.h [new file with mode: 0755]
include/utils/MsgContact.h [new file with mode: 0755]
include/utils/MsgDebug.h [new file with mode: 0755]
include/utils/MsgDrmWrapper.h [new file with mode: 0755]
include/utils/MsgException.h [new file with mode: 0755]
include/utils/MsgGconfWrapper.h [new file with mode: 0755]
include/utils/MsgIpcSocket.h [new file with mode: 0755]
include/utils/MsgMemory.h [new file with mode: 0755]
include/utils/MsgMmsMessage.h [new file with mode: 0755]
include/utils/MsgMutex.h [new file with mode: 0755]
include/utils/MsgNotificationWrapper.h [new file with mode: 0755]
include/utils/MsgSoundPlayer.h [new file with mode: 0755]
include/utils/MsgSpamFilter.h [new file with mode: 0755]
include/utils/MsgSqliteWrapper.h [new file with mode: 0755]
include/utils/MsgTextConvert.h [new file with mode: 0755]
include/utils/MsgUtilFile.h [new file with mode: 0755]
include/utils/MsgUtilFunction.h [new file with mode: 0755]
include/utils/MsgUtilStorage.h [new file with mode: 0755]
include/utils/MsgVMessage.h [new file with mode: 0755]
mapi/CMakeLists.txt [new file with mode: 0755]
mapi/msg_control.cpp [new file with mode: 0755]
mapi/msg_filter.cpp [new file with mode: 0755]
mapi/msg_message.cpp [new file with mode: 0755]
mapi/msg_mms.cpp [new file with mode: 0755]
mapi/msg_setting.cpp [new file with mode: 0755]
mapi/msg_storage.cpp [new file with mode: 0755]
mapi/msg_svc.cpp [new file with mode: 0755]
mapi/msg_transport.cpp [new file with mode: 0755]
mms-plugin.manifest [new file with mode: 0755]
msg-server [new file with mode: 0755]
msg-service-tools.manifest [new file with mode: 0755]
msg-service.manifest [new file with mode: 0755]
msg-service.pc.in [new file with mode: 0755]
msg_helper/CMakeLists.txt [new file with mode: 0755]
msg_helper/MsgSensorWrapper.cpp [new file with mode: 0755]
msg_helper/MsgSoundPlayer.cpp [new file with mode: 0755]
msg_helper/main.cpp [new file with mode: 0755]
packaging/msg-service.service [new file with mode: 0644]
packaging/msg-service.spec [new file with mode: 0755]
plugin/mms_plugin/CMakeLists.txt [new file with mode: 0755]
plugin/mms_plugin/MmsPluginAvCodec.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginCodecCommon.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginConnManWrapper.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginDecode.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginDrm.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginEncode.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginEventHandler.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginHttp.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginInternal.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginMIME.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginMain.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginMessage.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginSMILValidate.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginSmil.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginStorage.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginTextConvert.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginTransport.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginUserAgent.cpp [new file with mode: 0755]
plugin/mms_plugin/MmsPluginUtil.cpp [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginAvCodec.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginCodec.h [new file with mode: 0755]
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/MmsPluginConnManWrapper.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginDebug.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginDecode.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginDrm.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginEncode.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginEventHandler.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginHttp.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginInternal.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginMIME.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginMain.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginMessage.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginSMILValidate.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginSmil.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginStorage.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginTextConvert.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginTransport.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginTypes.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginUserAgent.h [new file with mode: 0755]
plugin/mms_plugin/include/MmsPluginUtil.h [new file with mode: 0755]
plugin/sms_plugin/CMakeLists.txt [new file with mode: 0755]
plugin/sms_plugin/SmsPluginCallback.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginCbMsgHandler.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginConcatHandler.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginEventHandler.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginMain.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginParamCodec.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginSatHandler.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginSetting.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginSimMsg.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginStorage.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginTpduCodec.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginTransport.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginUAManager.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginUDCodec.cpp [new file with mode: 0755]
plugin/sms_plugin/SmsPluginWapPushHandler.cpp [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginCallback.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginCbMsgHandler.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginConcatHandler.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginEventHandler.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginMain.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginParamCodec.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginSatHandler.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginSetting.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginSimMsg.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginStorage.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginTpduCodec.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginTransport.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginTypes.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginUAManager.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginUDCodec.h [new file with mode: 0755]
plugin/sms_plugin/include/SmsPluginWapPushHandler.h [new file with mode: 0755]
proxy/CMakeLists.txt [new file with mode: 0755]
proxy/MsgHandleControl.cpp [new file with mode: 0755]
proxy/MsgHandleFilter.cpp [new file with mode: 0755]
proxy/MsgHandleSetting.cpp [new file with mode: 0755]
proxy/MsgHandleStorage.cpp [new file with mode: 0755]
proxy/MsgHandleTransport.cpp [new file with mode: 0755]
proxy/MsgProxyListener.cpp [new file with mode: 0755]
sms-plugin.manifest [new file with mode: 0755]
utils/CMakeLists.txt [new file with mode: 0755]
utils/MsgContact.cpp [new file with mode: 0755]
utils/MsgDebug.cpp [new file with mode: 0755]
utils/MsgDrmWrapper.cpp [new file with mode: 0755]
utils/MsgException.cpp [new file with mode: 0755]
utils/MsgGconfWrapper.cpp [new file with mode: 0755]
utils/MsgIpcSocket.cpp [new file with mode: 0755]
utils/MsgMemory.cpp [new file with mode: 0755]
utils/MsgMmsMessage.cpp [new file with mode: 0755]
utils/MsgMutex.cpp [new file with mode: 0755]
utils/MsgNotificationWrapper.cpp [new file with mode: 0755]
utils/MsgSoundPlayer.cpp [new file with mode: 0755]
utils/MsgSpamFilter.cpp [new file with mode: 0755]
utils/MsgSqliteWrapper.cpp [new file with mode: 0755]
utils/MsgTextConvert.cpp [new file with mode: 0755]
utils/MsgUtilFile.cpp [new file with mode: 0755]
utils/MsgUtilFunction.cpp [new file with mode: 0755]
utils/MsgUtilStorage.cpp [new file with mode: 0755]
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]
vobject-engine/test_code/CQ_VCARD.c [new file with mode: 0755]
vobject-engine/test_code/uts_vdata_vcard_decode.c [new file with mode: 0755]
vobject-engine/test_code/uts_vdata_vcard_encode.c [new file with mode: 0755]

diff --git a/AUTHORS b/AUTHORS
new file mode 100755 (executable)
index 0000000..fd16fcc
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +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
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..1c1e1c1
--- /dev/null
@@ -0,0 +1,64 @@
+
+##########################################################
+# Set Variables
+##########################################################
+SET(VOBJECT-LIB msg_vobject)
+SET(UTILS-LIB msg_utils)
+SET(PLUGIN-MANAGER-LIB msg_plugin_manager)
+SET(FW-HANDLER-LIB msg_framework_handler)
+SET(TRANS-MANAGER-LIB msg_transaction_manager)
+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)
+
+
+##########################################################
+# Add Subdirectories
+##########################################################
+ADD_SUBDIRECTORY(vobject-engine)
+ADD_SUBDIRECTORY(utils)
+ADD_SUBDIRECTORY(framework)
+ADD_SUBDIRECTORY(proxy)
+ADD_SUBDIRECTORY(mapi)
+ADD_SUBDIRECTORY(plugin/sms_plugin)
+ADD_SUBDIRECTORY(plugin/mms_plugin)
+ADD_SUBDIRECTORY(msg_helper)
+
+
+##########################################################
+# Install Header Files
+##########################################################
+SET(MAPI-HEADERS
+       ${CMAKE_CURRENT_SOURCE_DIR}/include/mapi/msg.h
+       ${CMAKE_CURRENT_SOURCE_DIR}/include/mapi/msg_types.h
+       ${CMAKE_CURRENT_SOURCE_DIR}/include/mapi/msg_storage.h
+       ${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)
+
+
+##########################################################
+# 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/)
+
+CONFIGURE_FILE(msg-service.pc.in msg-service.pc @ONLY)
+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)
+
+INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/packaging/msg-service.service DESTINATION /usr/lib/systemd/user)
+
+# LICENSE file
+INSTALL(FILES ${CMAKE_SOURCE_DIR}/LICENSE.Flora DESTINATION /usr/share/license/msg-service)
diff --git a/LICENSE.Flora b/LICENSE.Flora
new file mode 100755 (executable)
index 0000000..ce5b4df
--- /dev/null
@@ -0,0 +1,77 @@
+Copyright (c) 2012 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+
+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/NOTICE b/NOTICE
new file mode 100755 (executable)
index 0000000..4f7ab4a
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,4 @@
+Copyright (c) 2013 Samsung Electronics Co., Ltd. All rights reserved.
+Except as noted, this software is licensed under Flora License, Version 1.
+Please, see the LICENSE.Flora file for Flora License, Version 1 terms and conditions.
+
diff --git a/SLP_MessagingFW_PG.h b/SLP_MessagingFW_PG.h
new file mode 100755 (executable)
index 0000000..ecff3d7
--- /dev/null
@@ -0,0 +1,869 @@
+/**
+ *
+ * @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
new file mode 100755 (executable)
index 0000000..c7c77d1
Binary files /dev/null and b/config/alert_on_call.mp3 differ
diff --git a/config/message_tone/Sherbet.wav b/config/message_tone/Sherbet.wav
new file mode 100755 (executable)
index 0000000..3d352e4
Binary files /dev/null and b/config/message_tone/Sherbet.wav differ
diff --git a/config/plugin.cfg b/config/plugin.cfg
new file mode 100755 (executable)
index 0000000..498d80d
--- /dev/null
@@ -0,0 +1,7 @@
+[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/framework/CMakeLists.txt b/framework/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..15756dc
--- /dev/null
@@ -0,0 +1,159 @@
+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 Plugin Manager
+##########################################################
+
+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/common
+       ${CMAKE_SOURCE_DIR}/include/framework
+       ${CMAKE_SOURCE_DIR}/include/utils
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(plugin_manager_pkgs REQUIRED glib-2.0 dlog vconf)
+
+FOREACH(flag ${plugin_manager_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_LIBRARY(${PLUGIN-MANAGER-LIB} SHARED ${PLUGIN-MANAGER-SRCS})
+TARGET_LINK_LIBRARIES(${PLUGIN-MANAGER-LIB} ${plugin_manager_pkgs_LDFLAGS} ${UTILS-LIB} dl)
+
+INSTALL(TARGETS ${PLUGIN-MANAGER-LIB} LIBRARY DESTINATION lib)
+
+##########################################################
+# Define Messaging Framework Handler
+##########################################################
+
+SET(FW-HANDLER-SRCS
+       ${CMAKE_SOURCE_DIR}/framework/setting-handler/MsgSettingHandler.cpp
+       ${CMAKE_SOURCE_DIR}/framework/storage-handler/MsgStorageManager.cpp
+       ${CMAKE_SOURCE_DIR}/framework/storage-handler/MsgStorageMessage.cpp
+       ${CMAKE_SOURCE_DIR}/framework/storage-handler/MsgStorageMms.cpp
+       ${CMAKE_SOURCE_DIR}/framework/storage-handler/MsgStorageFolder.cpp
+       ${CMAKE_SOURCE_DIR}/framework/storage-handler/MsgStorageFilter.cpp
+       ${CMAKE_SOURCE_DIR}/framework/storage-handler/MsgStorageSim.cpp
+       ${CMAKE_SOURCE_DIR}/framework/storage-handler/MsgStorageUtil.cpp
+       ${CMAKE_SOURCE_DIR}/framework/submit-handler/MsgSubmitHandler.cpp
+       ${CMAKE_SOURCE_DIR}/framework/deliver-handler/MsgDeliverHandler.cpp
+)
+
+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}/vobject-engine/include      
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(fw_handler_pkgs REQUIRED glib-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}")
+
+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})
+
+INSTALL(TARGETS ${FW-HANDLER-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
+
+##########################################################
+# Define Transaction Manager
+##########################################################
+
+SET(TRANS-MANAGER-SRCS
+       ${CMAKE_SOURCE_DIR}/framework/transaction-manager/MsgCmdHandlerSetting.cpp
+       ${CMAKE_SOURCE_DIR}/framework/transaction-manager/MsgCmdHandlerStorage.cpp
+       ${CMAKE_SOURCE_DIR}/framework/transaction-manager/MsgCmdHandlerTransport.cpp
+       ${CMAKE_SOURCE_DIR}/framework/transaction-manager/MsgCmdHandlerFilter.cpp
+       ${CMAKE_SOURCE_DIR}/framework/transaction-manager/MsgTransManager.cpp
+)
+
+INCLUDE_DIRECTORIES(
+    ${CMAKE_SOURCE_DIR}/include/mapi
+       ${CMAKE_SOURCE_DIR}/include/common
+       ${CMAKE_SOURCE_DIR}/include/framework
+       ${CMAKE_SOURCE_DIR}/include/utils
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(trans_manager_pkgs REQUIRED glib-2.0 security-server dlog vconf)
+
+FOREACH(flag ${trans_manager_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_LIBRARY(${TRANS-MANAGER-LIB} SHARED ${TRANS-MANAGER-SRCS})
+TARGET_LINK_LIBRARIES(${TRANS-MANAGER-LIB} ${trans_manager_pkgs_LDFLAGS} ${UTILS-LIB} ${FW-HANDLER-LIB})
+
+INSTALL(TARGETS ${TRANS-MANAGER-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
+
+##########################################################
+# Define Execute File
+##########################################################
+
+SET(MAIN-SRCS
+       ${CMAKE_SOURCE_DIR}/framework/main.cpp
+)
+
+INCLUDE_DIRECTORIES(
+    ${CMAKE_SOURCE_DIR}/include/mapi
+       ${CMAKE_SOURCE_DIR}/include/common
+       ${CMAKE_SOURCE_DIR}/include/framework
+       ${CMAKE_SOURCE_DIR}/include/utils
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(main_pkgs REQUIRED glib-2.0 dbus-glib-1 dlog vconf)
+
+FOREACH(flag ${main_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(${PROJECT_NAME} ${MAIN-SRCS})
+TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${main_pkgs_LDFLAGS} ${UTILS-LIB} ${PLUGIN-MANAGER-LIB} ${TRANS-MANAGER-LIB} ${FW-HANDLER-LIB})
+
+INSTALL(TARGETS ${PROJECT_NAME} DESTINATION bin)
+
diff --git a/framework/deliver-handler/MsgDeliverHandler.cpp b/framework/deliver-handler/MsgDeliverHandler.cpp
new file mode 100755 (executable)
index 0000000..c7ed741
--- /dev/null
@@ -0,0 +1,384 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgDebug.h"
+#include "MsgUtilFile.h"
+#include "MsgContact.h"
+#include "MsgUtilStorage.h"
+#include "MsgGconfWrapper.h"
+#include "MsgSoundPlayer.h"
+#include "MsgSpamFilter.h"
+#include "MsgPluginManager.h"
+#include "MsgStorageHandler.h"
+#include "MsgDeliverHandler.h"
+#include "MsgNotificationWrapper.h"
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+extern MsgDbHandler dbHandle;
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+msg_error_t MsgHandleMmsConfIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_request_id_t reqID)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       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
+               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)
+                       pMsgInfo->msgType.subType = MSG_NOTIFICATIONIND_MMS;
+
+               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 ###");
+                       //Update Mms Message to MMS Plugin DB
+
+                       // MMS Received Ind Process Func
+                       MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(pMsgInfo->msgType.mainType);
+
+                       //Contents of msg Data was removed and replaced to retrievedFilePath
+                       // NOTICE:: now it was moved to handleEvent in MsgListnerThread
+                       err = plg->updateMessage(pMsgInfo, NULL, NULL);
+                       if (err != MSG_SUCCESS)
+                               return MSG_ERR_STORAGE_ERROR;
+               }
+
+               MSG_DEBUG(" ######################### MESSAGE UPDATE COMPLETED!!! ######################");
+
+               bool readStatus = false;
+
+               MsgStoGetReadStatus(pMsgInfo->msgId, &readStatus);
+               MSG_DEBUG("### readStatus = %d ###", readStatus);
+
+               //Update Read Status to Unread beacaus 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 (subType == MSG_RETRIEVE_AUTOCONF_MMS) {
+                       // play message-tone when MMS retrieved
+                       MsgSoundPlayStart(false);
+
+                       // add phone log
+                       MSG_DEBUG("Enter MsgAddPhoneLog() for mms message.");
+                       MsgAddPhoneLog(pMsgInfo);
+
+                       MsgInsertNoti(pMsgInfo);
+               }  else if (subType == MSG_RETRIEVE_MANUALCONF_MMS) {
+                       if (pMsgInfo->networkStatus == MSG_NETWORK_RETRIEVE_SUCCESS) {
+                               MSG_DEBUG("Manual success");
+                               MsgInsertTicker("Message Retrieved", MESSAGE_RETRIEVED);
+                       } else if (pMsgInfo->networkStatus == MSG_NETWORK_RETRIEVE_FAIL) {
+                               MSG_DEBUG("Manual failed");
+                               MsgInsertTicker("Retrieving message failed", RETRIEVING_MESSAGE_FAILED);
+                       }
+               }
+       }
+       else if (pMsgInfo->msgType.subType == MSG_SENDREQ_MMS || pMsgInfo->msgType.subType == MSG_SENDCONF_MMS)
+       {
+               MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(pMsgInfo->msgType.mainType);
+               // change subType for storage update
+               pMsgInfo->msgType.subType = MSG_SENDCONF_MMS;
+
+               err = MsgStoUpdateMMSMessage(pMsgInfo);
+               if (err == MSG_SUCCESS)
+                       MSG_DEBUG("Command Handle Success : MsgStoUpdateMMSMessage()");
+
+               err = plg->updateMessage(pMsgInfo, NULL, NULL);
+               if (err != MSG_SUCCESS)
+                       return MSG_ERR_STORAGE_ERROR;
+
+               MSG_DEBUG("pMsg->networkStatus : %d", pMsgInfo->networkStatus);
+               err = MsgStoUpdateNetworkStatus(&dbHandle, pMsgInfo, pMsgInfo->networkStatus);
+               if (err != MSG_SUCCESS)
+                       return MSG_ERR_STORAGE_ERROR;
+
+               if (pMsgInfo->networkStatus == MSG_NETWORK_SEND_SUCCESS)
+               {
+                       err = MsgStoMoveMessageToFolder(pMsgInfo->msgId, MSG_SENTBOX_ID);
+                       if (err != MSG_SUCCESS)
+                               return MSG_ERR_STORAGE_ERROR;
+               }
+
+               // Get subject and text
+               MsgStoGetText(pMsgInfo->msgId, pMsgInfo->subject, pMsgInfo->msgText);
+
+               MSG_DEBUG(" ######################### MESSAGE UPDATE COMPLETED!!! ######################");
+       }
+       return err;
+}
+
+msg_error_t MsgHandleIncomingMsg(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       if (pMsgInfo->msgType.mainType == MSG_SMS_TYPE) {
+
+               bool bOnlyNoti = false;
+
+               err = MsgHandleSMS(pMsgInfo, pSendNoti, &bOnlyNoti);
+
+               if (err == MSG_SUCCESS&& ((*pSendNoti)||bOnlyNoti)) {
+                       MsgSoundPlayStart(false);
+                       if (*pSendNoti == true) {
+                               int smsCnt = 0, mmsCnt = 0;
+
+                               smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
+                               mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
+
+                               MsgSettingHandleNewMsg(smsCnt, mmsCnt);
+                               MsgInsertNoti(pMsgInfo);
+                       } else if (bOnlyNoti == true) {
+                               MsgInsertNoti(pMsgInfo);
+                       }
+               }
+       }
+       else if (pMsgInfo->msgType.mainType == MSG_MMS_TYPE)
+       {
+               err = MsgHandleMMS(pMsgInfo, pSendNoti);
+       }
+
+       //Add Phone Log Data
+       if ((err == MSG_SUCCESS) &&
+               (pMsgInfo->folderId == MSG_INBOX_ID || pMsgInfo->folderId == MSG_SPAMBOX_ID) &&
+               (pMsgInfo->msgType.mainType == MSG_SMS_TYPE) &&
+               (pMsgInfo->msgType.subType != MSG_WAP_SL_SMS)) {
+
+               MSG_DEBUG("Enter MsgAddPhoneLog() : pMsg->folderId [%d]", pMsgInfo->folderId);
+
+               MsgAddPhoneLog(pMsgInfo);
+       }
+
+       MSG_END();
+
+       return err;
+}
+
+
+msg_error_t MsgHandleSMS(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti, bool *bOnlyNoti)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (pMsgInfo->msgPort.valid == true) {
+                       *pSendNoti = false;
+                       *bOnlyNoti = false;
+                       return MSG_SUCCESS;
+       }
+       if (pMsgInfo->msgType.subType == MSG_NORMAL_SMS) {
+               if (MsgCheckFilter(&dbHandle, pMsgInfo) == true) {
+                       // Move to SpamBox
+                       err = MsgStoMoveMessageToFolder(pMsgInfo->msgId, MSG_SPAMBOX_ID);
+
+                       if (err != MSG_SUCCESS) {
+                               MSG_DEBUG("MsgStoMoveMessageToFolder() Error : [%d]", err);
+                       } else {
+                               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.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;
+
+               switch (pMsgInfo->msgType.subType) {
+                       case MSG_WAP_SL_SMS:
+                       {
+                               *pSendNoti = false;
+
+                               if (serviceType == MSG_PUSH_SERVICE_ALWAYS) {
+                                       if (service_create(&svc_handle) < 0) {
+                                               MSG_DEBUG("Fail to create service handle");
+                                               break;
+                                       }
+                                       if (!svc_handle) {
+                                               MSG_DEBUG("Service handle is NULL");
+                                               break;
+                                       }
+                                       if (service_set_operation(svc_handle, SERVICE_OPERATION_VIEW) < 0) {
+                                               MSG_DEBUG("Fail to create service handle");
+                                               service_destroy(svc_handle);
+                                               break;
+                                       }
+                                       if (service_set_uri(svc_handle, pMsgInfo->msgText) < 0) {
+                                               MSG_DEBUG("Fail to set uri");
+                                               service_destroy(svc_handle);
+                                               break;
+                                       }
+                                       if (service_set_package(svc_handle, MSG_SVC_PKG_NAME_BROWSER) < 0) {
+                                               MSG_DEBUG("Fail to set package");
+                                               service_destroy(svc_handle);
+                                               break;
+                                       }
+                                       if (service_send_launch_request(svc_handle, NULL, NULL) < 0) {
+                                               MSG_DEBUG("Fail to launch browser");
+                                               service_destroy(svc_handle);
+                                               break;
+                                       }
+
+                                       service_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, "/usr/apps/org.tizen.message/bin/message-dialog -m PUSH_MSG_ALWAYS_ASK -u %s &", pMsgInfo->msgText);
+
+                                       system(urlString);
+                               }
+
+                       }
+                       break;
+
+                       case MSG_WAP_SI_SMS:
+                               *pSendNoti = true;
+                               break;
+                       case MSG_WAP_CO_SMS:
+                               *pSendNoti = false;
+                               break;
+               }
+       } else if (pMsgInfo->msgType.subType == MSG_STATUS_REPORT_SMS) {
+               *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;
+               }
+       } 
+
+
+       return err;
+}
+
+
+msg_error_t MsgHandleMMS(MSG_MESSAGE_INFO_S *pMsgInfo,  bool *pSendNoti)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       MSG_REQUEST_INFO_S request = {0};
+       bool bReject = false;
+       bool bFiltered = false;
+
+       // MMS Received Ind Process Func
+       MSG_MAIN_TYPE_T msgMainType = pMsgInfo->msgType.mainType;
+       MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(msgMainType);
+
+       // Need to process m-delivery-ind, m-notification-ind, m-read-orig-ind
+       err = plg->processReceivedInd(pMsgInfo, &request, &bReject);
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Process Message Success : processReceivedInd(), btextsms %d", pMsgInfo->bTextSms);
+       } else {
+               MSG_DEBUG("Process Message Fail : processReceivedInd()");
+               return err;
+       }
+
+       // Add into DB
+       if ((pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS) && bReject == false) {
+               bFiltered = MsgCheckFilter(&dbHandle, pMsgInfo);
+
+               if (bFiltered == true) {
+                       pMsgInfo->networkStatus = MSG_NETWORK_RETRIEVE_FAIL;
+                       *pSendNoti = false;
+               }
+
+               err = MsgStoAddMessage(pMsgInfo, NULL);
+
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgStoAddMessage() Error: [%d]", err);
+                       return err;
+               }
+       } else if (pMsgInfo->msgType.subType == MSG_READORGIND_MMS || pMsgInfo->msgType.subType == MSG_DELIVERYIND_MMS) {
+               if (MsgInsertMmsReportToNoti(&dbHandle, pMsgInfo) == MSG_SUCCESS) {
+                       MsgSoundPlayStart(false);
+                       *pSendNoti = false;
+               }
+       }
+
+       //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(false);
+
+                       int smsCnt = 0;
+                       int mmsCnt = 0;
+
+                       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
+                       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
+
+                       MsgSettingHandleNewMsg(smsCnt, mmsCnt);
+                       MsgInsertNoti(pMsgInfo);
+               }
+
+               request.msgInfo.msgId = pMsgInfo->msgId;
+
+               MSG_DEBUG("-=====================[[[ %s ]]]] =========================", pMsgInfo->msgData);
+               err = plg->submitReq(&request);
+
+               if (err == MSG_SUCCESS) {
+                       MSG_DEBUG("Process Message Success : processReceivedInd()");
+               } else {
+                       MSG_DEBUG("Process Message Fail : processReceivedInd()");
+               }
+       }
+
+       return err;
+}
+
diff --git a/framework/main.cpp b/framework/main.cpp
new file mode 100755 (executable)
index 0000000..b7f5340
--- /dev/null
@@ -0,0 +1,491 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 FILES
+==================================================================================================*/
+#include "MsgDebug.h"
+#include "MsgException.h"
+#include "MsgContact.h"
+#include "MsgMemory.h"
+#include "MsgGconfWrapper.h"
+#include "MsgPluginManager.h"
+#include "MsgSettingHandler.h"
+#include "MsgStorageHandler.h"
+#include "MsgSubmitHandler.h"
+#include "MsgDeliverHandler.h"
+#include "MsgTransManager.h"
+#include "MsgStorageTypes.h"
+#include "MsgSoundPlayer.h"
+#include "MsgCmdHandler.h"
+#include "MsgUtilStorage.h"
+#include "MsgNotificationWrapper.h"
+
+#include <errno.h>
+#include <glib.h>
+#include <dbus/dbus-glib.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)
+       {
+               if (errno == EEXIST)
+               {
+                       MSG_DEBUG("The %s already exists", MSG_DATA_ROOT_PATH);
+               }
+               else
+               {
+                       MSG_DEBUG("Error while mkdir %s", MSG_DATA_ROOT_PATH);
+                       return MSG_ERR_DB_MAKE_DIR;
+               }
+       }
+
+       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);
+               }
+               else
+               {
+                       MSG_DEBUG("Error while mkdir %s", MSG_SMIL_FILE_PATH);
+                       return MSG_ERR_DB_MAKE_DIR;
+               }
+       }
+
+       if (mkdir(MSG_DATA_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0)
+       {
+               if (errno == EEXIST)
+               {
+                       MSG_DEBUG("The %s already exists", MSG_DATA_PATH);
+               }
+               else
+               {
+                       MSG_DEBUG("Error while mkdir %s", MSG_DATA_PATH);
+                       return MSG_ERR_DB_MAKE_DIR;
+               }
+       }
+
+       if (mkdir(MSG_THUMBNAIL_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
+               if (errno == EEXIST) {
+                       MSG_DEBUG("The %s already exists.", MSG_THUMBNAIL_PATH);
+               } else {
+                       MSG_DEBUG(" Error while mkdir %s", MSG_THUMBNAIL_PATH);
+                       return MSG_ERR_DB_MAKE_DIR;
+               }
+       }
+
+       if (mkdir(MSG_IPC_DATA_PATH, S_IRWXU ) < 0)
+       {
+               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);
+               }
+               else
+               {
+                       MSG_DEBUG("Error while mkdir %s", MSG_IPC_DATA_PATH);
+                       return MSG_ERR_DB_MAKE_DIR;
+               }
+       }
+
+       if(chmod( 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);
+       }
+       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 (bEnabled == false)
+       {
+               MSG_DEBUG("Mobile Tracker Option [%d]", bEnabled);
+               return;
+       }
+       // to wait modem init
+       // temporary code.
+       else
+       {
+               MSG_DEBUG("Waiting for modem ready, 22 sec.");
+               sleep(22);
+       }
+
+       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 (msgText == NULL) {
+                       MSG_DEBUG("msgText is NULL.");
+                       return;
+               }
+       }
+
+       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");
+               free(msgText);
+               msgText = NULL;
+               return;
+       }
+
+       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, "|");
+
+       MSG_MAIN_TYPE_T mainType = MSG_SMS_TYPE;
+       MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(mainType);
+
+       msg_error_t err = MSG_SUCCESS;
+
+       while (token)
+       {
+               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;
+                       }
+               }
+
+               token = strtok(NULL, "|");
+       }
+
+       if (msgText) {
+               free(msgText);
+               msgText = NULL;
+       }
+
+       if (orgRecipientList) {
+               free(orgRecipientList);
+               orgRecipientList = NULL;
+       }
+
+
+       MSG_END();
+
+       return;
+}
+
+
+void* StartMsgServer(void*)
+{
+
+       MsgOpenContactSvc();
+
+       try
+       {
+               MsgTransactionManager::instance()->run();
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+       }
+       catch (exception& e)
+       {
+               MSG_FATAL("%s", e.what());
+       }
+
+       if (g_main_loop_is_running(mainloop))
+               g_main_loop_quit(mainloop);
+
+       MsgCloseContactSvc();
+
+       return (void*)0;
+}
+
+
+void* InitMsgServer(void*)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       MsgOpenContactSvc();
+
+       try
+       {
+               // plugin manager initialize
+               MsgPluginManager::instance()->initialize();
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+       }
+       catch (exception& e)
+       {
+               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
+       if(MsgSettingSetBool(VCONFKEY_MSG_SERVER_READY, true) != MSG_SUCCESS)
+               MSG_DEBUG("MsgSettingSetBool FAIL : VCONFKEY_MSG_SERVER_READY");
+       MSG_DEBUG("### VCONFKEY_MSG_SERVER_READY ###");
+
+       if (plg == NULL) {
+               MSG_DEBUG("No plugin for %d type", mainType);
+
+               MsgReleaseMemory();
+               return (void*)0;
+       }
+
+       // Clear and reset notification
+       MsgCleanAndResetNoti();
+
+       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();
+
+       // Register Callback to get the change of contact
+       MsgInitContactSvc(&MsgContactChangedCallback);
+
+       MsgSoundInitRepeatAlarm();
+
+       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 );
+
+////////////////////////////////////
+
+
+       MSG_DEBUG("===========START MESSAGING FRAMEWORK==========");
+
+       // Reset message server ready flag
+       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();
+
+       pthread_t startThreadId;
+
+       // start transaction manager
+       if (pthread_create(&startThreadId, NULL, StartMsgServer, NULL) != 0)
+       {
+               MSG_DEBUG("StartMsgServer not invoked: %s", strerror(errno));
+               return -1;
+       }
+
+       MsgTransactionManager::instance()->getTMStatus();
+
+       mainloop = g_main_loop_new(NULL, FALSE);
+
+       g_type_init();
+
+       g_idle_add(InitThreadFunc, NULL);
+
+       if (mainloop != NULL)
+       {
+               MSG_DEBUG("Start Messaging Framework!!!");
+
+               // Run GMainLoop
+               g_main_loop_run(mainloop);
+       }
+       else
+       {
+               MSG_DEBUG("Fail to start Messaging Framework!!!");
+       }
+
+       // Remove vconf CB
+       MsgSettingRemoveVconfCB();
+
+       // Close Contact Sevice
+       MsgCloseContactSvc();
+
+       // Disconnect to DB
+       MsgStoDisconnectDB();
+
+       return 0;
+}
+
diff --git a/framework/plugin-manager/MsgPluginConfig.cpp b/framework/plugin-manager/MsgPluginConfig.cpp
new file mode 100755 (executable)
index 0000000..2a7d842
--- /dev/null
@@ -0,0 +1,237 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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());
+}
+
diff --git a/framework/plugin-manager/MsgPluginManager.cpp b/framework/plugin-manager/MsgPluginManager.cpp
new file mode 100755 (executable)
index 0000000..29353c4
--- /dev/null
@@ -0,0 +1,822 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <dlfcn.h>
+
+#include "MsgDebug.h"
+#include "MsgUtilFile.h"
+#include "MsgException.h"
+#include "MsgIpcSocket.h"
+#include "MsgCmdTypes.h"
+#include "MsgGconfWrapper.h"
+#include "MsgPluginManager.h"
+#include "MsgMmsTypes.h"
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+void MsgSentStatusListener(MSG_SENT_STATUS_S *pSentStatus)
+{
+       MSG_BEGIN();
+
+       MSG_DEBUG("SENT STATUS %d, %d", pSentStatus->reqId, pSentStatus->status);
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       client.connect(MSG_SOCKET_PATH);
+
+       // composing command
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_SENT_STATUS_S); // cmd type, MSG_SENT_STATUS
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_PLG_SENT_STATUS_CNF;
+
+       memset(pCmd->cmdCookie, 0x00, MAX_COOKIE_LEN);
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pSentStatus, sizeof(MSG_SENT_STATUS_S));
+
+       // Send Command to Transaction Manager
+       client.write(cmdBuf, cmdSize);
+
+       // Receive result from Transaction Manager
+       MSG_DEBUG("Waiting result for SENT STATUS");
+
+       char *temp = NULL;
+       AutoPtr<char> wrap(&temp);
+       unsigned int len;
+       client.read(&temp, &len);
+
+       // close connection to msgfw daemon
+       client.close();
+
+       MSG_END();
+}
+
+
+void MsgStorageChangeListener(msg_storage_change_type_t storageChangeType, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       MSG_DEBUG("StorageChangeType : [%d], msg ID : [%d]", storageChangeType, pMsgInfo->msgId);
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       client.connect(MSG_SOCKET_PATH);
+
+       // composing command
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_MESSAGE_INFO_S) + sizeof(msg_storage_change_type_t);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_PLG_STORAGE_CHANGE_IND;
+
+       memset(pCmd->cmdCookie, 0x00, MAX_COOKIE_LEN);
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_MESSAGE_INFO_S)), &storageChangeType, sizeof(msg_storage_change_type_t));
+
+       // Send Command to Transaction Manager
+       client.write(cmdBuf, cmdSize);
+
+       // Receive result from Transaction Manager
+       MSG_DEBUG("Waiting result for STORAGE CHANGE");
+
+       char *temp = NULL;
+       AutoPtr<char> wrap(&temp);
+       unsigned int len;
+       client.read(&temp, &len);
+
+       // close connection to msgfw daemon
+       client.close();
+
+       MSG_END();
+}
+
+
+msg_error_t MsgIncomingMessageListener(MSG_MESSAGE_INFO_S *pMsg)
+{
+       MSG_BEGIN();
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       client.connect(MSG_SOCKET_PATH);
+
+       // Check Invalid Message Structure
+       if (pMsg == NULL)
+       {
+               MSG_DEBUG("pMsg is NULL !!");
+
+               return MSG_ERR_NULL_MESSAGE;
+       }
+
+       // composing command
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_MESSAGE_INFO_S); // 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_INCOMING_MSG_IND;
+
+       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));
+
+       // Send Command to Messaging FW
+       client.write(cmdBuf, cmdSize);
+
+       char* retBuf = NULL;
+       AutoPtr<char> wrap(&retBuf);
+       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_MSG_IND)
+               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 MsgIncomingSyncMLMessageListener(MSG_SYNCML_MESSAGE_DATA_S *pSyncMLData)
+{
+       MSG_BEGIN();
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       client.connect(MSG_SOCKET_PATH);
+
+       // composing command
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_SYNCML_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_SYNCML_IND;
+
+       memset(pCmd->cmdCookie, 0x00, MAX_COOKIE_LEN);
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pSyncMLData, sizeof(MSG_SYNCML_MESSAGE_DATA_S));
+
+       // Send Command to Messaging FW
+       client.write(cmdBuf, cmdSize);
+
+       // Receive result from Transaction Manager
+       char* retBuf = NULL;
+       AutoPtr<char> wrap(&retBuf);
+       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_SYNCML_MSG_IND)
+               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;
+       client.connect(MSG_SOCKET_PATH);
+
+       // 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;
+       AutoPtr<char> wrap(&retBuf);
+       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)
+               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_BEGIN();
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       client.connect(MSG_SOCKET_PATH);
+
+       // Check Invalid Message Structure
+       if (pCbMsg == NULL)
+       {
+               MSG_DEBUG("pMsg is NULL !!");
+
+               return MSG_ERR_NULL_MESSAGE;
+       }
+
+       // composing command
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_CB_MSG_S); // 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));
+
+       // Send Command to Messaging FW
+       client.write(cmdBuf, cmdSize);
+
+       char* retBuf = NULL;
+       AutoPtr<char> wrap(&retBuf);
+       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)
+               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 MsgIncomingLBSMessageListener(MSG_LBS_MESSAGE_DATA_S *pLBSData)
+{
+       MSG_BEGIN();
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       client.connect(MSG_SOCKET_PATH);
+
+       // composing command
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_LBS_MESSAGE_DATA_S); // cmd type, MSG_LBS_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_LBS_IND;
+
+       memset(pCmd->cmdCookie, 0x00, MAX_COOKIE_LEN);
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pLBSData, sizeof(MSG_LBS_MESSAGE_DATA_S));
+
+       // Send Command to Messaging FW
+       client.write(cmdBuf, cmdSize);
+
+       // Receive result from Transaction Manager
+       char* retBuf = NULL;
+       AutoPtr<char> wrap(&retBuf);
+       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_LBS_MSG_IND)
+               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 MsgInitSimBySatListener()
+{
+       MSG_BEGIN();
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       client.connect(MSG_SOCKET_PATH);
+
+       // 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_INIT_SIM_BY_SAT;
+
+       // Send Command to Transaction Manager
+       client.write(cmdBuf, cmdSize);
+
+       // Receive result from Transaction Manager
+       char* retBuf = NULL;
+       AutoPtr<char> wrap(&retBuf);
+       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_INIT_SIM_BY_SAT)
+               THROW(MsgException::INVALID_RESULT, "Wrong result(evt type %d : %s) received", pEvent->eventType, MsgDbgEvtStr(pEvent->eventType));
+
+       MSG_END();
+
+       return (pEvent->result);
+}
+
+/* MMS_Incoming_listener */
+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);
+
+       // establish connection to msgfw daemon
+       MsgIpcClientSocket client;
+       client.connect(MSG_SOCKET_PATH);
+
+       // 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
+       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_MMS_CONF; // cmd type
+
+       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));
+
+       // Send Command to Messaging FW
+       client.write(cmdBuf, cmdSize);
+
+       // Receive result from Transaction Manager
+       char *retBuf = NULL;
+       AutoPtr<char> wrap(&retBuf);
+       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
+       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));
+
+       MSG_END();
+
+       return (pEvent->result);
+}
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgPlugin - Member Functions
+==================================================================================================*/
+MsgPlugin::MsgPlugin(MSG_MAIN_TYPE_T mainType, const char *libPath): mSupportedMsg(mainType)
+{
+       MSG_DEBUG("msg type : [%d] library path : [%s]", mainType, libPath);
+
+       bzero(&mPlgHandler, sizeof(mPlgHandler));
+
+       if (libPath == NULL)
+               THROW(MsgException::INVALID_PARAM, "libPath NULL");
+
+       mLibHandler = NULL;
+
+       mLibHandler = dlopen(libPath, RTLD_NOW);
+
+       if (!mLibHandler)
+               THROW(MsgException::PLUGIN_ERROR, "ERROR dlopen library : [%s] [%s]", libPath, dlerror());
+
+       // Clear Error
+       dlerror();
+
+       // assign the c function pointers
+       msg_error_t(*pFunc)(MSG_PLUGIN_HANDLER_S*) = NULL;
+
+       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());
+
+       if ((*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.pfSyncMLMsgIncomingCb        = &MsgIncomingSyncMLMessageListener;
+       fwListener.pfLBSMsgIncomingCb           = &MsgIncomingLBSMessageListener;
+       fwListener.pfMmsConfIncomingCb = &MsgMmsConfIncomingListener;
+       fwListener.pfPushMsgIncomingCb          = &MsgIncomingPushMessageListener;
+       fwListener.pfCBMsgIncomingCb            = &MsgIncomingCBMessageListener;
+
+       if (registerListener(&fwListener) != MSG_SUCCESS)
+               THROW(MsgException::PLUGIN_ERROR, "ERROR to register listener");
+
+}
+
+
+MsgPlugin::~MsgPlugin()
+{
+       this->finalize();
+       // close mLibHandler.
+       if (mLibHandler != NULL)
+               dlclose(mLibHandler);
+}
+
+
+msg_error_t MsgPlugin::initialize()
+{
+       if ( mPlgHandler.pfInitialize != NULL)
+               return mPlgHandler.pfInitialize();
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+
+void MsgPlugin::finalize()
+{
+       if (mPlgHandler.pfFinalize != NULL)
+               mPlgHandler.pfFinalize();
+}
+
+
+msg_error_t MsgPlugin::submitReq(MSG_REQUEST_INFO_S *pReqInfo)
+{
+       if (mPlgHandler.pfSubmitRequest != NULL)
+               return mPlgHandler.pfSubmitRequest(pReqInfo);
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+
+msg_error_t MsgPlugin::registerListener(MSG_PLUGIN_LISTENER_S *pListener)
+{
+       if (mPlgHandler.pfRegisterListener != NULL)
+               return mPlgHandler.pfRegisterListener(pListener);
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+
+msg_error_t MsgPlugin::checkSimStatus(MSG_SIM_STATUS_T *pStatus)
+{
+       if (mPlgHandler.pfRegisterListener != NULL)
+               return mPlgHandler.pfCheckSimStatus(pStatus);
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+
+msg_error_t MsgPlugin::checkDeviceStatus()
+{
+       if (mPlgHandler.pfRegisterListener != NULL)
+               return mPlgHandler.pfCheckDeviceStatus();
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+
+msg_error_t MsgPlugin::initSimMessage()
+{
+       if (mPlgHandler.pfInitSimMessage != NULL)
+               return mPlgHandler.pfInitSimMessage();
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+
+msg_error_t MsgPlugin::saveSimMessage(MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList)
+{
+       if (mPlgHandler.pfSaveSimMessage != NULL)
+               return mPlgHandler.pfSaveSimMessage(pMsgInfo, pSimIdList);
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+
+msg_error_t MsgPlugin::deleteSimMessage(msg_sim_id_t SimMsgId)
+{
+       if (mPlgHandler.pfDeleteSimMessage != NULL)
+               return mPlgHandler.pfDeleteSimMessage(SimMsgId);
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+
+msg_error_t MsgPlugin::setReadStatus(msg_sim_id_t SimMsgId)
+{
+       if (mPlgHandler.pfSetReadStatus != NULL)
+               return mPlgHandler.pfSetReadStatus(SimMsgId);
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+
+msg_error_t MsgPlugin::setMemoryStatus(msg_error_t Error)
+{
+       if (mPlgHandler.pfSetMemoryStatus != NULL)
+               return mPlgHandler.pfSetMemoryStatus(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;
+}
+
+
+msg_error_t MsgPlugin::setConfigData(const MSG_SETTING_S *pSetting)
+{
+       if (mPlgHandler.pfSetConfigData != NULL)
+               return mPlgHandler.pfSetConfigData(pSetting);
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+
+msg_error_t MsgPlugin::getConfigData(MSG_SETTING_S *pSetting)
+{
+       if (mPlgHandler.pfGetConfigData != NULL)
+               return mPlgHandler.pfGetConfigData(pSetting);
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+msg_error_t MsgPlugin::addMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData)
+{
+       if (mPlgHandler.pfAddMessage != NULL) {
+               return mPlgHandler.pfAddMessage(pMsgInfo, pSendOptInfo, pFileData);
+       } else {
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+       }
+}
+
+msg_error_t MsgPlugin::updateMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData)
+{
+       if (mPlgHandler.pfUpdateMessage != NULL) {
+               return mPlgHandler.pfUpdateMessage(pMsgInfo, pSendOptInfo, pFileData);
+       } else {
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+       }
+}
+
+
+msg_error_t MsgPlugin::processReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST_INFO_S *pRequest, bool *bReject)
+{
+       if (mPlgHandler.pfProcessReceivedInd != NULL) {
+               return mPlgHandler.pfProcessReceivedInd(pMsgInfo, pRequest, bReject);
+       } else {
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+       }
+}
+
+
+msg_error_t MsgPlugin::getMmsMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo,  MMS_MESSAGE_DATA_S *pMmsMsg, char **pDestMsg)
+{
+       if (mPlgHandler.pfGetMmsMessage != NULL) {
+               return mPlgHandler.pfGetMmsMessage(pMsg, pSendOptInfo, pMmsMsg, pDestMsg);
+       } else {
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+       }
+}
+
+
+msg_error_t MsgPlugin::updateRejectStatus(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       if (mPlgHandler.pfUpdateRejectStatus != NULL) {
+               return mPlgHandler.pfUpdateRejectStatus(pMsgInfo);
+       } else {
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+       }
+}
+
+
+msg_error_t MsgPlugin::composeReadReport(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       if (mPlgHandler.pfComposeReadReport != NULL) {
+               return mPlgHandler.pfComposeReadReport(pMsgInfo);
+       } else {
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+       }
+}
+
+
+msg_error_t MsgPlugin::restoreMsg(MSG_MESSAGE_INFO_S *pMsgInfo, char* pRecvBody, int rcvdBodyLen, char* filePath)
+{
+       if (mPlgHandler.pfRestoreMsg != NULL)
+               return mPlgHandler.pfRestoreMsg(pMsgInfo,pRecvBody, rcvdBodyLen, filePath);
+       else
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+}
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgPluginManager - Member Functions
+==================================================================================================*/
+MsgPluginManager* MsgPluginManager::pInstance = NULL;
+
+
+MsgPluginManager* MsgPluginManager::instance()
+{
+       if (pInstance == NULL)
+               pInstance = new MsgPluginManager();
+
+       return pInstance;
+}
+
+
+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);
+
+       loadPlugins(path);
+}
+
+
+void MsgPluginManager::finalize()
+{
+       MsgPluginMap::iterator it;
+
+       for (it = plgMap.begin(); it != plgMap.end(); it++)
+       {
+               MsgPlugin *temp = it->second;
+               delete temp;
+       }
+
+       plgMap.clear();
+}
+
+
+void MsgPluginManager::loadPlugins(const char* path)
+{
+       /* 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 = new MsgPlugin(mainType, libPath);
+
+               plgMap.insert(make_pair(mainType, newPlg));
+       }
+
+       MsgCloseFile(fp);
+}
+
+
+MsgPlugin* MsgPluginManager::getPlugin(MSG_MAIN_TYPE_T mainType)
+{
+       /* Implementing the content */
+       MsgPluginMap::iterator it = plgMap.find(mainType);
+
+       if (it == plgMap.end())
+               return NULL;
+
+       return it->second;
+}
+
diff --git a/framework/setting-handler/MsgSettingHandler.cpp b/framework/setting-handler/MsgSettingHandler.cpp
new file mode 100755 (executable)
index 0000000..b79098b
--- /dev/null
@@ -0,0 +1,1427 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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"
+
+
+#define DEF_BUF_LEN    128
+
+/*==================================================================================================
+                                                               STATIC FUNCTION PROTOTYPES
+==================================================================================================*/
+
+/*==================================================================================================
+                                     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;
+
+#ifdef USE_GCONF
+       err = MsgGconfGetClient();
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("Get GConf Client Error");
+               return MSG_ERR_NULL_POINTER;
+       }
+#endif
+
+       MSG_DEBUG("Setting Type : %d", pSetting->type);
+
+       switch (pSetting->type)
+       {
+               case MSG_GENERAL_OPT :
+                       err = MsgSetGeneralOpt(pSetting);
+                       break;
+               case MSG_SMS_SENDOPT :
+                       err = MsgSetSMSSendOpt(pSetting);
+                       break;
+               case MSG_SMSC_LIST :
+                       err = MsgSetSMSCList(pSetting, true);
+                       break;
+               case MSG_MMS_SENDOPT :
+                       err = MsgSetMMSSendOpt(pSetting);
+                       break;
+               case MSG_MMS_RECVOPT :
+                       err = MsgSetMMSRecvOpt(pSetting);
+                       break;
+               case MSG_MMS_STYLEOPT :
+                       err = MsgSetMMSStyleOpt(pSetting);
+                       break;
+               case MSG_PUSHMSG_OPT :
+                       err = MsgSetPushMsgOpt(pSetting);
+                       break;
+               case MSG_CBMSG_OPT :
+                       err = MsgSetCBMsgOpt(pSetting, true);
+                       break;
+               case MSG_VOICEMAIL_OPT :
+                       err = MsgSetVoiceMailOpt(pSetting, true);
+                       break;
+               case MSG_MSGSIZE_OPT:
+                       err = MsgSetMsgSizeOpt(pSetting);
+                       break;
+               default :
+                       break;
+       }
+
+#ifdef USE_GCONF
+       MsgGconfUnrefClient();
+#endif
+
+       return err;
+}
+
+
+msg_error_t MsgGetConfigData(MSG_SETTING_S *pSetting)
+{
+#ifdef USE_GCONF
+       msg_error_t err = MsgGconfGetClient();
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("Get GConf Client Error");
+               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);
+
+       switch (pSetting->type)
+       {
+               case MSG_GENERAL_OPT :
+                       MsgGetGeneralOpt(pSetting);
+                       break;
+               case MSG_SMS_SENDOPT :
+                       MsgGetSMSSendOpt(pSetting);
+                       break;
+               case MSG_SMSC_LIST :
+               {
+                       if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
+                               MSG_DEBUG("SIM is not present..");
+                               return MSG_ERR_NO_SIM;
+                       }
+                       MsgGetSMSCList(pSetting);
+               }
+               break;
+               case MSG_MMS_SENDOPT :
+                       MsgGetMMSSendOpt(pSetting);
+                       break;
+               case MSG_MMS_RECVOPT :
+                       MsgGetMMSRecvOpt(pSetting);
+                       break;
+               case MSG_MMS_STYLEOPT :
+                       MsgGetMMSStyleOpt(pSetting);
+                       break;
+               case MSG_PUSHMSG_OPT :
+                       MsgGetPushMsgOpt(pSetting);
+                       break;
+               case MSG_CBMSG_OPT :
+               {
+                       if (simStatus == MSG_SIM_STATUS_NOT_FOUND) {
+                               MSG_DEBUG("SIM is not present..");
+                               return MSG_ERR_NO_SIM;
+                       }
+                       MsgGetCBMsgOpt(pSetting);
+               }
+               break;
+               case MSG_VOICEMAIL_OPT :
+                       MsgGetVoiceMailOpt(pSetting);
+                       break;
+               case MSG_MSGSIZE_OPT :
+                       MsgGetMsgSizeOpt(pSetting);
+                       break;
+
+               default :
+                       break;
+       }
+
+#ifdef USE_GCONF
+       MsgGconfUnrefClient();
+#endif
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgSetGeneralOpt(const MSG_SETTING_S *pSetting)
+{
+       MSG_GENERAL_OPT_S generalOpt;
+       bool bValue = false;
+
+       memcpy(&generalOpt, &(pSetting->option.generalOpt), sizeof(MSG_GENERAL_OPT_S));
+
+       MsgSettingGetBool(MSG_KEEP_COPY, &bValue);
+       if (bValue != generalOpt.bKeepCopy) {
+               if (MsgSettingSetBool(MSG_KEEP_COPY, generalOpt.bKeepCopy) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_KEEP_COPY);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MSG_AUTO_ERASE, &bValue);
+       if (bValue != generalOpt.bAutoErase) {
+               if (MsgSettingSetBool(MSG_AUTO_ERASE, generalOpt.bAutoErase) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_AUTO_ERASE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+#ifdef __NOT_USED_BY_DESIGN_CHANGE__
+       iValue = MsgSettingGetInt(MSG_ALERT_TONE);
+       if (iValue != (int)generalOpt.alertTone) {
+               if (MsgSettingSetInt(MSG_ALERT_TONE, (int)generalOpt.alertTone) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSG_ALERT_TONE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+#endif /* __NOT_USED_BY_DESIGN_CHANGE__ */
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgSetSMSSendOpt(const MSG_SETTING_S *pSetting)
+{
+       MSG_SMS_SENDOPT_S sendOpt;
+       int iValue = 0;
+       bool bValue = false;
+
+       memcpy(&sendOpt, &(pSetting->option.smsSendOpt), sizeof(MSG_SMS_SENDOPT_S));
+
+       iValue = MsgSettingGetInt(SMS_SEND_DCS);
+       if (iValue != (int)sendOpt.dcs) {
+               if (MsgSettingSetInt(SMS_SEND_DCS, (int)sendOpt.dcs) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", SMS_SEND_DCS);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(SMS_SEND_NETWORK_MODE);
+       if (iValue != (int)sendOpt.netMode) {
+               if (MsgSettingSetInt(SMS_SEND_NETWORK_MODE, (int)sendOpt.netMode) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", SMS_SEND_NETWORK_MODE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(SMS_SEND_REPLY_PATH, &bValue);
+       if (bValue != sendOpt.bReplyPath) {
+               if (MsgSettingSetBool(SMS_SEND_REPLY_PATH, sendOpt.bReplyPath) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", SMS_SEND_REPLY_PATH);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(SMS_SEND_DELIVERY_REPORT, &bValue);
+       if (bValue != sendOpt.bDeliveryReport) {
+               if (MsgSettingSetBool(SMS_SEND_DELIVERY_REPORT, sendOpt.bDeliveryReport) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", SMS_SEND_DELIVERY_REPORT);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(SMS_SEND_SAVE_STORAGE);
+       if (iValue != (int)sendOpt.saveStorage) {
+               if (MsgSettingSetInt(SMS_SEND_SAVE_STORAGE, (int)sendOpt.saveStorage) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", SMS_SEND_SAVE_STORAGE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+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;
+
+       memcpy(&smscList, &(pSetting->option.smscList), sizeof(MSG_SMSC_LIST_S));
+
+       char keyName[DEF_BUF_LEN] = {0, };
+
+       // 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;
+               }
+       }
+
+       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;
+       }
+
+       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;
+
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_ADDRESS, i);
+
+               if ((err = MsgSettingSetString(keyName, smscList.smscData[i].smscAddr.address)) != MSG_SUCCESS)
+                       break;
+       }
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("Error to set config data [%s]", keyName);
+       }
+
+       return err;
+}
+
+
+msg_error_t MsgSetMMSSendOpt(const MSG_SETTING_S *pSetting)
+{
+       MSG_MMS_SENDOPT_S sendOpt;
+       int iValue = 0;
+       bool bValue = false;
+
+       memcpy(&sendOpt, &(pSetting->option.mmsSendOpt), sizeof(MSG_MMS_SENDOPT_S));
+
+       iValue = MsgSettingGetInt(MMS_SEND_MSG_CLASS);
+       if (iValue != (int)sendOpt.msgClass) {
+               if (MsgSettingSetInt(MMS_SEND_MSG_CLASS, (int)sendOpt.msgClass) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_MSG_CLASS);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_SEND_PRIORITY);
+       if (iValue != (int)sendOpt.priority) {
+               if (MsgSettingSetInt(MMS_SEND_PRIORITY, (int)sendOpt.priority) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_PRIORITY);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_SEND_EXPIRY_TIME);
+       if (iValue != (int)sendOpt.expiryTime) {
+               if (MsgSettingSetInt(MMS_SEND_EXPIRY_TIME, (int)sendOpt.expiryTime) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_EXPIRY_TIME);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_SEND_DELIVERY_TIME);
+       if (iValue != (int)sendOpt.deliveryTime) {
+               if (MsgSettingSetInt(MMS_SEND_DELIVERY_TIME, (int)sendOpt.deliveryTime) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_DELIVERY_TIME);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_SEND_CUSTOM_DELIVERY);
+       if (iValue != (int)sendOpt.customDeliveryTime) {
+               if (MsgSettingSetInt(MMS_SEND_CUSTOM_DELIVERY, sendOpt.customDeliveryTime) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_CUSTOM_DELIVERY);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MMS_SEND_SENDER_VISIBILITY, &bValue);
+       if (bValue != sendOpt.bSenderVisibility) {
+               if (MsgSettingSetBool(MMS_SEND_SENDER_VISIBILITY, sendOpt.bSenderVisibility) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_SENDER_VISIBILITY);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MMS_SEND_DELIVERY_REPORT, &bValue);
+       if (bValue != sendOpt.bDeliveryReport) {
+               if (MsgSettingSetBool(MMS_SEND_DELIVERY_REPORT, sendOpt.bDeliveryReport) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_DELIVERY_REPORT);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MMS_SEND_READ_REPLY, &bValue);
+       if (bValue != sendOpt.bReadReply) {
+               if (MsgSettingSetBool(MMS_SEND_READ_REPLY, sendOpt.bReadReply) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_READ_REPLY);
+                       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) {
+               if (MsgSettingSetBool(MMS_SEND_BODY_REPLYING, sendOpt.bBodyReplying) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_BODY_REPLYING);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MMS_SEND_HIDE_RECIPIENTS, &bValue);
+       if (bValue != sendOpt.bHideRecipients) {
+               if (MsgSettingSetBool(MMS_SEND_HIDE_RECIPIENTS, sendOpt.bHideRecipients) != MSG_SUCCESS)
+               {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_HIDE_RECIPIENTS);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_SEND_REPLY_CHARGING);
+       if (iValue != sendOpt.replyCharging) {
+               if (MsgSettingSetInt(MMS_SEND_REPLY_CHARGING, sendOpt.replyCharging) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_REPLY_CHARGING);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_SEND_REPLY_CHARGING_DEADLINE);
+       if (iValue != (int)sendOpt.replyChargingDeadline) {
+               if (MsgSettingSetInt(MMS_SEND_REPLY_CHARGING_DEADLINE, sendOpt.replyChargingDeadline) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_REPLY_CHARGING_DEADLINE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_SEND_REPLY_CHARGING_SIZE);
+       if (iValue != (int)sendOpt.replyChargingSize) {
+               if (MsgSettingSetInt(MMS_SEND_REPLY_CHARGING_SIZE, sendOpt.replyChargingSize) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_REPLY_CHARGING_SIZE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_SEND_CREATION_MODE);
+       if (iValue != sendOpt.creationMode) {
+               if (MsgSettingSetInt(MMS_SEND_CREATION_MODE, sendOpt.creationMode) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_SEND_CREATION_MODE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgSetMMSRecvOpt(const MSG_SETTING_S *pSetting)
+{
+       MSG_MMS_RECVOPT_S recvOpt;
+       int iValue = 0;
+       bool bValue = false;
+
+       memcpy(&recvOpt, &(pSetting->option.mmsRecvOpt), sizeof(MSG_MMS_RECVOPT_S));
+
+       iValue = MsgSettingGetInt(MMS_RECV_HOME_NETWORK);
+       if (iValue != (int)recvOpt.homeNetwork) {
+               if (MsgSettingSetInt(MMS_RECV_HOME_NETWORK, (int)recvOpt.homeNetwork) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_RECV_HOME_NETWORK);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_RECV_ABROAD_NETWORK);
+       if (iValue != (int)recvOpt.abroadNetwok) {
+               if (MsgSettingSetInt(MMS_RECV_ABROAD_NETWORK, (int)recvOpt.abroadNetwok) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_RECV_ABROAD_NETWORK);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MMS_RECV_READ_RECEIPT, &bValue);
+       if (bValue != recvOpt.readReceipt) {
+               if (MsgSettingSetBool(MMS_RECV_READ_RECEIPT, recvOpt.readReceipt) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_RECV_READ_RECEIPT);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MMS_RECV_DELIVERY_RECEIPT, &bValue);
+       if (bValue != recvOpt.bDeliveryReceipt) {
+               if (MsgSettingSetBool(MMS_RECV_DELIVERY_RECEIPT, recvOpt.bDeliveryReceipt) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_RECV_DELIVERY_RECEIPT);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MMS_RECV_REJECT_UNKNOWN, &bValue);
+       if (bValue != recvOpt.bRejectUnknown) {
+               if (MsgSettingSetBool(MMS_RECV_REJECT_UNKNOWN, recvOpt.bRejectUnknown) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_RECV_REJECT_UNKNOWN);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MMS_RECV_REJECT_ADVERTISE, &bValue);
+       if (bValue != recvOpt.bRejectAdvertisement) {
+               if (MsgSettingSetBool(MMS_RECV_REJECT_ADVERTISE, recvOpt.bRejectAdvertisement) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_RECV_REJECT_ADVERTISE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgSetMMSStyleOpt(const MSG_SETTING_S *pSetting)
+{
+       MSG_MMS_STYLEOPT_S styleOpt;
+       int iValue = 0;
+       bool bValue = false;
+
+       memcpy(&styleOpt, &(pSetting->option.mmsStyleOpt), sizeof(MSG_MMS_STYLEOPT_S));
+
+       iValue = MsgSettingGetInt(MMS_STYLE_FONT_SIZE);
+       if (iValue != (int)styleOpt.fontSize) {
+               if (MsgSettingSetInt(MMS_STYLE_FONT_SIZE, styleOpt.fontSize) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_FONT_SIZE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MMS_STYLE_FONT_STYLE_BOLD, &bValue);
+       if (bValue != styleOpt.bFontStyleBold) {
+               if (MsgSettingSetBool(MMS_STYLE_FONT_STYLE_BOLD, styleOpt.bFontStyleBold) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_FONT_STYLE_BOLD);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MMS_STYLE_FONT_STYLE_ITALIC, &bValue);
+       if (bValue != styleOpt.bFontStyleItalic) {
+               if (MsgSettingSetBool(MMS_STYLE_FONT_STYLE_ITALIC, styleOpt.bFontStyleItalic) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_FONT_STYLE_ITALIC);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       MsgSettingGetBool(MMS_STYLE_FONT_STYLE_UNDERLINE, &bValue);
+       if (bValue != styleOpt.bFontStyleUnderline) {
+               if (MsgSettingSetBool(MMS_STYLE_FONT_STYLE_UNDERLINE, styleOpt.bFontStyleUnderline) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_FONT_STYLE_UNDERLINE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_STYLE_FONT_COLOR_RED);
+       if (iValue != (int)styleOpt.fontColorRed) {
+               if (MsgSettingSetInt(MMS_STYLE_FONT_COLOR_RED, styleOpt.fontColorRed) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_FONT_COLOR_RED);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_STYLE_FONT_COLOR_GREEN);
+       if (iValue != (int)styleOpt.fontColorGreen) {
+               if (MsgSettingSetInt(MMS_STYLE_FONT_COLOR_GREEN, styleOpt.fontColorGreen) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_FONT_COLOR_GREEN);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_STYLE_FONT_COLOR_BLUE);
+       if (iValue != (int)styleOpt.fontColorBlue) {
+               if (MsgSettingSetInt(MMS_STYLE_FONT_COLOR_BLUE, styleOpt.fontColorBlue) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_FONT_COLOR_BLUE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_STYLE_FONT_COLOR_HUE);
+       if (iValue != (int)styleOpt.fontColorHue) {
+               if (MsgSettingSetInt(MMS_STYLE_FONT_COLOR_HUE, styleOpt.fontColorHue) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_FONT_COLOR_HUE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_STYLE_BG_COLOR_RED);
+       if (iValue != (int)styleOpt.bgColorRed) {
+               if (MsgSettingSetInt(MMS_STYLE_BG_COLOR_RED, styleOpt.bgColorRed) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_BG_COLOR_RED);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_STYLE_BG_COLOR_GREEN);
+       if (iValue != (int)styleOpt.bgColorGreen) {
+               if (MsgSettingSetInt(MMS_STYLE_BG_COLOR_GREEN, styleOpt.bgColorGreen) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_BG_COLOR_GREEN);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_STYLE_BG_COLOR_BLUE);
+       if (iValue != (int)styleOpt.bgColorBlue) {
+               if (MsgSettingSetInt(MMS_STYLE_BG_COLOR_BLUE, styleOpt.bgColorBlue) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_BG_COLOR_BLUE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_STYLE_BG_COLOR_HUE);
+       if (iValue != (int)styleOpt.bgColorHue) {
+               if (MsgSettingSetInt(MMS_STYLE_BG_COLOR_HUE, styleOpt.bgColorHue) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_BG_COLOR_HUE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_STYLE_PAGE_DUR);
+       if (iValue != (int)styleOpt.pageDur) {
+               if (MsgSettingSetInt(MMS_STYLE_PAGE_DUR, styleOpt.pageDur) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_PAGE_DUR);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_STYLE_PAGE_CUSTOM_DUR);
+       if (iValue != (int)styleOpt.pageCustomDur) {
+               if (MsgSettingSetInt(MMS_STYLE_PAGE_CUSTOM_DUR, styleOpt.pageCustomDur) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_PAGE_CUSTOM_DUR);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(MMS_STYLE_PAGE_DUR_MANUAL);
+       if (iValue != (int)styleOpt.pageDurManual) {
+               if (MsgSettingSetInt(MMS_STYLE_PAGE_DUR_MANUAL, styleOpt.pageDurManual) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MMS_STYLE_PAGE_DUR_MANUAL);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t MsgSetPushMsgOpt(const MSG_SETTING_S *pSetting)
+{
+       MSG_PUSHMSG_OPT_S pushOpt;
+       int iValue = 0;
+       bool bValue = false;
+
+       memcpy(&pushOpt, &(pSetting->option.pushMsgOpt), sizeof(MSG_PUSHMSG_OPT_S));
+
+       MsgSettingGetBool(PUSH_RECV_OPTION, &bValue);
+       if (bValue != pushOpt.bReceive) {
+               if (MsgSettingSetBool(PUSH_RECV_OPTION, pushOpt.bReceive) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", PUSH_RECV_OPTION);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       iValue = MsgSettingGetInt(PUSH_SERVICE_TYPE);
+       if (iValue != (int)pushOpt.serviceType) {
+               if (MsgSettingSetInt(PUSH_SERVICE_TYPE, (int)pushOpt.serviceType) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", PUSH_SERVICE_TYPE);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgSetCBMsgOpt(const MSG_SETTING_S *pSetting, bool bSetSim)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       MSG_CBMSG_OPT_S cbOpt;
+       int iValue = 0;
+       bool bValue = false;
+
+       memcpy(&cbOpt, &(pSetting->option.cbMsgOpt), sizeof(MSG_CBMSG_OPT_S));
+
+       if (bSetSim == true) {
+               cbOpt.maxSimCnt = MsgSettingGetInt(CB_MAX_SIM_COUNT);
+
+               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;
+               }
+
+               err = MsgSetConfigInSim(pSetting);
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data in sim [%d]", err);
+                       return err;
+               }
+       }
+
+       MsgSettingGetBool(CB_RECEIVE, &bValue);
+       if (bValue != cbOpt.bReceive) {
+               if (MsgSettingSetBool(CB_RECEIVE, cbOpt.bReceive) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", CB_RECEIVE);
+                       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;
+               }
+       }
+
+       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);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       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);
+
+               if ((err = MsgSettingSetString(keyName, cbOpt.channelData.channelInfo[i].name)) != MSG_SUCCESS)
+                       break;
+       }
+
+       if (bSetSim == true)
+       {
+               for (int i = MSG_CBLANG_TYPE_ALL; i < MSG_CBLANG_TYPE_MAX; i++)
+               {
+                       memset(keyName, 0x00, sizeof(keyName));
+                       snprintf(keyName, DEF_BUF_LEN, "%s/%d", CB_LANGUAGE, i);
+
+                       if (MsgSettingSetBool(keyName, cbOpt.bLanguage[i]) != MSG_SUCCESS)
+                       {
+                               MSG_DEBUG("Error to set config data [%s]", keyName);
+                               return MSG_ERR_SET_SETTING;
+                       }
+               }
+       }
+
+       return err;
+}
+
+
+msg_error_t MsgSetVoiceMailOpt(const MSG_SETTING_S *pSetting, bool bSetSim)
+{
+       MSG_VOICEMAIL_OPT_S voiceMailOpt;
+       char *pValue = NULL;
+       msg_error_t err = MSG_SUCCESS;
+
+       memcpy(&voiceMailOpt, &(pSetting->option.voiceMailOpt), sizeof(MSG_VOICEMAIL_OPT_S));
+
+       pValue = MsgSettingGetString(VOICEMAIL_NUMBER);
+       if (pValue != NULL && strcmp(pValue, voiceMailOpt.mailNumber) == 0) {
+               /* Value is same with previous one. Therefore, we don't need to save it. */
+       } else {
+               if (bSetSim == true) {
+                       err = MsgSetConfigInSim(pSetting);
+
+                       if (err == MSG_SUCCESS) {
+                               err = MsgSettingSetString(VOICEMAIL_NUMBER, voiceMailOpt.mailNumber);
+                               if (err != MSG_SUCCESS)
+                                       MSG_DEBUG("Error to set config data [%s]", VOICEMAIL_NUMBER);
+                       } else {
+                               MSG_DEBUG("Error to set config data in sim [%d]", err);
+                       }
+               } else {
+                       err = MsgSettingSetString(VOICEMAIL_NUMBER, voiceMailOpt.mailNumber);
+                       if (err != MSG_SUCCESS)
+                               MSG_DEBUG("Error to set config data [%s]", VOICEMAIL_NUMBER);
+               }
+       }
+
+       if (pValue != NULL) {
+               free(pValue);
+               pValue = NULL;
+       }
+
+       return err;
+}
+
+
+msg_error_t MsgSetMsgSizeOpt(const MSG_SETTING_S *pSetting)
+{
+       MSG_MSGSIZE_OPT_S msgSizeOpt;
+       int iValue = 0;
+
+       memcpy(&msgSizeOpt, &(pSetting->option.msgSizeOpt), sizeof(MSG_MSGSIZE_OPT_S));
+
+       iValue = MsgSettingGetInt(MSGSIZE_OPTION);
+       if (iValue != msgSizeOpt.nMsgSize) {
+               if (MsgSettingSetInt(MSGSIZE_OPTION, msgSizeOpt.nMsgSize) != MSG_SUCCESS) {
+                       MSG_DEBUG("Error to set config data [%s]", MSGSIZE_OPTION);
+                       return MSG_ERR_SET_SETTING;
+               }
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+void MsgGetGeneralOpt(MSG_SETTING_S *pSetting)
+{
+       memset(&(pSetting->option.generalOpt), 0x00, sizeof(MSG_GENERAL_OPT_S));
+
+       MsgSettingGetBool(MSG_KEEP_COPY, &pSetting->option.generalOpt.bKeepCopy);
+
+#ifdef __NOT_USED_BY_DESIGN_CHANGE__
+       pSetting->option.generalOpt.alertTone = (MSG_ALERT_TONE_T)MsgSettingGetInt(MSG_ALERT_TONE);
+
+       MsgSettingGetBool(MSG_AUTO_ERASE, &pSetting->option.generalOpt.bAutoErase);
+#endif /* __NOT_USED_BY_DESIGN_CHANGE__ */
+}
+
+
+void MsgGetSMSSendOpt(MSG_SETTING_S *pSetting)
+{
+       memset(&(pSetting->option.smsSendOpt), 0x00, sizeof(MSG_SMS_SENDOPT_S));
+
+       pSetting->option.smsSendOpt.dcs = (msg_encode_type_t)MsgSettingGetInt(SMS_SEND_DCS);
+
+       pSetting->option.smsSendOpt.netMode = (MSG_SMS_NETWORK_MODE_T)MsgSettingGetInt(SMS_SEND_NETWORK_MODE);
+
+       MsgSettingGetBool(SMS_SEND_REPLY_PATH, &pSetting->option.smsSendOpt.bReplyPath);
+
+       MsgSettingGetBool(SMS_SEND_DELIVERY_REPORT, &pSetting->option.smsSendOpt.bDeliveryReport);
+
+       pSetting->option.smsSendOpt.saveStorage = (MSG_SMS_SAVE_STORAGE_T)MsgSettingGetInt(SMS_SEND_SAVE_STORAGE);
+}
+
+
+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);
+
+       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.smscList.smscData[i].pid = (MSG_SMS_PID_T)MsgSettingGetInt(keyName);
+
+#ifdef __NOT_USED_BY_DESIGN_CHANGE__
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_DCS, i);
+
+               pSetting->option.smscList.smscData[i].dcs = (msg_encode_type_t)MsgSettingGetInt(keyName);
+#endif /* __NOT_USED_BY_DESIGN_CHANGE__ */
+
+               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);
+
+               memset(pSetting->option.smscList.smscData[i].name, 0x00, SMSC_NAME_MAX+1);
+
+               tmpValue = MsgSettingGetString(keyName);
+               if (tmpValue != NULL) {
+                       strncpy(pSetting->option.smscList.smscData[i].name, tmpValue, SMSC_NAME_MAX);
+                       free(tmpValue);
+                       tmpValue = NULL;
+               }
+
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_TON, i);
+
+               pSetting->option.smscList.smscData[i].smscAddr.ton = (MSG_SMS_TON_T)MsgSettingGetInt(keyName);
+
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, DEF_BUF_LEN, "%s/%d", SMSC_NPI, i);
+
+               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);
+
+               memset(pSetting->option.smscList.smscData[i].smscAddr.address, 0x00, sizeof(pSetting->option.smscList.smscData[i].smscAddr.address));
+
+               tmpValue = MsgSettingGetString(keyName);
+               if (tmpValue != NULL) {
+                       strncpy(pSetting->option.smscList.smscData[i].smscAddr.address, tmpValue, SMSC_ADDR_MAX);
+                       free(tmpValue);
+                       tmpValue = NULL;
+               }
+       }
+}
+
+
+void MsgGetMMSSendOpt(MSG_SETTING_S *pSetting)
+{
+       memset(&(pSetting->option.mmsSendOpt), 0x00, sizeof(MSG_MMS_SENDOPT_S));
+
+       pSetting->option.mmsSendOpt.msgClass = (MSG_MMS_MSG_CLASS_TYPE_T)MsgSettingGetInt(MMS_SEND_MSG_CLASS);
+
+       pSetting->option.mmsSendOpt.priority = (msg_priority_type_t)MsgSettingGetInt(MMS_SEND_PRIORITY);
+
+       pSetting->option.mmsSendOpt.expiryTime = (MSG_MMS_EXPIRY_TIME_T)MsgSettingGetInt(MMS_SEND_EXPIRY_TIME);
+
+       pSetting->option.mmsSendOpt.deliveryTime = (MSG_MMS_DELIVERY_TIME_T)MsgSettingGetInt(MMS_SEND_DELIVERY_TIME);
+
+       pSetting->option.mmsSendOpt.customDeliveryTime = MsgSettingGetInt(MMS_SEND_CUSTOM_DELIVERY);
+
+       MsgSettingGetBool(MMS_SEND_SENDER_VISIBILITY, &pSetting->option.mmsSendOpt.bSenderVisibility);
+
+       MsgSettingGetBool(MMS_SEND_DELIVERY_REPORT, &pSetting->option.mmsSendOpt.bDeliveryReport);
+
+       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);
+
+       pSetting->option.mmsSendOpt.replyCharging = MsgSettingGetInt(MMS_SEND_REPLY_CHARGING);
+
+       pSetting->option.mmsSendOpt.replyChargingDeadline = MsgSettingGetInt(MMS_SEND_REPLY_CHARGING_DEADLINE);
+
+       pSetting->option.mmsSendOpt.replyChargingSize = MsgSettingGetInt(MMS_SEND_REPLY_CHARGING_SIZE);
+
+       pSetting->option.mmsSendOpt.creationMode = MsgSettingGetInt(MMS_SEND_CREATION_MODE);
+}
+
+
+void MsgGetMMSRecvOpt(MSG_SETTING_S *pSetting)
+{
+       memset(&(pSetting->option.mmsRecvOpt), 0x00, sizeof(MSG_MMS_RECVOPT_S));
+
+       pSetting->option.mmsRecvOpt.homeNetwork = (MSG_MMS_HOME_RETRIEVE_TYPE_T)MsgSettingGetInt(MMS_RECV_HOME_NETWORK);
+
+       pSetting->option.mmsRecvOpt.abroadNetwok = (MSG_MMS_ABROAD_RETRIEVE_TYPE_T)MsgSettingGetInt(MMS_RECV_ABROAD_NETWORK);
+
+       MsgSettingGetBool(MMS_RECV_READ_RECEIPT, &pSetting->option.mmsRecvOpt.readReceipt);
+
+       MsgSettingGetBool(MMS_RECV_DELIVERY_RECEIPT, &pSetting->option.mmsRecvOpt.bDeliveryReceipt);
+
+       MsgSettingGetBool(MMS_RECV_REJECT_UNKNOWN, &pSetting->option.mmsRecvOpt.bRejectUnknown);
+
+       MsgSettingGetBool(MMS_RECV_REJECT_ADVERTISE, &pSetting->option.mmsRecvOpt.bRejectAdvertisement);
+}
+
+
+void MsgGetMMSStyleOpt(MSG_SETTING_S *pSetting)
+{
+       memset(&(pSetting->option.mmsStyleOpt), 0x00, sizeof(MSG_MMS_STYLEOPT_S));
+
+       pSetting->option.mmsStyleOpt.fontSize = MsgSettingGetInt(MMS_STYLE_FONT_SIZE);
+
+       MsgSettingGetBool(MMS_STYLE_FONT_STYLE_BOLD, &pSetting->option.mmsStyleOpt.bFontStyleBold);
+
+       MsgSettingGetBool(MMS_STYLE_FONT_STYLE_ITALIC, &pSetting->option.mmsStyleOpt.bFontStyleItalic);
+
+       MsgSettingGetBool(MMS_STYLE_FONT_STYLE_UNDERLINE, &pSetting->option.mmsStyleOpt.bFontStyleUnderline);
+
+       pSetting->option.mmsStyleOpt.fontColorRed = MsgSettingGetInt(MMS_STYLE_FONT_COLOR_RED);
+
+       pSetting->option.mmsStyleOpt.fontColorGreen = MsgSettingGetInt(MMS_STYLE_FONT_COLOR_GREEN);
+
+       pSetting->option.mmsStyleOpt.fontColorBlue = MsgSettingGetInt(MMS_STYLE_FONT_COLOR_BLUE);
+
+       pSetting->option.mmsStyleOpt.fontColorHue = MsgSettingGetInt(MMS_STYLE_FONT_COLOR_HUE);
+
+       pSetting->option.mmsStyleOpt.bgColorRed = MsgSettingGetInt(MMS_STYLE_BG_COLOR_RED);
+
+       pSetting->option.mmsStyleOpt.bgColorGreen = MsgSettingGetInt(MMS_STYLE_BG_COLOR_GREEN);
+
+       pSetting->option.mmsStyleOpt.bgColorBlue = MsgSettingGetInt(MMS_STYLE_BG_COLOR_BLUE);
+
+       pSetting->option.mmsStyleOpt.bgColorHue = MsgSettingGetInt(MMS_STYLE_BG_COLOR_HUE);
+
+       pSetting->option.mmsStyleOpt.pageDur = MsgSettingGetInt(MMS_STYLE_PAGE_DUR);
+
+       pSetting->option.mmsStyleOpt.pageCustomDur = MsgSettingGetInt(MMS_STYLE_PAGE_CUSTOM_DUR);
+
+       pSetting->option.mmsStyleOpt.pageDurManual = MsgSettingGetInt(MMS_STYLE_PAGE_DUR_MANUAL);
+}
+
+
+void MsgGetPushMsgOpt(MSG_SETTING_S *pSetting)
+{
+       memset(&(pSetting->option.pushMsgOpt), 0x00, sizeof(MSG_PUSHMSG_OPT_S));
+
+       MsgSettingGetBool(PUSH_RECV_OPTION, &pSetting->option.pushMsgOpt.bReceive);
+
+       pSetting->option.pushMsgOpt.serviceType = (MSG_PUSH_SERVICE_TYPE_T)MsgSettingGetInt(PUSH_SERVICE_TYPE);
+}
+
+
+void MsgGetCBMsgOpt(MSG_SETTING_S *pSetting)
+{
+       char keyName[DEF_BUF_LEN] = {0, };
+       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));
+               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);
+
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, DEF_BUF_LEN, "%s/%d", CB_CHANNEL_NAME, i);
+
+               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;
+               }
+       }
+
+       for (int i = MSG_CBLANG_TYPE_ALL; i < MSG_CBLANG_TYPE_MAX; i++)
+       {
+               memset(keyName, 0x00, sizeof(keyName));
+               snprintf(keyName, DEF_BUF_LEN, "%s/%d", CB_LANGUAGE, i);
+
+               MsgSettingGetBool(keyName, &pSetting->option.cbMsgOpt.bLanguage[i]);
+       }
+}
+
+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;
+       }
+}
+
+
+void MsgGetMsgSizeOpt(MSG_SETTING_S *pSetting)
+{
+       memset(&(pSetting->option.msgSizeOpt), 0x00, sizeof(MSG_MSGSIZE_OPT_S));
+
+       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;
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("Error. Error code is %d.", err);
+               return err;
+       }
+
+       return err;
+}
+
+#ifdef __NOT_USED_BY_ENV_CHANGE__
+void MsgSetDefaultConfig()
+{
+       bool bTmp = false;
+       char keyName[128];
+
+       // Set Default General SendOpt
+       if (MsgSettingGetBool(MSG_KEEP_COPY, &bTmp) < 0)
+               MsgSettingSetBool(MSG_KEEP_COPY, true);
+
+       if (MsgSettingGetInt(MSG_ALERT_TONE) < 0)
+               MsgSettingSetInt(MSG_ALERT_TONE, (int)MSG_ALERT_TONE_ONCE);
+
+       if (MsgSettingGetBool(MSG_AUTO_ERASE, &bTmp) < 0)
+               MsgSettingGetBool(MSG_AUTO_ERASE, false);
+
+       // Set Default SMS SendOpt
+       if (MsgSettingGetInt(SMS_SEND_DCS) < 0)
+               MsgSettingSetInt(SMS_SEND_DCS, (int)MSG_ENCODE_AUTO);
+
+       if (MsgSettingGetInt(SMS_SEND_NETWORK_MODE) < 0)
+               MsgSettingSetInt(SMS_SEND_NETWORK_MODE, (int)MSG_SMS_NETWORK_CS_ONLY);
+
+       if (MsgSettingGetBool(SMS_SEND_REPLY_PATH, &bTmp) < 0)
+               MsgSettingSetBool(SMS_SEND_REPLY_PATH, false);
+
+       if (MsgSettingGetBool(SMS_SEND_DELIVERY_REPORT, &bTmp) < 0)
+               MsgSettingSetBool(SMS_SEND_DELIVERY_REPORT, false);
+
+       if (MsgSettingGetInt(SMS_SEND_SAVE_STORAGE) < 0)
+               MsgSettingSetInt(SMS_SEND_SAVE_STORAGE, (int)MSG_SMS_SAVE_STORAGE_PHONE);
+
+       // Set Default SMSC List
+       if (MsgSettingGetInt(SMSC_SELECTED) < 0)
+               MsgSettingSetInt(SMSC_SELECTED, 0);
+
+       if (MsgSettingGetInt(SMSC_TOTAL_COUNT) < 0)
+               MsgSettingSetInt(SMSC_TOTAL_COUNT, 1);
+
+       memset(keyName, 0x00, sizeof(keyName));
+       sprintf(keyName, "%s/%d", SMSC_PID, 0);
+
+       if (MsgSettingGetInt(keyName) < 0)
+               MsgSettingSetInt(keyName, (int)MSG_PID_TEXT);
+
+       memset(keyName, 0x00, sizeof(keyName));
+       sprintf(keyName, "%s/%d", SMSC_VAL_PERIOD, MSG_VAL_MAXIMUM);
+
+       if (MsgSettingGetInt(keyName) < 0)
+               MsgSettingSetInt(keyName, 0);
+
+       memset(keyName, 0x00, sizeof(keyName));
+       sprintf(keyName, "%s/%d", SMSC_NAME, 0);
+
+       char *smscName = NULL;
+
+       smscName = MsgSettingGetString(keyName);
+
+       if (smscName == NULL) {
+               MsgSettingSetString(keyName, (char*)"SMS Centre 1");
+       } else {
+               free(smscName);
+               smscName = NULL;
+       }
+
+       memset(keyName, 0x00, sizeof(keyName));
+       sprintf(keyName, "%s/%d", SMSC_TON, 0);
+
+       if (MsgSettingGetInt(keyName) < 0)
+               MsgSettingSetInt(keyName, (int)MSG_TON_INTERNATIONAL);
+
+       memset(keyName, 0x00, sizeof(keyName));
+       sprintf(keyName, "%s/%d", SMSC_NPI, 0);
+
+       if (MsgSettingGetInt(keyName) < 0)
+               MsgSettingSetInt(keyName, (int)MSG_NPI_ISDN);
+
+       memset(keyName, 0x00, sizeof(keyName));
+       sprintf(keyName, "%s/%d", SMSC_ADDRESS, 0);
+
+       char *smscAddress = NULL;
+
+       smscAddress = MsgSettingGetString(keyName);
+
+       if (smscAddress == NULL) {
+               MsgSettingSetString(keyName, (char*)"8210911111");
+       } else {
+               free(smscAddress);
+               smscAddress = NULL;
+       }
+
+       // Set Default MMS Send Opt
+       if (MsgSettingGetInt(MMS_SEND_MSG_CLASS) < 0)
+               MsgSettingSetInt(MMS_SEND_MSG_CLASS, (int)MSG_CLASS_AUTO);
+
+       if (MsgSettingGetInt(MMS_SEND_PRIORITY) < 0)
+               MsgSettingSetInt(MMS_SEND_PRIORITY, (int)MSG_MESSAGE_PRIORITY_NORMAL);
+
+       if (MsgSettingGetInt(MMS_SEND_EXPIRY_TIME) < 0)
+               MsgSettingSetInt(MMS_SEND_EXPIRY_TIME, 86400);
+
+       if (MsgSettingGetInt(MMS_SEND_DELIVERY_TIME) < 0)
+               MsgSettingSetInt(MMS_SEND_DELIVERY_TIME, 0);
+
+       if (MsgSettingGetInt(MMS_SEND_CUSTOM_DELIVERY) < 0)
+               MsgSettingSetInt(MMS_SEND_CUSTOM_DELIVERY, 0);
+
+       if (MsgSettingGetBool(MMS_SEND_SENDER_VISIBILITY, &bTmp) < 0)
+               MsgSettingSetBool(MMS_SEND_SENDER_VISIBILITY, false);
+
+       if (MsgSettingGetBool(MMS_SEND_DELIVERY_REPORT, &bTmp) < 0)
+               MsgSettingSetBool(MMS_SEND_DELIVERY_REPORT, true);
+
+       if (MsgSettingGetBool(MMS_SEND_READ_REPLY, &bTmp) < 0)
+               MsgSettingSetBool(MMS_SEND_READ_REPLY, false);
+
+       if (MsgSettingGetBool(MMS_SEND_KEEP_COPY, &bTmp) < 0)
+               MsgSettingSetBool(MMS_SEND_KEEP_COPY, false);
+
+       if (MsgSettingGetBool(MMS_SEND_BODY_REPLYING, &bTmp) < 0)
+               MsgSettingSetBool(MMS_SEND_BODY_REPLYING, false);
+
+       if (MsgSettingGetBool(MMS_SEND_HIDE_RECIPIENTS, &bTmp) < 0)
+               MsgSettingSetBool(MMS_SEND_HIDE_RECIPIENTS, false);
+
+       if (MsgSettingGetInt(MMS_SEND_REPLY_CHARGING) < 0)
+               MsgSettingSetInt(MMS_SEND_REPLY_CHARGING, (int)MSG_REPLY_CHARGING_NONE);
+
+       if (MsgSettingGetInt(MMS_SEND_REPLY_CHARGING_DEADLINE) < 0)
+               MsgSettingSetInt(MMS_SEND_REPLY_CHARGING_DEADLINE, 0);
+
+       if (MsgSettingGetInt(MMS_SEND_REPLY_CHARGING_SIZE) < 0)
+               MsgSettingSetInt(MMS_SEND_REPLY_CHARGING_SIZE, 0);
+
+       // Set Default MMS Recv Opt
+       if (MsgSettingGetInt(MMS_RECV_HOME_NETWORK) < 0)
+               MsgSettingSetInt(MMS_RECV_HOME_NETWORK, (int)MSG_HOME_AUTO_DOWNLOAD);
+
+       if (MsgSettingGetInt(MMS_RECV_ABROAD_NETWORK) < 0)
+               MsgSettingSetInt(MMS_RECV_ABROAD_NETWORK, (int)MSG_ABROAD_RESTRICTED);
+
+       if (MsgSettingGetInt(MMS_RECV_READ_RECEIPT) < 0)
+               MsgSettingSetInt(MMS_RECV_READ_RECEIPT, (int)MSG_SEND_READ_REPORT_NEVER);
+
+       if (MsgSettingGetBool(MMS_RECV_DELIVERY_RECEIPT, &bTmp) < 0)
+               MsgSettingSetBool(MMS_RECV_DELIVERY_RECEIPT, true);
+
+       if (MsgSettingGetBool(MMS_RECV_REJECT_UNKNOWN, &bTmp) < 0)
+               MsgSettingSetBool(MMS_RECV_REJECT_UNKNOWN, false);
+
+       if (MsgSettingGetBool(MMS_RECV_REJECT_ADVERTISE, &bTmp) < 0)
+               MsgSettingSetBool(MMS_RECV_REJECT_ADVERTISE, false);
+
+       // Set Default MMS Style Opt
+       if (MsgSettingGetInt(MMS_STYLE_FONT_SIZE) < 0)
+               MsgSettingSetInt(MMS_STYLE_FONT_SIZE, 30);
+
+       if (MsgSettingGetInt(MMS_STYLE_FONT_STYLE) < 0)
+               MsgSettingSetInt(MMS_STYLE_FONT_STYLE, 0);
+
+       if (MsgSettingGetInt(MMS_STYLE_FONT_COLOR_RED) < 0)
+               MsgSettingSetInt(MMS_STYLE_FONT_COLOR_RED, 0);
+
+       if (MsgSettingGetInt(MMS_STYLE_FONT_COLOR_GREEN) < 0)
+               MsgSettingSetInt(MMS_STYLE_FONT_COLOR_GREEN, 0);
+
+       if (MsgSettingGetInt(MMS_STYLE_FONT_COLOR_BLUE) < 0)
+               MsgSettingSetInt(MMS_STYLE_FONT_COLOR_BLUE, 0);
+
+       if (MsgSettingGetInt(MMS_STYLE_FONT_COLOR_HUE) < 0)
+               MsgSettingSetInt(MMS_STYLE_FONT_COLOR_HUE, 255);
+
+       if (MsgSettingGetInt(MMS_STYLE_BG_COLOR_RED) < 0)
+               MsgSettingSetInt(MMS_STYLE_BG_COLOR_RED, 255);
+
+       if (MsgSettingGetInt(MMS_STYLE_BG_COLOR_GREEN) < 0)
+               MsgSettingSetInt(MMS_STYLE_BG_COLOR_GREEN, 255);
+
+       if (MsgSettingGetInt(MMS_STYLE_BG_COLOR_BLUE) < 0)
+               MsgSettingSetInt(MMS_STYLE_BG_COLOR_BLUE, 255);
+
+       if (MsgSettingGetInt(MMS_STYLE_BG_COLOR_HUE) < 0)
+               MsgSettingSetInt(MMS_STYLE_FONT_COLOR_HUE, 255);
+
+       if (MsgSettingGetInt(MMS_STYLE_PAGE_DUR) < 0)
+               MsgSettingSetInt(MMS_STYLE_PAGE_DUR, 2);
+
+       if (MsgSettingGetInt(MMS_STYLE_PAGE_CUSTOM_DUR) < 0)
+               MsgSettingSetInt(MMS_STYLE_PAGE_CUSTOM_DUR, 0);
+
+       if (MsgSettingGetInt(MMS_STYLE_PAGE_DUR_MANUAL) < 0)
+               MsgSettingSetInt(MMS_STYLE_PAGE_DUR_MANUAL, 0);
+
+       // Set Default Push Msg Opt
+       if (MsgSettingGetBool(PUSH_RECV_OPTION, &bTmp) < 0)
+               MsgSettingSetBool(PUSH_RECV_OPTION, false);
+
+       if (MsgSettingGetInt(PUSH_SERVICE_TYPE) < 0)
+               MsgSettingSetInt(PUSH_SERVICE_TYPE, (int)MSG_PUSH_SERVICE_PROMPT);
+
+       // Set Default Cb Msg Opt
+       if (MsgSettingGetBool(CB_RECEIVE, &bTmp) < 0)
+               MsgSettingSetBool(CB_RECEIVE, false);
+
+       if (MsgSettingGetBool(CB_ALL_CHANNEL, &bTmp) < 0)
+               MsgSettingSetBool(CB_ALL_CHANNEL, false);
+
+       if (MsgSettingGetInt(CB_MAX_SIM_COUNT) < 0)
+               MsgSettingSetInt(CB_MAX_SIM_COUNT, 0);
+
+       if (MsgSettingGetInt(CB_CHANNEL_COUNT) < 0)
+               MsgSettingSetInt(CB_CHANNEL_COUNT, 0);
+
+       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);
+
+               if (MsgSettingGetBool(keyName, &bTmp) < 0)
+                       MsgSettingSetBool(keyName, false);
+       }
+
+       // Set Default SOS Msg Opt
+       if (MsgSettingGetBool(SOS_SEND_OPTION, &bTmp) < 0)
+               MsgSettingSetBool(SOS_SEND_OPTION, false);
+
+       if (MsgSettingGetInt(SOS_RECIPIENT_COUNT) < 0)
+               MsgSettingSetInt(SOS_RECIPIENT_COUNT, 0);
+
+       if (MsgSettingGetInt(SOS_REPEAT_COUNT) < 0)
+               MsgSettingSetInt(SOS_REPEAT_COUNT, (int)MSG_SOS_REPEAT_ONCE);
+
+       char *tmpValue = NULL;
+
+       tmpValue = MsgSettingGetString(keyName);
+
+       if (tmpValue == NULL) {
+               MsgSettingSetString(keyName, NULL);
+       } else {
+               free(tmpValue);
+               tmpValue = NULL;
+       }
+
+       if (MsgSettingGetInt(SOS_ALERT_TYPE) < 0)
+               MsgSettingSetInt(SOS_ALERT_TYPE, (int)MSG_SOS_ALERT_TYPE_SOS);
+
+       if (MsgSettingGetInt(MSGSIZE_OPTION) < 0)
+               MsgSettingSetInt(MSGSIZE_OPTION, 300);
+}
+#endif /* __NOT_USED_BY_ENV_CHANGE__ */
\ No newline at end of file
diff --git a/framework/storage-handler/MsgStorageFilter.cpp b/framework/storage-handler/MsgStorageFilter.cpp
new file mode 100755 (executable)
index 0000000..9cefcc8
--- /dev/null
@@ -0,0 +1,265 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgSqliteWrapper.h"
+#include "MsgStorageHandler.h"
+
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+extern MsgDbHandler dbHandle;
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+msg_error_t MsgStoCheckDuplicatedFilter(const MSG_FILTER_S *pFilter)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+       int rowCnt = 0;
+
+       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 FILTER_VALUE = '%s';",
+                       MSGFW_FILTER_TABLE_NAME, pFilter->filterType, pFilter->filterValue);
+
+       MSG_DEBUG("sql : %s", sqlQuery);
+
+       err = dbHandle.getTable(sqlQuery, &rowCnt);
+
+       if (err == MSG_SUCCESS)
+               err = MSG_ERR_FILTER_DUPLICATED;
+       else if (err == MSG_ERR_DB_NORECORD)
+               err = MSG_SUCCESS;
+
+       dbHandle.freeTable();
+
+       MSG_END();
+
+       return err;
+}
+
+
+msg_error_t MsgStoAddFilter(const MSG_FILTER_S *pFilter)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       //check duplication
+       err = MsgStoCheckDuplicatedFilter(pFilter);
+
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Filter is duplicated : [%d]", err);
+               return err;
+       }
+
+       unsigned int rowId = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       err = dbHandle.getRowId(MSGFW_FILTER_TABLE_NAME, &rowId);
+
+       if (err != MSG_SUCCESS)
+               return err;
+
+       // Add Filter
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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)
+               return MSG_ERR_DB_EXEC;
+
+       dbHandle.bindText(pFilter->filterValue, 1);
+
+       if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_EXEC;
+       }
+
+       dbHandle.finalizeQuery();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoUpdateFilter(const MSG_FILTER_S *pFilter)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       //check duplication
+       err = MsgStoCheckDuplicatedFilter(pFilter);
+
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Filter is duplicated : [%d]", err);
+               return err;
+       }
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       // Update Filter
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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)
+               return MSG_ERR_DB_PREPARE;
+
+       dbHandle.bindText(pFilter->filterValue, 1);
+
+       if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_EXEC;
+       }
+
+       dbHandle.finalizeQuery();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoDeleteFilter(msg_filter_id_t filterId)
+{
+       MSG_BEGIN();
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       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);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       dbHandle.endTrans(true);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetFilterList(msg_struct_list_s *pFilterList)
+{
+       MSG_BEGIN();
+
+       if (pFilterList == NULL) {
+               MSG_DEBUG("pFilterList is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       int rowCnt = 0, index = 4;
+
+       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, FILTER_ACTIVE FROM %s;", MSGFW_FILTER_TABLE_NAME);
+
+       msg_error_t err = MSG_SUCCESS;
+
+       err = dbHandle.getTable(sqlQuery, &rowCnt);
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               pFilterList->nCount = 0;
+               pFilterList->msg_struct_info = NULL;
+
+               dbHandle.freeTable();
+
+               return MSG_SUCCESS;
+       } else if (err != MSG_SUCCESS) {
+               dbHandle.freeTable();
+               return err;
+       }
+
+       pFilterList->nCount = rowCnt;
+
+       MSG_DEBUG("pMsgCommInfoList->nCount [%d]", pFilterList->nCount);
+
+       pFilterList->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_FILTER_S *)*rowCnt];
+
+       msg_struct_s* pTmp = NULL;
+
+       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);
+               pFilter->bActive = dbHandle.getColumnToInt(index++);
+       }
+
+
+       dbHandle.freeTable();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoSetFilterActivation(msg_filter_id_t filterId, bool bActive)
+{
+       MSG_BEGIN();
+
+       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();
+
+       return MSG_SUCCESS;
+}
diff --git a/framework/storage-handler/MsgStorageFolder.cpp b/framework/storage-handler/MsgStorageFolder.cpp
new file mode 100755 (executable)
index 0000000..55a2038
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilStorage.h"
+#include "MsgSqliteWrapper.h"
+#include "MsgStorageHandler.h"
+
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+extern MsgDbHandler dbHandle;
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+msg_error_t MsgStoAddFolder(const MSG_FOLDER_INFO_S *pFolderInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       unsigned int rowId = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       err = dbHandle.getRowId(MSGFW_FOLDER_TABLE_NAME, &rowId);
+
+       if (err != MSG_SUCCESS)
+               return err;
+
+       // Add Folder
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       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)
+               return MSG_ERR_DB_EXEC;
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoUpdateFolder(const MSG_FOLDER_INFO_S *pFolderInfo)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       // 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)
+               return MSG_ERR_DB_EXEC;
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoDeleteFolder(const msg_folder_id_t folderId)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       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);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE FOLDER_ID = %d;",
+                       MSGFW_FOLDER_TABLE_NAME, folderId);
+
+       // Delete Message in the folder from msg table
+       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;
+       }
+
+       dbHandle.endTrans(true);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetFolderList(msg_struct_list_s *pFolderList)
+{
+       if (pFolderList == NULL) {
+               MSG_DEBUG("pFolderList is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       int rowCnt = 0;
+       int index = 3;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       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();
+               return MSG_ERR_DB_GETTABLE;
+       }
+
+       pFolderList->nCount = rowCnt;
+
+       MSG_DEBUG("pFolderList->nCount [%d]", pFolderList->nCount);
+
+       pFolderList->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_FOLDER_INFO_S *)*rowCnt];
+
+       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)];
+               pTmp = (msg_struct_s *)pFolderList->msg_struct_info[i];
+               pTmp->type = MSG_STRUCT_FOLDER_INFO;
+               pTmp->data = new char[sizeof(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->folderType = dbHandle.getColumnToInt(index++);
+
+               memset(pFolder->folderName, 0x00, sizeof(pFolder->folderName));
+               dbHandle.getColumnToString(index++, MAX_FOLDER_NAME_SIZE, pFolder->folderName);
+
+       }
+
+       dbHandle.freeTable();
+
+       return MSG_SUCCESS;
+}
diff --git a/framework/storage-handler/MsgStorageManager.cpp b/framework/storage-handler/MsgStorageManager.cpp
new file mode 100755 (executable)
index 0000000..3ed7eb6
--- /dev/null
@@ -0,0 +1,1302 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <sys/stat.h>
+#include <errno.h>
+
+#include <VMessage.h>
+#include <VCard.h>
+#include "MsgVMessage.h"
+
+#include "MsgDebug.h"
+#include "MsgUtilFile.h"
+#include "MsgUtilStorage.h"
+#include "MsgGconfWrapper.h"
+#include "MsgSqliteWrapper.h"
+#include "MsgPluginManager.h"
+#include "MsgStorageHandler.h"
+
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+MsgDbHandler dbHandle;
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+msg_error_t MsgStoConnectDB()
+{
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoDisconnectDB()
+{
+       if (dbHandle.disconnect() != MSG_SUCCESS) {
+               MSG_DEBUG("DB Disconnect Fail");
+               return MSG_ERR_DB_DISCONNECT;
+       }
+
+       MSG_DEBUG("DB Disconnect Success");
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoInitDB(bool bSimChanged)
+{
+       MSG_BEGIN();
+
+       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)) {
+               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);
+
+               if (err == MSG_SUCCESS)
+                       MSG_DEBUG("SUCCESS : create %s.", MSGFW_CONVERSATION_TABLE_NAME);
+               else
+                       MSG_DEBUG("FAIL : create %s [%d].", MSGFW_CONVERSATION_TABLE_NAME, err);
+       }
+
+       return err;
+}
+
+
+msg_error_t MsgCreateAddressTable()
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       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);
+
+               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);
+       }
+
+       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);
+       }
+
+       return err;
+}
+
+
+msg_error_t MsgCreateMsgTable()
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       if (!dbHandle.checkTableExist(MSGFW_MESSAGE_TABLE_NAME)) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+               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 , \
+                               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);
+       }
+
+       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);
+       }
+
+       return err;
+}
+
+
+msg_error_t MsgCreateWAPMessageTable()
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       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);
+       }
+
+       return err;
+}
+
+
+msg_error_t MsgCreateCBMessageTable()
+{
+       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);
+
+               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);
+       }
+
+       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);
+
+               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);
+       }
+
+       return err;
+}
+
+msg_error_t MsgCreateSmsSendOptTable()
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       if (!dbHandle.checkTableExist(MSGFW_SMS_SENDOPT_TABLE_NAME)) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+               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);
+
+               err = dbHandle.execQuery(sqlQuery);
+
+               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;
+}
+
+
+msg_error_t MsgCreateFilterTable()
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       if (!dbHandle.checkTableExist(MSGFW_FILTER_TABLE_NAME)) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "CREATE TABLE %s ( \
+                               FILTER_ID INTEGER PRIMARY KEY , \
+                               FILTER_TYPE INTEGER NOT NULL , \
+                               FILTER_VALUE TEXT NOT NULL , \
+                               FILTER_ACTIVE INTEGER DEFAULT 0);",
+                               MSGFW_FILTER_TABLE_NAME);
+
+               err = dbHandle.execQuery(sqlQuery);
+
+               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;
+}
+
+
+msg_error_t MsgCreateMmsTable()
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       if (!dbHandle.checkTableExist(MMS_PLUGIN_MESSAGE_TABLE_NAME)) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+               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);
+
+               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);
+       }
+
+       return err;
+}
+
+
+msg_error_t MsgAddDefaultFolders()
+{
+       int nRowCnt = 0;
+       int nResult = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       // 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();
+               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, 'INBOX', %d);",
+                               MSGFW_FOLDER_TABLE_NAME, MSG_INBOX_ID, MSG_FOLDER_TYPE_INBOX);
+
+               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_EXEC;
+       }
+
+       // OUTBOX
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       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();
+               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, 'OUTBOX', %d);",
+                               MSGFW_FOLDER_TABLE_NAME, MSG_OUTBOX_ID, MSG_FOLDER_TYPE_OUTBOX);
+
+               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_EXEC;
+       }
+
+       // SENTBOX
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       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();
+               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, 'SENTBOX', %d);",
+                               MSGFW_FOLDER_TABLE_NAME, MSG_SENTBOX_ID, MSG_FOLDER_TYPE_OUTBOX);
+
+               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_EXEC;
+       }
+
+       // DRAFT
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       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();
+               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, 'DRAFT', %d);",
+                               MSGFW_FOLDER_TABLE_NAME, MSG_DRAFT_ID, MSG_FOLDER_TYPE_DRAFT);
+
+               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_EXEC;
+       }
+
+       // CBMSGBOX
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       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();
+               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, 'CBMSGBOX', %d);",
+                               MSGFW_FOLDER_TABLE_NAME, MSG_CBMSGBOX_ID, MSG_FOLDER_TYPE_INBOX);
+
+               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_EXEC;
+       }
+
+       // SPAMBOX
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       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();
+               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, '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)
+                       return MSG_ERR_DB_EXEC;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgAddDefaultAddress()
+{
+       MSG_BEGIN();
+
+       int nRowCnt = 0, nResult = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       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();
+               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 (0, 0, 0, '', 0, '', '', '', '', 0, 0, 0, 0, 0, 0, 0, 0, '');",
+                               MSGFW_ADDRESS_TABLE_NAME);
+
+               MSG_DEBUG("%s", sqlQuery);
+
+               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_EXEC;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoResetDatabase()
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       const char* tableList[] = {MSGFW_FOLDER_TABLE_NAME, MSGFW_FILTER_TABLE_NAME,
+                       MSGFW_PUSH_MSG_TABLE_NAME, MSGFW_CB_MSG_TABLE_NAME,
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, MSGFW_SYNCML_MSG_TABLE_NAME,
+                       MSGFW_SMS_SENDOPT_TABLE_NAME};
+
+       int listCnt = sizeof(tableList)/sizeof(char*);
+
+       dbHandle.beginTrans();
+
+       // Delete Database
+       for (int i = 0; i < listCnt; i++)
+       {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s;", tableList[i]);
+
+               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle.endTrans(false);
+                       return MSG_ERR_DB_EXEC;
+               }
+       }
+
+       // Delete Message Table
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       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);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       // Delete Conversation Table
+       err = MsgStoClearConversationTable(&dbHandle);
+
+       if (err != MSG_SUCCESS) {
+               dbHandle.endTrans(false);
+               return err;
+       }
+
+       // Add Default Folders
+       if (MsgAddDefaultFolders() != MSG_SUCCESS) {
+               MSG_DEBUG("Add Default Folders Fail");
+               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);
+               return MSG_ERR_DB_STORAGE_INIT;
+       }
+
+       dbHandle.endTrans(true);
+
+       // Delete MMS Files
+       MsgRmRf((char*)MSG_DATA_PATH);
+       MsgRmRf((char*)MSG_SMIL_FILE_PATH);
+
+       // Reset SMS Count
+       if (MsgSettingSetIndicator(0, 0) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgSettingSetIndicator() FAILED");
+               return MSG_ERR_SET_SETTING;
+       }
+
+       // Reset MMS Count
+       if (MsgSettingSetIndicator(0, 0) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgSettingSetIndicator() FAILED");
+               return MSG_ERR_SET_SETTING;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoBackupMessage(msg_message_backup_type_t type, const char *filepath)
+{
+       msg_error_t     err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       int rowCnt = 0;
+       int index = 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_DEBUG("Fail to delete [%s].", fileName);
+       }
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       MSG_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);
+
+       if (err != MSG_SUCCESS) {
+               dbHandle.freeTable();
+               return err;
+       }
+       MSG_DEBUG("backup number = %d", rowCnt);
+
+       for (int i = 0; i < rowCnt; i++) {
+               err = MsgStoGetMessage(dbHandle.getColumnToInt(++index), &msgInfo, NULL);
+               if(err != MSG_SUCCESS) {
+                       dbHandle.freeTable();
+                       return err;
+               }
+
+               encoded_data = MsgVMessageAddRecord(&dbHandle, &msgInfo);
+
+               if (encoded_data != NULL) {
+                       if (MsgAppendFile(fileName, encoded_data, strlen(encoded_data)) == false) {
+                               dbHandle.freeTable();
+                               free(encoded_data);
+                               return MSG_ERR_STORAGE_ERROR;
+                       }
+
+                       free(encoded_data);
+               }
+
+               memset(&msgInfo, 0, sizeof(MSG_MESSAGE_INFO_S));
+       }
+
+       dbHandle.freeTable();
+       MSG_END();
+       return MSG_SUCCESS;
+
+}
+
+msg_error_t MsgStoUpdateMms(MSG_MESSAGE_INFO_S *pMsg)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       if (pMsg->msgType.subType == MSG_SENDCONF_MMS) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+               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);
+                       return MSG_ERR_DB_EXEC;
+               }
+
+
+               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);
+                       return MSG_ERR_DB_EXEC;
+               }
+
+               dbHandle.finalizeQuery();
+               dbHandle.endTrans(true);
+       } else {
+               MsgStoUpdateMMSMessage(pMsg);
+       }
+       return MSG_SUCCESS;
+}
+
+msg_error_t MsgStoRestoreMessage(const char *filepath)
+{
+       msg_error_t err = MSG_SUCCESS;
+       MSG_MESSAGE_INFO_S msgInfo = {0,};
+
+       VTree* vMsg = NULL;
+       VObject* pObject = NULL;
+
+       int dataSize = 0;
+
+       char fileName[MSG_FILENAME_LEN_MAX+1];
+       char *pData = NULL;
+       char *pCurrent = NULL;
+       char *pTemp = 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)
+               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);
+#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);
+                                                       return MSG_ERR_STORAGE_ERROR;
+                                               }
+                                       }
+                                       break;
+
+                                       case VMSG_TYPE_MSGBOX :
+                                       {
+                                               if(!strncmp(pObject->pszValue[0], "INBOX", strlen("INBOX"))) {
+                                                       msgInfo.folderId= MSG_INBOX_ID;
+                                                       msgInfo.direction=MSG_DIRECTION_TYPE_MT;
+
+                                                       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);
+                                                       return MSG_ERR_STORAGE_ERROR;
+                                               }
+                                       }
+                                       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);
+                                                       return MSG_ERR_STORAGE_ERROR;
+                                               }
+                                       }
+                                       break;
+
+                                       case VMSG_TYPE_DATE :
+                                       {
+                                               struct tm       displayTime;
+
+                                               if (!_convert_vdata_str_to_tm(pObject->pszValue[0], &displayTime)) {
+                                                       vmsg_free_vtree_memory( vMsg );
+                                                       return MSG_ERR_STORAGE_ERROR;
+                                               }
+
+                                               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);
+                                                                       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, 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(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);
+                                                               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);
+                                                               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_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);
+///////////////////////////
+                                                       }
+                                               }
+                                       }
+                                       break;
+
+                                       case VCARD_TYPE_TEL :
+                                       {
+                                               msgInfo.nAddressCnt++;
+
+                                               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);
+
+               vmsg_free_vtree_memory(vMsg);
+
+               vMsg = NULL;
+               pCurrent = pTemp + strlen("END:VMSG");
+       }
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t MsgStoAddPushEvent(MSG_PUSH_EVENT_INFO_S* pPushEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+       char sqlQuery[MAX_QUERY_LEN+1];
+       unsigned int rowId = 0;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       // Check whether Same record exists or not.
+       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);
+
+       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();
+       err = dbHandle.getRowId(MSGFW_PUSH_CONFIG_TABLE_NAME, &rowId);
+       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)
+{
+       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 MsgStoUpdatePushEvent(MSG_PUSH_EVENT_INFO_S* pSrc, MSG_PUSH_EVENT_INFO_S* pDst)
+{
+       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;
+}
diff --git a/framework/storage-handler/MsgStorageMessage.cpp b/framework/storage-handler/MsgStorageMessage.cpp
new file mode 100755 (executable)
index 0000000..252c372
--- /dev/null
@@ -0,0 +1,3328 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <locale>
+#include <glib.h>
+
+#include "MsgDebug.h"
+#include "MsgCppTypes.h"
+#include "MsgContact.h"
+#include "MsgUtilFile.h"
+#include "MsgMutex.h"
+#include "MsgUtilStorage.h"
+#include "MsgSoundPlayer.h"
+#include "MsgGconfWrapper.h"
+#include "MsgSqliteWrapper.h"
+#include "MsgPluginManager.h"
+#include "MsgStorageHandler.h"
+#include "MsgNotificationWrapper.h"
+#include "MsgMmsMessage.h"
+
+using namespace std;
+
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+extern MsgDbHandler dbHandle;
+
+Mutex delNotiMx;
+CndVar delNoticv;
+bool delNotiRunning = false;
+
+Mutex delLogMx;
+CndVar delLogcv;
+bool delLogRunning = false;
+
+
+/*==================================================================================================
+                                     FUNCTION FOR THREAD
+==================================================================================================*/
+static gboolean updateUnreadMsgCount(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);
+
+       MSG_END();
+
+       return FALSE;
+}
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+msg_error_t MsgStoAddMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       unsigned int rowId = 0;
+       msg_thread_id_t convId = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       dbHandle.beginTrans();
+
+       if (pMsg->nAddressCnt > 0) {
+               err = MsgStoAddAddress(&dbHandle, pMsg, &convId);
+
+               if (err != MSG_SUCCESS) {
+                       dbHandle.endTrans(false);
+                       return err;
+               }
+
+               pMsg->threadId = convId;
+       }
+
+       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;
+
+       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;
+               }
+               MSG_DEBUG("file size [%d]", fileSize);
+       }
+
+       // 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, ?, ?, ?, ?, 0);",
+                       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_DEBUG("QUERY : %s", sqlQuery);
+
+       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->bTextSms == false)
+               dbHandle.bindText(pFileData, 4);
+       else
+               dbHandle.bindText(pMsg->msgText, 4);
+
+       if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle.finalizeQuery();
+               dbHandle.endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       dbHandle.finalizeQuery();
+
+       if (pMsg->msgType.subType != MSG_SENDREQ_MMS) {
+               err = MsgStoUpdateConversation(&dbHandle, convId);
+
+               if (err != MSG_SUCCESS) {
+                       dbHandle.endTrans(false);
+                       return err;
+               }
+       }
+
+       dbHandle.endTrans(true);
+
+       /* 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->msgType.subType != MSG_DELIVERYIND_MMS && pMsg->msgType.subType != MSG_READORGIND_MMS) {
+                       MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_MMS_TYPE);
+
+                       err = plg->addMessage(pMsg, pSendOptInfo, pFileData);
+
+                       if (err != MSG_SUCCESS)
+                               return MSG_ERR_STORAGE_ERROR;
+
+                       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)
+                                       return MSG_ERR_STORAGE_ERROR;
+
+                       }
+               }
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoUpdateMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       msg_thread_id_t convId = 0;
+
+       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.endTrans(false);
+               return err;
+       }
+
+       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;
+               }
+       }
+
+       if (pSendOptInfo != NULL) {
+               // Get Global setting value if bSetting == false
+               if (pSendOptInfo->bSetting == false) {
+                       MsgSettingGetBool(MSG_KEEP_COPY, &pSendOptInfo->bKeepCopy);
+
+                       if (pMsg->msgType.mainType == MSG_SMS_TYPE) {
+                               MsgSettingGetBool(SMS_SEND_DELIVERY_REPORT, &pSendOptInfo->bDeliverReq);
+                               MsgSettingGetBool(SMS_SEND_REPLY_PATH, &pSendOptInfo->option.smsSendOptInfo.bReplyPath);
+                       } else if (pMsg->msgType.mainType == MSG_MMS_TYPE) {
+                               MsgSettingGetBool(MMS_SEND_DELIVERY_REPORT, &pSendOptInfo->bDeliverReq);
+                               MsgSettingGetBool(MMS_SEND_READ_REPLY, &pSendOptInfo->option.mmsSendOptInfo.bReadReq);
+                               pSendOptInfo->option.mmsSendOptInfo.expiryTime.time = (unsigned int)MsgSettingGetInt(MMS_SEND_EXPIRY_TIME);
+
+                               MSG_MMS_DELIVERY_TIME_T deliveryTime = (MSG_MMS_DELIVERY_TIME_T)MsgSettingGetInt(MMS_SEND_DELIVERY_TIME);
+
+                               if (deliveryTime == MSG_DELIVERY_TIME_CUSTOM) {
+                                       pSendOptInfo->option.mmsSendOptInfo.bUseDeliveryCustomTime = true;
+                                       pSendOptInfo->option.mmsSendOptInfo.deliveryTime.time = (unsigned int)MsgSettingGetInt(MMS_SEND_CUSTOM_DELIVERY);
+                               } else {
+                                       pSendOptInfo->option.mmsSendOptInfo.bUseDeliveryCustomTime = false;
+                                       pSendOptInfo->option.mmsSendOptInfo.deliveryTime.time = (unsigned int)deliveryTime;
+                               }
+
+                               pSendOptInfo->option.mmsSendOptInfo.priority = (msg_priority_type_t)MsgSettingGetInt(MMS_SEND_PRIORITY);
+                       }
+               }
+       }
+
+       // Update Message
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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 = ? \
+                       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.finalizeQuery();
+               dbHandle.endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       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);
+                               return MSG_ERR_DB_EXEC;
+                       }
+               }
+       } else if (pMsg->msgType.mainType == MSG_MMS_TYPE) {
+               MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_MMS_TYPE);
+
+               err = plg->updateMessage(pMsg, pSendOptInfo, pFileData);
+
+               if (err != MSG_SUCCESS) {
+                       dbHandle.endTrans(false);
+                       return MSG_ERR_STORAGE_ERROR;
+               }
+
+               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) {
+                               return MSG_ERR_STORAGE_ERROR;
+                       }
+               }
+       }
+
+       err = MsgStoUpdateConversation(&dbHandle, convId);
+
+       if (err != MSG_SUCCESS) {
+               dbHandle.endTrans(false);
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       err = MsgStoClearConversationTable(&dbHandle);
+
+       if (err != MSG_SUCCESS) {
+               dbHandle.endTrans(false);
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       dbHandle.endTrans(true);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoUpdateReadStatus(msg_message_id_t msgId, bool bRead)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       msg_storage_id_t storageId;
+
+       if (MsgStoSetReadStatus(&dbHandle, msgId, bRead) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgStoSetReadStatus() Error");
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       // 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)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+               storageId = dbHandle.columnInt(0);
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       MSG_DEBUG("StorageId:[%d]", storageId);
+
+       // Update Read Status for SIM Msg
+       if (storageId == MSG_STORAGE_SIM) {
+               MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
+
+               if (plg == NULL) {
+                       MSG_DEBUG("SMS Plug-in is NULL");
+                       return MSG_ERR_NULL_POINTER;
+               }
+
+               // Get SIM Msg 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);
+
+               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_PREPARE;
+
+               msg_sim_id_t simId;
+
+               while (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+                       simId = dbHandle.columnInt(0);
+
+                       if (plg->setReadStatus(simId) != MSG_SUCCESS) {
+                               MSG_DEBUG("Fail to Set Read Status for SIM SMS");
+                               continue;
+                       }
+               }
+
+               dbHandle.finalizeQuery();
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoUpdateThreadReadStatus(msg_thread_id_t threadId)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       int rowCnt = 0;
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       // 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);
+
+       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();
+
+       // set read status
+       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);
+
+       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+
+       if (MsgStoUpdateConversation(&dbHandle, threadId) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgStoUpdateConversation() Error");
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       if (g_idle_add(updateUnreadMsgCount, NULL) == 0) {
+               MSG_DEBUG("updateUnreadMsgCount() Error");
+       }
+
+       MsgRefreshNoti(false);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoUpdateProtectedStatus(msg_message_id_t msgId, bool bProtected)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       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)
+               return MSG_ERR_DB_EXEC;
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoDeleteMessage(msg_message_id_t msgId, bool bCheckIndication)
+{
+       MSG_BEGIN();
+
+       MSG_DEBUG("Msg Id : %d", msgId);
+
+       msg_error_t err = MSG_SUCCESS;
+
+       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, STORAGE_ID, READ_STATUS, CONV_ID \
+                       FROM %s WHERE MSG_ID = %d;", MSGFW_MESSAGE_TABLE_NAME, msgId);
+
+       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Query Failed [%s]", sqlQuery);
+               return MSG_ERR_DB_PREPARE;
+       }
+
+       MSG_MESSAGE_TYPE_S msgType;
+       msg_folder_id_t folderId;
+       msg_storage_id_t storageId;
+       msg_thread_id_t convId;
+       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);
+
+               MSG_DEBUG("Main Type:[%d] SubType:[%d] FolderId:[%d] StorageId:[%d] ConversationId:[%d]", msgType.mainType, msgType.subType, folderId, storageId, convId);
+       } else {
+               MSG_DEBUG("MsgStepQuery() Error [%s]", sqlQuery);
+
+               dbHandle.finalizeQuery();
+
+               return MSG_ERR_DB_STEP;
+       }
+
+       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();
+
+       // 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_DEBUG("sqlQuery is [%s]", sqlQuery);
+
+               msg_sim_id_t simMsgId;
+
+               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle.endTrans(false);
+                       return MSG_ERR_DB_PREPARE;
+               }
+
+               while (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+                       simMsgId = dbHandle.columnInt(0);
+
+                       MSG_DEBUG("SIM Msg Id : [%d]", simMsgId);
+
+                       err = plg->deleteSimMessage(simMsgId);
+
+                       if (err != MSG_SUCCESS) {
+                               dbHandle.finalizeQuery();
+                               dbHandle.endTrans(false);
+                               return err;
+                       }
+
+                       //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);
+
+                       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle.finalizeQuery();
+                               dbHandle.endTrans(false);
+                               return MSG_ERR_DB_EXEC;
+                       }
+               }
+
+               dbHandle.finalizeQuery();
+       }
+
+       /* each type has to be handled in plug in ? */
+       if (msgType.mainType == MSG_SMS_TYPE) {
+               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;
+                       }
+               }
+       } else if (msgType.mainType == MSG_MMS_TYPE) {
+
+               char filePath[MSG_FILEPATH_LEN_MAX] = {0,};
+               char dirPath[MSG_FILEPATH_LEN_MAX]= {0,};
+
+               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);
+                       return MSG_ERR_DB_PREPARE;
+               }
+
+               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);
+                       else
+                               MSG_DEBUG("Success to delete file [%s]", filePath);
+
+                       MsgRmRf(dirPath);
+
+                       rmdir(dirPath);
+
+               } else {
+                       MSG_DEBUG("MsgStepQuery() Error [%s]", sqlQuery);
+                       dbHandle.finalizeQuery();
+                       dbHandle.endTrans(false);
+                       return MSG_ERR_DB_STEP;
+               }
+
+               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_DEBUG("Fail to delete file [%s]", filePath);
+                       else
+                               MSG_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);
+                       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;
+               }
+       }
+
+       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.endTrans(false);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       if (convId > 0) {
+               // 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 (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) {
+                       MSG_DEBUG("Set Memory Status");
+
+                       plg->setMemoryStatus(MSG_SUCCESS);
+               }
+       }
+
+       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);
+
+               MsgRefreshNoti(false);
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoDeleteAllMessageInFolder(msg_folder_id_t folderId, bool bOnlyDB, msg_id_list_s *pMsgIdList)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       queue<msg_thread_id_t> threadList;
+
+       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};
+
+       int listCnt = sizeof(tableList)/sizeof(char *);
+       int rowCnt = 0;
+
+       // Get conversation ID from Folder
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT(CONV_ID) FROM %s WHERE FOLDER_ID = %d",
+                       MSGFW_MESSAGE_TABLE_NAME, folderId);
+
+       err = dbHandle.getTable(sqlQuery, &rowCnt);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               MSG_DEBUG("sql query is %s.", sqlQuery);
+
+               dbHandle.freeTable();
+               return err;
+       }
+
+       if (rowCnt <= 0) {
+               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));
+       }
+
+       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));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE FOLDER_ID = %d",
+                       MSGFW_MESSAGE_TABLE_NAME, folderId);
+
+       rowCnt = 0;
+       int index = 1;
+
+       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 In Folder **/
+       if (folderId >= MSG_INBOX_ID) {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+               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);
+
+               if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+                       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;
+                       }
+
+                       //Delete phone log
+//                     MsgDeletePhoneLog(dbHandle.getColumnToInt(i));
+               }
+
+               dbHandle.freeTable();
+       }
+
+       dbHandle.beginTrans();
+
+       for (int i = 0; i < listCnt; i++) {
+               if (!strcmp(tableList[i], MMS_PLUGIN_MESSAGE_TABLE_NAME)) {
+
+                       int rowCnt = 0;
+
+                       char filePath[MSG_FILEPATH_LEN_MAX] = {0,};
+                       char dirPath[MSG_FILEPATH_LEN_MAX] = {0,};
+
+                       //get mms msg id list
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT B.FILE_PATH FROM %s A, %s B \
+                                       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);
+                       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++) {
+
+                               memset(filePath, 0x00, sizeof(filePath));
+                               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);
+
+                               rmdir(dirPath);
+
+                       }
+
+                       dbHandle.freeTable();
+               }
+
+               // 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;
+               }
+
+               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_DEBUG("Fail to delete file [%s]", filePath);
+                       else
+                               MSG_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 \
+                               (SELECT MSG_ID FROM %s WHERE FOLDER_ID = %d);",
+                               tableList[i], MSGFW_MESSAGE_TABLE_NAME, folderId);
+
+               // 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;
+       }
+
+       // Update Address
+       while (!threadList.empty()) {
+               err = MsgStoUpdateConversation(&dbHandle, threadList.front());
+
+               threadList.pop();
+
+               if (err != MSG_SUCCESS) {
+                       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);
+       }
+
+/*** 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 (!bOnlyDB) {
+               if (pToDeleteMsgIdList->nCount > 0) {
+//                     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
+                                       if (pToDeleteMsgIdList->msgIdList != NULL)
+                                               delete [] pToDeleteMsgIdList->msgIdList;
+
+                                       delete [] pToDeleteMsgIdList;
+                               }
+//                             err = MSG_ERR_UNKNOWN;
+//                     }
+
+                       MsgRefreshNoti(false);
+               }
+       }
+/*** **/
+
+       return MSG_SUCCESS;
+
+FREE_MEMORY:
+       MSG_DEBUG("Error case Free Memory");
+
+       while (!threadList.empty()) {
+               threadList.front();
+               threadList.pop();
+       }
+
+       // memory free
+       if (pToDeleteMsgIdList != NULL) {
+               //free peer info list
+               if (pToDeleteMsgIdList->msgIdList != NULL)
+                       delete [] pToDeleteMsgIdList->msgIdList;
+
+               delete [] pToDeleteMsgIdList;
+       }
+
+       return err;
+
+}
+
+
+msg_error_t MsgStoDeleteMessageByList(msg_id_list_s *pMsgIdList)
+{
+       MSG_BEGIN();
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       char whereQuery[MAX_QUERY_LEN+1];
+       char sqlQuerySubset[(MAX_QUERY_LEN/5)+1];
+
+       queue<msg_thread_id_t> threadList;
+
+       const char *tableList[] = {MSGFW_PUSH_MSG_TABLE_NAME, MSGFW_CB_MSG_TABLE_NAME,
+                                               MSGFW_SYNCML_MSG_TABLE_NAME, MSGFW_SMS_SENDOPT_TABLE_NAME,
+                                               MSGFW_MMS_PREVIEW_TABLE_NAME, MSGFW_REPORT_TABLE_NAME,
+                                               MMS_PLUGIN_MESSAGE_TABLE_NAME,  MSGFW_MESSAGE_TABLE_NAME};
+
+       int listCnt = sizeof(tableList)/sizeof(char *);
+       int rowCnt = 0;
+
+       memset(whereQuery, 0x00, sizeof(whereQuery));
+
+       if (pMsgIdList->nCount < 1) {
+               return MSG_SUCCESS;
+       } else {
+               for (int i=0; i < pMsgIdList->nCount; i++) {
+                       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+                       if (i==0)
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "(MSG_ID = %d ", pMsgIdList->msgIdList[i]);
+                       else
+                               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "OR MSG_ID = %d ", pMsgIdList->msgIdList[i]);
+                       strncat(whereQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(whereQuery));
+               }
+       }
+       strncat(whereQuery, ");", MAX_QUERY_LEN-strlen(whereQuery));
+
+       // Get conversation ID from Folder
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT(CONV_ID) FROM %s WHERE ", MSGFW_MESSAGE_TABLE_NAME);
+       strncat(sqlQuery, whereQuery, MAX_QUERY_LEN-strlen(sqlQuery));
+
+       err = dbHandle.getTable(sqlQuery, &rowCnt);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               MSG_DEBUG("sql query is %s.", sqlQuery);
+               dbHandle.freeTable();
+               return err;
+       }
+
+       if (rowCnt <= 0) {
+               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));
+       }
+
+       dbHandle.freeTable();
+
+       /*** Delete Sim Message In Folder **/
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE STORAGE_ID = %d AND ", MSGFW_MESSAGE_TABLE_NAME, MSG_STORAGE_SIM);
+       strncat(sqlQuery, whereQuery, MAX_QUERY_LEN-strlen(sqlQuery));
+
+       rowCnt = 0;
+
+       err = dbHandle.getTable(sqlQuery, &rowCnt);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               MSG_DEBUG("sql query is %s.", sqlQuery);
+               dbHandle.freeTable();
+               return err;
+       }
+
+       for (int i = 1; i <= rowCnt; i++) {
+               err = MsgStoDeleteMessage(dbHandle.getColumnToInt(i), false);
+
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgStoDeleteMessage() Error!!!");
+                       dbHandle.freeTable();
+                       return err;
+               }
+       }
+
+       dbHandle.freeTable();
+       /*** **/
+
+       dbHandle.beginTrans();
+
+       for (int i = 0; i < listCnt; i++) {
+               if (!strcmp(tableList[i], MMS_PLUGIN_MESSAGE_TABLE_NAME)) {
+
+                       int rowCnt = 0;
+
+                       char filePath[MSG_FILEPATH_LEN_MAX] = {0,};
+                       char dirPath[MSG_FILEPATH_LEN_MAX] = {0,};
+//                     char thumbnailPath[MSG_FILEPATH_LEN_MAX] = {0,};
+
+                       //get mms msg id list
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT FILE_PATH FROM %s WHERE ", MMS_PLUGIN_MESSAGE_TABLE_NAME);
+                       strncat(sqlQuery, whereQuery, MAX_QUERY_LEN-strlen(sqlQuery));
+
+                       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);
+                               return err;
+                       }
+
+                       for (int i = 1; i <= rowCnt; i++) {
+                               memset(filePath, 0x00, sizeof(filePath));
+                               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);
+
+                               rmdir(dirPath);
+                       }
+
+                       dbHandle.freeTable();
+               } else if (!strcmp(tableList[i], MSGFW_MMS_PREVIEW_TABLE_NAME)) {
+                       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 ",
+                                       MSGFW_MMS_PREVIEW_TABLE_NAME, MSG_MMS_ITEM_TYPE_IMG, MSG_MMS_ITEM_TYPE_VIDEO);
+
+                       strncat(sqlQuery, whereQuery, MAX_QUERY_LEN-strlen(sqlQuery));
+
+                       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_DEBUG("Fail to delete file [%s]", filePath);
+                               else
+                                       MSG_DEBUG("Success to delete file [%s]", filePath);
+                       }
+
+                       dbHandle.finalizeQuery();
+               }
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE ", tableList[i]);
+               strncat(sqlQuery, whereQuery, MAX_QUERY_LEN-strlen(sqlQuery));
+
+               // Delete Message in specific folder from table
+               err = dbHandle.execQuery(sqlQuery);
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+                       dbHandle.endTrans(false);
+                       return err;
+               }
+       }
+
+       // Clear Conversation table
+       err = MsgStoClearConversationTable(&dbHandle);
+       if (err != MSG_SUCCESS) {
+               dbHandle.endTrans(false);
+               return err;
+       }
+
+       // Update Address
+       while (!threadList.empty()) {
+               err = MsgStoUpdateConversation(&dbHandle, threadList.front());
+
+               threadList.pop();
+
+               if (err != MSG_SUCCESS) {
+                       dbHandle.endTrans(false);
+                       return err;
+               }
+       }
+
+       dbHandle.endTrans(true);
+
+       int smsCnt = 0;
+       int mmsCnt = 0;
+
+       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
+       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
+
+       MsgSettingSetIndicator(smsCnt, mmsCnt);
+
+#if 0
+/*** Create thread  for noti and phone log delete. **/
+       if (pMsgIdList->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 = pMsgIdList->nCount;
+               pToDeleteMsgIdListCpy->msgIdList = (msg_message_id_t *)new char[sizeof(msg_message_id_t)*pMsgIdList->nCount];
+               memcpy(pToDeleteMsgIdListCpy->msgIdList, pMsgIdList->msgIdList, sizeof(msg_message_id_t)*pMsgIdList->nCount);
+
+               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;
+               }
+       }
+/*** **/
+#endif
+
+       MsgRefreshNoti(false);
+
+       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];
+
+       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);
+
+       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];
+
+       MSG_DEBUG("msgId : %d, destStorageId : %d", msgId, destStorageId);
+
+       switch (destStorageId) {
+       case MSG_STORAGE_SIM : // Move message to sim card
+               {
+                       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 ((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 WHERE MSG_ID = %d;",
+                                       MSGFW_MESSAGE_TABLE_NAME, destStorageId, msgId);
+
+                       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);",
+                                               MSGFW_SIM_MSG_TABLE_NAME, msgId, simIdList.simId[i]);
+
+                               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);
+
+                       if (err != MSG_SUCCESS) {
+                               dbHandle.freeTable();
+                               return err;
+                       }
+
+                       if (dbHandle.getColumnToInt(1) == MSG_STORAGE_SIM) {
+                               MSG_DEBUG("It is SIM Message");
+                               bSimMsg = true;
+                       }
+
+                       dbHandle.freeTable();
+
+                       if (bSimMsg == true) {
+                               msg_sim_id_t simMsgId;
+
+                               // 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_DEBUG("sqlQuery is %s.", sqlQuery);
+
+                               err = dbHandle.getTable(sqlQuery, &rowCnt);
+
+                               if (err != MSG_SUCCESS) {
+                                       dbHandle.freeTable();
+                                       return err;
+                               }
+
+                               //Delete messages in sim card
+                               MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(MSG_SMS_TYPE);
+
+                               for (int i = 0; i < rowCnt; i++) {
+                                       simMsgId = dbHandle.getColumnToInt(i+1);
+
+                                       MSG_DEBUG("simMsgId is %d.", simMsgId);
+
+                                       if ((err = plg->deleteSimMessage(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("sqlQuery is %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);
+
+                               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
+                                       dbHandle.endTrans(false);
+                                       return MSG_ERR_DB_EXEC;
+                               }
+
+                               dbHandle.endTrans(true);
+                       }
+               }
+       }
+
+       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];
+
+       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)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+               pCountInfo->nReadCnt = dbHandle.columnInt(0);
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+               pCountInfo->nUnreadCnt = dbHandle.columnInt(0);
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+               pCountInfo->nSms = dbHandle.columnInt(0);
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+               pCountInfo->nMms = dbHandle.columnInt(0);
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoCountMsgByType(const MSG_MESSAGE_TYPE_S *pMsgType, int *pMsgCount)
+{
+       if (pMsgType == NULL) {
+               MSG_DEBUG("pMsgType is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       *pMsgCount = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       // SMS
+       if ((pMsgType->mainType == MSG_SMS_TYPE) &&
+                       (pMsgType->subType == MSG_NORMAL_SMS || pMsgType->subType == MSG_STATUS_REPORT_SMS || pMsgType->subType == MSG_CONCAT_SIM_SMS)) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE MAIN_TYPE = %d AND SUB_TYPE IN (%d, %d, %d);",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsgType->mainType, MSG_NORMAL_SMS, MSG_STATUS_REPORT_SMS, MSG_CONCAT_SIM_SMS);
+       } else if ((pMsgType->mainType == MSG_SMS_TYPE) &&
+                       (pMsgType->subType == MSG_WAP_SI_SMS || pMsgType->subType == MSG_WAP_SL_SMS)) {
+               // PUSH
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE MAIN_TYPE = %d AND SUB_TYPE IN (%d, %d);",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsgType->mainType, MSG_WAP_SI_SMS, MSG_WAP_SL_SMS);
+       } else if ((pMsgType->mainType == MSG_MMS_TYPE) &&
+                       (pMsgType->subType == MSG_SENDREQ_MMS || pMsgType->subType == MSG_SENDCONF_MMS || pMsgType->subType == MSG_RETRIEVE_AUTOCONF_MMS || pMsgType->subType == MSG_RETRIEVE_MANUALCONF_MMS)) {
+               // MMS
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE MAIN_TYPE = %d AND SUB_TYPE IN (%d, %d, %d, %d);",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsgType->mainType, MSG_SENDREQ_MMS, MSG_SENDCONF_MMS, MSG_RETRIEVE_AUTOCONF_MMS, MSG_RETRIEVE_MANUALCONF_MMS);
+       } else {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+               *pMsgCount = dbHandle.columnInt(0);
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+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 \
+                       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) {
+               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) {
+                       if (pMsg->dataSize > MAX_MSG_TEXT_LEN) {
+                               char msgData[pMsg->dataSize+1];
+                               memset(msgData, 0x00, sizeof(msgData));
+
+                               strncpy(msgData, (char *)dbHandle.columnText(16), pMsg->dataSize);
+
+                               // Save Message Data into File
+                               char fileName[MSG_FILENAME_LEN_MAX+1];
+                               memset(fileName, 0x00, sizeof(fileName));
+
+                               if (MsgCreateFileName(fileName) == false) {
+                                       dbHandle.finalizeQuery();
+                                       return MSG_ERR_STORAGE_ERROR;
+                               }
+
+                               MSG_DEBUG("Save Message Data into file : size[%d] name[%s]\n", pMsg->dataSize, fileName);
+
+                               if (MsgWriteIpcFile(fileName, msgData, pMsg->dataSize) == false) {
+                                       dbHandle.finalizeQuery();
+                                       return MSG_ERR_STORAGE_ERROR;
+                               }
+
+                               strncpy(pMsg->msgData, fileName, MAX_MSG_DATA_LEN);
+
+                               pMsg->bTextSms = false;
+                       } else {
+                               memset(pMsg->msgText, 0x00, sizeof(pMsg->msgText));
+                               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);
+                                       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);
+               }
+
+               // thumbnail path
+               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);
+               }
+       } else {
+               dbHandle.finalizeQuery();
+               MSG_DEBUG("%s", sqlQuery);
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+
+       // get address information.
+       MsgStoGetAddressByMsgId(&dbHandle, pMsg->msgId, order, &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) {
+               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 (err != MSG_SUCCESS) {
+                       if (pDestMsg) {
+                               free(pDestMsg);
+                               pDestMsg = NULL;
+                       }
+                       return MSG_ERR_STORAGE_ERROR;
+               }
+
+               memset(pMsg->msgData, 0, MAX_MSG_DATA_LEN+1);
+
+               // Encode MMS specific data to MMS_MESSAGE_DATA_S
+               if (pMsg->dataSize > MAX_MSG_DATA_LEN) {
+                       // Save Message Data into File
+                       char tempFileName[MSG_FILENAME_LEN_MAX+1];
+                       memset(tempFileName, 0x00, sizeof(tempFileName));
+
+                       if (MsgCreateFileName(tempFileName) == false) {
+                               if(pDestMsg) {
+                                       free (pDestMsg);
+                                       pDestMsg = NULL;
+                               }
+                               return MSG_ERR_STORAGE_ERROR;
+                       }
+                       MSG_DEBUG("Save Message Data into file : size[%d] name[%s]\n", pMsg->dataSize, tempFileName);
+
+                       if (MsgWriteIpcFile(tempFileName, pDestMsg, pMsg->dataSize) == false) {
+                               if(pDestMsg) {
+                                       free (pDestMsg);
+                                       pDestMsg = NULL;
+                               }
+                               return MSG_ERR_STORAGE_ERROR;
+                       }
+                       strncpy(pMsg->msgData, tempFileName, MAX_MSG_DATA_LEN);
+                       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;
+               }
+       }
+
+       // Get SMS Sending Options
+       if (pMsg->msgType.mainType == MSG_SMS_TYPE && pSendOptInfo != NULL)
+               MsgStoGetSmsSendOpt(pMsg->msgId, pSendOptInfo);
+
+       return MSG_SUCCESS;
+}
+
+
+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;
+       }
+
+       int rowCnt = 0;
+       int index = 19; // numbers of index
+
+
+       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);
+
+       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("sqlQuery is - %s", sqlQuery);
+               dbHandle.freeTable();
+               return err;
+       }
+
+       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, 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;
+
+               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);
+       }
+
+       dbHandle.freeTable();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoAddSyncMLMessage(MSG_MESSAGE_INFO_S *pMsgInfo, int extId, int pinCode)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       unsigned int rowId = 0;
+       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;
+               }
+       }
+
+       // Add Message Table
+       pMsgInfo->threadId = convId;
+       rowId = MsgStoAddMessageTable(&dbHandle, pMsgInfo);
+
+       if (rowId <= 0) {
+               dbHandle.endTrans(false);
+               return MSG_ERR_DB_ROW;
+       }
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       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);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       if (MsgStoUpdateConversation(&dbHandle, convId) != MSG_SUCCESS) {
+               dbHandle.endTrans(false);
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       dbHandle.endTrans(true);
+
+       pMsgInfo->msgId = (msg_message_id_t)rowId;
+
+       MsgSoundPlayStart(false);
+
+       int smsCnt = 0;
+       int mmsCnt = 0;
+
+       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
+       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
+
+       MsgSettingHandleNewMsg(smsCnt, mmsCnt);
+
+       MsgInsertNoti(pMsgInfo);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetMsgType(msg_message_id_t msgId, MSG_MESSAGE_TYPE_S *pMsgType)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+               pMsgType->mainType = dbHandle.columnInt(0);
+               pMsgType->subType = dbHandle.columnInt(1);
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetQuickPanelData(msg_quickpanel_type_t QPtype, MSG_MESSAGE_INFO_S *pMsg)
+{
+       msg_error_t     err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       if (QPtype == MSG_QUICKPANEL_SMS) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE FOLDER_ID = %d AND MAIN_TYPE = %d AND SUB_TYPE = %d AND READ_STATUS = 0 ORDER BY DISPLAY_TIME DESC;",
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_INBOX_ID, MSG_SMS_TYPE, MSG_NORMAL_SMS);
+       } else if (QPtype == MSG_QUICKPANEL_MMS) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE FOLDER_ID = %d AND MAIN_TYPE = %d AND SUB_TYPE IN (%d, %d) AND READ_STATUS = 0 ORDER BY DISPLAY_TIME DESC;",
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_INBOX_ID, MSG_MMS_TYPE, MSG_RETRIEVE_AUTOCONF_MMS, MSG_RETRIEVE_MANUALCONF_MMS);
+       } else if (QPtype == MSG_QUICKPANEL_DELIVER_REP) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE SUB_TYPE IN (%d, %d) AND READ_STATUS = 0 ORDER BY DISPLAY_TIME DESC;",
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_STATUS_REPORT_SMS, MSG_DELIVERYIND_MMS);
+       } else if (QPtype == MSG_QUICKPANEL_READ_REP) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE MAIN_TYPE = %d AND SUB_TYPE = %d AND READ_STATUS = 0 ORDER BY DISPLAY_TIME DESC;",
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_MMS_TYPE, MSG_READORGIND_MMS);
+       } else if (QPtype == MSG_QUICKPANEL_VOICEMAIL) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE FOLDER_ID = %d AND MAIN_TYPE = %d AND SUB_TYPE = %d AND READ_STATUS = 0 ORDER BY DISPLAY_TIME DESC;",
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_INBOX_ID, MSG_SMS_TYPE, MSG_MWI_VOICE_SMS);
+       } else if (QPtype == MSG_QUICKPANEL_MMS_NOTI) {
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s WHERE FOLDER_ID = %d AND MAIN_TYPE = %d AND SUB_TYPE = %d AND READ_STATUS = 0 ORDER BY DISPLAY_TIME DESC;",
+                               MSGFW_MESSAGE_TABLE_NAME, MSG_INBOX_ID, MSG_MMS_TYPE, MSG_NOTIFICATIONIND_MMS);
+       }
+
+       // Get Message ID
+       msg_message_id_t msgId;
+
+       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+               msgId = dbHandle.columnInt(0);
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       // Get Message Info
+       err = MsgStoGetMessage(msgId, pMsg, NULL);
+
+       return err;
+}
+
+
+msg_error_t MsgStoGetThreadViewList(const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pThreadViewList)
+{
+       pThreadViewList->nCount = 0;
+       pThreadViewList->msg_struct_info = NULL;
+
+       int rowCnt = 0;
+       int index = 11; // numbers of index
+
+       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, \
+                       (SELECT COUNT(*) FROM %s B WHERE B.CONV_ID = A.CONV_ID AND B.PROTECTED = 1) AS PROTECTED \
+                       FROM %s A WHERE A.SMS_CNT > 0 OR A.MMS_CNT > 0 ORDER BY A.DISPLAY_TIME DESC;",
+                       MSGFW_MESSAGE_TABLE_NAME, MSGFW_CONVERSATION_TABLE_NAME);
+
+       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;
+       }
+
+       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 *)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++);
+
+               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;
+       }
+
+       dbHandle.freeTable();
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t MsgStoGetConversationPreview(MSG_CONVERSATION_VIEW_S *pConv)
+{
+       MsgDbHandler dbHandleForInner;
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       int rowCnt;
+       int index = 3;
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       if (pConv == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       //(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_DEBUG("QUERY : [%s]", sqlQuery);
+
+       msg_error_t err = dbHandleForInner.getTable(sqlQuery, &rowCnt);
+       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);
+                               dbHandleForInner.getColumnToInt(index++);
+                       } else if (type == MSG_MMS_ITEM_TYPE_PAGE) {
+                               index++;
+                               pConv->pageCount = dbHandleForInner.getColumnToInt(index++);
+                       } else {
+                               MSG_DEBUG("Unknown item type [%d]", type);
+                               index+=2;
+                       }
+               }
+       }
+
+       dbHandleForInner.freeTable();
+       return MSG_SUCCESS;
+}
+
+msg_error_t MsgStoGetConversationViewItem(msg_message_id_t msgId, MSG_CONVERSATION_VIEW_S *pConv)
+{
+       int rowCnt = 0;
+       int index = 16; /** numbers of index */
+       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 \
+                       FROM %s WHERE MSG_ID=%d;",
+                       MSGFW_MESSAGE_TABLE_NAME, msgId);
+
+       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;
+       }
+
+       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[MAX_MMS_TEXT_LEN+1];
+                       memset(tmpMmsText, 0x00, MAX_MMS_TEXT_LEN+1);
+
+                       dbHandle.getColumnToString(index++, MAX_MMS_TEXT_LEN, tmpMmsText);
+
+                       pConv->textSize = strlen(tmpMmsText);
+
+                       pConv->pText = new char[pConv->textSize+2];
+                       memset(pConv->pText, 0x00, pConv->textSize+2);
+
+                       strncpy(pConv->pText, tmpMmsText, pConv->textSize+1);
+
+                       MsgStoGetConversationPreview(pConv);
+               }
+       }
+
+       pConv->attachCount = dbHandle.getColumnToInt(index++);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t MsgStoGetConversationViewList(msg_thread_id_t threadId, msg_struct_list_s *pConvViewList)
+{
+       MSG_BEGIN();
+
+       pConvViewList->nCount = 0;
+       pConvViewList->msg_struct_info = NULL;
+
+       int rowCnt = 0;
+       int index = 16; /** numbers of index */
+       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 \
+                       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);
+
+       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];
+       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 char[sizeof(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 char[sizeof(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[MAX_MMS_TEXT_LEN+1];
+                               memset(tmpMmsText, 0x00, MAX_MMS_TEXT_LEN+1);
+
+                               dbHandle.getColumnToString(index++, MAX_MMS_TEXT_LEN, tmpMmsText);
+
+                               pTmp->textSize = strlen(tmpMmsText);
+
+                               pTmp->pText = new char[pTmp->textSize+2];
+                               memset(pTmp->pText, 0x00, pTmp->textSize+2);
+
+                               strncpy(pTmp->pText, tmpMmsText, pTmp->textSize+1);
+                       }
+               }
+
+               pTmp->attachCount = dbHandle.getColumnToInt(index++);
+
+               MsgStoGetConversationPreview(pTmp);
+       }
+
+       dbHandle.freeTable();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoDeleteThreadMessageList(msg_thread_id_t threadId, bool bIncludeProtect, msg_id_list_s *pMsgIdList)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       /*** Get msg id list **/
+       int rowCnt = 0;
+       int index = 1;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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);
+       }
+
+       err = dbHandle.getTable(sqlQuery, &rowCnt);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+               dbHandle.freeTable();
+       }
+
+       if (rowCnt <= 0) {
+               dbHandle.freeTable();
+               err = MSG_SUCCESS;
+       }
+
+       pMsgIdList->nCount = rowCnt;
+
+       MSG_DEBUG("pMsgIdList->nCount [%d]", pMsgIdList->nCount);
+
+       pMsgIdList->msgIdList = (msg_message_id_t *)new char[sizeof(msg_message_id_t) * rowCnt];
+
+       for (int i = 0; i < rowCnt; i++)
+               pMsgIdList->msgIdList[i] = dbHandle.getColumnToInt(index++);
+
+       dbHandle.freeTable();
+       /*** **/
+
+       err = MsgStoDeleteMessageByList(pMsgIdList);
+
+       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 CONV_ID, UNREAD_CNT, SMS_CNT, MMS_CNT, DISPLAY_NAME, \
+                       MAIN_TYPE, SUB_TYPE, MSG_DIRECTION, DISPLAY_TIME, MSG_TEXT \
+                       FROM %s WHERE DISPLAY_NAME LIKE '%%%s%%' ESCAPE '\\' ORDER BY DISPLAY_TIME DESC;",
+                       MSGFW_CONVERSATION_TABLE_NAME, 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, pTmp->dataSize + 2);
+
+                       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++);
+
+               dbHandle.getColumnToString(index++, MAX_ADDRESS_VAL_LEN, address->addressVal);
+
+               memset(displayName, 0x00, sizeof(displayName));
+               dbHandle.getColumnToString(index++, MAX_DISPLAY_NAME_LEN, displayName);
+
+               memset(firstName, 0x00, sizeof(firstName));
+               dbHandle.getColumnToString(index++, MAX_DISPLAY_NAME_LEN, firstName);
+
+               memset(lastName, 0x00, sizeof(lastName));
+               dbHandle.getColumnToString(index++, MAX_DISPLAY_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));
+                               }
+                       }
+               }
+
+               strncpy(address->displayName, displayName, MAX_DISPLAY_NAME_LEN);
+
+               pTmp->addr_list = addr_list;
+
+               pTmp->attachCount = dbHandle.getColumnToInt(index++);
+
+               dbHandle.getColumnToString(index++, MSG_FILEPATH_LEN_MAX, pTmp->thumbPath);
+
+       }
+       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];
+
+       pDestNum[i] = '\0';
+}
+
+
+msg_error_t MsgStoGetRejectMsgList(const char *pNumber, msg_struct_list_s *pRejectMsgList)
+{
+       // Clear Out Parameter
+       pRejectMsgList->nCount = 0;
+       pRejectMsgList->msg_struct_info = NULL;
+
+       int rowCnt = 0;
+       int index = 3; // numbers of index
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       // Search Reject Msg
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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);
+
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("%s", sqlQuery);
+
+               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;
+
+       for (int i = 0; i < rowCnt; i++) {
+               pRejectMsgList->msg_struct_info[i] = (msg_struct_t)new char[sizeof(msg_struct_s)];
+
+               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++);
+       }
+
+       dbHandle.freeTable();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetSyncMLExtId(msg_message_id_t msgId, int *extId)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT EXT_ID FROM %s WHERE MSG_ID = %d;",
+                       MSGFW_SYNCML_MSG_TABLE_NAME, msgId);
+
+       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.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t MsgStoGetReportStatus(msg_message_id_t msgId, int *count, MSG_REPORT_STATUS_INFO_S **pReportStatus)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       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;
+       msg_error_t  err = dbHandle.getTable(sqlQuery, &rowCnt);
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("%s", sqlQuery);
+               dbHandle.freeTable();
+               return err;
+       }
+
+       int index = 4;
+
+       *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++) {
+               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++);
+
+               MSG_DEBUG("(%d/%d) addr = %s, report_type = %d, report_status = %d, report_time = %d", i, rowCnt, report_status[i].addressVal, report_status[i].type, report_status[i].status, report_status[i].statusTime );
+       }
+
+       *pReportStatus = report_status;
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetThreadIdByAddress(const MSG_MESSAGE_INFO_S *pMsg, msg_thread_id_t *pThreadId)
+{
+       if(pMsg->nAddressCnt > 0) {
+               if (MsgExistAddress(&dbHandle, pMsg, pThreadId) == true) {
+                       MSG_DEBUG("Conversation ID : [%d]", *pThreadId);
+               } else {
+                       *pThreadId = 0;
+                       return MSG_ERR_STORAGE_ERROR;
+               }
+       } else {
+               *pThreadId = 0;
+       }
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetThreadUnreadCnt(msg_thread_id_t threadId, int *cnt)
+{
+       MSG_BEGIN();
+
+       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)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+               msgCnt = dbHandle.columnInt(0);
+       }
+
+       dbHandle.finalizeQuery();
+
+       *cnt = msgCnt;
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+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 = 11; // numbers of index
+
+       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, \
+                       (SELECT COUNT(*) FROM %s B WHERE B.CONV_ID = A.CONV_ID AND B.PROTECTED = 1) AS PROTECTED \
+                       FROM %s A WHERE A.CONV_ID = %d;",
+                       MSGFW_MESSAGE_TABLE_NAME, MSGFW_CONVERSATION_TABLE_NAME, threadId);
+
+       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;
+       }
+
+       if (rowCnt < 1) {
+               MSG_DEBUG("rowCnt is %d", rowCnt);
+               dbHandle.freeTable();
+               return err;
+       } else {
+               pThreadInfo->threadId = 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->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);
+
+               memset(pThreadInfo->threadData, 0x00, sizeof(pThreadInfo->threadData));
+               dbHandle.getColumnToString(index++, MAX_THREAD_DATA_LEN, pThreadInfo->threadData);
+
+               int protectedCnt = dbHandle.getColumnToInt(index++);
+               if (protectedCnt > 0)
+                       pThreadInfo->bProtected = true;
+       }
+
+       dbHandle.freeTable();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+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)
+{
+       // Clear Out Parameter
+       pMsgList->nCount = 0;
+       pMsgList->msg_struct_info = NULL;
+
+       int rowCnt = 0;
+       int index = 19; // numbers of index
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       char sqlQuerySubset[(MAX_QUERY_LEN/5)+1];
+
+       // Get Name Order
+       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, ATTACHMENT_COUNT, THUMB_PATH \
+                       FROM %s WHERE ", MSGFW_MESSAGE_TABLE_NAME);
+
+
+       //// folder
+       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+
+       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);
+
+       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+
+       //// thread
+       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+
+       if (threadId > 0)
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND CONV_ID = %d ", threadId);
+
+       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+
+       //// msg type
+       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+
+       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;
+
+               case MSG_TYPE_MMS:
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND MAIN_TYPE = %d ", MSG_MMS_TYPE);
+                       break;
+
+               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;
+
+               case MSG_TYPE_SMS_SYNCML:
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND MAIN_TYPE = %d AND SUB_TYPE = %d ", MSG_SMS_TYPE, MSG_SYNCML_CP);
+                       break;
+
+               case MSG_TYPE_SMS_REJECT:
+                       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND MAIN_TYPE = %d AND SUB_TYPE = %d ", MSG_SMS_TYPE, MSG_REJECT_SMS);
+                       break;
+
+               default:
+                       MSG_DEBUG("msg type is not set.");
+       }
+
+       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+       //// storage
+       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+
+       if (storageId > MSG_STORAGE_UNKNOWN)
+               snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "AND STORAGE_ID = %d ", storageId);
+
+       strncat(sqlQuery, sqlQuerySubset, MAX_QUERY_LEN-strlen(sqlQuery));
+
+
+       /// order
+       memset(sqlQuerySubset, 0x00, sizeof(sqlQuerySubset));
+       snprintf(sqlQuerySubset, sizeof(sqlQuerySubset), "ORDER BY 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 {
+                       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);
+
+               // add address information.
+               order = MsgGetContactNameOrder();
+
+               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;
+       }
+       dbHandle.freeTable();
+
+       return MSG_SUCCESS;
+}
diff --git a/framework/storage-handler/MsgStorageMms.cpp b/framework/storage-handler/MsgStorageMms.cpp
new file mode 100755 (executable)
index 0000000..61b6c74
--- /dev/null
@@ -0,0 +1,431 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilFile.h"
+#include "MsgUtilStorage.h"
+#include "MsgSqliteWrapper.h"
+#include "MsgStorageHandler.h"
+#include "MsgContact.h"
+
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+extern MsgDbHandler dbHandle;
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+msg_error_t MsgStoGetText(msg_message_id_t msgId, char *pSubject, char *pMsgText)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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)
+               return MSG_ERR_DB_PREPARE;
+
+       if(dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+
+               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();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+
+}
+
+
+
+msg_error_t MsgStoUpdateMMSMessage(MSG_MESSAGE_INFO_S *pMsg)
+{
+       MSG_BEGIN();
+
+       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);
+
+                       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                               dbHandle.endTrans(false);
+                               return MSG_ERR_DB_PREPARE;
+                       }
+
+                       dbHandle.bindText(pMsg->subject, 1);
+                       dbHandle.bindText(pMsg->msgText, 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);
+                               return MSG_ERR_DB_PREPARE;
+                       }
+
+                       dbHandle.bindText(pMsg->subject, 1);
+                       dbHandle.bindText(pMsg->msgText, 2);
+               }
+       } else if (pMsg->msgType.subType == MSG_SENDREQ_MMS) {
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                               "UPDATE %s SET MSG_DATA = '%s', MSG_TEXT = ?, THUMB_PATH = '%s', DATA_SIZE = %d WHERE MSG_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsg->msgData, pMsg->thumbPath, pMsg->dataSize, pMsg->msgId);
+
+               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle.endTrans(false);
+                       return MSG_ERR_DB_PREPARE;
+               }
+
+               dbHandle.bindText(pMsg->msgText, 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 (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle.endTrans(false);
+                       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);
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       msg_thread_id_t convId = 0;
+       int row = 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);
+               return MSG_ERR_DB_PREPARE;
+       }
+
+       if (row > 0) {
+               convId = dbHandle.getColumnToInt(1);
+
+               MSG_DEBUG("Conversation id:[%d]", convId);
+
+               if (MsgStoUpdateConversation(&dbHandle, convId) != MSG_SUCCESS) {
+                       MSG_DEBUG("MsgStoUpdateConversation() Error");
+                       dbHandle.freeTable();
+                       dbHandle.endTrans(false);
+
+                       return MSG_ERR_STORAGE_ERROR;
+               }
+
+       } else {
+               MSG_DEBUG("MsgStepQuery() Error [%s]", sqlQuery);
+               dbHandle.freeTable();
+               dbHandle.endTrans(false);
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.freeTable();
+       dbHandle.endTrans(true);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetContentLocation(MSG_MESSAGE_INFO_S* pMsgInfo)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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)
+               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);
+                       pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
+               } else {
+                       dbHandle.finalizeQuery();
+                       return MSG_ERR_DB_NORECORD;
+               }
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoSetReadReportSendStatus(msg_message_id_t msgId, int readReportSendStatus)
+{
+       bool bReadReportSent = false;
+
+       if((MmsRecvReadReportSendStatus)readReportSendStatus == MMS_RECEIVE_READ_REPORT_SENT)
+               bReadReportSent = true;
+       else
+               bReadReportSent = false;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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)
+               return MSG_ERR_DB_EXEC;
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetOrgAddressList(MSG_MESSAGE_INFO_S *pMsg)
+{
+       msg_error_t err = MSG_SUCCESS;
+       char sqlQuery[MAX_QUERY_LEN+1];
+       int rowCnt = 0;
+       int index = 3;
+
+       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, pMsg->msgId);
+
+       err = dbHandle.getTable(sqlQuery, &rowCnt);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               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->nAddressCnt = rowCnt;
+
+       dbHandle.freeTable();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetSubject(msg_message_id_t msgId, char *pSubject)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT SUBJECT 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) {
+               strncpy(pSubject, (char*)dbHandle.columnText(0), MAX_SUBJECT_LEN);
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+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;
+
+       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();
+               return MSG_ERR_DB_GETTABLE;
+       }
+
+       pRecipientList->recipientCnt= rowCnt;
+
+       MSG_DEBUG("pRecipientList->recipientCnt [%d]", pRecipientList->recipientCnt);
+
+       pRecipientList->recipientAddr= (MSG_ADDRESS_INFO_S*)new char[sizeof(MSG_ADDRESS_INFO_S)*rowCnt];
+
+       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++);
+
+               memset(pTmp->addressVal, 0x00, sizeof(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);
+
+               pTmp++;
+       }
+
+       dbHandle.freeTable();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetReadStatus(msg_message_id_t msgId, bool *pReadStatus)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT READ_STATUS 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) {
+               *pReadStatus = (bool)dbHandle.columnInt(0);
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetAddrInfo(msg_message_id_t msgId, MSG_ADDRESS_INFO_S *pAddrInfo)
+{
+       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);
+
+       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;
+}
diff --git a/framework/storage-handler/MsgStorageSim.cpp b/framework/storage-handler/MsgStorageSim.cpp
new file mode 100755 (executable)
index 0000000..9c6ffb6
--- /dev/null
@@ -0,0 +1,156 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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>
+
+#include "MsgDebug.h"
+#include "MsgUtilFile.h"
+#include "MsgContact.h"
+#include "MsgUtilStorage.h"
+#include "MsgGconfWrapper.h"
+#include "MsgSqliteWrapper.h"
+#include "MsgPluginManager.h"
+#include "MsgStorageHandler.h"
+
+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()
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       queue<msg_thread_id_t> threadList;
+
+       // Get Address ID of SIM Message
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT(CONV_ID) FROM %s WHERE STORAGE_ID = %d",
+                       MSGFW_MESSAGE_TABLE_NAME, MSG_STORAGE_SIM);
+
+       int rowCnt = 0;
+
+       err = dbHandle.getTable(sqlQuery, &rowCnt);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               MSG_DEBUG("sql query is %s.", sqlQuery);
+
+               dbHandle.freeTable();
+               return err;
+       }
+
+       if (rowCnt <= 0) {
+               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));
+       }
+
+       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();
+
+       for (int i = 0; i < listCnt; i++)
+       {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+               snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE MSG_ID IN \
+                               (SELECT MSG_ID FROM %s WHERE STORAGE_ID = %d);",
+                               tableList[i], MSGFW_MESSAGE_TABLE_NAME, MSG_STORAGE_SIM);
+
+               // Delete SIM Message in tables
+               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 Address
+       while (!threadList.empty())
+       {
+               err = MsgStoUpdateConversation(&dbHandle, threadList.front());
+
+               threadList.pop();
+
+               if (err != MSG_SUCCESS) {
+                       dbHandle.endTrans(false);
+                       return err;
+               }
+       }
+
+       dbHandle.endTrans(true);
+
+       return MSG_SUCCESS;
+}
+
diff --git a/framework/storage-handler/MsgStorageUtil.cpp b/framework/storage-handler/MsgStorageUtil.cpp
new file mode 100755 (executable)
index 0000000..9ed3801
--- /dev/null
@@ -0,0 +1,287 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgDebug.h"
+#include "MsgCppTypes.h"
+#include "MsgUtilFile.h"
+#include "MsgContact.h"
+#include "MsgSoundPlayer.h"
+#include "MsgGconfWrapper.h"
+#include "MsgSqliteWrapper.h"
+#include "MsgPluginManager.h"
+#include "MsgUtilStorage.h"
+#include "MsgStorageHandler.h"
+
+/*==================================================================================================
+                                     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)
+{
+       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);
+
+       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       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);
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetMmsSendOpt(msg_message_id_t msgId, MSG_SENDINGOPT_INFO_S* pSendOpt)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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)
+               return MSG_ERR_DB_PREPARE;
+
+       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);
+       } else {
+               dbHandle.finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+bool MsgStoCheckSyncMLMsgInThread(msg_thread_id_t threadId)
+{
+       msg_error_t err = MSG_SUCCESS;
+       int rowCnt = 0;
+       bool isSyncMLMsg = false;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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 (rowCnt > 0) isSyncMLMsg = true;
+
+       MSG_DEBUG("rowCnt [%d]", rowCnt);
+
+       dbHandle.freeTable();
+
+       return isSyncMLMsg;
+}
+
+
+msg_error_t MsgStoResetNetworkStatus()
+{
+       MSG_BEGIN();
+
+       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,
+                       MSGFW_MESSAGE_TABLE_NAME, MSG_NETWORK_RETRIEVE_FAIL, MSG_NETWORK_RETRIEVING);
+
+       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoCleanAbnormalMmsData()
+{
+       MSG_BEGIN();
+
+       int rowCnt = 0, index = 2; // numbers of index
+
+       msg_message_id_t msgId;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       char    filePath[MSG_FILEPATH_LEN_MAX];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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);
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               dbHandle.freeTable();
+               return MSG_SUCCESS;
+       } else if (err != MSG_SUCCESS) {
+               MSG_DEBUG("%s", sqlQuery);
+               dbHandle.freeTable();
+               return err;
+       }
+
+
+       for (int i = 0; i < rowCnt; i++)
+       {
+               memset(filePath, 0x00, sizeof(filePath));
+
+               msgId = dbHandle.getColumnToInt(index++);
+
+               dbHandle.getColumnToString(index++, MSG_FILEPATH_LEN_MAX, filePath);
+
+               if(strlen(filePath) > 1) {
+                       MSG_DEBUG("strlen(filePath) [%d]", strlen(filePath));
+                       MSG_DEBUG("filePath [%s]", filePath);
+
+                       if(MsgGetFileSize(filePath) < 0) {
+                               // abnormal mms message
+                               MSG_DEBUG("abnormal mms message [%d]", msgId);
+
+                               // delete mms message
+                               MsgStoDeleteMessage(msgId, false);
+                       }
+               }
+
+       }
+       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);
+       if(bReadReportRequested == false)
+               return MSG_ERR_READREPORT_NOT_REQUESTED;
+
+       bReadReportIsSent = MsgStoCheckReadReportIsSent(&dbHandle, msgId);
+       if(bReadReportIsSent == true)
+               return MSG_ERR_READREPORT_ALEADY_SENT;
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
diff --git a/framework/submit-handler/MsgSubmitHandler.cpp b/framework/submit-handler/MsgSubmitHandler.cpp
new file mode 100755 (executable)
index 0000000..f739065
--- /dev/null
@@ -0,0 +1,418 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilFile.h"
+#include "MsgUtilStorage.h"
+#include "MsgException.h"
+#include "MsgGconfWrapper.h"
+#include "MsgPluginManager.h"
+#include "MsgStorageHandler.h"
+#include "MsgSubmitHandler.h"
+
+
+extern MsgDbHandler dbHandle;
+
+/*==================================================================================================
+                                     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;
+       reqId++;
+
+       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_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_DEBUG("==== bSetting = [%d] ====", pReqInfo->sendOptInfo.bSetting);
+
+       if (pReqInfo->msgInfo.msgType.mainType == MSG_SMS_TYPE)
+       {
+               MSG_DEBUG("==== deliver = [%d] ====", pReqInfo->sendOptInfo.bDeliverReq);
+               MSG_DEBUG("==== keepcopy = [%d] ====", pReqInfo->sendOptInfo.bKeepCopy);
+               MSG_DEBUG("==== bReplyPath = [%d] ====", pReqInfo->sendOptInfo.option.smsSendOptInfo.bReplyPath);
+
+               err = MsgSubmitReqSMS(pReqInfo);
+       }
+       else if (pReqInfo->msgInfo.msgType.mainType == MSG_MMS_TYPE)
+       {
+               MSG_DEBUG("==== deliver = [%d] ====", pReqInfo->sendOptInfo.bDeliverReq);
+               MSG_DEBUG("==== keepcopy = [%d] ====", pReqInfo->sendOptInfo.bKeepCopy);
+               MSG_DEBUG("==== bReadReq = [%d] ====", pReqInfo->sendOptInfo.option.mmsSendOptInfo.bReadReq);
+               MSG_DEBUG("==== priority = [%d] ====", pReqInfo->sendOptInfo.option.mmsSendOptInfo.priority);
+               MSG_DEBUG("==== expiryTime = [%d] ====", pReqInfo->sendOptInfo.option.mmsSendOptInfo.expiryTime.time);
+
+               err = MsgSubmitReqMMS(pReqInfo);
+       }
+
+       return err;
+}
+
+
+msg_error_t MsgSubmitReqSMS(MSG_REQUEST_INFO_S *pReqInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       // submit request based on msgType;
+       MSG_MAIN_TYPE_T mainType = pReqInfo->msgInfo.msgType.mainType;
+       MsgPlugin* plg = MsgPluginManager::instance()->getPlugin(mainType);
+
+       if (plg == NULL)
+               THROW(MsgException::PLUGIN_ERROR, "No plugin for %d type", mainType);
+
+       // 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));
+       }
+
+       err = plg->submitReq(pReqInfo);
+
+       return err;
+}
+
+
+msg_error_t MsgSubmitReqMMS(MSG_REQUEST_INFO_S *pReqInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       MSG_RECIPIENTS_LIST_S pRecipientList;
+
+       MSG_MAIN_TYPE_T msgMainType = pReqInfo->msgInfo.msgType.mainType;
+       MsgPlugin *plg = MsgPluginManager::instance()->getPlugin(msgMainType);
+
+       if(!plg)
+       {
+               MsgStoUpdateNetworkStatus(&dbHandle, &(pReqInfo->msgInfo), MSG_NETWORK_SEND_FAIL);
+               MSG_DEBUG("No Plugin for %d type", msgMainType);
+
+               return MSG_ERR_INVALID_PLUGIN_HANDLE;
+       }
+
+       //      If MSG ID > 0 -> MSG in DRAFT
+       // Move Folder to OUTBOX
+       /* reject_msg_support */
+       MSG_DEBUG("Not scheduled MMS, pReqInfo->msgInfo.msgType.subType [%d]", pReqInfo->msgInfo.msgType.subType);
+
+       if(pReqInfo->msgInfo.msgType.subType == MSG_SENDREQ_JAVA_MMS)
+       {
+               char fileName[MAX_COMMON_INFO_SIZE+1] = {0};
+
+               // 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);
+
+               MSG_DEBUG("JAVA MMS PDU filepath:%s", pReqInfo->msgInfo.msgData);
+
+               // submit request
+               err = plg->submitReq(pReqInfo);
+
+               if(err != MSG_SUCCESS)
+               {
+                       MSG_DEBUG("Update Network Status : [%d]", err);
+                       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");
+                       }
+
+                       pReqInfo->msgInfo.folderId = MSG_OUTBOX_ID;
+                       err = MsgStoUpdateMessage(&(pReqInfo->msgInfo), &(pReqInfo->sendOptInfo));
+
+                       MsgStoUpdateNetworkStatus(&dbHandle, &(pReqInfo->msgInfo), pReqInfo->msgInfo.networkStatus);
+               } else {
+                       //new message case
+                       MSG_DEBUG("New Message");
+                       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)
+       {
+               err = MsgStoCheckReadReportStatus(pReqInfo->msgInfo.msgId);
+               if(err != MSG_SUCCESS)
+                       return err;
+
+               err = MsgStoGetRecipientList(pReqInfo->msgInfo.msgId, &pRecipientList);
+               if(err != MSG_SUCCESS)
+                       return MSG_ERR_PLUGIN_STORAGE;
+
+               pReqInfo->msgInfo.nAddressCnt = pRecipientList.recipientCnt;
+
+               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];
+
+               err = MsgStoGetSubject(pReqInfo->msgInfo.msgId, subject);
+               if(err != MSG_SUCCESS)
+                       MSG_DEBUG("Getting subject returned not a MSG_SUCCESS");
+
+               strncpy(pReqInfo->msgInfo.subject, subject, MAX_SUBJECT_LEN);
+
+               err = plg->composeReadReport(&(pReqInfo->msgInfo));
+       }
+       else if(pReqInfo->msgInfo.msgType.subType == MSG_RETRIEVE_MMS)
+       {
+               MsgStoUpdateNetworkStatus(&dbHandle, &(pReqInfo->msgInfo), pReqInfo->msgInfo.networkStatus);
+       }
+
+       /* reject_msg_support */
+
+       if(err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("Fail to Add/Update Message : MsgStoMoveMessageToFolder()/MsgStoAddMessage()");
+               return err;
+       }
+
+       switch(pReqInfo->msgInfo.msgType.subType)
+       {
+               case MSG_SENDREQ_MMS:
+               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);
+                       break;
+
+               case MSG_READREPLY_MMS:
+               case MSG_READRECIND_MMS:
+                       break;
+               default:
+                       break;
+       }
+
+       // update content location from db
+       if(pReqInfo->msgInfo.msgType.subType == MSG_RETRIEVE_MMS)
+               err = MsgStoGetContentLocation(&(pReqInfo->msgInfo));
+       /* reject_msg_support */
+       else if(pReqInfo->msgInfo.msgType.subType == MSG_NOTIFYRESPIND_MMS)
+               err = plg->updateRejectStatus(&(pReqInfo->msgInfo));
+       /* reject_msg_support */
+
+       // 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...");
+               MsgStoUpdateNetworkStatus(&dbHandle, &(pReqInfo->msgInfo), MSG_NETWORK_SEND_FAIL);
+
+               return MSG_ERR_NO_SIM;
+       }
+
+       if(err == MSG_SUCCESS)
+               err = plg->submitReq(pReqInfo);
+
+       if(err == MSG_SUCCESS && ( pReqInfo->msgInfo.msgType.subType == MSG_READREPLY_MMS || pReqInfo->msgInfo.msgType.subType == MSG_READRECIND_MMS ))
+               MsgStoSetReadReportSendStatus(pReqInfo->msgInfo.msgId, MMS_RECEIVE_READ_REPORT_SENT);
+
+       if (err != MSG_SUCCESS)
+       {
+               if(pReqInfo->msgInfo.msgType.subType == MSG_RETRIEVE_MMS )
+                       MsgStoUpdateNetworkStatus(&dbHandle, &(pReqInfo->msgInfo), MSG_NETWORK_RETRIEVE_FAIL);
+               else
+                       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;
+
+       return err;
+}
+
+
+msg_error_t MsgUpdateSentMsg(msg_message_id_t MsgId, msg_network_status_t Status)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       bool bKeepCopy = true;
+
+#ifdef MSG_MMS_KEEPCOPY
+       MSG_SENDINGOPT_INFO_S sendOpt = {};
+
+       if (msgType.mainType == MSG_MMS_TYPE)
+       {
+               if (MsgStoGetMmsSendOpt(MsgId, &sendOpt) == MSG_SUCCESS)
+               {
+                       bKeepCopy = sendOpt.bKeepCopy;
+               }
+               else
+               {
+                       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);
+               if (bKeepCopy == true)
+                       err = MsgStoMoveMessageToFolder(MsgId, MSG_SENTBOX_ID);
+               else
+                       err = MsgStoDeleteMessage(MsgId, false);
+       }
+
+       return err;
+}
+
+
+void MsgCopyReqInfo(MSG_REQUEST_INFO_S *pSrc, int addrIdx, MSG_REQUEST_INFO_S *pDest)
+{
+       MSG_BEGIN();
+
+       memset(pDest, 0x00, sizeof(MSG_REQUEST_INFO_S));
+
+       // Copy Request ID
+       pDest->reqId = pSrc->reqId;
+
+       // Copy Msg Info
+       pDest->msgInfo.msgId = pSrc->msgInfo.msgId;
+
+       pDest->msgInfo.threadId = pSrc->msgInfo.threadId;
+
+       pDest->msgInfo.folderId = pSrc->msgInfo.folderId;
+
+       pDest->msgInfo.msgType.mainType = pSrc->msgInfo.msgType.mainType;
+       pDest->msgInfo.msgType.subType = pSrc->msgInfo.msgType.subType;
+       pDest->msgInfo.msgType.classType = pSrc->msgInfo.msgType.classType;
+
+       pDest->msgInfo.storageId = pSrc->msgInfo.storageId;
+
+       pDest->msgInfo.nAddressCnt = 1;
+
+       pDest->msgInfo.addressList[0].addressType = pSrc->msgInfo.addressList[addrIdx].addressType;
+       pDest->msgInfo.addressList[0].recipientType = pSrc->msgInfo.addressList[addrIdx].recipientType;
+       pDest->msgInfo.addressList[0].contactId = pSrc->msgInfo.addressList[addrIdx].contactId;
+       strncpy(pDest->msgInfo.addressList[0].addressVal, pSrc->msgInfo.addressList[addrIdx].addressVal, MAX_ADDRESS_VAL_LEN);
+       strncpy(pDest->msgInfo.addressList[0].displayName, pSrc->msgInfo.addressList[addrIdx].displayName, MAX_DISPLAY_NAME_LEN);
+
+       strncpy(pDest->msgInfo.replyAddress, pSrc->msgInfo.replyAddress, MAX_PHONE_NUMBER_LEN);
+       strncpy(pDest->msgInfo.subject, pSrc->msgInfo.subject, MAX_SUBJECT_LEN);
+
+       pDest->msgInfo.displayTime = pSrc->msgInfo.displayTime;
+       pDest->msgInfo.networkStatus = pSrc->msgInfo.networkStatus;
+       pDest->msgInfo.encodeType = pSrc->msgInfo.encodeType;
+       pDest->msgInfo.bRead = pSrc->msgInfo.bRead;
+       pDest->msgInfo.bProtected = pSrc->msgInfo.bProtected;
+       pDest->msgInfo.priority = pSrc->msgInfo.priority;
+       pDest->msgInfo.direction = pSrc->msgInfo.direction;
+
+       pDest->msgInfo.msgPort.valid = pSrc->msgInfo.msgPort.valid;
+
+       if (pDest->msgInfo.msgPort.valid == true)
+       {
+               pDest->msgInfo.msgPort.dstPort = pSrc->msgInfo.msgPort.dstPort;
+               pDest->msgInfo.msgPort.srcPort = pSrc->msgInfo.msgPort.srcPort;
+       }
+
+       pDest->msgInfo.bTextSms = pSrc->msgInfo.bTextSms;
+       pDest->msgInfo.dataSize = pSrc->msgInfo.dataSize;
+
+       strncpy(pDest->msgInfo.msgData, pSrc->msgInfo.msgData, MAX_MSG_DATA_LEN);
+
+       if (pDest->msgInfo.bTextSms == true)
+       {
+               memcpy(pDest->msgInfo.msgText, pSrc->msgInfo.msgText, pDest->msgInfo.dataSize);
+               pDest->msgInfo.msgText[pDest->msgInfo.dataSize] = '\0';
+       }
+
+       // Set Sending Info
+       pDest->sendOptInfo.bSetting = pSrc->sendOptInfo.bSetting;
+
+       if (pDest->sendOptInfo.bSetting == true)
+       {
+               pDest->sendOptInfo.bDeliverReq = pSrc->sendOptInfo.bDeliverReq;
+               pDest->sendOptInfo.bKeepCopy = pSrc->sendOptInfo.bKeepCopy;
+
+               if (pDest->msgInfo.msgType.mainType == MSG_SMS_TYPE)
+               {
+                       pDest->sendOptInfo.option.smsSendOptInfo.bReplyPath = pSrc->sendOptInfo.option.smsSendOptInfo.bReplyPath;
+               }
+               else if (pDest->msgInfo.msgType.mainType == MSG_MMS_TYPE)
+               {
+                       pDest->sendOptInfo.option.mmsSendOptInfo.priority = pSrc->sendOptInfo.option.mmsSendOptInfo.priority;
+                       pDest->sendOptInfo.option.mmsSendOptInfo.bReadReq = pSrc->sendOptInfo.option.mmsSendOptInfo.bReadReq;
+
+                       pDest->sendOptInfo.option.mmsSendOptInfo.expiryTime.type = pSrc->sendOptInfo.option.mmsSendOptInfo.expiryTime.type;
+                       pDest->sendOptInfo.option.mmsSendOptInfo.expiryTime.time = pSrc->sendOptInfo.option.mmsSendOptInfo.expiryTime.time;
+
+                       pDest->sendOptInfo.option.mmsSendOptInfo.bUseDeliveryCustomTime = pSrc->sendOptInfo.option.mmsSendOptInfo.bUseDeliveryCustomTime;
+                       pDest->sendOptInfo.option.mmsSendOptInfo.deliveryTime.type = pSrc->sendOptInfo.option.mmsSendOptInfo.deliveryTime.type;
+                       pDest->sendOptInfo.option.mmsSendOptInfo.deliveryTime.time = pSrc->sendOptInfo.option.mmsSendOptInfo.deliveryTime.time;
+               }
+       }
+
+       MSG_END();
+}
+
diff --git a/framework/transaction-manager/MsgCmdHandlerFilter.cpp b/framework/transaction-manager/MsgCmdHandlerFilter.cpp
new file mode 100755 (executable)
index 0000000..964c849
--- /dev/null
@@ -0,0 +1,243 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilFunction.h"
+#include "MsgCppTypes.h"
+#include "MsgSpamFilter.h"
+#include "MsgStorageHandler.h"
+#include "MsgCmdHandler.h"
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+int MsgAddFilterHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       // Get Filter Structure
+       MSG_FILTER_S* pFilter = (MSG_FILTER_S*)pCmd->cmdData;
+
+       // Add Filter
+       err = MsgStoAddFilter(pFilter);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoAddFilter()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoAddFilter()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_ADD_FILTER, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgUpdateFilterHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       // Get Filter Structure
+       MSG_FILTER_S* pFilter = (MSG_FILTER_S*)pCmd->cmdData;
+
+       // Update Filter
+       err = MsgStoUpdateFilter(pFilter);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoUpdateFilter()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoUpdateFilter()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_UPDATE_FILTER, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgDeleteFilterHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       // Get Filter Structure
+       msg_filter_id_t  *pFilterId = (msg_filter_id_t *)pCmd->cmdData;
+
+       MSG_DEBUG("Delete Filter id : %d", *pFilterId);
+
+       // Delete Filter
+       err = MsgStoDeleteFilter(*pFilterId);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoDeleteFilter()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoDeleteFilter()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_DELETE_FILTER, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgSetFilterActivationHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       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;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Filter List
+       msg_struct_list_s filterList;
+
+       err = MsgStoGetFilterList(&filterList);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoGetFilterList()");
+
+               // Encoding Filter List Data
+               dataSize = MsgEncodeFilterList(&filterList, &encodedData);
+
+               delete [] filterList.msg_struct_info;
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoGetFilterList()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_FILTERLIST, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgSetFilterOperationHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       // Get Filter Flag
+       bool setFlag = false;
+
+       memcpy(&setFlag, pCmd->cmdData, sizeof(bool));
+
+       // Add Filter
+       err = MsgSetFilterOperation(setFlag);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgSetFilterOperation()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgSetFilterOperation()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_SET_FILTER_OPERATION, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetFilterOperationHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Filter List
+       bool setFlag = false;
+
+       err = MsgGetFilterOperation(&setFlag);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgGetFilterOperation()");
+
+               // Encoding Filter List Data
+               dataSize = MsgEncodeFilterFlag(&setFlag, &encodedData);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgFilterGetFilterList()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_FILTER_OPERATION, err, (void**)ppEvent);
+
+       return eventSize;
+}
diff --git a/framework/transaction-manager/MsgCmdHandlerSetting.cpp b/framework/transaction-manager/MsgCmdHandlerSetting.cpp
new file mode 100755 (executable)
index 0000000..ad92be8
--- /dev/null
@@ -0,0 +1,229 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgCmdHandler.h"
+#include "MsgSettingHandler.h"
+#include "MsgUtilFunction.h"
+#include "MsgCppTypes.h"
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+int MsgSetConfigHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+       int eventType = -1;
+
+       // Get Setting Structure
+       MSG_SETTING_S* pSetting = (MSG_SETTING_S*)pCmd->cmdData;
+
+       // Set Config Data
+       err = MsgSetConfigData(pSetting);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgSetConfigData()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgSetConfigData()");
+       }
+
+       // Make Event Data
+       switch (pCmd->cmdType) {
+       case MSG_CMD_SET_SMSC_OPT :
+               eventType = MSG_EVENT_SET_SMSC_OPT;
+               break;
+       case MSG_CMD_SET_CB_OPT :
+               eventType = MSG_EVENT_SET_CB_OPT;
+               break;
+       case MSG_CMD_SET_SMS_SEND_OPT :
+               eventType = MSG_EVENT_SET_SMS_SEND_OPT;
+               break;
+       case MSG_CMD_SET_MMS_SEND_OPT :
+               eventType = MSG_EVENT_SET_MMS_SEND_OPT;
+               break;
+       case MSG_CMD_SET_MMS_RECV_OPT :
+               eventType = MSG_EVENT_SET_MMS_RECV_OPT;
+               break;
+       case MSG_CMD_SET_PUSH_MSG_OPT :
+               eventType = MSG_EVENT_SET_PUSH_MSG_OPT;
+               break;
+       case MSG_CMD_SET_VOICE_MSG_OPT :
+               eventType = MSG_EVENT_SET_VOICE_MSG_OPT;
+               break;
+       case MSG_CMD_SET_GENERAL_MSG_OPT :
+               eventType = MSG_EVENT_SET_GENERAL_MSG_OPT;
+               break;
+       case MSG_CMD_SET_MSG_SIZE_OPT :
+                       eventType = MSG_EVENT_SET_MSG_SIZE_OPT;
+                       break;
+       default :
+               break;
+       }
+
+       eventSize = MsgMakeEvent(NULL, 0, eventType, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetConfigHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0;
+       int eventSize = 0;
+       int eventType = -1;
+
+       // Get Option Type
+       MSG_OPTION_TYPE_T* type = (MSG_OPTION_TYPE_T*)pCmd->cmdData;
+
+       // Get Config Data
+       MSG_SETTING_S setting;
+       setting.type = *type;
+
+       err = MsgGetConfigData(&setting);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgGetConfigData()");
+
+               // Encoding Config Data
+               switch (setting.type)
+                       {
+                               case MSG_GENERAL_OPT :
+                                       dataSize += sizeof(MSG_GENERAL_OPT_S);
+                                       break;
+                               case MSG_SMS_SENDOPT :
+                                       dataSize += sizeof(MSG_SMS_SENDOPT_S);
+                                       break;
+                               case MSG_SMSC_LIST :
+                                       dataSize += sizeof(MSG_SMSC_LIST_S);
+                                       break;
+                               case MSG_MMS_SENDOPT :
+                                       dataSize += sizeof(MSG_MMS_SENDOPT_S);
+                                       break;
+                               case MSG_MMS_RECVOPT :
+                                       dataSize += sizeof(MSG_MMS_RECVOPT_S);
+                                       break;
+                               case MSG_MMS_STYLEOPT :
+                                       dataSize += sizeof(MSG_MMS_STYLEOPT_S);
+                                       break;
+                               case MSG_PUSHMSG_OPT :
+                                       dataSize += sizeof(MSG_PUSHMSG_OPT_S);
+                                       break;
+                               case MSG_CBMSG_OPT :
+                                       dataSize += sizeof(MSG_CBMSG_OPT_S);
+                                       break;
+                               case MSG_VOICEMAIL_OPT :
+                                       dataSize += sizeof(MSG_VOICEMAIL_OPT_S);
+                                       break;
+                               case MSG_MSGSIZE_OPT :
+                                       dataSize += sizeof(MSG_MSGSIZE_OPT_S);
+                                       break;
+                               default:
+                                       break;
+                       }
+
+                       encodedData = (char*)new char[dataSize];
+                       void* p = (void*)encodedData;
+
+                       switch (setting.type)
+                       {
+                       case MSG_GENERAL_OPT :
+                               memcpy(p, &(setting.option.generalOpt), dataSize);
+                               break;
+                       case MSG_SMS_SENDOPT :
+                               memcpy(p, &(setting.option.smsSendOpt), dataSize);
+                               break;
+                       case MSG_SMSC_LIST :
+                               memcpy(p, &(setting.option.smscList), dataSize);
+                               break;
+                       case MSG_MMS_SENDOPT :
+                               memcpy(p, &(setting.option.mmsSendOpt), dataSize);
+                               break;
+                       case MSG_MMS_RECVOPT :
+                               memcpy(p, &(setting.option.mmsRecvOpt), dataSize);
+                               break;
+                       case MSG_MMS_STYLEOPT :
+                               memcpy(p, &(setting.option.mmsStyleOpt), dataSize);
+                               break;
+                       case MSG_PUSHMSG_OPT :
+                               memcpy(p, &(setting.option.pushMsgOpt), dataSize);
+                               break;
+                       case MSG_CBMSG_OPT :
+                               memcpy(p, &(setting.option.cbMsgOpt), dataSize);
+                               break;
+                       case MSG_VOICEMAIL_OPT :
+                               memcpy(p, &(setting.option.voiceMailOpt), dataSize);
+                               break;
+                       case MSG_MSGSIZE_OPT :
+                               memcpy(p, &(setting.option.msgSizeOpt), dataSize);
+                               break;
+                       default:
+                               break;
+                       }
+       } else {
+               MSG_DEBUG("Command Handle Fail : MsgGetConfigData()");
+       }
+
+       MSG_DEBUG("dataSize [%d]", dataSize);
+
+       switch (pCmd->cmdType) {
+       case MSG_CMD_GET_SMSC_OPT :
+               eventType = MSG_EVENT_GET_SMSC_OPT;
+               break;
+       case MSG_CMD_GET_CB_OPT :
+               eventType = MSG_EVENT_GET_CB_OPT;
+               break;
+       case MSG_CMD_GET_SMS_SEND_OPT :
+               eventType = MSG_EVENT_GET_SMS_SEND_OPT;
+               break;
+       case MSG_CMD_GET_MMS_SEND_OPT :
+               eventType = MSG_EVENT_GET_MMS_SEND_OPT;
+               break;
+       case MSG_CMD_GET_MMS_RECV_OPT :
+               eventType = MSG_EVENT_GET_MMS_RECV_OPT;
+               break;
+       case MSG_CMD_GET_PUSH_MSG_OPT :
+               eventType = MSG_EVENT_GET_PUSH_MSG_OPT;
+               break;
+       case MSG_CMD_GET_VOICE_MSG_OPT :
+               eventType = MSG_EVENT_GET_VOICE_MSG_OPT;
+               break;
+       case MSG_CMD_GET_GENERAL_MSG_OPT :
+               eventType = MSG_EVENT_GET_GENERAL_MSG_OPT;
+               break;
+       case MSG_CMD_GET_MSG_SIZE_OPT :
+                       eventType = MSG_EVENT_GET_MSG_SIZE_OPT;
+               break;
+       default :
+               break;
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, eventType, err, (void**)ppEvent);
+
+       return eventSize;
+}
diff --git a/framework/transaction-manager/MsgCmdHandlerStorage.cpp b/framework/transaction-manager/MsgCmdHandlerStorage.cpp
new file mode 100755 (executable)
index 0000000..4f51994
--- /dev/null
@@ -0,0 +1,1472 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgDebug.h"
+#include "MsgUtilFile.h"
+#include "MsgException.h"
+#include "MsgCppTypes.h"
+//#include "MsgSoundPlayer.h"
+#include "MsgUtilFunction.h"
+#include "MsgStorageHandler.h"
+#include "MsgPluginManager.h"
+#include "MsgTransManager.h"
+#include "MsgCmdHandler.h"
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+int MsgAddMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Message Info
+       MSG_MESSAGE_INFO_S* pMsgInfo = (MSG_MESSAGE_INFO_S*)pCmd->cmdData;
+
+       // Get Sending Option
+       MSG_SENDINGOPT_INFO_S* pSendOptInfo = (MSG_SENDINGOPT_INFO_S*)(pCmd->cmdData + sizeof(MSG_MESSAGE_INFO_S));
+
+       // Add Message
+       err = MsgStoAddMessage(pMsgInfo, pSendOptInfo);
+
+       if (err == MSG_SUCCESS) {
+                       MSG_DEBUG("Command Handle Success : MsgStoAddMessage()");
+
+                       // Encoding Message ID
+                       dataSize = MsgEncodeMsgId(&(pMsgInfo->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;
+       msg_message_id_t msgIds[1];
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+       msgIdList.nCount = 1;
+       msgIds[0] = pMsgInfo->msgId;
+       msgIdList.msgIdList = msgIds;
+
+       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_ADD_MSG, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgAddSyncMLMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       int extId = 0, pinCode = 0;
+
+       MSG_MESSAGE_INFO_S msgInfo = {};
+
+       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));
+
+       // Add Message
+       err = MsgStoAddSyncMLMessage(&msgInfo, extId, pinCode);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoAddSyncMLMessage()");
+
+               // broadcast to listener threads, here
+               MsgTransactionManager::instance()->broadcastIncomingMsgCB(err, &msgInfo);
+               //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;
+
+               MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoAddSyncMLMessage()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_ADD_SYNCML_MSG, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgUpdateMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       // Get Message Info
+       MSG_MESSAGE_INFO_S* pMsgInfo = (MSG_MESSAGE_INFO_S*)pCmd->cmdData;
+
+       // Get Sending Option
+       MSG_SENDINGOPT_INFO_S* pSendOptInfo = (MSG_SENDINGOPT_INFO_S*)(pCmd->cmdData + sizeof(MSG_MESSAGE_INFO_S));
+
+       // Update Message
+       err = MsgStoUpdateMessage(pMsgInfo, pSendOptInfo);
+
+       if (err == MSG_SUCCESS)
+               MSG_DEBUG("Command Handle Success : MsgStoUpdateMessage()");
+       else
+               MSG_DEBUG("Command Handle Fail : MsgStoUpdateMessage()");
+
+       // Delete Temp File for Message Data
+       if (pMsgInfo->bTextSms == false)
+               MsgDeleteFile(pMsgInfo->msgData); //ipc
+
+       //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] = pMsgInfo->msgId;
+       msgIdList.msgIdList = msgIds;
+
+       MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_UPDATE_MSG, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgUpdateReadStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       msg_message_id_t msgId;
+       bool readStatus;
+
+       memcpy(&msgId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_message_id_t));
+       memcpy(&readStatus, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_message_id_t)), sizeof(bool));
+
+       // Update Read Status
+       err = MsgStoUpdateReadStatus(msgId, readStatus);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoUpdateReadStatus()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoUpdateReadStatus()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_UPDATE_READ, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgUpdateThreadReadStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       msg_thread_id_t threadId;
+       int unReadCnt = 0;
+
+       memcpy(&threadId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_thread_id_t));
+
+       MsgStoGetThreadUnreadCnt(threadId, &unReadCnt);
+
+       MSG_DEBUG("unReadCnt [%d]", unReadCnt);
+
+       if (unReadCnt > 0) {
+
+               err = MsgStoUpdateThreadReadStatus(threadId);
+
+               if (err == MSG_SUCCESS)
+                       MSG_DEBUG("Command Handle Success : MsgStoUpdateThreadReadStatus()");
+               else
+                       MSG_DEBUG("Command Handle Fail : MsgStoUpdateThreadReadStatus()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_UPDATE_THREAD_READ, err, (void**)ppEvent);
+
+       return eventSize;
+
+}
+
+
+int MsgUpdateProtectedStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       msg_message_id_t msgId;
+       bool protectedStatus;
+
+       memcpy(&msgId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_message_id_t));
+       memcpy(&protectedStatus, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_message_id_t)), sizeof(bool));
+
+       // Update Protected Status
+       err = MsgStoUpdateProtectedStatus(msgId, protectedStatus);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoUpdateProtectedStatus()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoUpdateProtectedStatus()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_UPDATE_PROTECTED, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgDeleteMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       int extId = 0;
+
+       msg_message_id_t* msgId = (msg_message_id_t*)pCmd->cmdData;
+
+       MsgStoGetSyncMLExtId(*msgId, &extId);
+
+       // Delete Message
+       err = MsgStoDeleteMessage(*msgId, true);
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Command Handle Success : MsgStoDeleteMessage()");
+
+               if(extId > 0) {
+                       // broadcast to listener threads, here
+                       MsgTransactionManager::instance()->broadcastSyncMLMsgOperationCB(err, -1, extId);
+               }
+
+               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_DELETE, &msgIdList);
+       } else {
+               MSG_DEBUG("Command Handle Fail : MsgStoDeleteMessage()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_DELETE_MSG, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgDeleteAllMessageInFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       msg_folder_id_t* folderId = (msg_folder_id_t*)pCmd->cmdData;
+
+       bool bOnlyDB;
+       memcpy(&bOnlyDB, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_folder_id_t)), sizeof(bool));
+
+
+       msg_id_list_s msgIdList;
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+       // Delete Message
+       err = MsgStoDeleteAllMessageInFolder(*folderId, bOnlyDB, &msgIdList);
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Command Handle Success : MsgStoDeleteAllMessageInFolder()");
+               MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_DELETE, &msgIdList);
+               if(msgIdList.msgIdList != NULL)
+                       delete [] (char*)msgIdList.msgIdList;
+       } else {
+               MSG_DEBUG("Command Handle Fail : MsgStoDeleteAllMessageInFolder()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_DELALL_MSGINFOLDER, err, (void**)ppEvent);
+
+       return eventSize;
+
+}
+
+
+int MsgDeleteMessageByListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       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;
+
+       int eventSize = 0;
+
+       msg_message_id_t msgId;
+       msg_folder_id_t folderId;
+
+       memcpy(&msgId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_message_id_t));
+       memcpy(&folderId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_message_id_t)), sizeof(msg_folder_id_t));
+
+       // Move Message
+       err = MsgStoMoveMessageToFolder(msgId, folderId);
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Command Handle Success : MsgStoMoveMessageToFolder()");
+
+               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);
+       } else {
+               MSG_DEBUG("Command Handle Fail : MsgStoMoveMessageToFolder()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_MOVE_MSGTOFOLDER, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgMoveMessageToStorageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       msg_message_id_t msgId;
+       msg_storage_id_t storageId;
+
+       memcpy(&msgId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_message_id_t));
+       memcpy(&storageId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_message_id_t)), sizeof(msg_storage_id_t));
+
+       // Move Message
+       err = MsgStoMoveMessageToStorage(msgId, storageId);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoMoveMessageToStorage()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoMoveMessageToStorage()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_MOVE_MSGTOSTORAGE, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgCountMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Folder ID
+       msg_folder_id_t* folderId = (msg_folder_id_t*)pCmd->cmdData;
+
+       // Get Message Count
+       MSG_COUNT_INFO_S countInfo;
+
+       err = MsgStoCountMessage(*folderId, &countInfo);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoCountMessage()");
+
+               // Encoding Messaging Count Data
+               dataSize = MsgEncodeCountInfo(&countInfo, &encodedData);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoCountMessage()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_COUNT_MSG, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgCountMsgByTypeHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Folder ID
+       MSG_MESSAGE_TYPE_S* pMsgType = (MSG_MESSAGE_TYPE_S*)pCmd->cmdData;
+
+       int nMsgCnt = 0;
+
+       // Get Message Count
+       err = MsgStoCountMsgByType(pMsgType, &nMsgCnt);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoCountMsgByType()");
+
+               // Encoding Messaging Count Data
+               dataSize = MsgEncodeCountByMsgType(nMsgCnt, &encodedData);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoCountMsgByType()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_COUNT_BY_MSGTYPE, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       // Get Message ID
+       msg_message_id_t* msgId = (msg_message_id_t*)pCmd->cmdData;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Message
+       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));
+
+       err = MsgStoGetMessage(*msgId, &msgInfo, &sendOptInfo);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoGetMessage()");
+
+               // Encoding Message Info  Data
+               dataSize = MsgEncodeMsgInfo(&msgInfo, &sendOptInfo, &encodedData);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoGetMessage()");
+       }
+
+//     MsgSoundPlayStop();
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_MSG, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetFolderViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       // Get Folder ID
+       msg_folder_id_t folderId;
+       MSG_SORT_RULE_S sortRule;
+
+       memcpy(&folderId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_folder_id_t));
+       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);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Message Common Info
+       msg_struct_list_s folderViewList;
+
+       err = MsgStoGetFolderViewList(folderId, &sortRule, &folderViewList);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoGetFolderViewList()");
+
+               // Encoding Folder View List Data
+//             dataSize = MsgEncodeFolderViewList(&folderViewList, &encodedData);
+
+               MSG_DEBUG("dataSize [%d]", dataSize);
+
+               if (folderViewList.msg_struct_info != NULL)
+               {
+                       delete [] folderViewList.msg_struct_info;
+                       folderViewList.msg_struct_info = NULL;
+               }
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoGetFolderViewList()");
+               return err;
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_FOLDERVIEWLIST, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgAddFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       // Get Folder Info
+       MSG_FOLDER_INFO_S* pFolderInfo = (MSG_FOLDER_INFO_S*)pCmd->cmdData;
+
+       // Add Folder
+       err = MsgStoAddFolder(pFolderInfo);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoAddFolder()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoAddFolder()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_ADD_FOLDER, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgUpdateFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       // Get Folder Info
+       MSG_FOLDER_INFO_S* pFolderInfo = (MSG_FOLDER_INFO_S*)pCmd->cmdData;
+
+       // Update Folder
+       err = MsgStoUpdateFolder(pFolderInfo);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoUpdateFolder()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoUpdateFolder()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_UPDATE_FOLDER, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgDeleteFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       // Get Folder Info
+       msg_folder_id_t* pFolderInfo = (msg_folder_id_t*)pCmd->cmdData;
+
+       // Delete Folder
+       err = MsgStoDeleteFolder(*pFolderInfo);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoDeleteFolder()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoDeleteFolder()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_DELETE_FOLDER, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetFolderListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Storage List
+       msg_struct_list_s folderList;
+
+       err = MsgStoGetFolderList(&folderList);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoGetFolderList()");
+
+               // Encoding Folder List Data
+               dataSize = MsgEncodeFolderList(&folderList, &encodedData);
+
+               delete [] folderList.msg_struct_info;
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoGetFolderList()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_FOLDERLIST, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgInitSimBySatHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       // Sim Init - Later
+       //Run msg-init-app
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_INIT_SIM_BY_SAT, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetMsgTypeHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Message ID
+       msg_message_id_t msgId;
+
+       memcpy(&msgId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_message_id_t));
+
+       // Get Msg Type
+       MSG_MESSAGE_TYPE_S msgType;
+
+       err = MsgStoGetMsgType(msgId, &msgType);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoGetMsgType()");
+
+               // Encoding Storage List Data
+               dataSize = MsgEncodeMsgType(&msgType, &encodedData);
+
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoGetMsgType()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_MSG_TYPE, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetThreadViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       MSG_SORT_RULE_S sortRule = {0};
+
+       memcpy(&sortRule, pCmd->cmdData, sizeof(MSG_SORT_RULE_S));
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Thread View List
+       msg_struct_list_s msgThreadViewList;
+
+       err = MsgStoGetThreadViewList(&sortRule, &msgThreadViewList);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoGetThreadViewList()");
+
+               // Encoding Folder View List Data
+               dataSize = MsgEncodeThreadViewList(&msgThreadViewList, &encodedData);
+
+               MSG_DEBUG("dataSize [%d]", dataSize);
+
+               if (msgThreadViewList.msg_struct_info != NULL)
+               {
+                       delete [] msgThreadViewList.msg_struct_info;
+                       msgThreadViewList.msg_struct_info = NULL;
+               }
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoGetThreadViewList()");
+               return err;
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_THREADVIEWLIST, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetConversationViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       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);
+
+       int dataSize = 0, eventSize = 0;
+
+       msg_struct_list_s convViewList;
+
+       err = MsgStoGetConversationViewList(threadId, &convViewList);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoGetConversationViewList()");
+
+               // Encoding Folder View List Data
+               dataSize = MsgEncodeConversationViewList(&convViewList, &encodedData);
+
+               MSG_DEBUG("dataSize [%d]", dataSize);
+
+               if (convViewList.msg_struct_info != NULL)
+               {
+                       delete [] convViewList.msg_struct_info;
+                       convViewList.msg_struct_info = NULL;
+               }
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoGetConversationViewList()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_CONVERSATIONVIEWLIST, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgDeleteThreadMessageListHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       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;
+
+       isSyncMLMsg = MsgStoCheckSyncMLMsgInThread(threadId);
+
+       msg_id_list_s msgIdList;
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+       err = MsgStoDeleteThreadMessageList(threadId, bIncludeProtect, &msgIdList);
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Command Handle Success : MsgStoDeleteThreadMessageList()");
+
+               if(isSyncMLMsg == true) {
+                       // broadcast to listener threads, here
+                       MsgTransactionManager::instance()->broadcastSyncMLMsgOperationCB(err, -1, -1);
+               }
+
+               MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_DELETE, &msgIdList);
+               if(msgIdList.msgIdList != NULL)
+                       delete [] (char*)msgIdList.msgIdList;
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoDeleteThreadMessageList()");
+               if(msgIdList.msgIdList != NULL)
+                       delete [] (char*)msgIdList.msgIdList;
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_DELETE_THREADMESSAGELIST, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgCountMsgByContactHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       // 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);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Message Common Info
+       MSG_THREAD_COUNT_INFO_S threadCountInfo = {0};
+
+       err = MsgStoCountMsgByContact(&addrInfo, &threadCountInfo);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoCountMsgByContact()");
+
+               // Encoding Folder View List Data
+               dataSize = MsgEncodeMsgGetContactCount(&threadCountInfo, &encodedData);
+
+               MSG_DEBUG("dataSize [%d]", dataSize);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoCountMsgByContact()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_CONTACT_COUNT, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetQuickPanelDataHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       // Get Message ID
+       msg_quickpanel_type_t* type = (msg_quickpanel_type_t*)pCmd->cmdData;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Message
+       MSG_MESSAGE_INFO_S msgInfo;
+
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       err = MsgStoGetQuickPanelData(*type, &msgInfo);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoGetQuickPanelData()");
+
+               // Encoding Message Info Data
+               dataSize = MsgEncodeMsgInfo(&msgInfo, &encodedData);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoGetQuickPanelData()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_QUICKPANEL_DATA, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgResetDatabaseHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+
+       // Reset DB
+       err = MsgStoResetDatabase();
+
+       if (err == MSG_SUCCESS)
+               MSG_DEBUG("Command Handle Success : MsgStoResetDatabase()");
+       else
+               MSG_DEBUG("Command Handle Fail : MsgStoResetDatabase()");
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_RESET_DB, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetMemSizeHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0, eventSize = 0;
+
+       // Get Memory size
+       unsigned int memsize = 0;
+
+       memsize = MsgDu(MSG_DATA_ROOT_PATH);
+
+       dataSize = MsgEncodeMemSize(&memsize, &encodedData);
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_MEMSIZE, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgBackupMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       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));
+
+       MSG_DEBUG("type = %d, path = %s", type, path);
+
+       err = MsgStoBackupMessage(type, path);
+       if (err == MSG_SUCCESS)
+               MSG_DEBUG("Command Handle Success : MsgBackupMessageHandler()");
+       else
+               MSG_DEBUG("Command Handle Fail : MsgBackupMessageHandler()");
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_BACKUP_MESSAGE, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgRestoreMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int eventSize = 0;
+       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(path);
+
+       if (err == MSG_SUCCESS)
+               MSG_DEBUG("Command Handle Success : MsgStoRestoreMessage()");
+       else
+               MSG_DEBUG("Command Handle Fail : MsgStoRestoreMessage()");
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_RESTORE_MESSAGE, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetReportStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       // Get Message ID
+       msg_message_id_t* msgId = (msg_message_id_t*)pCmd->cmdData;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0, eventSize = 0;
+
+       MSG_REPORT_STATUS_INFO_S *reportStatus = NULL;
+       int report_count = 0;
+
+       err = MsgStoGetReportStatus(*msgId, &report_count, &reportStatus);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgGetReportStatusHandler()");
+
+               // Encoding Report Status Data
+               dataSize = MsgEncodeReportStatus(reportStatus, report_count, &encodedData);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgGetReportStatusHandler()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_REPORT_STATUS, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetThreadIdByAddressHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       int *addrCnt = (int *)pCmd->cmdData;
+       MSG_DEBUG("*addrCnt [%d]", *addrCnt);
+
+       msgInfo.nAddressCnt = *addrCnt;
+       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);
+
+       int dataSize = 0, eventSize = 0;
+
+       msg_thread_id_t threadId;
+
+       err = MsgStoGetThreadIdByAddress(&msgInfo, &threadId);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("threadId [%d]", threadId);
+               MSG_DEBUG("Command Handle Success : MsgGetThreadIdByAddressHandler()");
+
+               // Encoding threadId Data
+               dataSize = MsgEncodeThreadId(&threadId, &encodedData);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgGetThreadIdByAddressHandler()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_THREAD_ID_BY_ADDRESS, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgGetThreadInfoHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int dataSize = 0;
+       int eventSize = 0;
+
+       msg_thread_id_t threadId;
+
+       memcpy(&threadId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_thread_id_t));
+
+       MSG_THREAD_VIEW_S threadInfo;
+       memset(&threadInfo, 0x00, sizeof(threadInfo));
+
+       err = MsgStoGetThreadInfo(threadId, &threadInfo);
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Command Handle Success : MsgStoGetThreadInfo()");
+
+               // Encoding thread Info Data
+               dataSize = MsgEncodeThreadInfo(&threadInfo, &encodedData);
+       } else {
+               MSG_DEBUG("Command Handle Fail : MsgStoGetThreadInfo()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_GET_THREAD_INFO, err, (void**)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;
+       AutoPtr<char> buf(&encodedData);
+
+       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;
+       AutoPtr<char> buf(&encodedData);
+
+       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;
+       AutoPtr<char> buf(&encodedData);
+
+       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;
+       AutoPtr<char> buf(&encodedData);
+
+       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;
+       AutoPtr<char> buf(&encodedData);
+
+       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;
+
+       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 : MsgStoAddMessage()");
+       }
+
+       // 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;
+
+       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;
+
+
+       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;
+}
diff --git a/framework/transaction-manager/MsgCmdHandlerTransport.cpp b/framework/transaction-manager/MsgCmdHandlerTransport.cpp
new file mode 100755 (executable)
index 0000000..d137b14
--- /dev/null
@@ -0,0 +1,768 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgDebug.h"
+#include "MsgException.h"
+#include "MsgUtilFile.h"
+#include "MsgContact.h"
+#include "MsgSoundPlayer.h"
+#include "MsgGconfWrapper.h"
+#include "MsgNotificationWrapper.h"
+#include "MsgUtilFunction.h"
+#include "MsgSubmitHandler.h"
+#include "MsgDeliverHandler.h"
+#include "MsgStorageHandler.h"
+#include "MsgTransManager.h"
+#include "MsgPluginManager.h"
+#include "MsgCmdHandler.h"
+#include "MsgUtilStorage.h"
+
+#include <alarm.h>
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+int MsgSubmitReqHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+       bool bNewMsg = true;
+
+       int eventSize = 0;
+
+       MSG_REQUEST_INFO_S reqInfo = {0,};
+       MSG_PROXY_INFO_S proxyInfo = {0,};
+
+       // Get Message Request
+       memcpy(&reqInfo, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(MSG_REQUEST_INFO_S));
+
+       // 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));
+
+       if (reqInfo.msgInfo.msgId > 0)
+               bNewMsg = false;
+
+       // Submit Request
+       err = MsgSubmitReq(&reqInfo, false);
+
+       if (err == MSG_SUCCESS){
+               MSG_DEBUG("Command Handle Success : MsgSubmitReq()");
+       } else {
+               MSG_DEBUG("Command Handle Fail : MsgSubmitReq()");
+       }
+
+       int reqId = reqInfo.reqId;
+       proxyInfo.sentMsgId = reqInfo.msgInfo.msgId;
+
+       MSG_DEBUG("REQID: %d, MSGID: %d", reqId, proxyInfo.sentMsgId);
+
+       if (reqInfo.msgInfo.msgType.mainType == MSG_SMS_TYPE) {
+               MsgTransactionManager::instance()->insertSentMsg(reqId, &proxyInfo);
+       } else if (reqInfo.msgInfo.msgType.mainType == MSG_MMS_TYPE) {
+               // Retrieve MMS shall not be kept in sentMsg
+               if ((reqInfo.msgInfo.msgType.subType == MSG_SENDREQ_MMS) ||
+                       (reqInfo.msgInfo.msgType.subType == MSG_FORWARD_MMS) ||
+                       (reqInfo.msgInfo.msgType.subType == MSG_SENDREQ_JAVA_MMS))
+               MsgTransactionManager::instance()->insertSentMsg(reqId, &proxyInfo);
+       }
+
+       // keep transaction Id list for distinguish java MMS sent msg when sendconf received
+       if (reqInfo.msgInfo.msgType.mainType == MSG_MMS_TYPE &&
+               reqInfo.msgInfo.msgType.subType == MSG_SENDREQ_JAVA_MMS) {
+               MSG_CMD_REG_INCOMING_JAVAMMS_TRID_S trId={0};
+               memcpy(&trId.id, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(MSG_REQUEST_INFO_S)+sizeof(MSG_PROXY_INFO_S)), MMS_TR_ID_LEN);
+
+               char* pFileName;
+               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);
+
+               MsgTransactionManager* tm = MsgTransactionManager::instance();
+               tm->setJavaMMSList(&trId);
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(&reqId, sizeof(reqId), MSG_EVENT_SUBMIT_REQ, err, (void**)ppEvent);
+
+       /* reject_msg_support */
+       if(((reqInfo.msgInfo.msgType.subType == MSG_NOTIFYRESPIND_MMS) &&
+                (reqInfo.msgInfo.msgType.mainType == MSG_MMS_TYPE)))
+               err = MsgStoDeleteMessage(reqInfo.msgInfo.msgId, true);
+
+       /** send storage 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] = reqInfo.msgInfo.msgId;
+       msgIdList.msgIdList = msgIds;
+
+       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 if (err == MSG_ERR_SECURITY_ERROR) { // Case of MDM enabled, it returns MSG_ERR_SECURITY_ERROR.
+               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);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgSubCancelReq()");
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgSubCancelReq()");
+       }
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_CANCEL_REQ, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgRegSentStatusCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       // input check
+       if( !pCmd || !ppEvent)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       // Get Message Request
+       int listenerFd = *((int*) pCmd->cmdData);
+       MSG_DEBUG("Registering sent status CB for %d", listenerFd);
+
+       // storing dst fd in list
+       MsgTransactionManager::instance()->setSentStatusCB(listenerFd);
+
+       // Make Event Data
+       int eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_REG_SENT_STATUS_CB, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgRegIncomingMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       // input check
+       if( !pCmd || !ppEvent)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       // Get Message Request
+       MSG_CMD_REG_INCOMING_MSG_CB_S *pCmdData = (MSG_CMD_REG_INCOMING_MSG_CB_S*) pCmd->cmdData;
+       MSG_DEBUG("Registering incoming SMS CB for fd %d mType %d port %d", pCmdData->listenerFd, pCmdData->msgType, pCmdData->port);
+
+       // storing dst fd in list
+       MsgTransactionManager::instance()->setIncomingMsgCB(pCmdData);
+
+       // Make Event Data
+       int eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_REG_INCOMING_MSG_CB, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgRegIncomingMMSConfMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       // input check
+       if( !pCmd || !ppEvent)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       // Get Message Request
+       MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB_S *pCmdData = (MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB_S*) pCmd->cmdData;
+       MSG_DEBUG("Registering incoming MMS Conf CB for fd:%d mType:%d appId:%s", pCmdData->listenerFd, pCmdData->msgType, pCmdData->appId);
+
+       // storing dst fd in list
+       MsgTransactionManager::instance()->setMMSConfMsgCB(pCmdData);
+
+       // Make Event Data
+       int eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_REG_INCOMING_MMS_CONF_MSG_CB, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
+int MsgRegIncomingPushMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       // input check
+       if( !pCmd || !ppEvent)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       // 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);
+
+       // 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)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       // 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 Push Msg CB for fd:%d mType:%d", pCmdData->listenerFd, pCmdData->msgType);
+
+       // 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");
+
+       // Get Message Request
+       MSG_CMD_REG_INCOMING_SYNCML_MSG_CB_S *pCmdData = (MSG_CMD_REG_INCOMING_SYNCML_MSG_CB_S*) pCmd->cmdData;
+       MSG_DEBUG("Registering incoming Sync ML Msg CB for fd %d mType %d", pCmdData->listenerFd, pCmdData->msgType);
+
+       // storing dst fd in list
+       MsgTransactionManager::instance()->setSyncMLMsgCB(pCmdData);
+
+       // Make Event Data
+       int eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_REG_INCOMING_SYNCML_MSG_CB, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgRegIncomingLBSMsgCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       // input check
+       if( !pCmd || !ppEvent)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       // Get Message Request
+       MSG_CMD_REG_INCOMING_LBS_MSG_CB_S *pCmdData = (MSG_CMD_REG_INCOMING_LBS_MSG_CB_S*) pCmd->cmdData;
+       MSG_DEBUG("Registering incoming LBS Msg CB for fd %d mType %d", pCmdData->listenerFd, pCmdData->msgType);
+
+       // storing dst fd in list
+       MsgTransactionManager::instance()->setLBSMsgCB(pCmdData);
+
+       // Make Event Data
+       int eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_REG_INCOMING_LBS_MSG_CB, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgRegSyncMLMsgOperationCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       // input check
+       if( !pCmd || !ppEvent)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       // Get Message Request
+       MSG_CMD_REG_SYNCML_MSG_OPERATION_CB_S *pCmdData = (MSG_CMD_REG_SYNCML_MSG_OPERATION_CB_S*) pCmd->cmdData;
+       MSG_DEBUG("Registering SyncML Msg ooperation CB for fd %d mType %d", pCmdData->listenerFd, pCmdData->msgType);
+
+       // storing dst fd in list
+       MsgTransactionManager::instance()->setSyncMLMsgOperationCB(pCmdData);
+
+       // Make Event Data
+       int eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_REG_SYNCML_MSG_OPERATION_CB, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgRegStorageChangeCallbackHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       // input check
+       if( !pCmd || !ppEvent)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       // Get Message Request
+       int listenerFd = *((int*) pCmd->cmdData);
+       MSG_DEBUG("Registering storage change CB for %d", listenerFd);
+
+       // storing dst fd in list
+       MsgTransactionManager::instance()->setStorageChangeCB(listenerFd);
+
+       // Make Event Data
+       int eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_REG_STORAGE_CHANGE_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");
+
+       // Get Message Request
+       MSG_SENT_STATUS_S* pStatus = (MSG_SENT_STATUS_S*) pCmd->cmdData;
+
+       MSG_DEBUG("REQID %d, STATUS %d", pStatus->reqId, pStatus->status);
+
+       // 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)
+       {
+               return MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_SENT_STATUS_CNF, MSG_SUCCESS, (void**)ppEvent);
+       }
+
+       MSG_DEBUG("REQID %d, listenerFD %d, handleAddr %x, msgId %d", pStatus->reqId, prxInfo->listenerFd, prxInfo->handleAddr, prxInfo->sentMsgId);
+
+       // if APP send and quit(not exist at this time), don't send the data up.
+       if (prxInfo->handleAddr == 0)
+       {
+               // just making data which will be passed to plugin. it indicates "handling evt success"
+               MsgTransactionManager::instance()->delProxyInfo(pStatus->reqId);
+
+               return MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_SENT_STATUS_CNF, MSG_SUCCESS, (void**)ppEvent);
+       }
+
+       unsigned int ret[3] = {0}; //3// reqid, status, object
+
+       ret[0] = pStatus->reqId;
+       ret[1] = pStatus->status;
+       ret[2] = prxInfo->handleAddr;
+
+       // Make Event Data for APP
+       int 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);
+
+       MsgTransactionManager::instance()->delProxyInfo(pStatus->reqId);
+
+       return eventSize;
+}
+
+
+int MsgIncomingMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+       int eventSize = 0;
+       bool sendNoti = true;
+
+       // input check
+       if (!pCmd || !ppEvent)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       // 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));
+
+       // normal process
+       err = MsgHandleIncomingMsg(&msgInfo, &sendNoti);
+
+       // broadcast to listener threads, here
+       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 (sendNoti == true) {
+               MsgTransactionManager::instance()->broadcastIncomingMsgCB(err, &msgInfo);
+               MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+       } else if(msgInfo.msgPort.valid)
+       {
+               MsgTransactionManager::instance()->broadcastIncomingMsgCB(err, &msgInfo);
+       }
+       else if (msgInfo.folderId == MSG_SPAMBOX_ID) {
+               MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+       }
+
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_INCOMING_MSG_IND, err, (void**)ppEvent);
+
+       MSG_END();
+
+       return eventSize;
+}
+
+int MsgIncomingMMSConfMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       MSG_BEGIN();
+       msg_error_t err = MSG_SUCCESS;
+       int eventsize = 0;
+
+       MSG_MESSAGE_INFO_S msgInfo = {0};
+       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));
+
+       MSG_DEBUG(" pMsg = %s, pReqId = %d ", msgInfo.msgData, reqID);
+       MSG_DEBUG(" msgtype subtype is [%d]", msgInfo.msgType.subType);
+
+       // For Storage change callback
+       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;
+
+       err = MsgStoGetAddrInfo(msgInfo.msgId, &(msgInfo.addressList[0]));
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("MmsStoGetAddrInfo() success.");
+               msgInfo.nAddressCnt = 1;
+       } else {
+               MSG_DEBUG("MmsStoGetAddrInfo() fail.");
+       }
+
+       if(msgInfo.msgType.subType == MSG_RETRIEVE_AUTOCONF_MMS || msgInfo.msgType.subType == MSG_RETRIEVE_MANUALCONF_MMS) {
+
+               err = MsgHandleMmsConfIncomingMsg(&msgInfo, reqID);
+
+               if(err != MSG_SUCCESS)
+                       return err;
+
+               MMS_RECV_DATA_S* pMmsRecvData = (MMS_RECV_DATA_S*)msgInfo.msgData;
+
+               if (pMmsRecvData->msgAppId.valid == true) {
+                       MSG_DEBUG("valid : %d, appId : %s", pMmsRecvData->msgAppId.valid, pMmsRecvData->msgAppId.appId);
+               } else {
+                       msgInfo.bTextSms = true;
+                       msgInfo.dataSize = 0 ;
+                       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);
+       } else if (msgInfo.msgType.subType == MSG_SENDREQ_MMS || msgInfo.msgType.subType == MSG_SENDCONF_MMS) {
+               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 {
+                       // No need to update javaMMS sent messages
+                       javamms_list& listenerList = MsgTransactionManager::instance()->getJavaMMSList();
+                       javamms_list::iterator it = listenerList.begin();
+
+                       MSG_DEBUG("listenerList size:%d ",listenerList.size());
+
+                       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);
+                                               MsgDeleteFile(it->pduFileName);         // ipc
+                                               listenerList.erase(it);
+                                               goto __BYPASS_UPDATE;
+                                       }
+                               }
+                       } else {
+                               //msgData has MMS_RECV_DATA_S
+                               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);
+                                               MsgDeleteFile(it->pduFileName); // ipc
+                                               listenerList.erase(it);
+                                               goto __BYPASS_UPDATE;
+                                       }
+                               }
+                       }
+               }
+
+               err = MsgHandleMmsConfIncomingMsg(&msgInfo, reqID);
+
+               if(err != MSG_SUCCESS)
+                       return err;
+
+__BYPASS_UPDATE:
+               if (msgInfo.networkStatus == MSG_NETWORK_SEND_FAIL) {
+                       MSG_DEBUG("message-dialog: send fail");
+                       MsgInsertTicker("Sending multimedia message failed.", SENDING_MULTIMEDIA_MESSAGE_FAILED);
+               } 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);
+                       MsgAddPhoneLog(&msgInfo);
+               }
+
+               if (prxInfo) {
+                       if (prxInfo->handleAddr == 0) {
+                               // just making data which will be passed to plugin. it indicates "handling evt success"
+                               MsgTransactionManager::instance()->delProxyInfo(reqID);
+
+                               return MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_SENT_STATUS_CNF, MSG_SUCCESS, (void**)ppEvent);
+                       }
+
+                       unsigned int ret[3] = {0}; //3// reqid, status, object
+
+                       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);
+
+                       // Send to listener thread, here
+                       MsgTransactionManager::instance()->write(prxInfo->listenerFd, *ppEvent, eventsize);
+
+                       MsgTransactionManager::instance()->delProxyInfo(reqID);
+               }
+
+               msgInfo.bTextSms = true;
+               MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_UPDATE, &msgIdList);
+       }
+
+       MSG_END();
+       return eventsize;
+}
+
+int MsgIncomingPushMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       MSG_BEGIN();
+
+       int eventSize = 0;
+
+       // input check
+       if (!pCmd || !ppEvent)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       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)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       // 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_id_list_s msgIdList;
+       msg_message_id_t msgIds[1];
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+       MsgTransactionManager::instance()->broadcastCBMsgCB(err, &cbMsg);
+
+       bool bSave = false;
+       MsgSettingGetBool(CB_SAVE, &bSave);
+
+       if(bSave && cbMsg.type!= MSG_ETWS_SMS) {
+               msgIdList.nCount = 1;
+               msgIds[0] = (msg_message_id_t)cbMsg.messageId;
+               msgIdList.msgIdList = msgIds;
+               MsgTransactionManager::instance()->broadcastStorageChangeCB(err, MSG_STORAGE_CHANGE_INSERT, &msgIdList);
+       }
+       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");
+
+       MSG_SYNCML_MESSAGE_DATA_S syncMLData;
+       memset(&syncMLData, 0x00, sizeof(MSG_SYNCML_MESSAGE_DATA_S));
+
+       // Get Incoming Message
+       memcpy(&syncMLData, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(MSG_SYNCML_MESSAGE_DATA_S));
+
+       int eventSize = 0;
+
+       // broadcast to listener threads, here
+       MsgTransactionManager::instance()->broadcastSyncMLMsgCB(MSG_SUCCESS, &syncMLData);
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_INCOMING_SYNCML_MSG_IND, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+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");
+
+       MSG_LBS_MESSAGE_DATA_S lbsData;
+       memset(&lbsData, 0x00, sizeof(MSG_LBS_MESSAGE_DATA_S));
+
+       // Get Incoming Message
+       memcpy(&lbsData, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(MSG_LBS_MESSAGE_DATA_S));
+
+       // broadcast to listener threads, here
+       MsgTransactionManager::instance()->broadcastLBSMsgCB(MSG_SUCCESS, &lbsData);
+
+       // Make Event Data
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_INCOMING_LBS_MSG_IND, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgSyncMLMsgOperationHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       int eventSize = 0;
+
+       msg_message_id_t msgId = 0;
+       int extId = 0;
+
+       // input check
+       if (!pCmd || !ppEvent)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       // Get Data
+       memcpy(&msgId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), sizeof(msg_message_id_t));
+       memcpy(&extId, (void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_message_id_t)), sizeof(int));
+
+       err = MsgStoGetSyncMLExtId(msgId, &extId);
+
+       if (err == MSG_SUCCESS)
+       {
+               MSG_DEBUG("Command Handle Success : MsgStoGetSyncMLExtId()");
+
+               // broadcast to listener threads, here
+               MsgTransactionManager::instance()->broadcastSyncMLMsgOperationCB(err, msgId, extId);
+       }
+       else
+       {
+               MSG_DEBUG("Command Handle Fail : MsgStoGetSyncMLExtId()");
+       }
+
+       // Make Event Data to Client
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_SYNCML_OPERATION, err, (void**)ppEvent);
+
+       return eventSize;
+}
+
+
+int MsgStorageChangeHandler(const MSG_CMD_S *pCmd, char **ppEvent)
+{
+       // input check
+       if (!pCmd || !ppEvent)
+               THROW(MsgException::INVALID_PARAM, "pCmd or ppEvent is null");
+
+       msg_storage_change_type_t storageChangeType;
+
+       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));
+       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);
+
+       int eventSize = 0;
+
+       MSG_DEBUG("storageChangeType : [%d], msg Id : [%d]", storageChangeType, msgInfo.msgId);
+
+       // broadcast to listener threads, here
+       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;
+
+       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, storageChangeType, &msgIdList);
+
+       // Make Event Data to Client
+       eventSize = MsgMakeEvent(NULL, 0, MSG_EVENT_PLG_STORAGE_CHANGE_IND, MSG_SUCCESS, (void**)ppEvent);
+
+       return eventSize;
+}
diff --git a/framework/transaction-manager/MsgTransManager.cpp b/framework/transaction-manager/MsgTransManager.cpp
new file mode 100755 (executable)
index 0000000..b96a978
--- /dev/null
@@ -0,0 +1,1037 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <security-server.h>
+
+#include "MsgDebug.h"
+#include "MsgMemory.h"
+#include "MsgException.h"
+#include "MsgCppTypes.h"
+#include "MsgContact.h"
+#include "MsgIpcSocket.h"
+#include "MsgGconfWrapper.h"
+#include "MsgUtilFunction.h"
+#include "MsgCmdHandler.h"
+#include "MsgSettingHandler.h"
+#include "MsgStorageHandler.h"
+#include "MsgPluginManager.h"
+#include "MsgTransManager.h"
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+void MsgContactChangedCallback()
+{
+       msg_id_list_s msgIdList;
+       memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+       MsgTransactionManager::instance()->broadcastStorageChangeCB(MSG_SUCCESS, MSG_STORAGE_CHANGE_CONTACT, &msgIdList);
+}
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgTransactionManager - Member Functions
+==================================================================================================*/
+MsgTransactionManager* MsgTransactionManager::pInstance = NULL;
+MsgIpcServerSocket MsgTransactionManager::servSock;
+
+
+MsgTransactionManager::MsgTransactionManager() : running(false), mx(), cv()
+{
+       sentMsgMap.clear();
+
+       statusCBFdMap.clear();
+       newMsgCBList.clear();
+       newMMSConfMsgCBList.clear();
+       newSyncMLMsgCBList.clear();
+       newLBSMsgCBList.clear();
+       javaMMSList.clear();
+       operationSyncMLMsgCBList.clear();
+       storageChangeFdMap.clear();
+
+       handlerMap.clear();
+
+//     Fill in mMsgHandlers, as given in the below.
+       handlerMap[MSG_CMD_ADD_MSG]                             = &MsgAddMessageHandler;
+       handlerMap[MSG_CMD_ADD_SYNCML_MSG]              = &MsgAddSyncMLMessageHandler;
+       handlerMap[MSG_CMD_UPDATE_MSG]                  = &MsgUpdateMessageHandler;
+       handlerMap[MSG_CMD_UPDATE_READ]                         = &MsgUpdateReadStatusHandler;
+       handlerMap[MSG_CMD_UPDATE_PROTECTED]            = &MsgUpdateProtectedStatusHandler;
+       handlerMap[MSG_CMD_DELETE_MSG]                  = &MsgDeleteMessageHandler;
+       handlerMap[MSG_CMD_DELALL_MSGINFOLDER]  = &MsgDeleteAllMessageInFolderHandler;
+       handlerMap[MSG_CMD_MOVE_MSGTOFOLDER]    = &MsgMoveMessageToFolderHandler;
+       handlerMap[MSG_CMD_MOVE_MSGTOSTORAGE]   = &MsgMoveMessageToStorageHandler;
+       handlerMap[MSG_CMD_COUNT_MSG]                   = &MsgCountMessageHandler;
+       handlerMap[MSG_CMD_GET_MSG]                             = &MsgGetMessageHandler;
+       handlerMap[MSG_CMD_GET_FOLDERVIEWLIST]  = &MsgGetFolderViewListHandler;
+
+       handlerMap[MSG_CMD_ADD_FOLDER]                  = &MsgAddFolderHandler;
+       handlerMap[MSG_CMD_UPDATE_FOLDER]               = &MsgUpdateFolderHandler;
+       handlerMap[MSG_CMD_DELETE_FOLDER]               = &MsgDeleteFolderHandler;
+       handlerMap[MSG_CMD_GET_FOLDERLIST]              = &MsgGetFolderListHandler;
+
+       handlerMap[MSG_CMD_ADD_FILTER]                  = &MsgAddFilterHandler;
+       handlerMap[MSG_CMD_UPDATE_FILTER]                       = &MsgUpdateFilterHandler;
+       handlerMap[MSG_CMD_DELETE_FILTER]               = &MsgDeleteFilterHandler;
+       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_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;
+       handlerMap[MSG_CMD_PLG_INIT_SIM_BY_SAT] = &MsgInitSimBySatHandler;
+
+       handlerMap[MSG_CMD_GET_THREADVIEWLIST]  = &MsgGetThreadViewListHandler;
+       handlerMap[MSG_CMD_GET_CONVERSATIONVIEWLIST]    = &MsgGetConversationViewListHandler;
+       handlerMap[MSG_CMD_DELETE_THREADMESSAGELIST]    = &MsgDeleteThreadMessageListHandler;
+
+       handlerMap[MSG_CMD_GET_CONTACT_COUNT]   = &MsgCountMsgByContactHandler;
+       handlerMap[MSG_CMD_GET_QUICKPANEL_DATA]         = &MsgGetQuickPanelDataHandler;
+       handlerMap[MSG_CMD_COUNT_BY_MSGTYPE]    = &MsgCountMsgByTypeHandler;
+       handlerMap[MSG_CMD_RESET_DB]    = &MsgResetDatabaseHandler;
+       handlerMap[MSG_CMD_GET_MEMSIZE]         = &MsgGetMemSizeHandler;
+
+       handlerMap[MSG_CMD_BACKUP_MESSAGE]      = &MsgBackupMessageHandler;
+       handlerMap[MSG_CMD_RESTORE_MESSAGE] = &MsgRestoreMessageHandler;
+
+       handlerMap[MSG_CMD_UPDATE_THREAD_READ] = &MsgUpdateThreadReadStatusHandler;
+
+       handlerMap[MSG_CMD_SYNCML_OPERATION] = &MsgSyncMLMsgOperationHandler;
+       handlerMap[MSG_CMD_GET_REPORT_STATUS]                   = &MsgGetReportStatusHandler;
+
+       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;
+       handlerMap[MSG_CMD_GET_MMS_SEND_OPT] = &MsgGetConfigHandler;
+       handlerMap[MSG_CMD_GET_MMS_RECV_OPT] = &MsgGetConfigHandler;
+       handlerMap[MSG_CMD_GET_PUSH_MSG_OPT] = &MsgGetConfigHandler;
+       handlerMap[MSG_CMD_GET_VOICE_MSG_OPT] = &MsgGetConfigHandler;
+       handlerMap[MSG_CMD_GET_GENERAL_MSG_OPT] = &MsgGetConfigHandler;
+       handlerMap[MSG_CMD_GET_MSG_SIZE_OPT] = &MsgGetConfigHandler;
+
+       handlerMap[MSG_CMD_SET_SMSC_OPT] = &MsgSetConfigHandler;
+       handlerMap[MSG_CMD_SET_CB_OPT] = &MsgSetConfigHandler;
+       handlerMap[MSG_CMD_SET_SMS_SEND_OPT] = &MsgSetConfigHandler;
+       handlerMap[MSG_CMD_SET_MMS_SEND_OPT] = &MsgSetConfigHandler;
+       handlerMap[MSG_CMD_SET_MMS_RECV_OPT] = &MsgSetConfigHandler;
+       handlerMap[MSG_CMD_SET_PUSH_MSG_OPT] = &MsgSetConfigHandler;
+       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;
+}
+
+
+MsgTransactionManager::~MsgTransactionManager()
+{
+//     pthread_cond_init(&retCV, NULL); // = PTHREAD_COND_INITIALIZER;
+
+}
+
+
+MsgTransactionManager* MsgTransactionManager::instance()
+{
+       if (!pInstance)
+               pInstance = new MsgTransactionManager();
+
+       return pInstance;
+}
+
+
+void MsgTransactionManager::run()
+{
+       servSock.open(MSG_SOCKET_PATH);
+
+       fd_set readfds = servSock.fdSet();
+       int nfds = 0;
+
+       MSG_DEBUG("Start Transaction Manager");
+
+       while(1)
+       {
+               readfds = servSock.fdSet();
+               nfds = servSock.maxFd();
+
+               MSG_DEBUG("Wait For Select() : nfds %d", nfds);
+
+               // set Status;
+               setTMStatus();
+
+               if(select(nfds, &readfds, NULL, NULL, NULL) == -1) {
+                       THROW(MsgException::SELECT_ERROR, "select error : %s", strerror(errno));
+               }
+
+               try
+               {
+                       for (int i=0 ; i < nfds; i++)
+                       {
+                               if (FD_ISSET(i, &readfds))
+                               {
+                                       if (i == servSock.fd()) // if it is socket connection request
+                                               servSock.accept();
+                                       else
+                                               handleRequest(i);
+                               }
+                       }
+               }
+               catch (MsgException& e)
+               {
+                       MSG_FATAL("%s", e.what());
+               }
+               catch (exception& e)
+               {
+                       MSG_FATAL("%s", e.what());
+               }
+
+               // Release Memory
+               //MsgReleaseMemory();
+       }
+}
+
+
+void MsgTransactionManager::write(int fd, const char* buf, int len)
+{
+       servSock.write(fd, buf, len);
+}
+
+
+void MsgTransactionManager::insertSentMsg(int reqId, MSG_PROXY_INFO_S* pPrxInfo)
+{
+       if (pPrxInfo == NULL)
+               THROW(MsgException::SENT_STATUS_ERROR, "Input Parameter is NULL");
+
+       MSG_DEBUG("msg for submit: reqId %d listenerFd %d handleAddr %x", reqId, pPrxInfo->listenerFd, pPrxInfo->handleAddr);
+
+       fd_map::iterator it = statusCBFdMap.find(pPrxInfo->listenerFd);
+
+       if (it == statusCBFdMap.end()) { // if the status CB is not registered
+               MSG_DEBUG("No sent_status registered for fd %d", pPrxInfo->listenerFd);
+       } else {
+               sentMsgMap.insert(make_pair(reqId, *pPrxInfo));
+       }
+}
+
+
+MSG_PROXY_INFO_S* MsgTransactionManager::getProxyInfo(int reqId)
+{
+       sentmsg_map::iterator it = sentMsgMap.find(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)");
+               return NULL;
+       }
+
+       return &(it->second);
+}
+
+
+void MsgTransactionManager::delProxyInfo(int reqId)
+{
+       sentmsg_map::iterator it = sentMsgMap.find(reqId);
+
+       if (it == sentMsgMap.end())
+       {
+               THROW(MsgException::SENT_STATUS_ERROR, "channel info does not exist");
+       }
+
+       sentMsgMap.erase(it);
+}
+
+
+void MsgTransactionManager::handleRequest(int fd)
+{
+       MSG_BEGIN();
+
+       MSG_DEBUG("Event from fd %d", fd);
+
+       char* buf = NULL;
+       AutoPtr<char> wrap(&buf);
+       int len;
+       int ret = servSock.read(fd, &buf, &len);
+
+       if( ret == CLOSE_CONNECTION_BY_SIGNAL || ret == CLOSE_CONNECTION_BY_USER || ret < 0)
+       {
+               MSG_DEBUG("Read value [%d]", ret);
+               cleanup(fd);
+               return;
+       }
+
+       if (len <= 0)
+               THROW(MsgException::INVALID_RESULT, "read buffer size <= 0");
+
+       char* pEventData = NULL;
+       AutoPtr<char> eventBuf(&pEventData);
+
+       int eventSize = 0;
+
+       // decoding cmd from APP
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) buf;
+       MSG_DEBUG("Command Type [%d : %s]", pCmd->cmdType, MsgDbgCmdStr(pCmd->cmdType));
+
+       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)
+               {
+#ifdef MSG_CHECK_PRIVILEGE
+                       eventSize = sizeof(MSG_EVENT_S);
+
+                       pEventData = new char[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;
+#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);
+
+       servSock.write(fd, pEventData, eventSize);
+
+       MSG_END();
+}
+
+
+// terminating the socket connection between ipc server and ipc client
+void MsgTransactionManager::cleanup(int fd)
+{
+       MSG_BEGIN();
+
+       servSock.close(fd);
+
+       MSG_DEBUG("fd %d disonnected", fd);
+
+       // remove sent msg info for fd
+       sentmsg_map::iterator sentmsg_it = sentMsgMap.begin();
+
+       for (; sentmsg_it != sentMsgMap.end(); sentmsg_it++)
+       {
+               if (sentmsg_it->second.listenerFd == fd)
+               {
+                       sentmsg_it->second.listenerFd = 0;
+                       sentmsg_it->second.handleAddr = 0;
+               }
+       }
+
+       // remove sent status callback for fd
+       statusCBFdMap.erase(fd);
+
+       // remove all newMsgCBs for fd
+       newmsg_list::iterator newmsg_it = newMsgCBList.begin();
+
+       while (newmsg_it != newMsgCBList.end())
+       {
+               if (newmsg_it->listenerFd == fd)
+               {
+                       newmsg_it = newMsgCBList.erase(newmsg_it);
+               }
+               else
+               {
+                       ++newmsg_it;
+               }
+       }
+
+       // remove all newMMSConfMsgCBs for fd
+       mmsconf_list::iterator mmsconf_it = newMMSConfMsgCBList.begin();
+
+       while (mmsconf_it != newMMSConfMsgCBList.end())
+       {
+               if (mmsconf_it->listenerFd == fd)
+               {
+                       mmsconf_it = newMMSConfMsgCBList.erase(mmsconf_it);
+               }
+               else
+               {
+                       ++mmsconf_it;
+               }
+       }
+
+       // remove all newSyncMLMsgCBs for fd
+       syncmlmsg_list::iterator syncmlmsg_it = newSyncMLMsgCBList.begin();
+
+       while (syncmlmsg_it != newSyncMLMsgCBList.end())
+       {
+               if (syncmlmsg_it->listenerFd == fd)
+               {
+                       syncmlmsg_it = newSyncMLMsgCBList.erase(syncmlmsg_it);
+               }
+               else
+               {
+                       ++syncmlmsg_it;
+               }
+       }
+
+       // remove all newLBSMsgCBs for fd
+       lbsmsg_list::iterator lbsmsg_it = newLBSMsgCBList.begin();
+
+       while (lbsmsg_it != newLBSMsgCBList.end())
+       {
+               if (lbsmsg_it->listenerFd == fd)
+               {
+                       lbsmsg_it = newLBSMsgCBList.erase(lbsmsg_it);
+               }
+               else
+               {
+                       ++lbsmsg_it;
+               }
+       }
+
+       // 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();
+
+       while (syncmlop_it != operationSyncMLMsgCBList.end())
+       {
+               if (syncmlop_it->listenerFd == fd)
+               {
+                       syncmlop_it = operationSyncMLMsgCBList.erase(syncmlop_it);
+               }
+               else
+               {
+                       ++syncmlop_it;
+               }
+       }
+
+       // remove storage change callback for fd
+       storageChangeFdMap.erase(fd);
+
+       MSG_END();
+}
+
+
+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;
+       }
+
+       // Get Cookie from APP
+       if (pCookie == NULL)
+       {
+               MSG_DEBUG("Cookie is NULL");
+               return false;
+       }
+
+#ifdef MSG_FOR_DEBUG
+       for (int i = 0; i < MAX_COOKIE_LEN; i++)
+       {
+               MSG_DEBUG("cookie : [%02x]", pCookie[i]);
+       }
+#endif
+
+       // Check Cookie
+       size_t cookieSize;
+       gid_t gid;
+
+       cookieSize = security_server_get_cookie_size();
+
+       MSG_DEBUG("cookie size : [%d]", cookieSize);
+
+//     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)
+       {
+               MSG_DEBUG("get GID for message_lbs");
+               gid = security_server_get_gid("message_lbs");
+       }
+       else
+       {
+               MSG_DEBUG("get GID for message");
+               gid = security_server_get_gid("message");
+       }
+
+       MSG_DEBUG("gid [%d]", gid);
+
+       int retVal = 0;
+
+       retVal = security_server_check_privilege(pCookie, gid);
+
+       if (retVal < 0)
+       {
+               if (retVal == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
+               {
+                       MSG_DEBUG("access denied !! [%d]", retVal);
+               }
+               else
+               {
+                       MSG_DEBUG("fail to check privilege [%d]", retVal);
+               }
+
+               return false;
+       }
+
+       MSG_DEBUG("privilege check success !!");
+
+       return true;
+}
+
+
+void MsgTransactionManager::setSentStatusCB(int listenerFd)
+{
+       if (listenerFd <= 0)
+               THROW(MsgException::INVALID_PARAM,"InParam Error: listenerFd %d",listenerFd);
+
+       statusCBFdMap[listenerFd] = true;
+}
+
+
+void MsgTransactionManager::setIncomingMsgCB(MSG_CMD_REG_INCOMING_MSG_CB_S *pCbInfo)
+{
+       if (!pCbInfo)
+       {
+               MSG_FATAL("cbinfo NULL");
+               return;
+       }
+
+       newmsg_list::iterator it = newMsgCBList.begin();
+
+       for (; it != newMsgCBList.end(); it++)
+       {
+               if ((it->listenerFd == pCbInfo->listenerFd) && (it->msgType == pCbInfo->msgType) && (it->port == pCbInfo->port))
+               {
+                       MSG_DEBUG("Duplicated messageCB info fd %d, mType %d, port %d", it->listenerFd, it->msgType, it->port);
+                       return;
+               }
+       }
+
+       newMsgCBList.push_back(*pCbInfo);
+}
+
+
+void MsgTransactionManager::setMMSConfMsgCB(MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB_S *pCbInfo)
+{
+       if (!pCbInfo)
+       {
+               MSG_FATAL("cbinfo NULL");
+               return;
+       }
+
+       mmsconf_list::iterator it = newMMSConfMsgCBList.begin();
+
+       for (; it != newMMSConfMsgCBList.end(); it++)
+       {
+               if ((it->listenerFd == pCbInfo->listenerFd) && (it->msgType == pCbInfo->msgType) && (!strncmp(it->appId, pCbInfo->appId, MAX_MMS_JAVA_APPID_LEN)))
+               {
+                       MSG_DEBUG("Duplicated MMSConfMessageCB info fd:%d, mType:%d, appId:%s", it->listenerFd, it->msgType, it->appId);
+                       return;
+               }
+       }
+
+       newMMSConfMsgCBList.push_back(*pCbInfo);
+}
+
+
+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))
+               {
+                       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)
+{
+       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;
+               }
+       }
+
+       if(pCbInfo->bsave)
+               if(MsgSettingSetBool(CB_SAVE, pCbInfo->bsave) != MSG_SUCCESS)
+                       MSG_DEBUG("MsgSettingSetBool FAIL: CB_SAVE");
+
+
+       newCBMsgCBList.push_back(*pCbInfo);
+}
+
+void MsgTransactionManager::setSyncMLMsgCB(MSG_CMD_REG_INCOMING_SYNCML_MSG_CB_S *pCbInfo)
+{
+       if (!pCbInfo)
+       {
+               MSG_FATAL("cbinfo NULL");
+               return;
+       }
+
+       syncmlmsg_list::iterator it = newSyncMLMsgCBList.begin();
+
+       for (; it != newSyncMLMsgCBList.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;
+               }
+       }
+
+       newSyncMLMsgCBList.push_back(*pCbInfo);
+}
+
+
+void MsgTransactionManager::setLBSMsgCB(MSG_CMD_REG_INCOMING_LBS_MSG_CB_S *pCbInfo)
+{
+       if (!pCbInfo)
+       {
+               MSG_FATAL("cbinfo NULL");
+               return;
+       }
+
+       lbsmsg_list::iterator it = newLBSMsgCBList.begin();
+
+       for (; it != newLBSMsgCBList.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;
+               }
+       }
+
+       newLBSMsgCBList.push_back(*pCbInfo);
+}
+
+
+void MsgTransactionManager::setJavaMMSList(MSG_CMD_REG_INCOMING_JAVAMMS_TRID_S *pTrId)
+{
+       if (!pTrId)
+       {
+               MSG_FATAL("trId NULL");
+               return;
+       }
+
+       javamms_list::iterator it;
+
+       for (it = javaMMSList.begin(); it != javaMMSList.end(); it++)
+       {
+               if (!strcmp(it->id, pTrId->id))
+               {
+                       MSG_DEBUG("Duplicated javaMMS transaction Id:%s", it->id);
+                       return;
+               }
+       }
+
+       javaMMSList.push_back(*pTrId);
+}
+
+
+void MsgTransactionManager::setSyncMLMsgOperationCB(MSG_CMD_REG_SYNCML_MSG_OPERATION_CB_S *pCbInfo)
+{
+       if (!pCbInfo)
+       {
+               MSG_FATAL("cbinfo NULL");
+               return;
+       }
+
+       syncmlop_list::iterator it = operationSyncMLMsgCBList.begin();
+
+       for (; it != operationSyncMLMsgCBList.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;
+               }
+       }
+
+       operationSyncMLMsgCBList.push_back(*pCbInfo);
+}
+
+
+void MsgTransactionManager::setStorageChangeCB(int listenerFd)
+{
+       if (listenerFd <= 0)
+               THROW(MsgException::INVALID_PARAM,"InParam Error: listenerFd %d", listenerFd);
+
+       storageChangeFdMap[listenerFd] = true;
+}
+
+
+javamms_list& MsgTransactionManager::getJavaMMSList()
+{
+       return javaMMSList;
+}
+
+
+void MsgTransactionManager::broadcastIncomingMsgCB(const msg_error_t err, const MSG_MESSAGE_INFO_S *msgInfo)
+{
+       MSG_BEGIN();
+
+       char* pEventData = NULL;
+       AutoPtr<char> eventBuf(&pEventData);
+
+       int eventSize = MsgMakeEvent(msgInfo, sizeof(MSG_MESSAGE_INFO_S), MSG_EVENT_PLG_INCOMING_MSG_IND, err, (void**)(&pEventData));
+
+       MSG_DEBUG("valid %d dstport %d", msgInfo->msgPort.valid, msgInfo->msgPort.dstPort);
+
+       newmsg_list::iterator it = newMsgCBList.begin();
+
+       for (; it != newMsgCBList.end(); it++)
+       {
+               MSG_DEBUG("fd %d dstport %d",it->listenerFd, it->port);
+
+               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))
+               {
+                       MSG_DEBUG("Send incoming port msg to listener %d", it->listenerFd);
+                       write(it->listenerFd, pEventData, eventSize);
+               }
+       }
+
+       MSG_END();
+}
+
+
+void MsgTransactionManager::broadcastMMSConfCB(const msg_error_t err, const MSG_MESSAGE_INFO_S *msgInfo, const MMS_RECV_DATA_S *mmsRecvData)
+{
+       MSG_BEGIN();
+
+       char* pEventData = NULL;
+       AutoPtr<char> eventBuf(&pEventData);
+
+       int eventSize = MsgMakeEvent(msgInfo, sizeof(MSG_MESSAGE_INFO_S), MSG_EVENT_PLG_INCOMING_MMS_CONF, err, (void**)(&pEventData));
+
+       mmsconf_list::iterator it = newMMSConfMsgCBList.begin();
+
+       for (; it != newMMSConfMsgCBList.end(); it++)
+       {
+               MSG_DEBUG("fd:%d appId:%s",it->listenerFd, it->appId);
+
+               if (mmsRecvData->msgAppId.valid == true)
+               {
+                       if (!strcmp(it->appId, mmsRecvData->msgAppId.appId))
+                       {
+                               MSG_DEBUG("Send incoming java msg to listener %d", it->listenerFd);
+                               write(it->listenerFd, pEventData, eventSize);
+                       }
+               }
+               else
+               {
+                       if (strlen(it->appId) <= 0)
+                       {
+                               MSG_DEBUG("Send incoming normal msg to listener %d", it->listenerFd);
+                               write(it->listenerFd, pEventData, eventSize);
+                       }
+               }
+       }
+
+
+       MSG_END();
+}
+
+void MsgTransactionManager::broadcastPushMsgCB(const msg_error_t err, const MSG_PUSH_MESSAGE_DATA_S *pushData)
+{
+       MSG_BEGIN();
+
+       char* pEventData = NULL;
+       AutoPtr<char> eventBuf(&pEventData);
+
+       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++)
+       {
+               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;
+       AutoPtr<char> eventBuf(&pEventData);
+
+       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);
+
+       int eventSize = MsgMakeEvent(syncMLData, sizeof(MSG_SYNCML_MESSAGE_DATA_S), MSG_EVENT_PLG_INCOMING_SYNCML_MSG_IND, err, (void**)(&pEventData));
+
+       syncmlmsg_list::iterator it = newSyncMLMsgCBList.begin();
+
+       for (; it != newSyncMLMsgCBList.end(); it++)
+       {
+               MSG_DEBUG("Send incoming SyncML information to listener %d", it->listenerFd);
+               write(it->listenerFd, pEventData, eventSize);
+       }
+
+       MSG_END();
+}
+
+
+void MsgTransactionManager::broadcastLBSMsgCB(const msg_error_t err, const MSG_LBS_MESSAGE_DATA_S *lbsData)
+{
+       MSG_BEGIN();
+
+       char* pEventData = NULL;
+       AutoPtr<char> eventBuf(&pEventData);
+
+       int eventSize = MsgMakeEvent(lbsData, sizeof(MSG_LBS_MESSAGE_DATA_S), MSG_EVENT_PLG_INCOMING_LBS_MSG_IND, err, (void**)(&pEventData));
+
+       lbsmsg_list::iterator it = newLBSMsgCBList.begin();
+
+       for (; it != newLBSMsgCBList.end(); it++)
+       {
+               MSG_DEBUG("Send incoming LBS msg to listener %d", it->listenerFd);
+               write(it->listenerFd, pEventData, eventSize);
+       }
+
+       MSG_END();
+}
+
+
+void MsgTransactionManager::broadcastSyncMLMsgOperationCB(const msg_error_t err, const int msgId, const int extId)
+{
+       MSG_BEGIN();
+
+       char* pEventData = NULL;
+       AutoPtr<char> eventBuf(&pEventData);
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       // Encoding Storage Change Data
+       int dataSize = MsgEncodeSyncMLOperationData(msgId, extId, &encodedData);
+
+       int eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_SYNCML_OPERATION, err, (void**)(&pEventData));
+
+       syncmlop_list::iterator it = operationSyncMLMsgCBList.begin();
+
+       for( ; it != operationSyncMLMsgCBList.end() ; it++ )
+       {
+               MSG_DEBUG("Send SyncML operation to listener %d", it->listenerFd);
+               write(it->listenerFd, pEventData, eventSize);
+       }
+
+       MSG_END();
+}
+
+
+void MsgTransactionManager::broadcastStorageChangeCB(const msg_error_t err, const msg_storage_change_type_t storageChangeType, const msg_id_list_s *pMsgIdList)
+{
+       MSG_BEGIN();
+
+       if(pMsgIdList == NULL) {
+               MSG_DEBUG("pMsgIdList is NULL.");
+               return;
+       }
+
+       MSG_DEBUG("storageChangeType [%d]", storageChangeType);
+
+       int dataSize = 0;
+
+       char* pEventData = NULL;
+       AutoPtr<char> eventBuf(&pEventData);
+
+       char* encodedData = NULL;
+       AutoPtr<char> buf(&encodedData);
+
+       // Encoding Storage Change Data
+       dataSize = MsgEncodeStorageChangeData(storageChangeType, pMsgIdList, &encodedData);
+
+       int eventSize = MsgMakeEvent(encodedData, dataSize, MSG_EVENT_PLG_STORAGE_CHANGE_IND, err, (void**)(&pEventData));
+
+       fd_map::iterator it = storageChangeFdMap.begin();
+
+       for (; it != storageChangeFdMap.end(); it++)
+       {
+               MSG_DEBUG("Send Storage Change Callback to listener %d", it->first);
+               write(it->first, pEventData, eventSize);
+       }
+
+       MSG_END();
+}
+
+
+void MsgTransactionManager::setTMStatus()
+{
+       MSG_BEGIN();
+       mx.lock();
+       cv.signal();
+       mx.unlock();
+       MSG_END();
+}
+
+
+void MsgTransactionManager::getTMStatus()
+{
+       MSG_BEGIN();
+       mx.lock();
+
+       int ret = 0;
+
+       ret = cv.timedwait(mx.pMutex(), 3);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT)
+       {
+               MSG_DEBUG("MsgTransactionManager::getTMStatus TIME-OUT");
+       }
+       MSG_END();
+}
diff --git a/image/messaging_image001.png b/image/messaging_image001.png
new file mode 100755 (executable)
index 0000000..0c575c4
Binary files /dev/null and b/image/messaging_image001.png differ
diff --git a/include/common/MsgCmdTypes.h b/include/common/MsgCmdTypes.h
new file mode 100755 (executable)
index 0000000..6238bf0
--- /dev/null
@@ -0,0 +1,295 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_CMD_TYPES_H
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgTypes.h"
+
+
+/*==================================================================================================
+                                         DEFINES
+==================================================================================================*/
+#define MAX_COOKIE_LEN 20
+
+
+/*==================================================================================================
+                                         TYPES
+==================================================================================================*/
+typedef unsigned int MSG_CMD_TYPE_T;
+
+typedef unsigned int MSG_EVENT_TYPE_T;
+
+
+/*==================================================================================================
+                                         STRUCTURES
+==================================================================================================*/
+typedef struct _MSG_CMD_S
+{
+       MSG_CMD_TYPE_T  cmdType;
+       char                            cmdCookie[MAX_COOKIE_LEN];
+       char                            cmdData[2];
+} MSG_CMD_S;
+
+
+typedef struct _MSG_EVENT_S
+{
+       MSG_EVENT_TYPE_T        eventType;
+       msg_error_t                     result;
+       char                                    data[2];
+} MSG_EVENT_S;
+
+
+/*==================================================================================================
+                                         ENUMS
+==================================================================================================*/
+
+enum _MSG_CMD_TYPE_E
+{
+       MSG_CMD_OPEN_HANDLE = 0,
+       MSG_CMD_CLOSE_HANDLE,
+       MSG_CMD_GET_STORAGELIST,
+       MSG_CMD_ADD_MSG,
+       MSG_CMD_ADD_SYNCML_MSG,
+
+       MSG_CMD_UPDATE_MSG,
+       MSG_CMD_UPDATE_READ,
+       MSG_CMD_UPDATE_PROTECTED,
+       MSG_CMD_DELETE_MSG,
+       MSG_CMD_DELALL_MSGINFOLDER,
+
+// 10
+       MSG_CMD_MOVE_MSGTOFOLDER,
+       MSG_CMD_MOVE_MSGTOSTORAGE,
+       MSG_CMD_COUNT_MSG,
+       MSG_CMD_GET_MSG,
+       MSG_CMD_GET_FOLDERVIEWLIST,
+
+       MSG_CMD_ADD_FOLDER,
+       MSG_CMD_UPDATE_FOLDER,
+       MSG_CMD_DELETE_FOLDER,
+       MSG_CMD_GET_FOLDERLIST,
+       MSG_CMD_ADD_FILTER,
+
+// 20
+       MSG_CMD_UPDATE_FILTER,
+       MSG_CMD_DELETE_FILTER,
+       MSG_CMD_GET_FILTERLIST,
+       MSG_CMD_SET_FILTER_OPERATION,
+       MSG_CMD_GET_FILTER_OPERATION,
+
+       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,
+
+// 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,
+
+// 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,
+
+// 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,
+
+// 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,
+
+// 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,
+
+// 80
+       MSG_CMD_DELETE_PUSH_EVENT,
+       MSG_CMD_UPDATE_PUSH_EVENT,
+       MSG_CMD_DELETE_MESSAGE_BY_LIST,
+       MSG_CMD_SET_FILTER_ACTIVATION,
+
+// 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,
+       MSG_EVENT_CLOSE_HANDLE,
+       MSG_EVENT_GET_STORAGELIST,
+       MSG_EVENT_ADD_MSG,
+       MSG_EVENT_ADD_SYNCML_MSG,
+
+       MSG_EVENT_UPDATE_MSG,
+       MSG_EVENT_UPDATE_READ,
+       MSG_EVENT_UPDATE_PROTECTED,
+       MSG_EVENT_DELETE_MSG,
+       MSG_EVENT_DELALL_MSGINFOLDER,
+
+// 10
+       MSG_EVENT_MOVE_MSGTOFOLDER,
+       MSG_EVENT_MOVE_MSGTOSTORAGE,
+       MSG_EVENT_COUNT_MSG,
+       MSG_EVENT_GET_MSG,
+       MSG_EVENT_GET_FOLDERVIEWLIST,
+
+       MSG_EVENT_ADD_FOLDER,
+       MSG_EVENT_UPDATE_FOLDER,
+       MSG_EVENT_DELETE_FOLDER,
+       MSG_EVENT_GET_FOLDERLIST,
+       MSG_EVENT_ADD_FILTER,
+
+// 20
+       MSG_EVENT_UPDATE_FILTER,
+       MSG_EVENT_DELETE_FILTER,
+       MSG_EVENT_GET_FILTERLIST,
+       MSG_EVENT_SET_FILTER_OPERATION,
+       MSG_EVENT_GET_FILTER_OPERATION,
+
+       MSG_EVENT_GET_MSG_TYPE,
+       MSG_EVENT_SUBMIT_REQ,
+       MSG_EVENT_CANCEL_REQ,
+       MSG_EVENT_REG_SENT_STATUS_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,
+
+// 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,
+
+// 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,
+
+// 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,
+
+// 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,
+
+// 80
+       MSG_EVENT_DELETE_PUSH_EVENT,
+       MSG_EVENT_UPDATE_PUSH_EVENT,
+       MSG_EVENT_DELETE_MESSAGE_BY_LIST,
+       MSG_EVENT_SET_FILTER_ACTIVATION,
+
+// end of MSG_EVENT; new EVENT should be defined before MSG_EVENT_NUM
+       MSG_EVENT_NUM
+};
+
+#endif // MSG_CMD_TYPES_H
+
diff --git a/include/common/MsgCppTypes.h b/include/common/MsgCppTypes.h
new file mode 100755 (executable)
index 0000000..31d75ae
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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__
+#define __MSG_CPP_TYPES_H__
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <stdio.h>
+#include <vector>
+
+typedef std::vector<char> CharVector;
+
+template <class T>
+
+class AutoPtr
+{
+private:
+       T** ptr; // Caution: Memory allocation should be done by "new" not "malloc"
+
+
+public:
+       AutoPtr():ptr(NULL) {}
+
+       AutoPtr(T** target) { ptr = target; }
+
+       ~AutoPtr()
+       {
+               if (ptr)
+               {
+                       if ( *ptr )     delete[] *ptr;
+               }
+       }
+};
+
+#endif // #ifndef __MSG_CPP_TYPES_H__
+
diff --git a/include/common/MsgFilterTypes.h b/include/common/MsgFilterTypes.h
new file mode 100755 (executable)
index 0000000..d43bb96
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_FILTER_TYPES_H
+
+/**
+ *     @file           MsgFilterTypes.h
+ *     @brief          Defines filter types of messaging framework
+ *     @version        1.0
+ */
+
+/**
+ *     @section                Introduction
+ *     - Introduction : Overview on Messaging Filter Types
+ *     @section                Program
+ *     - Program : Messaging Filter Types Reference
+ */
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+
+#include "MsgTypes.h"
+
+/**
+ *     @ingroup                MESSAGING_FRAMEWORK
+ *     @defgroup       MESSAGING_FILTER_TYPES  Messaging Filter Types
+ *     @{
+ */
+
+/*==================================================================================================
+                                         STRUCTURES
+==================================================================================================*/
+
+/**
+ *     @brief  Represents filter informatioin. \n
+ *     It represents the basic filter unit.
+ */
+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. */
+       bool                                                    bActive;
+} MSG_FILTER_S;
+
+
+/**
+ *     @}
+ */
+
+#endif // MSG_FILTER_TYPES_H
+
diff --git a/include/common/MsgInternalTypes.h b/include/common/MsgInternalTypes.h
new file mode 100755 (executable)
index 0000000..feffe1d
--- /dev/null
@@ -0,0 +1,564 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_INTERNAL_TYPES_H
+
+/**
+ *     @file           MsgInternalTypes.h
+ *     @brief          Defines types of messaging framework
+ *     @version        1.0
+ */
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgMmsTypes.h"
+
+
+/*==================================================================================================
+                                    DEFINES
+==================================================================================================*/
+#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 TPDU_LOG_FILE                          MSG_DATA_ROOT_PATH"tpduLog.txt"
+#define MSG_NATIONAL_SIM       "memory/private/msg-service/national_sim"
+#define MSG_SIM_MSISDN "memory/private/msg-service/msisdn"
+#define MAX_FULL_PATH_SIZE             320     // max length for internal file path
+#define MAX_PRECONFIG_NUM              8
+#define MAX_THREAD_ADDR_LEN    40
+#define MAX_THREAD_NAME_LEN    195
+#define MAX_THREAD_DATA_LEN    128
+#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 SMS_MINIMUM_SPACE      (3 * 1024)
+#define MMS_MINIMUM_SPACE      (600 * 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_GENERAL_OPT_PATH               DEFAULT_SETTING_PATH"/general"
+#define DEFAULT_SMS_SEND_OPT_PATH      DEFAULT_SETTING_PATH"/sms_send"
+#define DEFAULT_SMSC_INFO_PATH                 DEFAULT_SETTING_PATH"/smsc"
+#define DEFAULT_MMS_SEND_OPT_PATH      DEFAULT_SETTING_PATH"/mms_send"
+#define DEFAULT_MMS_RECV_OPT_PATH      DEFAULT_SETTING_PATH"/mms_recv"
+#define DEFAULT_MMS_STYLE_OPT_PATH     DEFAULT_SETTING_PATH"/mms_style"
+#define DEFAULT_PUSH_MSG_OPT_PATH      DEFAULT_SETTING_PATH"/push_msg"
+#define DEFAULT_CB_MSG_OPT_PATH                DEFAULT_SETTING_PATH"/cb_msg"
+#define DEFAULT_VOICE_MAIL_OPT_PATH    DEFAULT_SETTING_PATH"/voice_mail"
+#define DEFAULT_MSGSIZE_OPT_PATH               DEFAULT_SETTING_PATH"/size_opt"
+#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_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 SMS_SEND_DCS                                                   DEFAULT_SMS_SEND_OPT_PATH"/dcs"
+#define SMS_SEND_NETWORK_MODE  VCONFKEY_MESSAGE_NETWORK_MODE
+#define SMS_SEND_REPLY_PATH                    DEFAULT_SMS_SEND_OPT_PATH"/reply_path"
+#define SMS_SEND_DELIVERY_REPORT       DEFAULT_SMS_SEND_OPT_PATH"/delivery_report"
+#define SMS_SEND_SAVE_STORAGE          DEFAULT_SMS_SEND_OPT_PATH"/save_storage"
+
+#define SMSC_TOTAL_COUNT               DEFAULT_SMSC_INFO_PATH"/total_count"
+#define SMSC_SELECTED                  DEFAULT_SMSC_INFO_PATH"/selected"
+#define SMSC_PID                                               DEFAULT_SMSC_INFO_PATH"/pid"
+#define SMSC_VAL_PERIOD                DEFAULT_SMSC_INFO_PATH"/val_period"
+#define SMSC_NAME                                      DEFAULT_SMSC_INFO_PATH"/name"
+#define SMSC_TON                                               DEFAULT_SMSC_INFO_PATH"/ton"
+#define SMSC_NPI                                               DEFAULT_SMSC_INFO_PATH"/npi"
+#define SMSC_ADDRESS                           DEFAULT_SMSC_INFO_PATH"/address"
+
+#define MMS_SEND_MSG_CLASS                                                     DEFAULT_MMS_SEND_OPT_PATH"/msg_class"
+#define MMS_SEND_PRIORITY                                                              DEFAULT_MMS_SEND_OPT_PATH"/priority"
+#define MMS_SEND_EXPIRY_TIME                                                   DEFAULT_MMS_SEND_OPT_PATH"/expiry_time"
+#define MMS_SEND_CUSTOM_DELIVERY                               DEFAULT_MMS_SEND_OPT_PATH"/custom_delivery"
+#define MMS_SEND_DELIVERY_TIME                                         DEFAULT_MMS_SEND_OPT_PATH"/delivery_time"
+#define MMS_SEND_SENDER_VISIBILITY                             DEFAULT_MMS_SEND_OPT_PATH"/sender_visibility"
+#define MMS_SEND_DELIVERY_REPORT                                       DEFAULT_MMS_SEND_OPT_PATH"/delivery_report"
+#define MMS_SEND_READ_REPLY                                                    DEFAULT_MMS_SEND_OPT_PATH"/read_reply"
+#define MMS_SEND_KEEP_COPY                                                     DEFAULT_MMS_SEND_OPT_PATH"/keep_copy"
+#define MMS_SEND_BODY_REPLYING                                         DEFAULT_MMS_SEND_OPT_PATH"/body_replying"
+#define MMS_SEND_HIDE_RECIPIENTS                                       DEFAULT_MMS_SEND_OPT_PATH"/hide_recipients"
+#define MMS_SEND_REPORT_ALLOWED                                DEFAULT_MMS_SEND_OPT_PATH"/report_allowed"
+#define MMS_SEND_REPLY_CHARGING                                        DEFAULT_MMS_SEND_OPT_PATH"/reply_charging"
+#define MMS_SEND_REPLY_CHARGING_DEADLINE       DEFAULT_MMS_SEND_OPT_PATH"/reply_charging_deadline"
+#define MMS_SEND_REPLY_CHARGING_SIZE                   DEFAULT_MMS_SEND_OPT_PATH"/reply_charging_size"
+#define MMS_SEND_CREATION_MODE                                 DEFAULT_MMS_SEND_OPT_PATH"/creation_mode"
+
+#define MMS_RECV_HOME_NETWORK          DEFAULT_MMS_RECV_OPT_PATH"/home_network"
+#define MMS_RECV_ABROAD_NETWORK        DEFAULT_MMS_RECV_OPT_PATH"/abroad_network"
+#define MMS_RECV_READ_RECEIPT                  DEFAULT_MMS_RECV_OPT_PATH"/read_receipt"
+#define MMS_RECV_DELIVERY_RECEIPT      DEFAULT_MMS_RECV_OPT_PATH"/delivery_receipt"
+#define MMS_RECV_REJECT_UNKNOWN                DEFAULT_MMS_RECV_OPT_PATH"/reject_unknown"
+#define MMS_RECV_REJECT_ADVERTISE      DEFAULT_MMS_RECV_OPT_PATH"/reject_advertisement"
+
+#define MMS_STYLE_FONT_SIZE                                                    DEFAULT_MMS_STYLE_OPT_PATH"/font_size"
+#define MMS_STYLE_FONT_STYLE_BOLD                      DEFAULT_MMS_STYLE_OPT_PATH"/font_style/bold"
+#define MMS_STYLE_FONT_STYLE_ITALIC                    DEFAULT_MMS_STYLE_OPT_PATH"/font_style/italic"
+#define MMS_STYLE_FONT_STYLE_UNDERLINE DEFAULT_MMS_STYLE_OPT_PATH"/font_style/underline"
+#define MMS_STYLE_FONT_COLOR_RED                       DEFAULT_MMS_STYLE_OPT_PATH"/font_color/red"
+#define MMS_STYLE_FONT_COLOR_GREEN             DEFAULT_MMS_STYLE_OPT_PATH"/font_color/green"
+#define MMS_STYLE_FONT_COLOR_BLUE                      DEFAULT_MMS_STYLE_OPT_PATH"/font_color/blue"
+#define MMS_STYLE_FONT_COLOR_HUE                       DEFAULT_MMS_STYLE_OPT_PATH"/font_color/hue"
+#define MMS_STYLE_BG_COLOR_RED                         DEFAULT_MMS_STYLE_OPT_PATH"/bg_color/red"
+#define MMS_STYLE_BG_COLOR_GREEN                       DEFAULT_MMS_STYLE_OPT_PATH"/bg_color/green"
+#define MMS_STYLE_BG_COLOR_BLUE                                DEFAULT_MMS_STYLE_OPT_PATH"/bg_color/blue"
+#define MMS_STYLE_BG_COLOR_HUE                         DEFAULT_MMS_STYLE_OPT_PATH"/bg_color/hue"
+#define MMS_STYLE_PAGE_DUR                                                     DEFAULT_MMS_STYLE_OPT_PATH"/page_dur"
+#define MMS_STYLE_PAGE_CUSTOM_DUR                      DEFAULT_MMS_STYLE_OPT_PATH"/page_custom_dur"
+#define MMS_STYLE_PAGE_DUR_MANUAL                      DEFAULT_MMS_STYLE_OPT_PATH"/page_dur_manual"
+
+#define PUSH_RECV_OPTION                               DEFAULT_PUSH_MSG_OPT_PATH"/recv_option"
+#define PUSH_SERVICE_TYPE                              DEFAULT_PUSH_MSG_OPT_PATH"/service_load"
+
+#define CB_RECEIVE                                             DEFAULT_CB_MSG_OPT_PATH"/receive"
+#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_CHANNEL_NAME                        DEFAULT_CB_MSG_OPT_PATH"/channel_name"
+#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 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"
+
+
+/*==================================================================================================
+                                         TYPES
+==================================================================================================*/
+
+/**
+ *     @brief  Represents a message main type. \n
+ *     The values for this type SHOULD be in _MSG_MAIN_TYPE_E.
+ */
+typedef unsigned char MSG_MAIN_TYPE_T;
+
+
+/**
+ *     @brief  Represents a message sub type. \n
+ *     Each main type of a message can be divided into some sub types. \n
+ *     For instance of SMS, the message sub type can be one of the NORMAL, WAPPUSH, CB and so on. \n
+ *     The values for this type SHOULD be in _MSG_SUB_TYPE_E.
+ */
+typedef unsigned char MSG_SUB_TYPE_T;
+
+
+/**
+ *     @brief  Represents a message class. \n
+ *     The values for this type SHOULD be in _MSG_CLASS_TYPE_E.
+ */
+typedef unsigned char MSG_CLASS_TYPE_T;
+
+
+/**
+ *     @brief  Represents a message class. \n
+ *     The values for this type SHOULD be in _MSG_MMS_TRANSACTION_TYPE_E.
+ */
+typedef unsigned char MSG_MMS_TRANSACTION_TYPE_T;
+
+
+/*==================================================================================================
+                                         STRUCTURES
+==================================================================================================*/
+
+/**
+ *     @brief  Represents a message type.
+ */
+typedef struct
+{
+       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_CLASS_TYPE_T        classType;      /**< Message class type. See enum _MSG_CLASS_TYPE_E */
+} MSG_MESSAGE_TYPE_S;
+
+
+/**
+ *     @brief  Represents a message in the framework.
+ */
+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+1];
+       bool                                    bStore;                                                                                 /**< Indicates whether the message is stored or not if it is MWI message. */
+} MSG_MESSAGE_INFO_S;
+
+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. see enum _MSG_FOLDER_TYPE_E */
+       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_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;
+       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. */
+       bool                                    bPortValid;                                                                     /**< Indicates whether port information is used or not. */
+       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+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*/
+} MSG_MESSAGE_HIDDEN_S;
+
+/**
+ *     @brief  Represents message information for thread view.
+ */
+typedef struct
+{
+       msg_thread_id_t                 threadId;                                                                                                                       /**< Indicates the thread ID of this peer. */
+       char                                    threadName[MAX_THREAD_NAME_LEN+1];              /**< Indicates the name of this peer. > */
+       MSG_MAIN_TYPE_T                 mainType;                                                               /**< Indicates the latest msg main type. */
+       MSG_SUB_TYPE_T                  subType;                                                                /**< Indicates the latest msg sub type. */
+       char                                    threadData[MAX_THREAD_DATA_LEN+1];              /**< Indicates the latest msg data. */
+       time_t                                  threadTime;                                                                                                             /**< Indicates the latest msg time. */
+       msg_direction_type_t    direction;                                                                                                                      /**< Indicates whether the message is MO or MT (affecting address). */
+       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.  */
+} 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*/
+} MSG_CONVERSATION_VIEW_S;
+
+
+/**
+ *     @brief  Represents sim message informatioin list.
+ */
+typedef struct
+{
+       int nIdxCnt;            /**< The count of sim index */
+       int nMsgCnt;            /**< The count of sim message */
+       MSG_MESSAGE_INFO_S              *simMsgInfo;            /**< The pointer to sim message informatioin */
+} MSG_SIM_MSG_INFO_LIST_S;
+
+
+/**
+ *     @brief  Represents a request in the framework. \n
+ *     Applications compose a request and send it to the framework via Message handle. \n
+ *     This request ID is used to manage the request by the framework.
+ */
+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;
+} MSG_REQUEST_INFO_S;
+
+
+/**
+ *     @brief  Represents proxy information. \n
+ *     This stucture contains the information about the status cnf of a sent message.
+ */
+typedef struct
+{
+       int                                             listenerFd;             /**< Rx fd for status cnf */
+       unsigned int                    handleAddr;             /**< Handle address for status cnf */
+       msg_message_id_t                sentMsgId;              /**< The ID of a sent message for updating message status */
+} MSG_PROXY_INFO_S;
+
+
+/**
+ *     @brief  Aux data structure for MSG_CMD_REG_INCOMING_MSG_CB. \n
+ *     This stucture contains the information about the receiver for msgType and port.
+ */
+typedef struct
+{
+       int                             listenerFd;
+       MSG_MAIN_TYPE_T         msgType;
+       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
+ *     This stucture contains the information about the receiver for msgType and port.
+ */
+typedef struct
+{
+       int                             listenerFd;
+       MSG_MAIN_TYPE_T         msgType;
+       char appId[MAX_MMS_JAVA_APPID_LEN+1];
+} MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB_S;
+
+
+/**
+ *     @brief  Aux data structure for MSG_CMD_REG_INCOMING_SYNCML_MSG_CB. \n
+ *     This stucture contains the information about the receiver for msgType and port.
+ */
+typedef struct
+{
+       int                             listenerFd;
+       MSG_MAIN_TYPE_T         msgType;
+} MSG_CMD_REG_INCOMING_SYNCML_MSG_CB_S;
+
+
+/**
+ *     @brief  Aux data structure for MSG_CMD_REG_INCOMING_LBS_MSG_CB_S. \n
+ *     This stucture contains the information about the receiver for msgType and port.
+ */
+typedef struct
+{
+       int                             listenerFd;
+       MSG_MAIN_TYPE_T         msgType;
+} MSG_CMD_REG_INCOMING_LBS_MSG_CB_S;
+
+
+/**
+ *     @brief  Aux data structure for MSG_CMD_REG_INCOMING_JAVAMMS_TRID_S. \n
+ *     This stucture contains the information about the sent Java MMS messge transactionId.
+ */
+typedef struct
+{
+       bool                    posted;
+       char                    id[MMS_TR_ID_LEN+1];
+       char                            pduFileName[MAX_COMMON_INFO_SIZE+1];
+} MSG_CMD_REG_INCOMING_JAVAMMS_TRID_S;
+
+
+/**
+ *     @brief  Aux data structure for MSG_CMD_REG_SYNCML_MSG_OPERATION_CB. \n
+ *     This stucture contains the information about the receiver for msgType and port.
+ */
+typedef struct
+{
+       int                             listenerFd;
+       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
+{
+       int                                             alarm_id;
+       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;
+
+
+/*==================================================================================================
+                                         ENUMS
+==================================================================================================*/
+
+/**
+ *     @brief  Represents the values of a message main type. \n
+ *     Three main types of a message are predefined : SMS, MMS, and Email. More main types of a message can be defined here. \n
+ *     This enum is used as the value of MSG_MAIN_TYPE_T.
+ */
+enum _MSG_MAIN_TYPE_E
+{
+       MSG_UNKNOWN_TYPE = 0,           /**< Unknown main type */
+       MSG_SMS_TYPE,                           /**< SMS */
+       MSG_MMS_TYPE,                           /**< MMS */
+};
+
+
+/**
+ *     @brief  Represents the values of a message sub type. \n
+ *     Three sub types of a message are predefined : NORMAL, WAPPUSH, and CB. More sub types of a message can be defined here. \n
+ *     This enum is used as the value of MSG_SUB_TYPE_T.
+ */
+enum _MSG_SUB_TYPE_E
+{
+       /* SMS Specific Message Type */
+       MSG_NORMAL_SMS = 0,                     /**< Text SMS message */
+       MSG_CB_SMS,                                     /**< Cell Broadcasting  message */
+       MSG_JAVACB_SMS,                         /**< JAVA Cell Broadcasting  message */
+       MSG_TYPE0_SMS,                                  /**< Short Message Type 0 */
+       MSG_REPLACE_TYPE1_SMS,          /**< Replace Short Message Type 1 */
+       MSG_REPLACE_TYPE2_SMS,          /**< Replace Short Message Type 2 */
+       MSG_REPLACE_TYPE3_SMS,          /**< Replace Short Message Type 3 */
+       MSG_REPLACE_TYPE4_SMS,          /**< Replace Short Message Type 4 */
+       MSG_REPLACE_TYPE5_SMS,          /**< Replace Short Message Type 5 */
+       MSG_REPLACE_TYPE6_SMS,          /**< Replace Short Message Type 6 */
+       MSG_REPLACE_TYPE7_SMS,          /**< Replace Short Message Type 7 */
+       MSG_WAP_SI_SMS,                         /**< WAP Push Message SI */
+       MSG_WAP_SL_SMS,                         /**< WAP Push Message SL */
+       MSG_WAP_CO_SMS,                         /**< WAP Push Message CO */
+       MSG_MWI_VOICE_SMS,                      /**< MWI Message Voice */
+       MSG_MWI_FAX_SMS,                                /**< MWI Message Fax */
+       MSG_MWI_EMAIL_SMS,                      /**< MWI Message Email */
+       MSG_MWI_OTHER_SMS,                      /**< MWI Message Other */
+       MSG_STATUS_REPORT_SMS,          /**< SMS-STATUS-REPORT */
+       MSG_SYNCML_CP,                          /**< SyncML Message CP */
+       MSG_LBS_SMS,                                    /**< LBS Message */
+       MSG_REJECT_SMS,                         /**< Reject Message */
+       MSG_CONCAT_SIM_SMS,                     /**< Concatenated Message in SIM */
+
+       /* MMS Specific Message Type */
+       MSG_SENDREQ_MMS = 24,                                   /**< MMS Send Request message */
+       MSG_SENDCONF_MMS,                               /**< MMS Send Confirm message */
+       MSG_NOTIFICATIONIND_MMS,                        /**< MMS Notification Indication message */
+       MSG_GET_MMS,                                            /**< MMS GET MMS message */
+       MSG_NOTIFYRESPIND_MMS,                  /**< MMS Notify Response Indication message */
+       MSG_RETRIEVE_MMS,                                       /**< MMS Retrive MMS message */
+       MSG_RETRIEVE_AUTOCONF_MMS,              /**< MMS Retrieve Confirm message by auto retrieving*/
+       MSG_RETRIEVE_MANUALCONF_MMS,    /**< MMS Retrieve Confirm message by manual retrieving*/
+       MSG_ACKNOWLEGEIND_MMS,                  /**< MMS Acknowledge Indication message */
+       MSG_DELIVERYIND_MMS,                            /**< MMS Delivery Indication message */
+       MSG_READRECIND_MMS,                             /**< MMS Read Receive Indication message */
+       MSG_READORGIND_MMS,                             /**< MMS Read Origin Indication message */
+       MSG_FORWARD_MMS,                                        /**< MMS Forward message */
+       MSG_FORWARDREQ_MMS,                             /**< MMS Forward Request message */
+       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,
+};
+
+/**
+ *     @brief  Represents the values of a message transaction type. \n
+ *     This enum is used as the value of MSG_MMS_TRANSACTION_TYPE_T.
+ */
+enum _MSG_MMS_TRANSACTION_TYPE_E
+{
+       MSG_MMS_SEND_COMPLETE = 0,
+       MSG_MMS_RETRIEVE_COMPLETE,
+       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 */
+};
+#endif
+
diff --git a/include/common/MsgMmsTypes.h b/include/common/MsgMmsTypes.h
new file mode 100755 (executable)
index 0000000..56a84b3
--- /dev/null
@@ -0,0 +1,244 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_MMS_TYPES_H
+
+/**
+ *     @file           MsgMmsTypes.h
+ *     @brief          Defines MMS types of messaging framework
+ *     @version        1.0
+ */
+
+/**
+ *     @section                Introduction
+ *     - Introduction : Overview on MMS message Types
+ *     @section                Program
+ *     - Program : MMS message Types Reference
+ */
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgTypes.h"
+
+
+#include <glib.h>
+
+
+/**
+ *     @ingroup                MESSAGING_FRAMEWORK
+ *     @defgroup       MESSAGING_MMS_TYPES     Messaging MMS Types
+ *     @{
+ */
+
+
+/*==================================================================================================
+                                         STRUCTURES
+==================================================================================================*/
+
+/**
+ *     @brief  Represents text information.
+ */
+typedef struct  {
+       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 */
+       int                             nDurTime; /**< Indicates the duration */
+       int                             nBgColor; /**< Indicates the background color of the text */
+       bool                    bBold;  /**< Indicates whether the text is bold */
+       bool                    bUnderLine; /**< Indicates whether the text is underlined */
+       bool                    bItalic;                /**< Indicates whether the text is Italic */
+       bool                    bReverse;       /**< Indicates whether the text is reversed */
+       MmsTextDirection        nDirection; /**< Indicates the text direction type. see enum MmsTextDirection */
+       int                             nSize;  /**< Indicates the font size */
+       int                             nColor; /**< Indicates the font color */
+}MmsSmilText;
+
+/**
+ *     @brief  Represents video information.
+ */
+typedef struct {
+       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 */
+       int                             nDurTime;  /**< Indicates the duration */
+       int                             nBgColor;  /**< Indicates the background color of the text */
+}MmsSmilAVI;
+
+/**
+ *     @brief  Represents media information.
+ */
+typedef struct
+{
+       MmsSmilMediaType        mediatype; /**< Indicates the SMIL media type. see enum MmsSmilMediaType */
+
+       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 + 1];  /**< Indicates the fullpath of the DRM */
+       union{
+               MmsSmilText     sText;  /**< Indicates the text attributes */
+               MmsSmilAVI      sAVI; /**< Indicates the video attributes */
+       } sMedia;
+}MMS_MEDIA_S;
+
+/**
+ *     @brief  Represents attachment information.
+ */
+typedef struct
+{
+       MimeType        mediatype;      /**< Indicates the file mime type. see enum MimeType */
+       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 + 1]; /**< Indicates the fullpath of the DRM */
+}MMS_ATTACH_S;
+
+/**
+ *     @brief  Represents SMIL page information.
+ */
+typedef struct
+{
+       int             mediaCnt;       /**< The count of the media */
+       GList   *medialist;     /**< The pointer to media list */
+       int             nDur;   /**< Indicates the duration of the page */
+       int             nBegin; /**< Indicates the begin time of the page */
+       int             nEnd;    /**< Indicates the end time of the page */
+       int             nMin;   /**< Indicates the min attribute of the page */
+       int             nMax;   /**< Indicates the max attribute of the page */
+       int             nRepeat;        /**< Indicates the page needs to be displayed repeatedly */
+
+}MMS_PAGE_S;
+
+/**
+ *     @brief  Represents length information.
+ */
+typedef struct
+{
+       bool    bUnitPercent; /**< Indicates the length is in percentage(%) or not */
+       int     value;  /**< Indicates the value for length */
+}MMS_LENGTH;
+
+/**
+ *     @brief  Represents SMIL region information.
+ */
+typedef struct
+{
+       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
+       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;
+
+/**
+ *     @brief  Represents SMIL root layout information.
+ */
+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
+       int                     bgColor;                /**< Indicates the background color of the root layout */
+}MMS_SMIL_ROOTLAYOUT;
+
+
+/**
+ *     @brief  Represents SMIL transition information.
+ */
+typedef struct
+{
+       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 */
+}MMS_SMIL_TRANSITION;
+
+
+/**
+ *     @brief  Represents SMIL meta information.
+ */
+typedef struct
+{
+       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;
+
+
+/**
+ *     @brief  Represents application id information for JAVA MMS msg.
+ */
+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 */
+}MMS_APPID_INFO_S;
+
+
+
+#define                MAX_FULL_PATH_SIZE_S    160     // max length for internal file path
+
+typedef struct
+{
+       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;
+
+
+/**
+ *     @brief  Represents MMS message data.
+ */
+typedef struct _MMS_MESSAGE_DATA_S
+{
+       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 */
+       GList                                   *regionlist;    /**< The pointer to SMIL regions list */
+       int                                             attachCnt;      /**< The count of the attachments */
+       GList                                   *attachlist;    /**< The pointer to attachment list */
+       int                                             transitionCnt;  /**< The count of the SMIL transitions information */
+       GList                                   *transitionlist;        /**< The pointer to SMIL transitions list */
+       int                                             metaCnt;        /**< The count of the SMIL meta information */
+       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;
+
+/**
+ *     @}
+ */
+
+
+
+#endif
+
diff --git a/include/common/MsgPluginInterface.h b/include/common/MsgPluginInterface.h
new file mode 100755 (executable)
index 0000000..b460cc3
--- /dev/null
@@ -0,0 +1,1097 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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           MsgPluginInterface.h
+ *     @brief          Defines plug-ins API of messaging framework
+ *     @version        1.0
+ */
+
+#ifndef MSG_PLUGIN_INTERFACE_H
+#define MSG_PLUGIN_INTERFACE_H
+
+/**
+ *     @section                Introduction
+ *     - Introduction : Overview on Messaging Plug-in API
+ *     @section                Program
+ *     - Program : Messaging Plug-in API Reference
+ */
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgTransportTypes.h"
+#include "MsgStorageTypes.h"
+#include "MsgSettingTypes.h"
+#include "MsgInternalTypes.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ *     @ingroup        MESSAGING_FRAMEWORK
+ *     @defgroup       MESSAGING_PLUGIN_API    Messaging Plug-in API
+ *     @{
+ */
+
+/*==================================================================================================
+                                         TYPE DEFINES
+==================================================================================================*/
+typedef struct _MSG_PLUGIN_HANDLER_S MSG_PLUGIN_HANDLER_S;
+
+typedef struct _MSG_PLUGIN_LISTENER_S MSG_PLUGIN_LISTENER_S;
+
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when the plug-in is loaded at Message Framework.
+ * ALL Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Create plug-in handle for Message Framework.
+ * Message Framework will able to reach plugin functions by handle.
+ *
+ * \par Typical use case:
+ * Create plug-in handle.
+ *
+ * \par Method of function operation:
+ * Set handle information by plug-in.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins..
+ *
+ * \param input - handle is Message handle.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ * - MSG_ERR_NULL_POINTER              Plug-in handle is invalid.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+msg_error_t MsgPlgCreateHandle(MSG_PLUGIN_HANDLER_S *pPluginHandle);
+
+
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when the plug-in is finalized at Message Framework.
+ * ALL Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Destroy plug-in handle for Message Framework.
+ *
+ * \par Typical use case:
+ * Destroy plug-in handle.
+ *
+ * \par Method of function operation:
+ * Remove handle information by plug-in.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins..
+ *
+ * \param input - handle is Message handle.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ * - MSG_ERR_NULL_POINTER              Plug-in handle is invalid.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+msg_error_t MsgPlgDestroyHandle(MSG_PLUGIN_HANDLER_S *pPluginHandle);
+
+
+
+
+// Control API
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when the plug-in is loaded at Message Framework.
+ * ALL Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Initializing plug-in.
+ * Precede jobs must done in this function.
+ *
+ * \par Typical use case:
+ * Initializing plug-in.
+ *
+ * \par Method of function operation:
+ * Make up pre-works for plug-in.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins..
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ * - MSG_ERR_PLUGIN_REGEVENT   Plug-in's error during operations.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgInitialize)();
+
+
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when the plug-in is loaded at Message Framework.
+ * ALL Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Create plug-in handle for Message Framework.
+ * Message Framework will able to reach plugin functions by handle.
+ *
+ * \par Typical use case:
+ * Create plug-in handle.
+ *
+ * \par Method of function operation:
+ * Set handle information by plug-in.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins..
+ *
+ * \param input - handle is Message handle.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ * - MSG_ERR_NULL_POINTER              Plug-in handle is invalid.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgFinalize)();
+
+
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when the plug-in is loaded at Message Framework.
+ * ALL Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Regist listeners to handle incomming messages..
+ * .
+ *
+ * \par Typical use case:
+ * Regist listeners.
+ *
+ * \par Method of function operation:
+ * Set listener informations in plug-in.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins..
+ *
+ * \param input - listener is callback listeners.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgRegisterListener)(MSG_PLUGIN_LISTENER_S *pListener);
+
+
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to check sim card status.
+ * SMS Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Checking sim card status  for Message Framework.
+ *
+ * \par Typical use case:
+ * To check sim card status.
+ *
+ * \par Method of function operation:
+ * Check SIM card status and return result of sim card is changed or not.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins..
+ *
+ * \param output - bChanged is a boolean type value which shows sim card status.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgCheckSimStatus)(MSG_SIM_STATUS_T *pStatus);
+
+
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to check device status.
+ * SMS Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Create plug-in handle for Message Framework.
+ * Message Framework will able to reach plugin functions by handle.
+ *
+ * \par Typical use case:
+ * Create plug-in handle.
+ *
+ * \par Method of function operation:
+ * Set handle information by plug-in.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins..
+ *
+ * \param input - handle is Message handle.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ * - MSG_ERR_NULL_POINTER              Plug-in handle is invalid.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgCheckDeviceStatus)();
+
+
+// Transport API
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to submit a message to send.
+ * ALL Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Send message..
+ *
+ * \par Typical use case:
+ * To send messages.
+ *
+ * \par Method of function operation:
+ * Convert message data to raw message data.
+ * Send raw message data to selected network.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins.
+ *
+ * \param input - pReqInfo is message data to send.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ * - MSG_ERR_PLUGIN_TRANSPORT  Exception is occured in plug-in.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgSubmitRequest)(MSG_REQUEST_INFO_S *pReqInfo);
+
+
+// Storage API
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to save a message to SIM card.
+ * SMS Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Save a message to SIM card.
+ *
+ * \par Typical use case:
+ * To save a message to SIM card..
+ *
+ * \par Method of function operation:
+ * Convert message data to raw message data.
+ * Save the raw message data to SIM card.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins.
+ *
+ * \param input - pMsgInfo is the information of message.
+ * \param output - pSimIdList is the list of messages saved in SIM card.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                               Success in operation.
+ * - MSG_ERR_PLUGIN_SIM_MSG_FULL       SIM card's capacity for SMS message is full.
+ * - MSG_ERR_PLUGIN_STORAGE            Exception is occured in plug-in.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgInitSimMessage)();
+
+
+// Storage API
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to save a message to SIM card.
+ * SMS Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Save a message to SIM card.
+ *
+ * \par Typical use case:
+ * To save a message to SIM card..
+ *
+ * \par Method of function operation:
+ * Convert message data to raw message data.
+ * Save the raw message data to SIM card.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins.
+ *
+ * \param input - pMsgInfo is the information of message.
+ * \param output - pSimIdList is the list of messages saved in SIM card.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                               Success in operation.
+ * - MSG_ERR_PLUGIN_SIM_MSG_FULL       SIM card's capacity for SMS message is full.
+ * - MSG_ERR_PLUGIN_STORAGE            Exception is occured in plug-in.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgSaveSimMessage)(const MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList);
+
+
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to delete a message in SIM card.
+ * SMS Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * delete a message in SIM card.
+ *
+ * \par Typical use case:
+ * To save a message to SIM card..
+ *
+ * \par Method of function operation:
+ * delete a message data in SIM card which is indexed by ID.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins.
+ *
+ * \param input - SimMsgId is the index of the message to delete.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                               Success in operation.
+ * - MSG_ERR_PLUGIN_STORAGE            Exception is occured in plug-in.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgDeleteSimMessage)(msg_sim_id_t SimMsgId);
+
+
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to set read status of  message in SIM card.
+ * SMS Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Set read status of SIM cad message.
+ *
+ * \par Typical use case:
+ * To set read status of SIM card message.
+ *
+ * \par Method of function operation:
+ * Save the given read status to SIM card message.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins.
+ *
+ * \param input - SimMsgId is the index of the message to set read status.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                               Success in operation.
+ * - MSG_ERR_PLUGIN_STORAGE            Exception is occured in plug-in.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgSetReadStatus)(msg_sim_id_t SimMsgId);
+
+
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to set read status of  message in SIM card.
+ * SMS Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Set read status of SIM cad message.
+ *
+ * \par Typical use case:
+ * To set read status of SIM card message.
+ *
+ * \par Method of function operation:
+ * Save the given read status to SIM card message.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins.
+ *
+ * \param input - SimMsgId is the index of the message to set read status.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                               Success in operation.
+ * - MSG_ERR_PLUGIN_STORAGE            Exception is occured in plug-in.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgSetMemoryStatus)(msg_error_t Error);
+
+
+// Setting API
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to save configuration of network to SIM card.
+ * SMS Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Save configuration information to SIM card.
+ *
+ * \par Typical use case:
+ * To save configuration information to SIM card.
+ *
+ * \par Method of function operation:
+ * Convert information data to raw data.
+ * Save raw data to SIM card.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins.
+ *
+ * \param input - pSetting is information of configuration.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ * - MSG_ERR_PLUGIN_SETTING            Exception is occured in plug-in.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgInitConfigData)(MSG_SIM_STATUS_T SimStatus);
+
+
+// Setting API
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to save configuration of network to SIM card.
+ * SMS Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Save configuration information to SIM card.
+ *
+ * \par Typical use case:
+ * To save configuration information to SIM card.
+ *
+ * \par Method of function operation:
+ * Convert information data to raw data.
+ * Save raw data to SIM card.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins.
+ *
+ * \param input - pSetting is information of configuration.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ * - MSG_ERR_PLUGIN_SETTING            Exception is occured in plug-in.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgSetConfigData)(const MSG_SETTING_S *pSetting);
+
+
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to get configuration of network from SIM card.
+ * SMS Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Get configuration information from SIM card.
+ *
+ * \par Typical use case:
+ * To get configuration information from SIM card.
+ *
+ * \par Method of function operation:
+ * Convert raw data to information data.
+ * Get configuration data from SIM card.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins.
+ *
+ * \param input - pSetting is information of configuration.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ * - MSG_ERR_PLUGIN_SETTING            Exception is occured in plug-in.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgGetConfigData)(MSG_SETTING_S *pSetting);
+
+// MMS API
+/**
+
+* \par Description:
+* A Prototype of the function which will be called when Message Framework has to store MMS message.
+* MMS Plug-in SHOULD implement this function.
+*
+* \par Purpose:
+* Save MMS message to plug-in defined DB.
+*
+* \par Typical use case:
+* To save MMS message to plug-in defined DB.
+*
+* \par Method of function operation:
+* Convert MMS Message data to cetain format for plug-in.
+* Save the certain format MMS message information to DB.
+*
+* \par Sync (or) Async:
+* This is a Synchronous API.
+*
+* \par Important notes:
+*  This function MUST be implement by plug-ins.
+*
+* \param input - pMsgInfo is information of MMS message.
+* \param input - pSendOptInfo is information of sending option.
+* \param output - pFileData is the file path of saved MMS message.
+*
+* \return Return Type (int(msg_error_t)) \n
+* - MSG_SUCCESS                                          Success in operation.
+* - MSG_ERR_PLUGIN_TRANSPORT   Exception is occured in plug-in.
+*
+* \par Prospective clients:
+* Internal/Plug-ins.
+*
+* \par Related functions:
+* None
+*
+* \par Known issues/bugs:
+* None
+*
+*/
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgAddMessage)(MSG_MESSAGE_INFO_S *pMsgInfo,  MSG_SENDINGOPT_INFO_S* pSendOptInfo, char* pFileData);
+
+
+/**
+
+* \par Description:
+* A Prototype of the function which will be called when Message Framework has to process received MMS message indicator.
+* MMS Plug-in SHOULD implement this function.
+*
+* \par Purpose:
+* Process MMS message indicator.
+*
+* \par Typical use case:
+* To process MMS message indicator.
+*
+* \par Method of function operation:
+* Procces MMS Message indicator in options.
+*
+* \par Sync (or) Async:
+* This is a Synchronous API.
+*
+* \par Important notes:
+*  This function MUST be implement by plug-ins.
+*
+* \param input - pMsgInfo is information of MMS message.
+* \param input - pRequest is information of request options.
+* \param output - bRejects shows the reject status.
+*
+* \return Return Type (int(msg_error_t)) \n
+* - MSG_SUCCESS                                          Success in operation.
+* - MSG_ERR_PLUGIN_TRANSPORT   Exception is occured in plug-in.
+*
+* \par Prospective clients:
+* Internal/Plug-ins.
+*
+* \par Related functions:
+* None
+*
+* \par Known issues/bugs:
+* None
+*
+*/
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgProcessReceivedInd)(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST_INFO_S* pRequest, bool* bReject);
+
+
+/**
+
+* \par Description:
+* A Prototype of the function which will be called when Message Framework has to update MMS message.
+* MMS Plug-in SHOULD implement this function.
+*
+* \par Purpose:
+* Update MMS message to plug-in defined DB.
+*
+* \par Typical use case:
+* To update MMS message to plug-in defined DB.
+*
+* \par Method of function operation:
+* Convert MMS Message data to cetain format for plug-in.
+* Update the certain format MMS message information to DB.
+*
+* \par Sync (or) Async:
+* This is a Synchronous API.
+*
+* \par Important notes:
+*  This function MUST be implement by plug-ins.
+*
+* \param input - pMsgInfo is information of MMS message.
+* \param input - pSendOptInfo is information of sending option.
+* \param output - pFileData is the file path of saved MMS message.
+*
+* \return Return Type (int(msg_error_t)) \n
+* - MSG_SUCCESS                                          Success in operation.
+* - MSG_ERR_PLUGIN_TRANSPORT   Exception is occured in plug-in.
+*
+* \par Prospective clients:
+* Internal/Plug-ins.
+*
+* \par Related functions:
+* None
+*
+* \par Known issues/bugs:
+* None
+*
+*/
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgUpdateMessage)(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S* pSendOptInfo, char* pFileData);
+
+
+/**
+
+* \par Description:
+* A Prototype of the function which will be called when Message Framework has to get MMS message.
+* MMS Plug-in SHOULD implement this function.
+*
+* \par Purpose:
+* Get MMS message.
+*
+* \par Typical use case:
+* To get MMS message.
+*
+* \par Method of function operation:
+* Get MMS Message from certian plug-in defined DB.
+*
+* \par Sync (or) Async:
+* This is a Synchronous API.
+*
+* \par Important notes:
+*  This function MUST be implement by plug-ins.
+*
+* \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
+* - MSG_SUCCESS                                          Success in operation.
+* - MSG_ERR_PLUGIN_TRANSPORT   Exception is occured in plug-in.
+*
+* \par Prospective clients:
+* Internal/Plug-ins.
+*
+* \par Related functions:
+* None
+*
+* \par Known issues/bugs:
+* None
+*
+*/
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgGetMmsMessage)(MSG_MESSAGE_INFO_S* pMsg,   MSG_SENDINGOPT_INFO_S* pSendOptInfo, MMS_MESSAGE_DATA_S* pMmsMsg, char** pDestMsg);
+
+
+/**
+
+* \par Description:
+* A Prototype of the function which will be called when Message Framework has to update reject status of MMS message.
+* MMS Plug-in SHOULD implement this function.
+*
+* \par Purpose:
+* Update reject status of MMS message.
+*
+* \par Typical use case:
+* To update reject status of MMS message.
+*
+* \par Method of function operation:
+* Update reject status of MMS Message from certian plug-in defined DB.
+*
+* \par Sync (or) Async:
+* This is a Synchronous API.
+*
+* \par Important notes:
+*  This function MUST be implement by plug-ins.
+*
+* \param input - pMsgInfo is information of MMS message.
+*
+* \return Return Type (int(msg_error_t)) \n
+* - MSG_SUCCESS                                          Success in operation.
+* - MSG_ERR_PLUGIN_TRANSPORT   Exception is occured in plug-in.
+*
+* \par Prospective clients:
+* Internal/Plug-ins.
+*
+* \par Related functions:
+* None
+*
+* \par Known issues/bugs:
+* None
+*
+*/
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgUpdateRejectStatus)(MSG_MESSAGE_INFO_S *pMsgInfo);
+
+
+/**
+
+* \par Description:
+* A Prototype of the function which will be called when Message Framework has to compose read report for MMS message.
+* MMS Plug-in SHOULD implement this function.
+*
+* \par Purpose:
+* Compose read report for MMS message.
+*
+* \par Typical use case:
+* To compose read report for MMS message.
+*
+* \par Method of function operation:
+* Compose read report for MMS message.
+* Send read report.
+*
+* \par Sync (or) Async:
+* This is a Synchronous API.
+*
+* \par Important notes:
+*  This function MUST be implement by plug-ins.
+*
+* \param input - pMsgInfo is information of MMS message.
+*
+* \return Return Type (int(msg_error_t)) \n
+* - MSG_SUCCESS                                          Success in operation.
+* - MSG_ERR_PLUGIN_TRANSPORT   Exception is occured in plug-in.
+*
+* \par Prospective clients:
+* Internal/Plug-ins.
+*
+* \par Related functions:
+* None
+*
+* \par Known issues/bugs:
+* None
+*
+*/
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgComposeReadReport)(MSG_MESSAGE_INFO_S *pMsgInfo);
+
+ /**
+
+ * \par Description:
+ * A Prototype of the function which will be called when Message Framework has to compose read report for MMS message.
+ * MMS Plug-in SHOULD implement this function.
+ *
+ * \par Purpose:
+ * Compose read report for MMS message.
+ *
+ * \par Typical use case:
+ * To compose read report for MMS message.
+ *
+ * \par Method of function operation:
+ * Compose read report for MMS message.
+ * Send read report.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ *     This function MUST be implement by plug-ins.
+ *
+ * \param input - pMsgInfo is information of MMS message.
+ *
+ * \return Return Type (int(msg_error_t)) \n
+ * - MSG_SUCCESS                                       Success in operation.
+ * - MSG_ERR_PLUGIN_TRANSPORT  Exception is occured in plug-in.
+ *
+ * \par Prospective clients:
+ * Internal/Plug-ins.
+ *
+ * \par Related functions:
+ * None
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ */
+/*================================================================================================*/
+typedef msg_error_t (*MsgPlgRestoreMsg)(MSG_MESSAGE_INFO_S *pMsg, char* pRcvdBody, int rcvdBodyLen, char* filePath);
+
+
+// framework defined callbacks.
+typedef void (*MsgPlgOnSentStatus)(MSG_SENT_STATUS_S *pSentStatus);
+typedef void (*MsgPlgOnStorageChange)(msg_storage_change_type_t storageChangeType, MSG_MESSAGE_INFO_S *pMsgInfo);
+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);
+typedef msg_error_t (*MsgPlgOnMmsConfIncoming)(MSG_MESSAGE_INFO_S *pMsgInfo, msg_request_id_t *pRequest);
+
+
+/*==================================================================================================
+                                         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. */
+       MsgPlgOnSyncMLMsgIncoming       pfSyncMLMsgIncomingCb;  /** The function pointer of receive syncML message callback. */
+       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 */
+};
+
+
+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;
+       MsgPlgAddMessage                                pfAddMessage;                   /**< The function pointer of  add Message. */
+       MsgPlgProcessReceivedInd                pfProcessReceivedInd;   /**< The function pointer of  Process Notification Ind. */
+       MsgPlgUpdateMessage                     pfUpdateMessage;                /**< The function pointer of Update MMS Message */
+       MsgPlgGetMmsMessage                     pfGetMmsMessage;
+       MsgPlgUpdateRejectStatus                pfUpdateRejectStatus;
+       MsgPlgComposeReadReport                 pfComposeReadReport;
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/common/MsgQueue.h b/include/common/MsgQueue.h
new file mode 100755 (executable)
index 0000000..18aa045
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+{
+public:
+       MsgThdSafeQ(){};
+       void pop_front ();
+       bool front(T* qItem);
+       void push_front(T const & input);
+       void push_back(T const & input);
+       int size();
+       bool empty();
+       void clear();
+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()
+{
+       MutexLocker lock(mx);
+       if( q.empty() ) return;
+
+       q.pop_front();
+}
+
+template <typename T> bool MsgThdSafeQ<T>::front(T* qItem)
+{
+       MutexLocker lock(mx);
+       if( qItem == NULL || q.empty() )
+               return false; // Fail
+
+       *qItem = q.front(); // copy
+
+       return true; // Success
+}
+
+
+template <typename T> void MsgThdSafeQ<T>::push_back(T const & qItem)
+{
+       MutexLocker lock(mx);
+       q.push_back(qItem);
+}
+
+template <typename T> void MsgThdSafeQ<T>::push_front(T const & qItem)
+{
+       MutexLocker lock(mx);
+       q.push_front(qItem);
+}
+
+
+template <typename T> int MsgThdSafeQ<T>::size()
+{
+       MutexLocker lock(mx);
+       return q.size();
+}
+
+template <typename T> bool MsgThdSafeQ<T>::empty()
+{
+       MutexLocker lock(mx);
+       return q.empty();
+}
+
+template <typename T> void MsgThdSafeQ<T>::clear()
+{
+       MutexLocker lock(mx);
+       q.clear();
+}
+
+#endif // __MsgThdSafeQ_H__
+
diff --git a/include/common/MsgSettingTypes.h b/include/common/MsgSettingTypes.h
new file mode 100755 (executable)
index 0000000..530a43a
--- /dev/null
@@ -0,0 +1,415 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_SETTING_TYPES_H
+
+/**
+ *     @file           MsgSettingTypes.h
+ *     @brief          Defines setting types of messaging framework
+ *     @version        1.0
+ */
+
+/**
+ *     @section                Introduction
+ *     - Introduction : Overview on Messaging Setting Types
+ *     @section                Program
+ *     - Program : Messaging Setting Types Reference
+ */
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgTypes.h"
+
+/**
+ *     @ingroup                MESSAGING_FRAMEWORK
+ *     @defgroup       MESSAGING_SETTING_TYPES Messaging Setting Types
+ *     @{
+ */
+
+/*==================================================================================================
+                                         TYPES
+==================================================================================================*/
+
+/**
+ *     @brief  Represents an option type. \n
+ *     The values for this type SHOULD be in _MSG_OPTION_TYPE_E.
+ */
+typedef unsigned int MSG_OPTION_TYPE_T;
+
+
+/**
+ *     @brief  Represents an SMS network mode. \n
+ *     The values for this type SHOULD be in _MSG_SMS_NETWORK_MODE_E.
+ */
+typedef unsigned char MSG_SMS_NETWORK_MODE_T;
+
+
+/**
+ *     @brief  Represents the period of playing alert tone. \n
+ *     The values for this type SHOULD be in _MSG_ALERT_TONE_E.
+ */
+typedef unsigned char MSG_ALERT_TONE_T;
+
+
+/**
+ *     @brief  Represents the default storage to save SMS. \n
+ *     The values for this type SHOULD be in _MSG_SMS_SAVE_STORAGE_E.
+ */
+typedef unsigned char MSG_SMS_SAVE_STORAGE_T;
+
+
+/**
+ *     @brief  Represents the type of number for SMS center address. \n
+ *     The values for this type SHOULD be in _MSG_SMS_TON_E.
+ */
+typedef unsigned char MSG_SMS_TON_T;
+
+
+/**
+ *     @brief  Represents the numbering plan ID for SMS center address. \n
+ *     The values for this type SHOULD be in _MSG_SMS_NPI_E.
+ */
+typedef unsigned char MSG_SMS_NPI_T;
+
+
+/**
+ *     @brief  Represents the protocol ID for SMS center address. \n
+ *     The values for this type SHOULD be in _MSG_SMS_PID_E.
+ */
+typedef unsigned char MSG_SMS_PID_T;
+
+
+/**
+ *     @brief  Represents the validity period of SMS. \n
+ *     The values for this type SHOULD be in _MSG_VAL_PERIOD_E.
+ */
+typedef unsigned char MSG_VAL_PERIOD_T;
+
+
+/**
+ *     @brief  Represents the class type of MMS. \n
+ *     The values for this type SHOULD be in _MSG_MMS_MSG_CLASS_TYPE_E.
+ */
+typedef unsigned char MSG_MMS_MSG_CLASS_TYPE_T;
+
+
+/**
+ *     @brief  Represents the expiry time of MMS. \n
+ *     The values for this type SHOULD be in _MSG_MMS_EXPIRY_TIME_E.
+ */
+typedef unsigned int MSG_MMS_EXPIRY_TIME_T;
+
+
+/**
+ *     @brief  Represents the delivery time of MMS. \n
+ *     The values for this type SHOULD be in _MSG_MMS_DELIVERY_TIME_E.
+ */
+typedef unsigned int MSG_MMS_DELIVERY_TIME_T;
+
+
+/**
+ *     @brief  Represents the reply charging type of MMS. \n
+ *     The values for this type SHOULD be in _MSG_MMS_REPLY_CHARGING_TYPE_E.
+ */
+typedef unsigned char MSG_MMS_REPLY_CHARGING_TYPE_T;
+
+
+/**
+ *     @brief  Represents the creation mode of MMS. \n
+ *     The values for this type SHOULD be in _MSG_MMS_CREATION_MODE_E.
+ */
+typedef unsigned char MSG_MMS_CREATION_MODE_T;
+
+/**
+ *     @brief  Represents the retrieve type for MMS home network. \n
+ *     The values for this type SHOULD be in _MSG_MMS_HOME_RETRIEVE_TYPE_E.
+ */
+typedef unsigned char MSG_MMS_HOME_RETRIEVE_TYPE_T;
+
+
+/**
+ *     @brief  Represents the retrieve type for MMS abroad network. \n
+ *     The values for this type SHOULD be in _MSG_MMS_ABROAD_RETRIEVE_TYPE_E.
+ */
+typedef unsigned char MSG_MMS_ABROAD_RETRIEVE_TYPE_T;
+
+
+/**
+ *     @brief  Represents the frequency of sending MMS read report. \n
+ *     The values for this type SHOULD be in _MSG_MMS_SEND_READ_REPORT_E.
+ */
+typedef unsigned char MSG_MMS_SEND_READ_REPORT_T;
+
+
+/**
+ *     @brief  Represents whether a push message is received or not. \n
+ *     The values for this type SHOULD be in _MSG_PUSH_RECEIVE_TYPE_E.
+ */
+typedef unsigned char MSG_PUSH_RECEIVE_TYPE_T;
+
+
+/**
+ *     @brief  Represents the service type for a push message. \n
+ *     The values for this type SHOULD be in _MSG_PUSH_SERVICE_TYPE_E.
+ */
+typedef unsigned char MSG_PUSH_SERVICE_TYPE_T;
+
+
+/**
+ *     @brief  Represents the language type for a cell broadcasting message. \n
+ *     The values for this type SHOULD be in _MSG_CB_LANGUAGE_TYPE_E.
+ */
+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.
+ */
+typedef unsigned char MSG_SIM_STATUS_T;
+
+
+/*==================================================================================================
+                                         STRUCTURES
+==================================================================================================*/
+
+/**
+ *     @brief  Represents SMSC address information.
+ */
+typedef struct
+{
+       MSG_SMS_TON_T                   ton;                                                            /**< Type of number */
+       MSG_SMS_NPI_T                   npi;                                                            /**< Numbering plan ID */
+       char                                            address[SMSC_ADDR_MAX+1];               /**< SMSC address */
+} MSG_SMSC_ADDRESS_S;
+
+
+/**
+ *     @brief  Represents SMSC data information.
+ */
+typedef struct
+{
+       MSG_SMS_PID_T                   pid;                                                    /**< Protocol idendifier */
+       MSG_VAL_PERIOD_T                valPeriod;                                      /**< Validity period value */
+       char                                            name[SMSC_NAME_MAX+1];          /**< SMSC name */
+       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                                             totalCnt;                                                       /**< The count of total SMSC addresses */
+       MSG_SMSC_DATA_S                 smscData[SMSC_LIST_MAX];                        /**< SMSC data information list*/
+}MSG_SMSC_LIST_S;
+
+/**
+ *     @brief  Represents an SMSC list.
+ */
+typedef struct
+{
+       int                                             selected;                               /**< Selected SMSC index */
+       msg_struct_list_s               *smsc_list;                             /**< SMSC data information list*/
+}MSG_SMSC_LIST_HIDDEN_S;
+
+/**
+ *     @brief  Represents the information of a cell broadcasting channel.
+ */
+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. */
+       char                    name[CB_CHANNEL_NAME_MAX+1];            /**< Indicates the name of a CB channel. */
+} MSG_CB_CHANNEL_INFO_S;
+
+
+/**
+ *     @brief  Represents cell broadcasting channel information.
+ */
+typedef struct
+{
+       int                                             channelCnt;                                     /**< The count of CB channels */
+       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. */
+}MSG_GENERAL_OPT_S;
+
+
+/**
+ *     @brief  Represents an SMS send option.
+ */
+typedef struct
+{
+       msg_encode_type_t                       dcs;                                    /**< Indicates the string encoding type. */
+       MSG_SMS_NETWORK_MODE_T  netMode;                                /**< Indicates the network mode (CS/PS) to send SMS. */
+       bool                                                    bReplyPath;                     /**< Indicates whether the SMS reply path is set or not. */
+       bool                                                    bDeliveryReport;                /**< Indicates whether the SMS delivery report will be sent or not. */
+       MSG_SMS_SAVE_STORAGE_T          saveStorage;                    /**< Indicates the default storage to save SMS. */
+}MSG_SMS_SENDOPT_S;
+
+
+/**
+ *     @brief  Represents an MMS send option.
+ */
+typedef struct
+{
+       MSG_MMS_MSG_CLASS_TYPE_T        msgClass;
+       msg_priority_type_t                     priority;                               /**< Indicates the priority of the message. */
+       MSG_MMS_EXPIRY_TIME_T           expiryTime;                     /**< Indicates the time when the message is to be removed from the MMSC. */
+       MSG_MMS_DELIVERY_TIME_T         deliveryTime;                   /**< Indicates the message transmission time which is set in the MMSC. */
+       unsigned int                                    customDeliveryTime;     /**< Indicates the message transmission time which is set in the MMSC. */
+       bool                                                    bSenderVisibility;              /**< Indicates whether the address is hidden or not. */
+       bool                                                    bDeliveryReport;                /**< Indicates whether the delivery report will be sent or not. */
+       bool                                                    bReadReply;                     /**< Indicates whether the read report will be sent or not. */
+       bool                                                    bKeepCopy;                      /**< Indicates whether the message copy is kept or not. */
+       bool                                                    bBodyReplying;          /**< Indicates whether the body is included when replying or not. */
+       bool                                                    bHideRecipients;                /**< Indicates whether the recipients are hidden or not. */
+
+       MSG_MMS_REPLY_CHARGING_TYPE_T   replyCharging;
+       unsigned int                                            replyChargingDeadline;
+       unsigned int /*long*/                           replyChargingSize;
+
+       MSG_MMS_CREATION_MODE_T creationMode;
+} MSG_MMS_SENDOPT_S;
+
+
+/**
+ *     @brief  Represents an MMS receive option.
+ */
+typedef struct
+{
+       MSG_MMS_HOME_RETRIEVE_TYPE_T            homeNetwork;    /**< Indicates the retrieve type for MMS home network. */
+       MSG_MMS_ABROAD_RETRIEVE_TYPE_T  abroadNetwok;   /**< Indicates the retrieve type for MMS abroad network. */
+//     MSG_MMS_SEND_READ_REPORT_T              readReceipt;    /**< Indicates whether the read report will be sent or not. */
+       bool                            readReceipt;                                    /**< Indicates whether the read report will be sent or not. */
+       bool                            bDeliveryReceipt;                       /**< Indicates whether the delivery report will be sent or not. */
+       bool                            bRejectUnknown;                 /**< Indicates whether unknown addresses are rejected or not. */
+       bool                            bRejectAdvertisement;   /**< Indicates whether advertisement is rejected or not. */
+} MSG_MMS_RECVOPT_S;
+
+
+/**
+ *     @brief  Represents an MMS style option.
+ */
+typedef struct
+{
+       unsigned int    fontSize;
+       bool                    bFontStyleBold;
+       bool                    bFontStyleItalic;
+       bool                    bFontStyleUnderline;
+       unsigned int    fontColorRed;
+       unsigned int    fontColorGreen;
+       unsigned int    fontColorBlue;
+       unsigned int    fontColorHue;
+       unsigned int    bgColorRed;
+       unsigned int    bgColorGreen;
+       unsigned int    bgColorBlue;
+       unsigned int    bgColorHue;
+       unsigned int    pageDur;
+       unsigned int    pageCustomDur;
+       unsigned int    pageDurManual;
+} MSG_MMS_STYLEOPT_S;
+
+
+/**
+ *     @brief  Represents a push message option.
+ */
+typedef struct
+{
+       bool                                            bReceive;               /**< Indicates whether the push message is received or not. */
+       MSG_PUSH_SERVICE_TYPE_T serviceType;            /**< Indicates the service type of a push message. */
+} MSG_PUSHMSG_OPT_S;
+
+
+/**
+ *     @brief  Represents a cell broadcasting message option.
+ */
+typedef struct
+{
+       bool                            bReceive;               /**< Indicates whether the CB message is received or not. */
+       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_CBMSG_OPT_S;
+
+typedef struct
+{
+       bool                                    bReceive;               /**< Indicates whether the CB message is received or not. */
+       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_CBMSG_OPT_HIDDEN_S;
+
+/**
+ *     @brief  Represents a voice mail number option.
+ */
+typedef struct
+{
+       char mailNumber[MAX_PHONE_NUMBER_LEN+1];
+} MSG_VOICEMAIL_OPT_S;
+
+
+/**
+ *     @brief  Represents a MMS size option.
+ */
+typedef struct
+{
+       int nMsgSize;
+} MSG_MSGSIZE_OPT_S;
+
+
+/**
+ *     @brief  Represents setting information.
+ */
+typedef struct
+{
+       MSG_OPTION_TYPE_T       type;           /**< The option type in a setting */
+
+       union
+       {
+               MSG_GENERAL_OPT_S               generalOpt;             /**< General option */
+               MSG_SMS_SENDOPT_S               smsSendOpt;             /**< SMS send option */
+               MSG_SMSC_LIST_S                 smscList;                       /**< SMSC list option */
+               MSG_MMS_SENDOPT_S               mmsSendOpt;             /**< MMS send option */
+               MSG_MMS_RECVOPT_S               mmsRecvOpt;             /**< MMS receive option */
+               MSG_MMS_STYLEOPT_S              mmsStyleOpt;            /**< MMS style option */
+               MSG_PUSHMSG_OPT_S               pushMsgOpt;             /**< Push message option */
+               MSG_CBMSG_OPT_S         cbMsgOpt;               /**< Cell broadcasting message option */
+               MSG_VOICEMAIL_OPT_S             voiceMailOpt;           /**< voice mail option */
+               MSG_MSGSIZE_OPT_S               msgSizeOpt;             /**< MMS size option */
+       } option;
+}MSG_SETTING_S;
+
+
+/**
+ *     @}
+ */
+
+#endif // MSG_SETTING_TYPES_H
+
diff --git a/include/common/MsgStorageTypes.h b/include/common/MsgStorageTypes.h
new file mode 100755 (executable)
index 0000000..5a74993
--- /dev/null
@@ -0,0 +1,152 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_STORAGE_TYPES_H
+
+
+/**
+ *     @file           MsgStorageTypes.h
+ *     @brief          Defines transport types of messaging framework
+ *     @version        1.0
+ */
+
+
+/**
+ *     @section                Introduction
+ *     - Introduction : Overview on Messaging Storage Types
+ *     @section                Program
+ *     - Program : Messaging Storage Types Reference
+ */
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <time.h>
+
+#include "MsgTypes.h"
+
+#include "msg_storage_types.h"
+
+
+/**
+ *     @ingroup                MESSAGING_FRAMEWORK
+ *     @defgroup       MESSAGING_STORAGE_TYPES Messaging Storage Types
+ *     @{
+ */
+/*==================================================================================================
+                                         STRUCTURES
+==================================================================================================*/
+
+/**
+ *     @brief  Represents the count of read/unread messages.
+ */
+typedef struct
+{
+       int     nReadCnt;               /**< The count of read messages */
+       int     nUnreadCnt;             /**< The count of unread messages */
+       int     nSms;                   /**< The count of sms type messages */
+       int     nMms;                   /**< The count of mms type messages */
+} MSG_COUNT_INFO_S;
+
+
+/**
+ *     @brief  Represents a reject message information.
+ */
+typedef struct
+{
+       msg_message_id_t                msgId;                  /**< Indicates the unique message ID. */
+       char                                            msgText[MAX_MSG_TEXT_LEN+1];    /**< Indicates the message text. */
+       time_t                                  displayTime;
+} MSG_REJECT_MSG_INFO_S;
+
+
+/**
+ *     @brief  Represents folder information.
+ */
+typedef struct
+{
+       msg_folder_id_t         folderId;                       /**< Indicates the unique folder ID. */
+       char                            folderName[MAX_FOLDER_NAME_SIZE+1];     /**< Indicates the name of the folder. */
+       msg_folder_type_t       folderType;             /**< Indicates the folder type. */
+} MSG_FOLDER_INFO_S;
+
+
+/**
+ *     @brief  Represents contact information.
+ */
+typedef struct
+{
+       msg_contact_id_t        contactId;                                                      /**< Indicates the unique contact 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                            imagePath[MAX_IMAGE_PATH_LEN+1];                /**< Indicates the image path of contact. */
+} MSG_CONTACT_INFO_S;
+
+
+/**
+ *     @brief  Represents a sort rule. \n
+ *     The sort rule structure includes a sort type and a sort order. \n
+ *     Applications can use the sort rule when querying messages.
+ */
+typedef struct
+{
+       msg_sort_type_t sortType;               /**< Indicates the sort type */
+       bool                                    bAscending;             /**< Indicates the sort order which is ascending or descending */
+}MSG_SORT_RULE_S;
+
+
+/**
+ *     @brief  Represents SIM ID List.
+ */
+typedef struct
+{
+       unsigned int            count;                                                                          /**< The total number of SIM Msg ID*/
+       msg_sim_id_t    simId[MAX_SEGMENT_NUM];                                         /**< The SIM Msg ID List */
+} SMS_SIM_ID_LIST_S;
+
+
+/**
+ *     @brief  Represents recipien list information.
+ */
+typedef struct
+{
+       int                                             recipientCnt;
+       MSG_ADDRESS_INFO_S*     recipientAddr;
+} MSG_RECIPIENTS_LIST_S;
+
+
+/**
+ *     @brief  Represents search condition values.
+ */
+typedef struct
+{
+       msg_folder_id_t         folderId;
+       msg_message_type_t              msgType;
+       char                                            *pAddressVal;
+       char                                            *pSearchVal;
+       int                                             reserved;
+} MSG_SEARCH_CONDITION_S;
+
+
+typedef struct
+{
+       int appcode;
+       char appid[MAX_WAPPUSH_ID_LEN];
+} PUSH_APPLICATION_INFO_S;
+
+#endif // MSG_STORAGE_TYPES_H
+
diff --git a/include/common/MsgThread.h b/include/common/MsgThread.h
new file mode 100755 (executable)
index 0000000..225308d
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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__
+#define __MSG_THREAD_H__
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <pthread.h>
+#include "MsgDebug.h"
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class MsgThread
+{
+public:
+       MsgThread(): thd(0) {};
+
+       virtual void start()
+       {
+               MSG_DEBUG("MsgThread::Start() called");
+
+               if (pthread_create(&thd, NULL, &MsgThread::thdMain, this) < 0)
+               {
+                       MSG_DEBUG("pthread_create() error");
+                       return;
+               }
+
+               pthread_detach(thd);
+       }
+
+       virtual void stop()
+       {
+               MSG_DEBUG("MsgThread::stop() called");
+       }
+
+       void wait()
+       {
+               MSG_DEBUG("MsgThread::Wait() called");
+               void* pData;
+               pthread_join(thd, &pData);
+       }
+
+private:
+       static void* thdMain(void* pInst)
+       {
+               MSG_DEBUG("MsgThread::thdMain() called");
+               MsgThread* pt = static_cast<MsgThread*>(pInst);
+               pt->run();
+               return NULL;
+       }
+
+       virtual void run() = 0;
+
+       pthread_t thd;
+};
+
+
+#endif //__MSG_THREAD_H__
+
diff --git a/include/common/MsgTransportTypes.h b/include/common/MsgTransportTypes.h
new file mode 100755 (executable)
index 0000000..e23db3f
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_TRANSPORT_TYPES_H
+
+/**
+ *     @file           MsgTransportTypes.h
+ *     @brief          Defines transport types of messaging framework
+ *     @version        1.0
+ */
+
+/**
+ *     @section                Introduction
+ *     - Introduction : Overview on Messaging Transport Types
+ *     @section                Program
+ *     - Program : Messaging Transport Types Reference
+ */
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgTypes.h"
+#include "MsgStorageTypes.h"
+#include "MsgMmsTypes.h"
+
+#include "msg_transport_types.h"
+
+/**
+ *     @ingroup                MESSAGING_FRAMEWORK
+ *     @defgroup       MESSAGING_TRANSPORT_TYPES       Messaging Transport Types
+ *     @{
+ */
+
+
+/*==================================================================================================
+                                         STRUCTURES
+==================================================================================================*/
+
+/**
+ *     @brief  Represents the status of a sent message. \n
+ *     This stucture contains the information about the status of a sent message that application has submitted to the framework.
+ */
+typedef struct
+{
+       msg_request_id_t                                reqId;          /**< Indicates the corresponding request Id. */
+       msg_network_status_t            status;         /**< Indicates the status of the corresponding request. Refer to enum _MSG_NETWORK_STATUS_E*/
+} MSG_SENT_STATUS_S;
+
+
+/*==================================================================================================
+                                         TYPES
+==================================================================================================*/
+
+
+
+/**
+ *     @}
+ */
+
+#endif // MSG_TRANSPORT_TYPES_H
+
diff --git a/include/common/MsgTypes.h b/include/common/MsgTypes.h
new file mode 100755 (executable)
index 0000000..5618c80
--- /dev/null
@@ -0,0 +1,326 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 MSG_TYPES_H
+
+/**
+ *     @file           MsgTypes.h
+ *     @brief          Defines common types of messaging framework
+ *     @version        1.0
+ */
+
+/**
+ *     @section                Introduction
+ *     - Introduction : Overview on Message Common Types
+ *     @section                Program
+ *     - Program : Message Common Types Reference
+ */
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include <stdbool.h>
+
+#include "msg_types.h"
+
+/**
+ *     @ingroup                MESSAGING_FRAMEWORK
+ *     @defgroup       MESSAGING_COMMON_TYPES  Messaging Common Types
+ *     @{
+ */
+
+/*==================================================================================================
+                                         TYPES
+==================================================================================================*/
+
+/**
+ *     @brief  Defines the enabled MMS version
+ */
+#define        MMS_V1_2                                                                // MMS Version : MMS_V1_0 / MMS_V1_1 / MMS_V1_2
+
+/**
+ *     @brief  Defines message struct handle.
+ */
+
+typedef struct _msg_struct{
+       int type;
+       void *data;
+}msg_struct_s;
+
+/*==================================================================================================
+                                         STRUCTURES
+==================================================================================================*/
+
+/**
+ *     @brief  Represents address information.
+ */
+
+typedef struct
+{
+       msg_address_type_t              addressType;                                                                                                    /**< The type of an address in case of an Email or a mobile phone */
+       msg_recipient_type_t    recipientType;                                                                                                  /**< The type of recipient address in case of To, Cc, and Bcc */
+       msg_contact_id_t                        contactId;                                                                                                                      /**< The contact ID of address */
+       char                                                                            addressVal[MAX_ADDRESS_VAL_LEN+1];              /**< The actual value of an address */
+       char                                                                            displayName[MAX_DISPLAY_NAME_LEN+1];    /**< The display name of an address */
+} MSG_ADDRESS_INFO_S;
+
+
+/**
+ *     @brief  Represents port number information.
+ */
+typedef struct
+{
+       bool                            valid;          /**< Indicates whether port information is used or not. */
+       unsigned short          dstPort;                /**< Recipient port number, not greater than 16 bit */
+       unsigned short          srcPort;                /**< Sender port number, not greater than 16 bit */
+} MSG_PORT_INFO_S;
+
+
+/**
+ *     @brief  Represents MMS Sending Option Structure in application.
+ */
+typedef struct
+{
+       bool                                    bReadReq;
+       time_t                          expiryTime;
+       bool                                    bUseDeliveryCustomTime;
+       time_t                          deliveryTime;
+       msg_priority_type_t     priority;
+} MMS_SENDINGOPT_S;
+
+
+/**
+ *     @brief  Represents SMS Sending Option Structure in application.
+ */
+typedef struct
+{
+       bool bReplyPath;
+} SMS_SENDINGOPT_S;
+
+
+/**
+ *     @brief  Represents MSG Sending Option Structure in application.
+ */
+typedef struct
+{
+       bool bSetting;
+       bool bDeliverReq;
+       bool bKeepCopy;
+       msg_struct_t mmsSendOpt;
+       msg_struct_t smsSendOpt;
+
+} MSG_SENDINGOPT_S;
+
+
+typedef        enum
+{
+       MMS_TIMETYPE_NONE               = -1,   // fixme: backward compatibility
+       MMS_TIMETYPE_ERROR              = -1,   // error return in Get method
+       MMS_TIMETYPE_RELATIVE   = 0,    // default
+       MMS_TIMETYPE_ABSOLUTE   = 1
+}MmsTimeType;
+
+
+typedef struct
+{
+       MmsTimeType     type;
+       unsigned int    time;
+}MmsTimeStruct;
+
+
+/**
+ *     @brief  Represents MMS Sending Option Structure in framework.
+ */
+typedef struct
+{
+       bool                                    bReadReq;
+       bool                                    bUseDeliveryCustomTime;
+       msg_priority_type_t     priority;
+       MmsTimeStruct                   expiryTime;
+       MmsTimeStruct                   deliveryTime;
+} MMS_SENDINGOPT_INFO_S;
+
+
+/**
+ *     @brief  Represents SMS Sending Option Structure in framework.
+ */
+typedef struct
+{
+       bool    bReplyPath;
+} SMS_SENDINGOPT_INFO_S;
+
+
+/**
+ *     @brief  Represents MSG Sending Option Structure in framework.
+ */
+typedef struct
+{
+       bool bSetting;
+       bool bDeliverReq;
+       bool bKeepCopy;
+
+       union
+       {
+               MMS_SENDINGOPT_INFO_S   mmsSendOptInfo;
+               SMS_SENDINGOPT_INFO_S   smsSendOptInfo;
+       } option;
+} MSG_SENDINGOPT_INFO_S;
+
+
+/**
+ *     @brief  Represents a request in the application. \n
+ *     Applications compose a request and send it to the framework via Message handle. \n
+ *     This request ID is used to manage the request by the framework.
+ */
+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_struct_t            msg;    /**< Indicates the message structure to be sent by applications. */
+       msg_struct_t            sendOpt;
+} MSG_REQUEST_S;
+
+
+/**
+ *     @brief  Represents Address information list.
+ */
+
+typedef struct
+{
+       msg_contact_id_t                contactId;                      /**< The contact id of message common informatioin */
+       MSG_ADDRESS_INFO_S              msgAddrInfo;            /**< The pointer to message common informatioin */
+} MSG_THREAD_LIST_INDEX_S;
+
+typedef struct
+{
+       msg_contact_id_t                contactId;                      /**< The contact id of message common informatioin */
+       msg_struct_t                    msgAddrInfo;            /**< The pointer to message common informatioin */
+} MSG_THREAD_LIST_INDEX_INFO_S;
+
+
+/**
+ *     @brief  Represents Peer Count Info.
+ */
+typedef struct
+{
+       int totalCount;                 /**< Indicates the total number of messages from the Peer. */
+       int unReadCount;                /**< Indicates the unread messages from the Peer. */
+       int smsMsgCount;                /**< Indicates the SMS messages from the Peer. */
+       int mmsMsgCount;                /**< Indicates the MMS messages from the Peer. */
+}MSG_THREAD_COUNT_INFO_S;
+
+
+/**
+ *     @brief  Represents the request information of Push Message (SI, SL).
+ */
+typedef struct
+{
+       msg_push_action_t       action;
+       unsigned long                   received;
+       unsigned long                   created;
+       unsigned long                   expires;
+       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;
+
+
+/**
+ *     @brief  Represents the request information of Push Message (CO).
+ */
+typedef struct
+{
+       int             invalObjectCnt;
+       int             invalServiceCnt;
+       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;
+
+
+/**
+ *     @brief  Represents the SyncML Message Information.
+ */
+typedef struct
+{
+       int                                     extId;
+       int                                     pinCode;
+       msg_struct_t            msg;
+}MSG_SYNCML_MESSAGE_S;
+
+
+/**
+ *     @brief  Represents the SyncML Message Data.
+ */
+ typedef struct
+{
+       msg_syncml_message_type_t       syncmlType;
+       int                                                     pushBodyLen;
+       char                                                    pushBody[MAX_WAPPUSH_CONTENTS_LEN + 1];
+       int                                                             wspHeaderLen;
+       char                                                    wspHeader[MAX_WAPPUSH_CONTENTS_LEN + 1];
+}MSG_SYNCML_MESSAGE_DATA_S;
+
+
+/**
+ *     @brief  Represents the SyncML Message Data.
+ */
+ typedef struct
+{
+       char                                                    pushHeader[MAX_WAPPUSH_CONTENTS_LEN + 1];
+       int                                                     pushBodyLen;
+       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
+{
+       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;
+
+/**
+ *     @}
+ */
+
+#endif // MSG_TYPES_H
+
diff --git a/include/framework/MsgCmdHandler.h b/include/framework/MsgCmdHandler.h
new file mode 100755 (executable)
index 0000000..dc52cd5
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_CMD_HANDLER_H
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgCmdTypes.h"
+#include "MsgInternalTypes.h"
+
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+int MsgAddMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgAddSyncMLMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgUpdateMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgUpdateReadStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+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);
+int MsgCountMsgByTypeHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgGetMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgGetFolderViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+
+int MsgAddFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgUpdateFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgDeleteFolderHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgGetFolderListHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+
+int MsgInitSimBySatHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgGetMsgTypeHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+
+int MsgGetThreadViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgGetConversationViewListHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgDeleteThreadMessageListHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+
+int MsgCountMsgByContactHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgGetQuickPanelDataHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgResetDatabaseHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgGetMemSizeHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgGetReportStatusHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgGetThreadIdByAddressHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgGetThreadInfoHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+
+int MsgBackupMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgRestoreMessageHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+
+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 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);
+
+int MsgIncomingMMSConfMsgHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgAddFilterHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+int MsgUpdateFilterHandler(const MSG_CMD_S *pCmd, char **ppEvent);
+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 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);
+
+
+#endif // MSG_CMD_HANDLER_H
diff --git a/include/framework/MsgDeliverHandler.h b/include/framework/MsgDeliverHandler.h
new file mode 100755 (executable)
index 0000000..0e94070
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_DELIVER_HANDLER_H
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgPluginInterface.h"
+#include "MsgTypes.h"
+
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+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, bool *bOnlyNoti);
+msg_error_t MsgHandleMMS(MSG_MESSAGE_INFO_S *pMsgInfo, bool *pSendNoti);
+
+/*==================================================================================================
+                                       DEFINES
+==================================================================================================*/
+#define MSG_SVC_PKG_NAME_BROWSER       "org.tizen.browser"
+
+#endif // MSG_DELIVER_HANDLER_H
+
diff --git a/include/framework/MsgPluginConfig.h b/include/framework/MsgPluginConfig.h
new file mode 100755 (executable)
index 0000000..1180d85
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
diff --git a/include/framework/MsgPluginManager.h b/include/framework/MsgPluginManager.h
new file mode 100755 (executable)
index 0000000..99f384d
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_PLUGIN_MANAGER_H
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <map>
+
+#include "MsgTypes.h"
+#include "MsgPluginInterface.h"
+#include "MsgPluginConfig.h"
+
+
+/*==================================================================================================
+                                    DEFINES
+==================================================================================================*/
+#define MSG_PLUGIN_CFG_PATH    "/usr/share/msg-service/"
+#define MSG_PLUGIN_CFG_NAME    "plugin.cfg"
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class MsgPlugin
+{
+public:
+       MsgPlugin(MSG_MAIN_TYPE_T plgType = MSG_UNKNOWN_TYPE, const char* libPath = NULL);
+       ~MsgPlugin();
+
+       msg_error_t initialize();
+       void finalize();
+
+       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);
+       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);
+       msg_error_t setConfigData(const MSG_SETTING_S *pSetting);
+       msg_error_t getConfigData(MSG_SETTING_S *pSetting);
+
+       // 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 updateRejectStatus(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t composeReadReport(MSG_MESSAGE_INFO_S *pMsgInfo);
+
+       msg_error_t restoreMsg(MSG_MESSAGE_INFO_S *pMsgInfo, char* pRecvBody, int rcvdBodyLen, char* filePath);
+
+       operator void*() const {
+               return (mSupportedMsg==MSG_UNKNOWN_TYPE)? NULL:(void*) this;
+       }
+
+private:
+       MSG_MAIN_TYPE_T                         mSupportedMsg;
+       MSG_PLUGIN_HANDLER_S    mPlgHandler;
+
+       void    *mLibHandler;    // plugin library pointer
+};
+
+
+/*==================================================================================================
+                                     GLOBAL VARIABLES
+==================================================================================================*/
+typedef std::map<MSG_MAIN_TYPE_T, MsgPlugin*> MsgPluginMap;
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class MsgPluginManager
+{
+public:
+       static MsgPluginManager* instance();
+
+       void initialize();
+       void finalize();
+       MsgPlugin* getPlugin(MSG_MAIN_TYPE_T mainType);
+       void loadPlugins(const char* path);
+
+private:
+       MsgPluginManager();
+       ~MsgPluginManager();
+
+       static MsgPluginManager* pInstance;
+       MsgPluginMap plgMap;
+};
+
+#endif // MSG_PLUGIN_MANAGER_H
+
diff --git a/include/framework/MsgSettingHandler.h b/include/framework/MsgSettingHandler.h
new file mode 100755 (executable)
index 0000000..054025f
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_SETTING_HANDLER_H
+
+
+/*==================================================================================================
+                                       INCLUDE FILES
+==================================================================================================*/
+#include "MsgSettingTypes.h"
+
+
+/*==================================================================================================
+                                       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);
+
+msg_error_t MsgSetGeneralOpt(const MSG_SETTING_S *pSetting);
+msg_error_t MsgSetSMSSendOpt(const MSG_SETTING_S *pSetting);
+msg_error_t MsgSetSMSCList(const MSG_SETTING_S *pSetting, bool bSetSim);
+msg_error_t MsgSetMMSSendOpt(const MSG_SETTING_S *pSetting);
+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, bool bSetSim);
+msg_error_t MsgSetMsgSizeOpt(const MSG_SETTING_S *pSetting);
+
+void MsgGetGeneralOpt(MSG_SETTING_S *pSetting);
+void MsgGetSMSSendOpt(MSG_SETTING_S *pSetting);
+void MsgGetSMSCList(MSG_SETTING_S *pSetting);
+void MsgGetMMSSendOpt(MSG_SETTING_S *pSetting);
+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);
+
+//void MsgSetDefaultConfig();
+
+#endif
+
diff --git a/include/framework/MsgStorageHandler.h b/include/framework/MsgStorageHandler.h
new file mode 100755 (executable)
index 0000000..6bc3df2
--- /dev/null
@@ -0,0 +1,140 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_STORAGE_HANDLER_H
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgStorageTypes.h"
+#include "MsgSettingTypes.h"
+#include "MsgFilterTypes.h"
+#include "MsgMmsTypes.h"
+#include "MsgTransportTypes.h"
+#include "MsgInternalTypes.h"
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+msg_error_t MsgStoConnectDB();
+msg_error_t MsgStoDisconnectDB();
+
+msg_error_t MsgStoInitDB(bool bSimChanged);
+
+msg_error_t MsgCreateConversationTable();
+msg_error_t MsgCreateAddressTable();
+msg_error_t MsgCreateFolderTable();
+msg_error_t MsgCreateMsgTable();
+msg_error_t MsgCreateSimMessageTable();
+msg_error_t MsgCreateWAPMessageTable();
+msg_error_t MsgCreateCBMessageTable();
+msg_error_t MsgCreateSyncMLMessageTable();
+msg_error_t MsgCreateSmsSendOptTable();
+msg_error_t MsgCreateFilterTable();
+msg_error_t MsgCreateMmsTable();
+msg_error_t MsgAddDefaultFolders();
+msg_error_t MsgAddDefaultAddress();
+msg_error_t MsgStoResetDatabase();
+
+msg_error_t MsgStoBackupMessage(msg_message_backup_type_t type, const char *filepath);
+msg_error_t MsgStoRestoreMessage(const char *filepath);
+
+msg_error_t MsgStoAddMessage(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 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 MsgStoGetConversationViewItem(msg_message_id_t msgId, MSG_CONVERSATION_VIEW_S *pConv);
+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, 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, 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);
+msg_error_t MsgStoUpdateFolder(const MSG_FOLDER_INFO_S *pFolderInfo);
+msg_error_t MsgStoDeleteFolder(msg_folder_id_t FolderId);
+msg_error_t MsgStoGetFolderList(msg_struct_list_s *pFolderList);
+
+// Filter
+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 MsgStoGetMmsSendOpt(msg_message_id_t MsgId, MSG_SENDINGOPT_INFO_S* pSendOpt);
+
+// SyncML Msg
+msg_error_t MsgStoGetSyncMLExtId(msg_message_id_t msgId, int *extId);
+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);
+
+
+///////////////////////////////////////////////////////////////////////////////////
+// For MMS - will be removed
+msg_error_t MsgStoGetOrgAddressList(MSG_MESSAGE_INFO_S *pMsg);
+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);
+msg_error_t MsgStoGetAddrInfo(msg_message_id_t MsgId, MSG_ADDRESS_INFO_S *pAddrInfo);
+
+///////////////////////////////////////////////////////////////////////////////////
+
+msg_error_t MsgStoResetNetworkStatus();
+msg_error_t MsgStoCleanAbnormalMmsData();
+msg_error_t MsgStoCheckReadReportStatus(msg_message_id_t msgId);
+
+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);
+
+#endif // MSG_STORAGE_HANDLER_H
+
diff --git a/include/framework/MsgSubmitHandler.h b/include/framework/MsgSubmitHandler.h
new file mode 100755 (executable)
index 0000000..ee455dd
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_SUBMIT_HANDLER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgInternalTypes.h"
+
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+msg_error_t MsgSubmitReq(MSG_REQUEST_INFO_S* pReq, bool bScheduled);
+msg_error_t MsgSubmitReqSMS(MSG_REQUEST_INFO_S *pReqInfo);
+msg_error_t MsgSubmitReqMMS(MSG_REQUEST_INFO_S *pReqInfo);
+
+msg_error_t MsgCancelReq(msg_request_id_t reqId);
+msg_error_t MsgUpdateSentMsg(msg_message_id_t MsgId, msg_network_status_t Status);
+
+void MsgCopyReqInfo(MSG_REQUEST_INFO_S *pSrc, int addrIdx, MSG_REQUEST_INFO_S *pDest);
+
+#endif // MSG_SUBMIT_HANDLER_H
+
diff --git a/include/framework/MsgTransManager.h b/include/framework/MsgTransManager.h
new file mode 100755 (executable)
index 0000000..ede7756
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_TRANSACTION_MANAGER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <list>
+#include <map>
+
+#include "MsgMutex.h"
+#include "MsgIpcSocket.h"
+#include "MsgCmdTypes.h"
+#include "MsgInternalTypes.h"
+#include "MsgTransportTypes.h"
+
+
+
+/*==================================================================================================
+                                         DEFINITION
+==================================================================================================*/
+typedef std::map<MSG_CMD_TYPE_T, int (*)(const MSG_CMD_S*, char**)> handler_map;
+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;
+typedef std::list<MSG_CMD_REG_SYNCML_MSG_OPERATION_CB_S> syncmlop_list;
+
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+void MsgContactChangedCallback();
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class MsgTransactionManager
+{
+public:
+       static MsgTransactionManager* instance();
+
+       void run();
+       void write(int fd, const char* buf, int len);
+
+       // methods for sent status event
+       void insertSentMsg(int reqId, MSG_PROXY_INFO_S* pChInfo);
+       MSG_PROXY_INFO_S* getProxyInfo(int reqId);
+       void delProxyInfo(int reqId);
+
+       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);
+
+       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 setTMStatus();
+       void getTMStatus();
+
+private:
+       MsgTransactionManager();
+       ~MsgTransactionManager();
+
+       void handleRequest(int fd);
+       void cleanup(int fd);
+       bool checkPrivilege(MSG_CMD_TYPE_T CmdType, const char *pCookie);
+
+       static MsgTransactionManager* pInstance;
+
+       static MsgIpcServerSocket servSock;
+       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
+
+       Mutex mx;
+       CndVar cv;
+};
+
+#endif //MSG_TRANSACTION_MANAGER_H
+
diff --git a/include/mapi/msg.h b/include/mapi/msg.h
new file mode 100755 (executable)
index 0000000..c1209f9
--- /dev/null
@@ -0,0 +1,243 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_
+#define MSG_H_
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <stdbool.h>
+
+#include "msg_types.h"
+
+#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.
+ *
+ * \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.
+ *
+ * \par Typical use case:
+ * Any application which utilizes the services of Messaging Framework needs to call this API.
+ *
+ * \par Method of function operation:
+ * Check for Message Server ready status. If ready connect to the Messaging Server socket and pass the handle application.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \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.
+ *
+ * \param msg_handle_t    input - handle to be passed for all Messaging Services .
+ *
+ * \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
+ *
+ * \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;
+ *
+ * err = msg_open_msg_handle(&msgHandle);
+ *
+ * if (err != MSG_SUCCESS)
+ * {
+ *     sprintf(str, "msg_open_msg_handle() Fail [%d]", err);
+ *     print(str);
+ *
+ *     return err; // if success, return OPERATION_SUCCESS. Or if fail, return related error code.
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+int msg_open_msg_handle(msg_handle_t *handle);
+
+
+/**
+
+ * \par Description:
+ * Closes the channel between application and messaging framework.
+ *
+ * \par Purpose:
+ * Once application utilizes services of Messaging Service, this API needs to be invoked the close the channel between application and Messaging Service.
+ *
+ * \par Typical use case:
+ * Any application which has completed using services of Messaging Framework needs to call this API.
+ *
+ * \par Method of function operation:
+ * Closes the connection to Messaging Service and deleted the reference to the handle object
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \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.
+ *
+ * \param msg_handle_t    input - handle to be passed for all Messaging Services .
+ *
+ * \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
+ *
+ * \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;
+ *
+ * ...
+ *
+ * err = msg_open_msg_handle(&msgHandle);
+ *
+ * ...
+ *
+ * err = msg_close_msg_handle(&msgHandle);
+ *
+ * if (err != MSG_SUCCESS)
+ * {
+ *     sprintf(str, "msg_close_msg_handle() Fail [%d]", err);
+ *     print(str);
+ *
+ *     return err; // if success, return OPERATION_SUCCESS. Or if fail, return related error code.
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+int msg_close_msg_handle(msg_handle_t *handle);
+
+
+
+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);
+
+int msg_get_int_value(msg_struct_t msg_struct_handle, int field, int *value);
+int msg_get_str_value(msg_struct_t msg_struct_handle, int field, char *value, int size);
+int msg_get_bool_value(msg_struct_t msg_struct_handle, int field, bool *value);
+int msg_get_struct_handle(msg_struct_t msg_struct_handle, int field, msg_struct_t *value);
+int msg_get_list_handle(msg_struct_t msg_struct_handle, int field, void **value);
+
+int msg_set_int_value(msg_struct_t msg_struct_handle, int field, int value);
+int msg_set_str_value(msg_struct_t msg_struct_handle, int field, char *value, int size);
+int msg_set_bool_value(msg_struct_t msg_struct_handle, int field, bool value);
+int msg_set_struct_handle(msg_struct_t msg_struct_handle, int field, msg_struct_t value);
+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);
+
+int msg_get_mms_struct(msg_struct_t msg_struct_handle, msg_struct_t mms_struct_handle);
+int msg_set_mms_struct(msg_struct_t msg_struct_handle, msg_struct_t mms_struct_handle);
+
+//list
+msg_struct_t msg_list_nth_data(msg_list_handle_t list_handle, int index);
+int msg_list_length(msg_list_handle_t list_handle);
+
+// filter
+int msg_add_filter(msg_handle_t handle, const msg_struct_t filter);
+int msg_update_filter(msg_handle_t handle, const msg_struct_t filter);
+int msg_delete_filter(msg_handle_t handle, msg_filter_id_t filter_id);
+int msg_get_filter_list(msg_handle_t handle, msg_struct_list_s *filter_list);
+int msg_set_filter_operation(msg_handle_t handle, bool set_flag);
+int msg_get_filter_operation(msg_handle_t handle, bool *set_flag);
+int msg_set_filter_active(msg_handle_t handle, msg_filter_id_t filter_id, bool active);
+
+//setting
+int msg_get_smsc_opt(msg_handle_t handle, msg_struct_t msg_struct);
+int msg_set_smsc_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+int msg_get_cb_opt(msg_handle_t handle, msg_struct_t msg_struct);
+int msg_set_cb_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+int msg_get_sms_send_opt(msg_handle_t handle, msg_struct_t msg_struct);
+int msg_set_sms_send_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+int msg_get_mms_send_opt(msg_handle_t handle, msg_struct_t msg_struct);
+int msg_set_mms_send_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+int msg_get_mms_recv_opt(msg_handle_t handle, msg_struct_t msg_struct);
+int msg_set_mms_recv_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+int msg_get_push_msg_opt(msg_handle_t handle, msg_struct_t msg_struct);
+int msg_set_push_msg_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+int msg_get_voice_msg_opt(msg_handle_t handle, msg_struct_t msg_struct);
+int msg_set_voice_msg_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+int msg_get_general_opt(msg_handle_t handle, msg_struct_t msg_struct);
+int msg_set_general_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+int msg_get_msgsize_opt(msg_handle_t handle, msg_struct_t msg_struct);
+int msg_set_msgsize_opt(msg_handle_t handle, msg_struct_t msg_struct);
+
+// text length calculate
+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
+
+#endif /* MSG_H_ */
diff --git a/include/mapi/msg_private.h b/include/mapi/msg_private.h
new file mode 100755 (executable)
index 0000000..6989ba5
--- /dev/null
@@ -0,0 +1,220 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_
+#define MSG_PRIVATE_H_
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+
+#include "MsgTypes.h"
+#include "MsgStorageTypes.h"
+#include "MsgTransportTypes.h"
+#include "MsgMmsTypes.h"
+#include "MsgFilterTypes.h"
+#include "MsgSettingTypes.h"
+
+
+/*==================================================================================================
+                                                                        FUNCTION PROTOTYPES
+==================================================================================================*/
+
+// message
+void msg_message_create_struct(msg_struct_s *msg_struct);
+int msg_message_release(msg_struct_s **msg_struct);
+
+int msg_message_get_int_value(void *data, int field, int *value);
+int msg_message_get_bool_value(void *data, int field, bool *value);
+int msg_message_get_str_value(void *data, int field, char *value, int size);
+int msg_message_get_struct_hnd(void *data, int field, void **value);
+int msg_message_get_list_hnd(void *data, int field, void **value);
+
+int msg_message_set_int_value(void *data, int field, int value);
+int msg_message_set_bool_value(void *data, int field, bool value);
+int msg_message_set_str_value(void *data, int field, char *value, int size);
+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);
+
+
+
+
+// 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);
+
+
+// mms
+msg_struct_s *msg_mms_create_struct(int field);
+void *msg_mms_create_struct_data(int field);
+int msg_mms_release_struct(msg_struct_s **msg_struct_data);
+
+int msg_mms_get_int_value(msg_struct_s *msg_struct, int field, int *value);
+int msg_mms_get_str_value(msg_struct_s *msg_struct, int field, char *src, int size);
+int msg_mms_get_bool_value(msg_struct_s *msg_struct, int field, bool *value);
+int msg_mms_get_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s **value);
+int msg_mms_get_list_handle(msg_struct_s *msg_struct, int field, msg_list_handle_t *value);
+
+int msg_mms_set_int_value(msg_struct_s *msg_struct, int field, int value);
+int msg_mms_set_str_value(msg_struct_s *msg_struct, int field, char *value, int size);
+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);
+
+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);
+
+// 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);
+int msg_setting_get_bool_value(msg_struct_s *msg_struct, int field, bool *value);
+int msg_setting_get_list_handle(msg_struct_s *msg_struct, int field, void **value);
+
+int msg_setting_set_int_value(msg_struct_s *msg_struct, int field, int value);
+int msg_setting_set_str_value(msg_struct_s *msg_struct, int field, char *value, int size);
+int msg_setting_set_bool_value(msg_struct_s *msg_struct, int field, bool value);
+
+int msg_get_smsc_opt_int(void *smsc_opt, int field);
+int msg_set_smsc_opt_int(void *smsc_opt, int field, int value);
+int msg_get_smsc_opt_list(void *smsc_opt, int field, void **value);
+
+int msg_get_smsc_info_int(void *smsc_info, int field);
+int msg_set_smsc_info_int(void *smsc_info, int field, int value);
+char* msg_get_smsc_info_str(void *smsc_info, int field);
+int msg_set_smsc_info_str(void *smsc_info, int field, char *val, int size);
+
+int msg_get_cb_option_int(void *cb_opt, int field);
+int msg_set_cb_option_int(void *cb_opt, int field, int value);
+bool msg_get_cb_option_bool(void *cb_opt, int field);
+int msg_set_cb_option_bool(void *cb_opt, int field, bool value);
+int msg_get_cb_option_list(void *cb_opt, int field, void **value);
+
+int msg_get_cb_channel_info_int(void *cb_ch_info, int field);
+int msg_set_cb_channel_info_int(void *cb_ch_info, int field, int value);
+bool msg_get_cb_channel_info_bool(void *cb_ch_info, int field);
+int msg_set_cb_channel_info_bool(void *cb_ch_info, int field, bool value);
+char *msg_get_cb_channel_info_str(void *cb_ch_info, int field);
+int msg_set_cb_channel_info_str(void *cb_ch_info, int field, char *val, int size);
+
+int msg_get_sms_send_opt_int(void *sms_send_opt, int field);
+int msg_set_sms_send_opt_int(void *sms_send_opt, int field, int value);
+bool msg_get_sms_send_opt_bool(void *sms_send_opt, int field);
+int msg_set_sms_send_opt_bool(void *sms_send_opt, int field, bool value);
+
+int msg_get_mms_send_opt_int(void *mms_send_opt, int field);
+int msg_set_mms_send_opt_int(void *mms_send_opt, int field, int value);
+bool msg_get_mms_send_opt_bool(void *mms_send_opt, int field);
+int msg_set_mms_send_opt_bool(void *mms_send_opt, int field, bool value);
+
+int msg_get_mms_recv_opt_int(void *mms_recv_opt, int field);
+int msg_set_mms_recv_opt_int(void *mms_recv_opt, int field, int value);
+bool msg_get_mms_recv_opt_bool(void *mms_recv_opt, int field);
+int msg_set_mms_recv_opt_bool(void *mms_recv_opt, int field, bool value);
+
+int msg_get_push_msg_opt_int(void *push_msg_opt, int field);
+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);
+
+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);
+
+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);
+
+
+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);
+int msg_thread_count_get_int(void *count_info, int field);
+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_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);
+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);
+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_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);
+char* msg_address_info_get_str(void *addr_info, int field, int size);
+char* msg_reject_message_get_str(void *msg_info, int field, int size);
+bool msg_mms_sendopt_get_bool(void *opt_info, int field);
+bool msg_sms_sendopt_get_bool(void *opt_info, int field);
+
+int msg_syncml_info_set_int(void *syncml_info, int field, int value);
+int msg_count_info_set_int(void *count_info, int field, int value);
+int msg_thread_count_set_int(void *count_info, int field, int value);
+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_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_sendopt_set_bool(void *send_opt, int field, bool value);
+int msg_sortrule_set_bool(void *sort_rule, 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_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_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);
+
+/* added internal apis for new managed api (transport) */
+int msg_request_get_int(void *request_info, int field);
+int msg_request_get_struct_handle(msg_struct_s *msg_struct, int field, void **value);
+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);
+
+
+#endif /* MSG_PRIVATE_H_ */
diff --git a/include/mapi/msg_storage.h b/include/mapi/msg_storage.h
new file mode 100755 (executable)
index 0000000..ba16db2
--- /dev/null
@@ -0,0 +1,2120 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+==================================================================================================*/
+
+#include "msg_storage_types.h"
+
+#ifdef __cplusplus
+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.
+ *
+ * \par Typical use case:
+ * Save Message feature is used when the message is to be stored to persistent memory for later reference.
+ *
+ * \par Method of function operation:
+ * Sets up the database connection and inserts the message to message table.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * - Mandatory fields of a message structure MUST be valid, otherwise the function will be failed.
+ *
+ * \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.
+ *
+ * \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.
+ *
+ * \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               msg;
+ * MSG_SENDINGOPT_S sendingOpt = {0};
+ *
+ * ...
+ *
+ * err = msg_open_msg_handle(&msgHandle);
+ *
+ * ...
+ *
+ * err = msg_add_message(handle, (msg_message_t) &msg, &sendingOpt);
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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.
+ *
+ * \par Method of function operation:
+ * Sets up the database connection and inserts the syncml message to message table.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * - Mandatory fields of a message structure MUST be valid, otherwise the function will be failed.
+ *
+ * \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 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
+ */
+/*================================================================================================*/
+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
+ */
+/*================================================================================================*/
+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};
+ *
+ * ...
+ *
+ * err = msg_open_msg_handle(&msgHandle);
+ *
+ * ...
+ *
+ * err = msg_update_message(hMsgHandle, pMsg, &sendOpt);
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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
+ * ...
+ *
+ * msg_handle_t msgHandle = NULL;
+ * MSG_SYNCML_MESSAGE_S syncMLMsg;
+ * MSG_SENDINGOPT_S sendingOpt = {0};
+ *
+ * ...
+ *
+ * err = msg_open_msg_handle(&msgHandle);
+ *
+ * ...
+ *
+ * err = msg_update_protected_status(hMsgHandle, 0, true);
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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
+ *
+ * \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_delete_message(msgHandle, 0);
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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
+ *
+ * \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_delete_all_msgs_in_folder(msgHandle, MSG_DRAFT_ID);
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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
+ *
+ * \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_move_msg_to_folder(hMsgHandle, 0, MSG_OUTBOX_ID);
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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.
+ *
+ * \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_move_msg_to_storage( msgHandle, 0, MSG_STORAGE_PHONE);
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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.
+ *
+ * \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_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
+ */
+/*================================================================================================*/
+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.
+ *
+ * \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_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
+ */
+/*================================================================================================*/
+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.
+ *
+ * \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.
+ *
+ * \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_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
+ */
+/*================================================================================================*/
+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.
+ *
+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.
+ *
+ * \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_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
+ */
+/*================================================================================================*/
+int msg_get_message(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_t msg, msg_struct_t send_opt);
+
+int msg_get_conversation(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_t conv);
+int msg_get_vobject_data(msg_handle_t handle, msg_message_id_t msg_id, void** encoded_data);
+
+/**
+
+ * \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.
+ *
+ * \par Typical use case:
+ * Get the common information from the specified folder from database.
+ *
+ * \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.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \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
+ *
+ * \par Sample code:
+ * \code
+ * ...
+ *
+ * msg_handle_t msgHandle = NULL;
+ *
+ * ...
+ * 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;
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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);
+
+
+/**
+
+ * \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.
+ *
+ * \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_thread_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 - 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.
+ *
+ * \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 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
+ */
+/*================================================================================================*/
+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
+ *
+ * \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_delete_thread_message_list(hMsgHandle, 0);
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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
+ *
+ * \par Sample code:
+ * \code
+ * ...
+ *
+ * msg_handle_t msgHandle = NULL;
+ *  Make Folder
+ * MSG_FOLDER_INFO_S folderInfo;
+ * ...
+ * err = msg_open_msg_handle(&msgHandle);
+ *
+ * folderInfo.folderId = 1;
+ * folderInfo.folderType = MSG_FOLDER_TYPE_USER_DEF;
+ * ...
+ *
+ * err = msg_add_folder(hMsgHandle, &folderInfo);
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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.
+ *
+ * \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
+ *
+ * \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
+ */
+/*================================================================================================*/
+int msg_update_folder(msg_handle_t handle, const msg_struct_t folder_info);
+
+
+/**
+
+ * \par Description:
+ * Deletes an exisiting folder.
+ *
+ * \par Purpose:
+ * This API is used to delete an existing folder.
+ *
+ * \par Typical use case:
+ * Deletes an existing folder.
+ *
+ * \par Method of function operation:
+ * Sets up the database connection and deletes an existing folder to the folder 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
+ *
+ * \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
+ */
+/*================================================================================================*/
+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.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * - None.
+ *
+ * \param input - handle is Message handle.
+ * \param output - folder_list is 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.
+ *
+ * \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
+ */
+/*================================================================================================*/
+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
+ */
+/*================================================================================================*/
+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.
+ *
+ * \par Important notes:
+ * - None
+ *
+ * \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.
+ *
+ * \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_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
+ */
+/*================================================================================================*/
+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.
+ *
+ * \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;
+ * err = msg_open_msg_handle(&msgHandle);
+ *
+ * ...
+ * err = msg_reset_database(msgHandle);
+ * if (err != MSG_SUCCESS)
+ *{
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \par Sample code:
+ * \code
+ * ...
+ *
+ * msg_handle_t msgHandle = NULL;
+ * int memsize = 0;
+ * err = msg_open_msg_handle(&msgHandle);
+ *
+ * ...
+ * err = msg_get_mem_size(msgHandle, &memsize);
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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.
+ * \param input - msg_message_backup_type_t  type is backup_type.
+ * \param input - backup_filepath is path to backup message.
+ *
+ * \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_message_backup_type_t type = MSG_BACKUP_TYPE_MMS;
+ * const char *filepath = "/backup_mms"
+ *
+ * ...
+ * err = msg_backup_message(&msgHandle, type, filepath);
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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.
+ * \param input - backup_filepath is path of backup file for restore.
+ *
+ *
+ * \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;
+ * const char *filepath = "/backup_mms"
+  * ...
+ * err = msg_restore_message(&msgHandle, filepath);
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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.
+ *
+ * \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.
+ *
+ * \par Important notes:
+ * None
+ *
+ * \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.
+ *
+ * \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;
+ * ...
+ * char* search_string = "hello";
+ * msg_struct_list_s threadViewList;
+ * ...
+ * err = msg_search_message_for_thread_view(&msgHandle, search_string, &threadViewList);
+ *
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+int msg_search_message_for_thread_view(msg_handle_t handle, const char *search_string, msg_struct_list_s *msg_thread_view_list);
+
+
+/**
+
+ * \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.
+ *
+ * \par Important notes:
+ * None
+ *
+ * \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.
+ *
+ * \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_struct_list_s msg_list;
+ * int offset = 0;
+ * int limit = 10;
+ *
+ * MSG_SEARCH_CONDITION_S searchCon;
+ *
+ * searchCon.msgType = MSG_TYPE_SMS;
+ * searchCon.folderId = MSG_INBOX_ID;
+ * searchCon.pSearchVal = "keyString";
+ * searchCon.pAddressVal = "01000000000";
+ *
+ * ...
+ * err = msg_search_message(hMsgHandle, &searchCon, offset, limit, &msgList);
+ *
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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);
+
+/**
+
+ * \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.
+ *
+ * \par Method of function operation:
+ * Get reject message list from storage.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * None
+ *
+ * \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.
+
+ * \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;
+ * ...
+ * char* phone_num = "01030016057";
+ * msg_struct_list_s rejectMsgList;
+ * ...
+ * err = msg_get_reject_msg_list(hMsgHandle, phone_num, &rejectMsgList);
+ *
+ * if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+int msg_get_reject_msg_list(msg_handle_t handle, const char* phone_num, msg_struct_list_s *msg_reject_msg_list);
+
+
+/**
+
+ * \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.
+ *
+ * \par Typical use case:
+ * Register a callback function about the change of storage status.
+ *
+ * \par Method of function operation:
+ * Adds the msg_storage_change_cb API to a callback function 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.
+ *
+ * \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_storage_change_callback(msgHandle, &storageCB, NULL);
+ * if (err != MSG_SUCCESS)
+ * {
+ * ...
+ * }
+ * return;
+ * }
+ *
+ * void storageCB(msg_handle_t handle, msg_thread_id_t threadId, msg_message_id_t msgId, void *user_param)
+ * {
+ *     ...
+ * }
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+int msg_reg_storage_change_callback(msg_handle_t handle, msg_storage_change_cb cb, void *user_param);
+
+
+/**
+
+ * \par Description:
+ * Gets the report status information of message.
+ *
+ * \par Purpose:
+ * This API is used to get the report status information of specified message.
+ *
+ * \par Typical use case:
+ * Gets the report status information of specified message from the database.
+ *
+ * \par Method of function operation:
+ * Sets up the database connection and Gets the report status information of specified message from the report 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.
+ * \param output - report_status is a pointer to a MSG_REPORT_STATUS_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
+ *
+ * \par Sample code:
+ * \code
+ * ...
+ *
+ * msg_handle_t msgHandle = NULL;
+ * MSG_REPORT_STATUS_INFO_S reportStatus;
+ *
+ * ...
+ *
+ * err = msg_open_msg_handle(&msgHandle);
+ *
+ * ...
+ *
+ * err = msg_get_report_status(msgHandle, msgID, &reportStatus)
+* if( err != MSG_SUCCESS )
+ * {
+ *     printf("err [%d]", err);
+ *     return err;
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+int msg_get_report_status(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_list_s *report_list);
+
+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_add_push_event(msg_handle_t handle, const msg_struct_t push_event);
+
+int msg_delete_push_event(msg_handle_t handle, const msg_struct_t push_event);
+
+int msg_update_push_event(msg_handle_t handle, const msg_struct_t src_event, const msg_struct_t dst_event);
+
+int msg_delete_msgs_by_list(msg_handle_t handle, msg_id_list_s *msg_id_list);
+/**
+ *     @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // MAPI_STORAGE_H
+
diff --git a/include/mapi/msg_storage_types.h b/include/mapi/msg_storage_types.h
new file mode 100755 (executable)
index 0000000..1244ae0
--- /dev/null
@@ -0,0 +1,211 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_
+#define MSG_STORAGE_TYPES_H_
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+
+#include "msg_types.h"
+
+/*==================================================================================================
+                                         STRUCTURES
+==================================================================================================*/
+
+/**
+ *     @brief  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 */
+}msg_id_list_s;
+
+
+/*==================================================================================================
+                                         TYPES
+==================================================================================================*/
+
+/**
+ *     @brief  Represents a folder type. \n
+ *     The values for this type SHOULD be in _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.
+ */
+typedef unsigned char msg_sort_type_t;
+
+
+/**
+ *     @brief  Represents a Saved SIM message ID.
+ */
+typedef signed short msg_sim_id_t;
+
+
+/**
+ *     @brief  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.
+ */
+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
+ */
+typedef void (*msg_storage_change_cb)(msg_handle_t handle, msg_storage_change_type_t storageChangeType, msg_id_list_s *pMsgIdList, void *user_param);
+
+
+/*==================================================================================================
+                                         ENUMS
+==================================================================================================*/
+
+/**
+ *     @brief  Represents 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. */
+};
+
+
+/**
+ *     @brief  Represents 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
+};
+
+
+/**
+ *     @brief  Represents 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_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.
+ */
+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_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_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*/
+};
+
+
+/**
+ *     @brief  Represents 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,
+};
+
+/**
+ *     @}
+ */
+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,
+};
+
+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,
+};
+
+enum _MSG_STORAGE_CHANGE_TYPE_E
+{
+       // msg data
+       MSG_STORAGE_CHANGE_INSERT = 1,
+       MSG_STORAGE_CHANGE_UPDATE,
+       MSG_STORAGE_CHANGE_DELETE,
+
+       // thread data
+       MSG_STORAGE_CHANGE_CONTACT,
+};
+
+
+#endif /* MSG_STORAGE_TYPES_H_ */
diff --git a/include/mapi/msg_transport.h b/include/mapi/msg_transport.h
new file mode 100755 (executable)
index 0000000..a20b9ad
--- /dev/null
@@ -0,0 +1,987 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+==================================================================================================*/
+
+#include "msg_transport_types.h"
+
+#ifdef __cplusplus
+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.
+ *
+ * \par Typical use case:
+ * Submit a request to Messaging Service such as Send Message, Forward etc.
+ *
+ * \par Method of function operation:
+ * Sets up the database connection and inserts the message to message table.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \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.
+ *
+ * \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;
+ * MSG_REQUEST_S req;
+ *
+ * req.msg = msg;
+ * req.sendOpt = sendOpt;
+
+ * err = msg_submit_req(msgHandle, &req);
+ * if (err != MSG_SUCCESS)
+ * {
+ * ...
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+int msg_submit_req(msg_handle_t handle, msg_struct_t req);
+
+
+/**
+
+ * \par Description:
+ * Registers sent status callback function to Message handle.
+ *
+ * \par Purpose:
+ * This API is used to register sent status callback function "msg_sent_status_cb" to Message handle.
+ *
+ * \par Typical use case:
+ * Register for sent status callback.
+ *
+ * \par Method of function operation:
+ * Adds the msg_sent_status_cb API to sent status 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.
+ *
+ * \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.
+ *
+ * \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_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
+ */
+/*================================================================================================*/
+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.
+ *
+ * \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.
+ *
+ * \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_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
+ */
+/*================================================================================================*/
+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.
+ *
+ * \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.
+ *
+ * \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_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
+ */
+/*================================================================================================*/
+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.
+ *
+ * \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 = 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
+ */
+/*================================================================================================*/
+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.
+ *
+ * \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.
+ *
+ * \par Method of function operation:
+ * Adds the msg_lbs_msg_incoming_cb API to incoming LBS Message 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.
+ *
+ * \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
+ */
+/*================================================================================================*/
+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.
+ *
+ * \par Typical use case:
+ * Register incoming SMS message callback.
+ *
+ * \par Method of function operation:
+ * Adds the msg_lbs_msg_incoming_cb API to incoming LBS Message 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.
+ *
+ * \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
+ */
+/*================================================================================================*/
+int msg_reg_syncml_message_operation_callback(msg_handle_t handle,  msg_syncml_msg_operation_cb cb, void *user_param);
+
+
+int msg_reg_push_message_callback(msg_handle_t handle,  msg_push_msg_incoming_cb cb, const char *app_id, void *user_param);
+
+int msg_reg_cb_message_callback(msg_handle_t handle, msg_cb_incoming_cb  cb, bool bsave, 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.
+ *
+ * \par Method of function operation:
+ * Adds the msg_lbs_msg_incoming_cb API to incoming LBS Message 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.
+ *
+ * \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
+ */
+/*================================================================================================*/
+int msg_syncml_message_operation(msg_handle_t handle,  msg_message_id_t msgId);
+
+
+/**
+
+ * \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.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * - None
+ *
+ * \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 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 = msg_sms_send("01000000000,01000000000", "1234567890", sentStatusCB, NULL);
+ * if (err != MSG_SUCCESS)
+ * {
+ * ...
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+int msg_sms_send(const char *phone_num, const char *sms_text, msg_simple_sent_status_cb cb, void *user_param);
+
+
+/**
+
+ * \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.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * - None
+ *
+ * \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 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_sms_send_message(msgHandle, &req);
+ * if (err != MSG_SUCCESS)
+ * {
+ * ...
+ * }
+ *
+ * ...
+ * \endcode
+ */
+/*================================================================================================*/
+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.
+ *
+ * \par Typical use case:
+ * Submits request to send MMS message.
+ *
+ * \par Method of function operation:
+ * Submits a request to send MMS.
+ *
+ * \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_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
+ */
+/*================================================================================================*/
+int msg_mms_send_message(msg_handle_t handle, msg_struct_t req);
+
+
+/**
+
+ * \par Description:
+ * Submits request to send MMS read report request.
+ *
+ * \par Purpose:
+ * This API is used to submit request to send MMS read report request.
+ *
+ * \par Typical use case:
+ * Submits request to send MMS read report request.
+ *
+ * \par Method of function operation:
+ * Submits a request to send MMS read report request.
+ *
+ * \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
+ */
+/*================================================================================================*/
+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.
+ *
+ * \par Purpose:
+ * This API is used to submit request to send forward MMS request.
+ *
+ * \par Typical use case:
+ * Submits request to send forward MMS request.
+ *
+ * \par Method of function operation:
+ * Submits a request to send forward MMS request.
+ *
+ * \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
+ */
+/*================================================================================================*/
+int msg_mms_forward_message(msg_handle_t handle, msg_struct_t req);
+
+
+/**
+
+ * \par Description:
+ * Submits request to retrieve MMS request.
+ *
+ * \par Purpose:
+ * This API is used to submit request to retrieve MMS request.
+ *
+ * \par Typical use case:
+ * Submits request to retrieve MMS request.
+ *
+ * \par Method of function operation:
+ * Submits a request to send forward MMS request.
+ *
+ * \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
+ */
+/*================================================================================================*/
+int msg_mms_retrieve_message(msg_handle_t handle, msg_struct_t req);
+
+
+/* reject_msg_support */
+/**
+
+ * \par Description:
+ * Submits request to reject MMS message.
+ *
+ * \par Purpose:
+ * This API is used to submit request to reject MMS message.
+ *
+ * \par Typical use case:
+ * Submits request to reject MMS message.
+ *
+ * \par Method of function operation:
+ * Submits a request to send forward reject MMS message.
+ *
+ * \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
+ */
+/*================================================================================================*/
+int msg_mms_reject_message(msg_handle_t handle, msg_struct_t req);
+
+/**
+ *     @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // MAPI_TRANSPORT_H
+
diff --git a/include/mapi/msg_transport_types.h b/include/mapi/msg_transport_types.h
new file mode 100755 (executable)
index 0000000..6188fdd
--- /dev/null
@@ -0,0 +1,136 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_
+#define MSG_TRANSPORT_TYPES_H_
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+
+#include "msg_types.h"
+#include "msg_storage_types.h"
+
+
+/*==================================================================================================
+                                    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
+ */
+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
+ */
+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
+ */
+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
+ */
+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
+ */
+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_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
+ */
+typedef void (*msg_syncml_msg_operation_cb)(msg_handle_t handle, int msgId, int extId, void *user_param);
+
+
+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);
+
+
+typedef void (*msg_cb_incoming_cb)(msg_handle_t handle, msg_struct_t msg, void *user_param);
+
+#endif /* MSG_TRANSPORT_TYPES_H_ */
diff --git a/include/mapi/msg_types.h b/include/mapi/msg_types.h
new file mode 100755 (executable)
index 0000000..e65be2a
--- /dev/null
@@ -0,0 +1,1660 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 MSG_TYPES_H_
+
+/*==================================================================================================
+                                    DEFINES
+==================================================================================================*/
+
+#define DEPRECATED __attribute__((deprecated))
+
+#ifndef EXPORT_API
+#define EXPORT_API __attribute__ ((visibility("default")))
+#endif
+
+#define MAX_TO_ADDRESS_CNT             10
+#define MAX_PHONE_NUMBER_LEN   20
+#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                             100
+#define MAX_WAPPUSH_CONTENT_TYPE_LEN   100
+#define MAX_WAPPUSH_HREF_LEN                   300
+#define MAX_WAPPUSH_CONTENTS_LEN               2048
+
+#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
+
+#define MAX_SEGMENT_NUM                        15
+
+/**
+ *     @brief  Defines the 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  Defines the maximum file name length
+ */
+#define        MSG_FILENAME_LEN_MAX    1024
+
+/**
+ *     @brief  Defines the maximum message id length
+ */
+#define        MSG_MSG_ID_LEN                  100
+
+/**
+ *     @brief  Defines the maximum in transition id length
+ */
+#define MAX_SMIL_TRANSIN_ID            100
+
+/**
+ *     @brief  Defines the maximum out transition id length
+ */
+#define MAX_SMIL_TRANSOUT_ID   100
+
+/**
+ *     @brief  Defines the maximum region id length
+ */
+#define        MAX_SMIL_REGION_ID              151
+
+/**
+ *     @brief  Defines the maximum transition id length
+ */
+#define MAX_SMIL_TRANSITION_ID         151
+
+/**
+ *     @brief  Defines the maximum meta id length
+ */
+#define MAX_SMIL_META_ID               151
+
+/**
+ *     @brief  Defines the maximum meta name length
+ */
+#define MAX_SMIL_META_NAME             100
+
+/**
+ *     @brief  Defines the maximum meta content length
+ */
+#define MAX_SMIL_META_CONTENT          255
+
+/**
+ *     @brief  Defines the maximum fit size
+ */
+#define        MAX_SMIL_FIT_SIZE               31
+
+/**
+ *     @brief  Defines the maximum pages in a MMS
+ */
+#define        MMS_PAGE_MAX                    20
+
+/**
+ *     @brief  Defines the maximum media in a MMS
+ */
+#define        MMS_MEDIA_MAX                   60
+
+/**
+ *     @brief  Defines the maximum alternate text length
+ */
+#define        MAX_SMIL_ALT_LEN                255
+
+
+//font size
+/**
+ *     @brief  Defines the small font size
+ */
+#define        MMS_SMIL_FONT_SIZE_SMALL                24
+
+/**
+ *     @brief  Defines the normal font size
+ */
+#define        MMS_SMIL_FONT_SIZE_NORMAL               30
+
+/**
+ *     @brief  Defines the large font size
+ */
+#define        MMS_SMIL_FONT_SIZE_LARGE                36
+
+#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
+
+#define MAX_MMS_JAVA_APPID_LEN 32
+
+#define CONV_THUMB_WIDTH       250
+#define CONV_THUMB_HEIGHT 170
+
+#define MMS_TR_ID_LEN          40
+#define MMS_MSG_ID_LEN         40
+#define MMS_LOCATION_LEN       100
+
+#define MAX_MMS_TEXT_LEN               2000
+/*==================================================================================================
+                                         TYPES
+==================================================================================================*/
+
+typedef struct opq_msg_svc_s *                 msg_handle_t;
+typedef struct opq_struct_s *                          msg_struct_t;
+
+
+typedef struct msg_list_handle *msg_list_handle_t;
+
+
+typedef struct {
+       int                                     nCount;                         /**< Indicates the count of msg_struct_t. */
+       msg_struct_t            *msg_struct_info;       /**< Indicates the msg_struct_t information list. */
+}msg_struct_list_s;
+
+
+/**
+ *     @brief  Represents a messsage ID.
+ */
+typedef unsigned int msg_message_id_t;
+
+
+/**
+ *     @brief  Represents a 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
+ */
+typedef char msg_folder_id_t;
+
+
+/**
+ *     @brief  Represents a 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.
+ */
+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.
+ */
+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.
+ */
+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.
+ */
+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.
+ */
+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.
+ */
+typedef unsigned char msg_encode_type_t;
+
+
+/**
+ *     @brief  Represents an 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.
+*/
+typedef unsigned char msg_push_action_t;
+
+
+/**
+\brief Represents SyncML Message Type.
+*/
+typedef unsigned short msg_syncml_message_type_t;
+
+
+/**
+ *     @brief  Represents a Contact ID.
+ */
+typedef unsigned int msg_contact_id_t;
+
+
+/**
+  *  @brief    Represents a Report Type.
+ *     The values for this type SHOULD be in _MSG_REPORT_TYPE_E
+  */
+typedef int msg_report_type_t;
+
+
+/**
+  *  @brief    Represents a Delivery Report Status.
+ *     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
+ */
+typedef int msg_read_report_status_t;
+
+
+/**
+ *     @brief  Represents a Message Type.
+ *     The values for this type SHOULD be in _MSG_MESSAGE_TYPE_E
+*/
+typedef unsigned short msg_message_type_t;
+
+/**
+ *     @brief  Represents a Message Backup Type.
+ *     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
+ */
+typedef unsigned int msg_thread_id_t;
+
+// filter
+/**
+ *     @brief  Represents a 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.
+ */
+typedef unsigned char msg_filter_type_t;
+
+
+
+/*==================================================================================================
+                                         ENUMS
+==================================================================================================*/
+
+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_CONV_INFO = 0x0400,
+       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_PUSH_CONFIG_INFO = 0x4700,                           /**< Indicates the MSG_STRUCT_PUSH_CONFIG_INFO */
+       MSG_STRUCT_CB_MSG = 0x4800,                                             /**< Indicates the MSG_STRUCT_CB_MSG */
+};
+
+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,
+};
+
+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 the filter. */
+       MSG_FILTER_ACTIVE_BOOL,                                 /**< Indicates the activation of the filter. */
+};
+
+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_PROTECTED_BOOL               /**< Indicates whether thread includes protected messages. */
+};
+
+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*/
+};
+
+enum _MSG_STRUCT_SETTING_SMSC_OPT_E {
+       MSG_SMSC_SELECTED_ID_INT = MSG_STRUCT_SETTING_SMSC_OPT+1,
+       MSG_SMSC_LIST_STRUCT
+};
+
+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*/
+};
+
+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_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 */
+};
+
+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. */
+};
+
+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 */
+};
+
+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 */
+};
+
+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. */
+};
+
+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. */
+};
+
+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 */
+};
+
+enum _MSG_STRUCT_VOICE_MSG_OPT_E {
+       MSG_VOICEMSG_ADDRESS_STR = MSG_STRUCT_SETTING_VOICE_MSG_OPT+1,          /**< Indicates the address for voice message. */
+};
+
+enum _MSG_STRUCT_MSGSISE_OPT_E {
+       MSG_MESSAGE_SIZE_INT = MSG_STRUCT_SETTING_MSGSIZE_OPT+1,                /**< Indicates the message size */
+};
+
+//MSG_MMS_DATA
+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
+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 */
+};
+
+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
+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 */
+};
+
+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 */
+};
+
+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 */
+};
+
+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 */
+};
+
+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 */
+};
+
+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 */
+};
+
+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 */
+};
+
+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 */
+};
+
+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 */
+};
+
+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. */
+};
+
+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 */
+};
+
+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 */
+};
+
+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. */
+};
+
+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,
+};
+
+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 */
+};
+
+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 */
+};
+
+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 */
+};
+
+enum MSG_SMS_SENDOPT_E {
+       MSG_SMS_SENDOPT_REPLYPATH_BOOL = MSG_STRUCT_SMS_SENDOPT+1,              /**< Indicates whether reply path is set */
+};
+
+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 */
+};
+
+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,
+};
+
+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*/
+};
+
+enum MSG_PUSH_CONFIG_INFO_E {
+       MSG_PUSH_CONFIG_CONTENT_TYPE_STR = MSG_STRUCT_PUSH_CONFIG_INFO+1,
+       MSG_PUSH_CONFIG_APPLICATON_ID_STR,
+       MSG_PUSH_CONFIG_PACKAGE_NAME_STR,
+       MSG_PUSH_CONFIG_LAUNCH_BOOL,
+};
+
+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,
+       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  Represents 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
+{
+       MSG_CLASS_0 = 0,                /**< Immediately presented on the recipient device display */
+       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,
+};
+
+/**
+ *     @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.
+ */
+enum _MSG_MESSAGE_TYPE_E
+{
+       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_ETWS_PRIMARY,              /** < CB - ETWS Primary Notification */
+       MSG_TYPE_SMS_ETWS_SECONDARY,    /** < CB - ETWS Secondary Notification */
+};
+
+/**
+ *     @brief  Represents 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,
+       MSG_BACKUP_TYPE_SMS,
+       MSG_BACKUP_TYPE_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.
+ */
+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 */
+
+       /* 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,
+       /* 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,
+       /* 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,
+       /* End Plugin Errors */
+
+       MSG_ERR_MESSAGE_COUNT_FULL = -53,
+       MSG_ERR_READREPORT_NOT_REQUESTED = -54,
+       MSG_ERR_READREPORT_ALEADY_SENT = -55,
+
+       MSG_ERR_FILTER_DUPLICATED = -56,                                /**< Filter duplicate error */
+       MSG_ERR_SECURITY_ERROR = -57,
+       MSG_ERR_NO_SIM = -58,
+       MSG_ERR_SERVER_NOT_READY= -59,
+};
+
+
+/**
+ *     @brief  Represents the values of a message priority. \n
+ *     This enum is used as the value of msg_priority_type_t.
+ */
+enum _MSG_PRIORITY_TYPE_E
+{
+       MSG_MESSAGE_PRIORITY_LOW,               /**< Low priority */
+       MSG_MESSAGE_PRIORITY_NORMAL,    /**< Normal priority */
+       MSG_MESSAGE_PRIORITY_HIGH,              /**< High priority */
+};
+
+
+/**
+ *     @brief  Represents 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 */
+};
+
+
+/**
+ *     @brief  Represents the values of an address type. \n
+ *     This enum is used as the value of msg_address_type_t.
+*/
+enum _MSG_ADDRESS_TYPE_E
+{
+       MSG_ADDRESS_TYPE_UNKNOWN = 0,   /**< The address type is unknown. */
+       MSG_ADDRESS_TYPE_PLMN,                  /**< The address type is for a phone number like +1012345678. */
+       MSG_ADDRESS_TYPE_EMAIL,                 /**< The address type is for an email address like abc@example.email. */
+};
+
+
+/**
+ *     @brief  Represents 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". */
+};
+
+
+/**
+ *     @brief  Represents the values of a direction type. \n
+ *     This enum is used as the value of msg_direction_type_t.
+ */
+enum _MSG_DIRECTION_TYPE_E
+{
+       MSG_DIRECTION_TYPE_MO = 0,              /**< The direction type is for mobile originated */
+       MSG_DIRECTION_TYPE_MT,                  /**< The direction type is for mobile terminated */
+};
+
+
+/**
+ *     @brief  Represents 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_ABNORMAL, /**< The string encoding type is GSM7BIT, but abnormal character included */
+};
+
+
+/**
+ *     @brief  Represents 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,
+
+       // SL Action
+       MSG_PUSH_SL_ACTION_EXECUTE_LOW,
+       MSG_PUSH_SL_ACTION_EXECUTE_HIGH,
+       MSG_PUSH_SL_ACTION_CACHE,
+};
+
+
+/**
+ *     @brief  Represents 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
+ {
+       DM_WBXML,                                       /** < DM WBXML SyncML Message */
+       DM_XML,                                         /** < DM XML SyncML Message */
+       DM_NOTIFICATION,                        /** < DM Notification SyncML Message */
+
+       DS_NOTIFICATION,                        /** < DS Notification SyncML Message */
+       DS_WBXML,                                       /** < DS WBXML SyncML Message */
+
+       CP_XML,                                         /** < CP XML SyncML Message */
+       CP_WBXML,                                       /** < CP WBXML SyncML Message */
+
+       OTHERS,                                         /** < Unknown SyncML Message */
+ };
+
+
+/**
+ *     @brief  Represents 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_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_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 */
+ };
+
+
+/**
+ *     @brief  Represents 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 */
+ };
+
+/**
+ *     @brief  Represents 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 */
+
+ };
+
+// filter
+/**
+ *     @brief  Represents 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 */
+};
+
+
+// mms
+
+/**
+ *     @brief  Represents the values of a mime type.
+ */
+typedef enum   _MimeType
+{
+       // 0
+       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 */
+
+       // 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_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 */
+
+       // 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  */
+
+       //85
+       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  */
+
+       // 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  */
+
+       // 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  */
+
+       // 119
+       MIME_IMAGE_X_BMP                                                                                = 0x3200, /**< Indicates the image x bmp type  */
+
+       // 120
+       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  */
+
+       // 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  */
+
+       // 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  */
+
+       // 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  */
+
+} MimeType;
+
+/**
+ *     @brief  Represents the values of a DRM type.
+ */
+//#ifdef __SUPPORT_DRM__
+typedef enum
+{
+       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
+}MsgDrmType;
+//#endif
+
+/**
+ *     @brief  Represents the values of a SMIL region type.
+ */
+typedef enum _REGION_FIT_TYPE_T
+{
+       MMSUI_IMAGE_REGION_FIT_HIDDEN,   /**< Indicates the hidden fit type */
+       MMSUI_IMAGE_REGION_FIT_MEET,     /**< Indicates the meet fit type */
+}REGION_FIT_TYPE_T;
+
+
+/**
+ *     @brief  Represents 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 */
+}MmsSmilMediaType;
+
+/**
+ *     @brief  Represents 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_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_ELLIPSEWIPE  = 11 /**< Indicates the ellipse wipe transition */
+}MmsSmilTransType;
+
+/**
+ *     @brief  Represents 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_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 */
+}MmsSmilTransSubType;
+
+/**
+ *     @brief  Represents 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_UNDERLINE = 4 /**< Indicates the font type underline */
+}MmsSmilFontType;
+
+/**
+ *     @brief  Represents 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
+} MmsTextDirection;
+
+/**
+ *     @brief  Represents 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
+} MmsRecvReadReportSendStatus ;
+
+
+// setting
+
+/**
+ *     @brief  Represents 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 */
+};
+
+
+/**
+ *     @brief  Represents 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 */
+};
+
+
+/**
+ *     @brief  Represents 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,
+};
+
+
+/**
+ *     @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.
+ */
+enum _MSG_SMS_SAVE_STORAGE_E
+{
+       MSG_SMS_SAVE_STORAGE_SIM,
+       MSG_SMS_SAVE_STORAGE_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.
+ */
+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 */
+};
+
+
+/**
+ *     @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.
+ */
+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 */
+};
+
+
+/**
+ *     @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.
+ */
+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 */
+};
+
+
+/**
+ *     @brief  Represents the values of the Validity Period for SMS center. \n
+ *     This enum is used as the value of MSG_VAL_PERIOD_T.
+ */
+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,
+};
+
+
+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,
+};
+
+
+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
+};
+
+
+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                                   /**< */
+};
+
+
+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
+};
+
+
+enum _MSG_MMS_CREATION_MODE_E
+{
+       MSG_CREATION_MODE_RESTRICTED,
+       MSG_CREATION_MODE_WARNING,
+       MSG_CREATION_MODE_FREE
+};
+
+
+/**
+ *     @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.
+ */
+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 */
+};
+
+
+/**
+ *     @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.
+ */
+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 */
+};
+
+
+/**
+ *     @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.
+ */
+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 */
+};
+
+
+/**
+ *     @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.
+ */
+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 */
+};
+
+
+/**
+ *     @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.
+ */
+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 */
+};
+
+
+/**
+ *     @brief  Represents 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,
+};
+
+
+#endif /* MSG_TYPES_H_ */
diff --git a/include/msg_helper/MsgHelper.h b/include/msg_helper/MsgHelper.h
new file mode 100755 (executable)
index 0000000..d6f83a2
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_NORMAL_SOUND_START "NORMAL_SOUND_START"
+#define MSG_EMERGENCY_SOUND_START      "EMERGENCY_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(bool isEmergency);
+void MsgSoundPlayStop();
+int MsgSoundPlayMelody(char *pMsgToneFilePath, bool bIncreasing);
+void MsgSoundPlayVibration(bool isOnCall);
+void MsgSoundPlayDtmf();
+
+//Sensor FW wrapper.
+msg_error_t MsgSensorConnect();
+void MsgSensorDisconnect();
+msg_error_t MsgRegSensorCB(msg_sensor_cb cb);
+
+#endif // MSG_HELPER_H
diff --git a/include/proxy/MsgHandle.h b/include/proxy/MsgHandle.h
new file mode 100755 (executable)
index 0000000..09092e9
--- /dev/null
@@ -0,0 +1,166 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_HANDLE_H
+
+#ifndef __cplusplus
+#error "This is a C++ header file; it requires C++ to compile."
+#endif
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgStorageTypes.h"
+#include "MsgTransportTypes.h"
+#include "MsgFilterTypes.h"
+#include "MsgSettingTypes.h"
+#include "MsgCmdTypes.h"
+#include "MsgInternalTypes.h"
+#include "MsgIpcSocket.h"
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+
+class MsgHandle
+{
+       public:
+               MsgHandle();
+               virtual ~MsgHandle();
+
+               // Control
+               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 operateSyncMLMessage(msg_message_id_t msgId);
+
+               // Storage
+               int addMessage(MSG_MESSAGE_HIDDEN_S *pMsg, const MSG_SENDINGOPT_S *pSendOpt);
+               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 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);
+               msg_error_t deleteFolder(msg_folder_id_t FolderId);
+               msg_error_t getFolderList(msg_struct_list_s *pFolderList);
+
+               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, 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);
+
+               msg_error_t getAddressList(const msg_thread_id_t threadId, msg_struct_list_s *pAddrList);
+
+               // Filter
+               msg_error_t addFilter(const MSG_FILTER_S *pFilter);
+               msg_error_t updateFilter(const MSG_FILTER_S *pFilter);
+               msg_error_t deleteFilter(msg_filter_id_t FilterId);
+               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);
+               msg_error_t setSMSCOption(msg_struct_t msg_struct);
+               msg_error_t getCBOption(msg_struct_t msg_struct);
+               msg_error_t setCBOption(msg_struct_t msg_struct);
+               msg_error_t getSmsSendOpt(msg_struct_t msg_struct);
+               msg_error_t setSmsSendOpt(msg_struct_t msg_struct);
+               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 getPushMsgOpt(msg_struct_t msg_struct);
+               msg_error_t setPushMsgOpt(msg_struct_t msg_struct);
+               msg_error_t getVoiceMsgOpt(msg_struct_t msg_struct);
+               msg_error_t setVoiceMsgOpt(msg_struct_t msg_struct);
+               msg_error_t getGeneralOpt(msg_struct_t msg_struct);
+               msg_error_t setGeneralOpt(msg_struct_t msg_struct);
+               msg_error_t getMsgSizeOpt(msg_struct_t msg_struct);
+               msg_error_t setMsgSizeOpt(msg_struct_t msg_struct);
+
+               //Backup & Restore
+               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_struct_list_s *report_list);
+               msg_error_t getThreadIdByAddress(msg_struct_list_s *pAddrList, 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);
+
+               // 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);
+
+       private:
+               void connectSocket();
+               void    disconnectSocket();
+               void write(const char *pCmd, int CmdSize, char **ppEvent);
+               void read(char **ppEvent);
+               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 mCookie[MAX_COOKIE_LEN];
+
+               MsgIpcClientSocket mClientSock;
+};
+
+#endif // MSG_HANDLE_H
+
diff --git a/include/proxy/MsgProxyListener.h b/include/proxy/MsgProxyListener.h
new file mode 100755 (executable)
index 0000000..9f64ee6
--- /dev/null
@@ -0,0 +1,175 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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__
+#define __MSG_PROXY_LISTENER_H__
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgIpcSocket.h"
+#include "MsgTypes.h"
+#include "MsgMutex.h"
+#include "MsgHandle.h"
+
+#include <map>
+#include <list>
+#include <glib.h>
+
+
+/*==================================================================================================
+                                         VARIABLES
+==================================================================================================*/
+typedef struct
+{
+       MsgHandle* hAddr;
+       msg_sent_status_cb pfSentStatusCB;
+       void* userParam;
+} MSG_SENT_STATUS_CB_ITEM_S;
+
+typedef struct
+{
+       MsgHandle* hAddr;
+       msg_sms_incoming_cb pfIncomingCB;
+       int port;
+       void* userParam;
+} MSG_INCOMING_CB_ITEM_S;
+
+typedef struct
+{
+       MsgHandle* hAddr;
+       msg_mms_conf_msg_incoming_cb pfMMSConfIncomingCB;
+       char appId[MAX_MMS_JAVA_APPID_LEN+1];
+       void* userParam;
+} MSG_MMS_CONF_INCOMING_CB_ITEM_S;
+
+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;
+
+typedef struct
+{
+       MsgHandle* hAddr;
+       msg_lbs_msg_incoming_cb pfLBSMsgIncoming;
+       void* userParam;
+} MSG_LBS_INCOMING_CB_ITEM_S;
+
+typedef struct
+{
+       MsgHandle* hAddr;
+       msg_syncml_msg_operation_cb pfSyncMLOperationCB;
+       void* userParam;
+} MSG_SYNCML_OPERATION_CB_ITEM_S;
+
+typedef struct
+{
+       MsgHandle* hAddr;
+       msg_storage_change_cb pfStorageChangeCB;
+       void* userParam;
+} MSG_STORAGE_CHANGE_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;
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class MsgProxyListener
+{
+public:
+       static MsgProxyListener* instance();
+
+       void start();
+       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);
+
+       void clearListOfClosedHandle(MsgHandle* pMsgHandle);
+
+       void handleEvent(const MSG_EVENT_S* ptr);
+
+       int getRemoteFd();
+       int readFromSocket(char** buf, unsigned int* len);
+#ifdef CHECK_SENT_STATUS_CALLBACK
+       int getSentStatusCbCnt();
+#endif
+
+private:
+       MsgProxyListener();
+       ~MsgProxyListener();
+
+       static MsgProxyListener* pInstance;
+
+       unsigned int running;
+
+       MsgIpcClientSocket cliSock;
+
+       Mutex mx;
+       CndVar cv;
+
+       MsgSentStatusCBList sentStatusCBList;
+       MsgNewMessageCBList newMessageCBList;
+       MsgNewMMSConfMessageCBList newMMSConfMessageCBList;
+       MsgNewPushMessageCBList newPushMessageCBList;
+       MsgNewCBMessageCBList newCBMessageCBList;
+       MsgNewSyncMLMessageCBList newSyncMLMessageCBList;
+       MsgNewLBSMessageCBList newLBSMessageCBList;
+       MsgOperationSyncMLMessageCBList operationSyncMLMessageCBList;
+       MsgStorageChangeCBList storageChangeCBList;
+
+       GIOChannel *channel;
+       guint eventSourceId;
+};
+
+#endif // __MSG_PROXY_LISTENER_H__
+
diff --git a/include/utils/MsgContact.h b/include/utils/MsgContact.h
new file mode 100755 (executable)
index 0000000..f6b759f
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_CONTACT_H
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgStorageTypes.h"
+#include "MsgInternalTypes.h"
+
+
+typedef void (*MsgContactChangeCB)();
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+msg_error_t MsgOpenContactSvc();
+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);
+
+void MsgSyncContact();
+
+bool MsgInsertContact(MSG_CONTACT_INFO_S *pContactInfo, const char *pNumber);
+bool MsgUpdateContact(int index, int type);
+bool MsgDeleteContact(int index);
+
+int MsgGetContactNameOrder();
+
+void MsgAddPhoneLog(const MSG_MESSAGE_INFO_S *pMsgInfo);
+void MsgDeletePhoneLog(msg_message_id_t msgId);
+
+int MsgContactSVCBeginTrans();
+int MsgContactSVCEndTrans(bool bSuccess);
+
+
+#endif //MSG_CONTACT_H
+
diff --git a/include/utils/MsgDebug.h b/include/utils/MsgDebug.h
new file mode 100755 (executable)
index 0000000..82555af
--- /dev/null
@@ -0,0 +1,230 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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__
+#define __MSG_DEBUG_H__
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <sys/types.h>
+#include <unistd.h>
+#include <string.h>
+#include <sys/time.h>
+#include <time.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
+
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+int get_tid();
+
+
+#if defined(DLOG_ENABLE)
+
+#define MSG_FATAL(fmt, ...) \
+       do \
+       {\
+               SLOGD(" ERROR << " fmt " >>\n\n", ##__VA_ARGS__);\
+       } while (0)
+
+#define MSG_DEBUG(fmt, ...)\
+       do\
+       {\
+               SLOGD(fmt"\n\n", ##__VA_ARGS__);\
+       } while (0)
+
+#define MSG_BEGIN() \
+       do\
+    {\
+               SLOGD(" BEGIN >>>> \n\n");\
+    } while( 0 )
+
+#define MSG_END() \
+       do\
+    {\
+               SLOGD(" END   <<<<  \n\n");\
+    } \
+    while( 0 )
+
+#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);       \
+       } while (0)
+
+#define MSG_PROFILE_END(pfid) \
+       unsigned int __prf_l2_##pfid = __LINE__;\
+       do { \
+               gettimeofday(&__prf_2_##pfid, 0);\
+               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,                \
+               __FUNCTION__, \
+               __prf_l1_##pfid,                                         \
+               __prf_l2_##pfid,                                         \
+               (unsigned int)(__ds),                                    \
+               (unsigned int)(__dm));                                   \
+       } while (0)
+
+
+#define MSG_SMS_VLD_INFO(fmt, ...)\
+       do\
+       {\
+               SLOG(LOG_DEBUG, MSG_SMS_VALID_TAG, "[SMS INFO]%s, "fmt"\n", __TIMESTAMP__, ##__VA_ARGS__);\
+       } while (0)
+
+#define MSG_SMS_VLD_TXT(fmt, ...)\
+       do\
+       {\
+               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)
+
+#elif defined(LOG_ENABLE)
+
+#define MSG_FATAL(fmt, ...) \
+       do \
+       {\
+               printf("\n[%d] [MSGFW: %s: %s(): %d] *FAILED* << " fmt" >>\n", get_tid(), rindex(__FILE__, '/')+1,  __FUNCTION__, __LINE__,  ##__VA_ARGS__);\
+       } while (0)
+
+#define MSG_DEBUG(fmt, ...) \
+       do\
+       {\
+               printf("\n[%d] [MSGFW: %s: %s(): %d] " fmt"\n", get_tid(), rindex(__FILE__, '/')+1, __FUNCTION__, __LINE__, ##__VA_ARGS__);\
+       } while (0)
+
+#define MSG_BEGIN() \
+       do\
+    {\
+        printf("\n[%d] BEGIN >>>> %s() at [MSGFW: %s: %d]\n", get_tid(),__FUNCTION__, rindex(__FILE__, '/')+1,  __LINE__ );\
+    } while( 0 )
+
+#define MSG_END() \
+       do\
+    {\
+        printf("\n[%d] END   <<<< %s() at [MSGFW: %s: %d]\n", get_tid(), __FUNCTION__, rindex(__FILE__, '/')+1,  __LINE__); \
+    } \
+    while( 0 )
+
+#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);       \
+       } while (0)
+
+#define MSG_PROFILE_END(pfid) \
+       unsigned int __prf_l2_##pfid = __LINE__;\
+       do { \
+               gettimeofday(&__prf_2_##pfid, 0);\
+               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; } \
+               printf("**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));                                   \
+       } while (0)
+
+#else
+
+#define MSG_FATAL(fmt, ...)
+#define MSG_DEBUG(fmt, ...)
+#define MSG_BEGIN()
+#define MSG_END()
+
+#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);       \
+       } while (0)
+
+#define MSG_PROFILE_END(pfid) \
+       unsigned int __prf_l2_##pfid = __LINE__;\
+       do { \
+               gettimeofday(&__prf_2_##pfid, 0);\
+               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; } \
+               printf("**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));                                   \
+       } while (0)
+
+#endif
+
+const char * MsgDbgCmdStr(MSG_CMD_TYPE_T cmdType);
+const char * MsgDbgEvtStr(MSG_EVENT_TYPE_T evtType);
+
+#endif //__MSG_DEBUG_H__
+
diff --git a/include/utils/MsgDrmWrapper.h b/include/utils/MsgDrmWrapper.h
new file mode 100755 (executable)
index 0000000..624d669
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_
+#define __MSG_DRM_WRAPPER_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+       MSG_MODE_FILE,
+       MSG_MODE_STREAM
+} MSG_DRM_OPENMODE;
+
+typedef        enum {
+       MSG_DRM_NONE = 0,
+       MSG_DRM_FORWARD_LOCK,
+       MSG_DRM_COMBINED_DELIVERY,
+       MSG_DRM_SEPARATE_DELIVERY
+} MSG_DRM_TYPE;
+
+
+bool MsgDrmRegisterFile(MSG_DRM_OPENMODE eMode, char *pBuffer, int nSize);
+bool MsgDrmUnregisterFile(char *szFilename);
+bool MsgDrmIsDrmFile(const char *szFilePath);
+bool MsgDrmGetMimeTypeEx(const char *szFileName, char *szMimeType, int nMimeTypeLen);
+bool MsgDrmGetContentID(const char *szFileName, char *szContentID, int nContentIDLen);
+bool MsgDrmGetDrmType(const char *szFileName, MSG_DRM_TYPE *eDRMType);
+bool MsgDrmConvertDmtoDcfType(char *inputFile, char *outputFile);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/include/utils/MsgException.h b/include/utils/MsgException.h
new file mode 100755 (executable)
index 0000000..aca73fb
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_EXCEPTION_H
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <stdexcept>
+#include <string>
+
+using namespace std;
+
+
+/*==================================================================================================
+                                         DEFINES
+==================================================================================================*/
+#define THROW(errCode, debugFmt,...) \
+do {\
+       char __debugBuf[256];\
+       snprintf(__debugBuf, 256, debugFmt, ##__VA_ARGS__);\
+       MsgException e(errCode, __debugBuf);\
+       MSG_FATAL("%s [%d]", e.what(), e.errorCode());\
+    throw e; \
+} while(0)
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class MsgException : public runtime_error //public exception
+{
+public:
+       MsgException(int errCode, const string& msg = "")
+           : runtime_error( errorStrings[errCode] + " : " +  msg), eCode(errCode)
+       {}
+
+       enum
+       {
+               SUCCESS = 0,
+
+               INVALID_PARAM,
+               INVALID_RESULT,
+               SELECT_ERROR,
+               IPC_ERROR,
+               OUT_OF_RANGE = 5,
+
+               SMS_PLG_ERROR,
+               MMS_PLG_ERROR,
+               PLUGIN_ERROR,
+               SENT_STATUS_ERROR,
+               INCOMING_MSG_ERROR = 10,
+
+               FILE_ERROR,
+               SECURITY_ERROR,
+               SERVER_READY_ERROR = 13,
+
+               // dont erase NUM_ERRORS. place a new error code in ahead of NUM_ERRORS
+               NUM_ERRORS
+       };
+
+       int errorCode() { return eCode; }
+
+private:
+       static string errorStrings[NUM_ERRORS];
+       int eCode;
+};
+
+#endif //#ifndef __MSG_EXCEPTION_H__
+
+
diff --git a/include/utils/MsgGconfWrapper.h b/include/utils/MsgGconfWrapper.h
new file mode 100755 (executable)
index 0000000..1504063
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_GCONF_WRAPPER_H
+
+//#define USE_GCONF
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgInternalTypes.h"
+
+#ifdef USE_GCONF
+#include <gconf/gconf-client.h>
+#include <glib.h>
+#else
+#include <vconf.h>
+#endif
+
+/*==================================================================================================
+                                         STRUCTURES
+==================================================================================================*/
+#ifdef USE_GCONF
+typedef struct _MSG_GOBJECT_CLIENT_S
+{
+       GObject* object;
+}MSG_GOBJECT_CLIENT_S;
+#endif
+
+
+typedef void (*_vconf_change_cb)(keynode_t *key, void* data);
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+msg_error_t    MsgSettingSetString(const char *pKey, const char *pSetValue);
+msg_error_t    MsgSettingSetInt(const char *pKey, int nSetValue);
+msg_error_t    MsgSettingSetBool(const char *pKey, bool bSetValue);
+
+char*                  MsgSettingGetString(const char *pKey);
+int                            MsgSettingGetInt(const char *pKey);
+int                            MsgSettingGetBool(const char *pKey, bool *pVal);
+
+void   MsgChangePmState();
+msg_error_t    MsgSettingHandleNewMsg(int SmsCnt, int MmsCnt);
+msg_error_t    MsgSettingSetIndicator(int SmsCnt, int MmsCnt);
+
+bool   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
diff --git a/include/utils/MsgIpcSocket.h b/include/utils/MsgIpcSocket.h
new file mode 100755 (executable)
index 0000000..72368a8
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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__
+#define __IPCSocket_H__
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <sys/types.h>
+#include <map>
+
+#include "MsgTypes.h"
+#include "MsgCppTypes.h"
+
+
+/*==================================================================================================
+                                         DEFINES
+==================================================================================================*/
+#define MSG_MAX_IPC_SIZE 50000 // 50 * 1000 = sizeof(msg common info) * max message count
+#define MAX_NUM_IPC_CLIENT 10
+
+#define MSG_SOCKET_PATH "/tmp/.msgfw_socket"
+
+#define CUSTOM_SOCKET_ERROR            -1
+#define CUSTOM_SOCKET_BACKLOG  10
+
+
+/*==================================================================================================
+                                         ENUM
+==================================================================================================*/
+typedef enum
+{
+       CLOSE_CONNECTION_BY_SIGNAL = 0,
+       CLOSE_CONNECTION_BY_USER = -17,
+} IPC_CONTROL_E;
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class MsgIpcClientSocket
+{
+public:
+       MsgIpcClientSocket();
+//     ~MsgIpcClientSocket();
+
+       int     maxFd() { return (maxfd+1); }
+       fd_set  fdSet() { return fds; }
+       int     fd() { return sockfd; }
+
+       msg_error_t connect(const char *path);
+       msg_error_t close();
+       /* write msg to ipc server */
+       int     write(const char* buf, unsigned int len);
+       /* read msg from ipc server */
+       int     read(char** buf, unsigned int* len);
+       void    addfd(int fd);
+       int             getRemoteFd() {return remotefd; }
+private:
+       int readn(char *buf, unsigned int len );
+       int writen (const char *buf, unsigned int len);
+
+       int sockfd, remotefd, maxfd;
+       fd_set fds;
+};
+
+
+class MsgIpcServerSocket
+{
+public:
+       MsgIpcServerSocket();
+       ~MsgIpcServerSocket() { mapFds.clear(); }
+       int     maxFd() { return (maxfd+1); }
+       fd_set  fdSet() { return fds; }
+       int     fd() { return sockfd; }
+
+       msg_error_t open(const char *path);
+       msg_error_t accept();
+       void            close(int fd);
+
+       /* 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, unsigned int len);
+       void    addfd(int fd);
+       void    setSockfd(int fd) { sockfd = fd; }
+
+private:
+       int readn(int fd, char *buf, unsigned int len );
+       int writen (int fd, const char *buf, unsigned int len);
+
+       /* server socket fd */
+       int sockfd;
+
+       /* information about IPC clients, it is used for select() */
+       fd_set                          fds;
+       int                             maxfd;
+       std::map<int, int>      mapFds;
+};
+
+#endif //__IPCSocket_H__
+
diff --git a/include/utils/MsgMemory.h b/include/utils/MsgMemory.h
new file mode 100755 (executable)
index 0000000..6e47e31
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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__
+#define __MSG_MEMORY_H__
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <stdio.h>
+#include <string.h>
+#include <sys/mman.h>
+
+
+/*==================================================================================================
+                                       DEFINES
+==================================================================================================*/
+#define GETSP() ({ unsigned int sp; asm volatile ("mov %0,sp " : "=r"(sp) ); sp;})
+#define BUF_SIZE                               256
+#define PAGE_SIZE                      (1 << 12)
+#define _ALIGN_UP(addr,size)    (((addr)+((size)-1))&(~((size)-1)))
+#define _ALIGN_DOWN(addr,size)  ((addr)&(~((size)-1)))
+#define PAGE_ALIGN(addr)        _ALIGN_DOWN(addr, PAGE_SIZE)
+
+
+/*==================================================================================================
+                                       FUNCTION PROTOTYPES
+==================================================================================================*/
+static inline void
+stack_trim(void)
+{
+       unsigned int sp;
+       char buf[BUF_SIZE];
+       FILE* file;
+       unsigned int stacktop;
+       int found = 0;
+
+       sp = GETSP();
+
+       snprintf(buf, BUF_SIZE, "/proc/%d/maps",getpid());
+       file = fopen(buf,"r");
+       while(fgets(buf, BUF_SIZE, file) != NULL) {
+               if(strstr(buf, "[stack]")){
+                       found = 1;
+                       break;
+               }
+       }
+       fclose(file);
+
+       if(found) {
+               sscanf(buf,"%x-",&stacktop);
+               if(madvise((void*)PAGE_ALIGN(stacktop), PAGE_ALIGN(sp)-stacktop, MADV_DONTNEED) < 0)
+                       perror("stack madvise fail");
+       }
+}
+
+
+void MsgReleaseMemory();
+
+
+#endif // __MSG_MEMORY_H__
+
diff --git a/include/utils/MsgMmsMessage.h b/include/utils/MsgMmsMessage.h
new file mode 100755 (executable)
index 0000000..6c4a597
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_MMS_MESSAGE_H
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#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);
+
+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);
+
+
+#endif // MSG_MMS_MESSAGE_H
diff --git a/include/utils/MsgMutex.h b/include/utils/MsgMutex.h
new file mode 100755 (executable)
index 0000000..d6c9f26
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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__
+#define __MSG_MUTEX_H__
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <iostream>
+#include <pthread.h>
+#include <sys/time.h>
+#include <time.h>
+
+using namespace std;
+
+int GetMsgReady();
+void WaitMsgReady(int sec);
+
+class Mutex
+{
+public:
+       Mutex(){ pthread_mutex_init(&m, 0); }
+       void lock(){ pthread_mutex_lock(&m); }
+       void unlock(){ pthread_mutex_unlock(&m); }
+       pthread_mutex_t* pMutex() { return &m; }
+
+private:
+       pthread_mutex_t m;
+};
+
+class MutexLocker
+{
+public:
+       MutexLocker(Mutex& mx)
+       {
+               pm = &mx;
+               pm->lock();
+       }
+
+       ~MutexLocker()
+       {
+               pm->unlock();
+       }
+
+private:
+       Mutex *pm;
+};
+
+class CndVar
+{
+public:
+       CndVar(){ pthread_cond_init(&c, 0); }
+       void wait(pthread_mutex_t* m) { pthread_cond_wait(&c, m); }
+       int timedwait(pthread_mutex_t* m, int sec)
+       {
+               struct timeval now = {0};
+               struct timespec timeout = {0};
+               gettimeofday(&now, NULL);
+               timeout.tv_sec = now.tv_sec+sec;
+               timeout.tv_nsec = now.tv_usec;
+               int retcode = pthread_cond_timedwait(&c, m, &timeout);
+               return retcode;
+       }
+       void signal(){ pthread_cond_signal(&c); }
+       void broadcast(){ pthread_cond_broadcast(&c); }
+
+private:
+       pthread_cond_t c;
+};
+
+#endif //__MUTEX_H__
+
diff --git a/include/utils/MsgNotificationWrapper.h b/include/utils/MsgNotificationWrapper.h
new file mode 100755 (executable)
index 0000000..032c5a7
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 MSG_APP_PACKAGE_NAME   "message"
+#define MSG_SYS_PACKAGE_NAME   "sys_string"
+#define NORMAL_MSG_ICON_PATH   "/usr/apps/org.tizen.message/res/icons/default/small/org.tizen.message.noti.png"
+#define VOICE_MSG_ICON_PATH            "/usr/apps/org.tizen.message/res/icons/default/small/org.tizen.message.voice.png"
+#define CB_MSG_ICON_PATH                       "/usr/apps/org.tizen.message/res/icons/default/small/org.tizen.message.noti.png"
+#define NOTI_MSG_ICON_PATH             "/usr/apps/org.tizen.message/res/icons/default/small/org.tizen.message.noti.png"
+
+#define MSG_APP_LOCALEDIR                      "/usr/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"
+#define SMS_MESSAGE_SENT                                       "Message sent"
+#define SMS_MESSAGE_SENDING_FAIL                       "Sending message failed"
+#define MESSAGE                                                "Message"
+#define NEW_MESSAGE                            "New message"
+#define NEW_MESSAGES                   "New messages"
+#define MSG_SYS_LOCALEDIR                      "/usr/share/locale"
+
+#define NOTIFICATION_PRIV_ID DEFAULT_SETTING_PATH"/notification_priv_id"
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+msg_error_t MsgInsertNoti(MSG_MESSAGE_INFO_S* pMsg);
+
+msg_error_t MsgInsertMmsReportToNoti(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S* pMsg);
+
+msg_error_t MsgRefreshNoti(bool bWithTicker);
+msg_error_t MsgCleanAndResetNoti();
+
+msg_error_t MsgInsertTicker(const char* pTickerMsg, const char* pLocaleTickerMsg);
+msg_error_t MsgInsertBadge(unsigned int unreadMsgCnt);
+
+#endif // MSG_QUICKPANEL_WRAPPER_H
diff --git a/include/utils/MsgSoundPlayer.h b/include/utils/MsgSoundPlayer.h
new file mode 100755 (executable)
index 0000000..01851fd
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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(bool isEmergency);
+void MsgSoundPlayStop();
+
+bool MsgSoundSetRepeatAlarm();
+bool MsgSoundCreateRepeatAlarm(int RepeatTime);
+int MsgSoundRepeatAlarmCB(int TimerId, void *pUserParam);
+int MsgSoundGetUnreadMsgCnt();
+void MsgSoundInitRepeatAlarm();
+
+#endif // MSG_SOUND_PLAYER_H
+
diff --git a/include/utils/MsgSpamFilter.h b/include/utils/MsgSpamFilter.h
new file mode 100755 (executable)
index 0000000..20c4861
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_SPAM_FILTER_H
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgFilterTypes.h"
+#include "MsgStorageTypes.h"
+#include "MsgInternalTypes.h"
+#include "MsgSqliteWrapper.h"
+
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+msg_error_t MsgSetFilterOperation(bool bSetFlag);
+msg_error_t MsgGetFilterOperation(bool *pSetFlag);
+
+bool MsgCheckFilter(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S *pMsgInfo);
+
+#endif // MSG_SPAM_FILTER_H
diff --git a/include/utils/MsgSqliteWrapper.h b/include/utils/MsgSqliteWrapper.h
new file mode 100755 (executable)
index 0000000..246b384
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_SQLITE_WRAPPER_H
+
+/*==================================================================================================
+                                    INCLUDE FILES
+==================================================================================================*/
+#include "MsgTypes.h"
+
+
+/*==================================================================================================
+                                    DEFINES
+==================================================================================================*/
+#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_ADDRESS_TABLE_NAME                       "MSG_ADDRESS_TABLE"
+#define MSGFW_CONVERSATION_TABLE_NAME          "MSG_CONVERSATION_TABLE"
+#define MSGFW_SIM_MSG_TABLE_NAME                               "MSG_SIM_TABLE"
+#define MSGFW_FILTER_TABLE_NAME                                        "MSG_FILTER_TABLE"
+#define MSGFW_PUSH_MSG_TABLE_NAME                      "MSG_PUSH_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"
+#define MSGFW_SMS_SENDOPT_TABLE_NAME           "MSG_SMS_SENDOPT_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 MAX_QUERY_LEN                                  3072
+#define MAX_FOLDER_NAME_LEN            20
+#define MAX_ACCOUNT_NAME_LEN   51
+
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+void   MsgReleaseMemoryDB();
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class MsgDbHandler
+{
+public:
+       MsgDbHandler();
+       ~MsgDbHandler();
+
+       msg_error_t connect();
+       msg_error_t disconnect();
+
+       bool checkTableExist(const char *pTableName);
+       msg_error_t execQuery(const char *pQuery);
+       msg_error_t getTable(const char *pQuery, int *pRowCnt);
+       void freeTable();
+       msg_error_t bindText(const char *pBindStr, 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 finalizeQuery();
+       int columnInt(int ColumnIndex);
+       const unsigned char* columnText(int ColumnIndex);
+       const void* columnBlob(int ColumnIndex);
+       msg_error_t beginTrans();
+       msg_error_t endTrans(bool Success);
+       int getColumnToInt(int RowIndex);
+       char getColumnToChar(int RowIndex);
+       void getColumnToString(int RowIndex, int Length, char *pString);
+       msg_error_t getRowId(const char *pTableName, unsigned int *pRowId);
+
+private:
+
+       char **result;
+
+};
+
+#endif // MSG_SQLITE_WRAPPER_H
+
diff --git a/include/utils/MsgTextConvert.h b/include/utils/MsgTextConvert.h
new file mode 100755 (executable)
index 0000000..8e818b7
--- /dev/null
@@ -0,0 +1,285 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_TEXT_CONVERT_H
+#define MSG_TEXT_CONVERT_H
+
+
+/*==================================================================================================
+                               INCLUDE FILES
+==================================================================================================*/
+#include <map>
+
+//#include "SmsPluginTypes.h"
+
+
+/*==================================================================================================
+                                DEFINES
+==================================================================================================*/
+#define IN
+#define OUT
+#define INOUT
+
+#define MAX_DUMP_COLUMN        16
+
+typedef unsigned short WCHAR;
+
+typedef unsigned char MSG_CHAR_TYPE_T;
+
+typedef unsigned char MSG_LANGUAGE_ID_T;
+
+
+/*==================================================================================================
+                                ENUMS
+==================================================================================================*/
+enum _MSG_CHAR_TYPE_E
+{
+       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[] =
+{
+       /* @ */
+       0x0040, 0x00A3, 0x0024, 0x00A5, 0x00E8, 0x00E9, 0x00F9, 0x00EC, 0x00F2, 0x00C7, 0x000A, 0x00D8, 0x00F8, 0x000D, 0x00C5, 0x00E5,
+       /* ï¿½ï¿½*/
+       0x0394, 0x005F, 0x03A6, 0x0393, 0x039B, 0x03A9, 0x03A0,         0x03A8, 0x03A3, 0x0398, 0x039E, 0x001B, 0x00C6, 0x00E6, 0x00DF, 0x00C9,
+       /* SP */
+       0x0020, 0x0021, 0x0022, 0x0023, 0x00A4, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F,
+       /* 0 */
+       0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F,
+       /* ï¿½ï¿½*/
+       0x00A1, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F,
+       /* P */
+       0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x00C4, 0x00D6, 0x00D1, 0x00DC, 0x00A7,
+       /* ï¿½ï¿½*/
+       0x00BF, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F,
+       /* p */
+       0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x00E4, 0x00F6, 0x00F1, 0x00FC, 0x00E0
+};
+
+
+//GSM 7 bit Default Alphabet Extension Table -> UCS2
+static const WCHAR g_GSM7BitExtToUCS2[] =
+{
+       // 0x0020 -> (SP) for invalid code
+                                                                                                                                    /* Page Break */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x000C, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
+                                                         /* ^ */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x005E, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x001B, 0x0020, 0x0020, 0x0020, 0x0020,
+                                                                                                           /* { */ /* } */                                                               /* \ */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x007B, 0x007D, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x005C,
+                                                                                                                                                             /* [ */ /* ~ */ /* ] */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x005B, 0x007E, 0x005D, 0x0020,
+       /* | */
+       0x007C, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
+                                                                     /* ï¿½ï¿½*/
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x20AC, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020
+};
+
+
+//Turkish National Language Single Shift Table -> UCS2
+static const WCHAR g_TurkishSingleToUCS2[] =
+{
+       // 0x0020 -> (SP) for invalid code
+                                                                                                                                    /* Page Break */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x000C, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
+                                                         /* ^ */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x005E, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x001B, 0x0020, 0x0020, 0x0020, 0x0020,
+                                                                                                           /* { */ /* } */                                                               /* \ */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x007B, 0x007D, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x005C,
+                                                                                                                                                             /* [ */ /* ~ */ /* ] */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x005B, 0x007E, 0x005D, 0x0020,
+       /* | */
+       0x007C, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x011E, 0x0020, 0x0130, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
+       0x0020, 0x0020, 0x0020, 0x015E, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
+                                                                     /* ï¿½ï¿½*/
+       0x0020, 0x0020, 0x0020, 0x00E7, 0x0020, 0x20AC, 0x0020, 0x011F, 0x0020, 0x0131, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
+       0x0020, 0x0020, 0x0020, 0x015F, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020
+};
+
+
+// Turkish National Language Locking Shift Table -> UCS2
+static const WCHAR g_TurkishLockingToUCS2[] =
+{
+       /* @ */
+       0x0040, 0x00A3, 0x0024, 0x00A5, 0x20AC, 0x00E9, 0x00F9, 0x00EC, 0x00F2, 0x00C7, 0x000A, 0x011E, 0x011F, 0x000D, 0x00C5, 0x00E5,
+       /* ï¿½ï¿½*/
+       0x0394, 0x005F, 0x03A6, 0x0393, 0x039B, 0x03A9, 0x03A0,         0x03A8, 0x03A3, 0x0398, 0x039E, 0x001B, 0x015E, 0x015F, 0x00DF, 0x00C9,
+       /* SP */
+       0x0020, 0x0021, 0x0022, 0x0023, 0x00A4, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F,
+       /* 0 */
+       0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F,
+       /* ï¿½ï¿½*/
+       0x0130, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F,
+       /* P */
+       0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x00C4, 0x00D6, 0x00D1, 0x00DC, 0x00A7,
+       /* c */
+       0x00E7, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F,
+       /* p */
+       0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x00E4, 0x00F6, 0x00F1, 0x00FC, 0x00E0
+};
+
+
+// Spanish National Language Single Shift Table -> UCS2
+static const WCHAR g_SpanishSingleToUCS2[] =
+{
+       // 0x0020 -> (SP) for invalid code
+                                                                                                                                    /* Page Break */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00E7, 0x000C, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
+                                                         /* ^ */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x005E, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x001B, 0x0020, 0x0020, 0x0020, 0x0020,
+                                                                                                           /* { */ /* } */                                                               /* \ */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x007B, 0x007D, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x005C,
+                                                                                                                                                             /* [ */ /* ~ */ /* ] */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x005B, 0x007E, 0x005D, 0x0020,
+       /* | */
+       0x007C, 0x00C1, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00CD, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00D3,
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00DA, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
+                                                                     /* ï¿½ï¿½*/
+       0x0020, 0x00E1, 0x0020, 0x0020, 0x0020, 0x20AC, 0x0020, 0x0020, 0x0020, 0x00ED, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00F3,
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00FA, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020
+};
+
+
+// Portuguese National Language Single Shift Table -> UCS2
+static const WCHAR g_PortuSingleToUCS2[] =
+{
+       // 0x0020 -> (SP) for invalid code
+                                                                                                                                    /* Page Break */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00EA, 0x0020, 0x0020, 0x0020, 0x00E7, 0x000C, 0x00D4, 0x00F4, 0x0020, 0x00C1, 0x00E1,
+                                                         /* ^ */
+       0x0020, 0x0020, 0x03A6, 0x0393, 0x005E, 0x03A9, 0x03A0, 0x03A8, 0x03A3, 0x0398, 0x0020, 0x001B, 0x0020, 0x0020, 0x0020, 0x00CA,
+                                                                                                           /* { */ /* } */                                                               /* \ */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x007B, 0x007D, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x005C,
+                                                                                                                                                             /* [ */ /* ~ */ /* ] */
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x005B, 0x007E, 0x005D, 0x0020,
+       /* | */
+       0x007C, 0x00C0, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00CD, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00D3,
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00DA, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00C3, 0x00D5, 0x0020, 0x0020, 0x0020,
+                                                                     /* ï¿½ï¿½*/
+       0x0020, 0x00C2, 0x0020, 0x0020, 0x0020, 0x20AC, 0x0020, 0x0020, 0x0020, 0x00ED, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00F3,
+       0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00FA, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x00E3, 0x00F5, 0x0020, 0x0020, 0x00E2
+};
+
+
+// Portuguese National Language Locking Shift Table -> UCS2
+static const WCHAR g_PortuLockingToUCS2[] =
+{
+       /* @ */
+       0x0040, 0x00A3, 0x0024, 0x00A5, 0x00EA, 0x00E9, 0x00FA, 0x00ED, 0x00F3, 0x00E7, 0x000A, 0x00D4, 0x00F4, 0x000D, 0x00C1, 0x00E1,
+       /* ï¿½ï¿½*/
+       0x0394, 0x005F, 0x0020, 0x00C7, 0x00C0, 0x0020, 0x005E,         0x005C, 0x20AC, 0x00D3, 0x007C, 0x001B, 0x00C2, 0x00E2, 0x00CA, 0x00C9,
+       /* SP */
+       0x0020, 0x0021, 0x0022, 0x0023, 0x00A4, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F,
+       /* 0 */
+       0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F,
+       /* ï¿½ï¿½*/
+       0x00CD, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F,
+       /* P */
+       0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x00C3, 0x00D5, 0x00DA, 0x00DC, 0x00A7,
+       /* ï¿½ï¿½*/
+       0x00BF, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F,
+       /* p */
+       0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x00E3, 0x00F5, 0x0020, 0x00FC, 0x00E0
+};
+
+
+/*==================================================================================================
+                                CLASS DEFINITIONS
+==================================================================================================*/
+class MsgTextConvert
+{
+public:
+       MsgTextConvert();
+       ~MsgTextConvert();
+
+       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);
+       int convertUTF8ToAuto(OUT unsigned char *pDestText, IN int maxLength,  IN const unsigned char *pSrcText, IN int srcTextLen, OUT msg_encode_type_t *pCharType);
+
+       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);
+
+private:
+       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 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 MSG_LANG_INFO_S *pLangInfo);
+
+       void convertDumpTextToHex(const unsigned char *pText, int length);
+
+       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;
+};
+
+#endif //MSG_TEXT_CONVERT_H
+
diff --git a/include/utils/MsgUtilFile.h b/include/utils/MsgUtilFile.h
new file mode 100755 (executable)
index 0000000..0cb142c
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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)
+
+/*==================================================================================================
+                                       FUNCTION PROTOTYPES
+==================================================================================================*/
+/**  file operation wrapper - for avoding runtime error */
+FILE* MsgOpenFile(const char* filepath, const char* opt);
+void MsgCloseFile(FILE* pFile);
+int MsgFseek(FILE* pFile, long int offset, int origin);
+size_t MsgWriteFile(const char* pData, size_t size, size_t count, FILE  *pFile);
+size_t MsgReadFile(void *pData, size_t size, size_t count, FILE *pFile);
+long int MsgFtell(FILE *pFile);
+int MsgFflush(FILE *pFile);
+int MsgFsync(FILE *pFile);
+
+bool MsgCreateFileName(char *pFileName);
+bool MsgOpenAndReadFile(const char *pFileName, char **ppData, int *pDataSize);
+bool MsgReadFileForDecode(FILE* pFile, char* pBuf, int length, int* nSize);
+bool   MsgWriteDataFromEncodeBuffer(FILE* pFile, char* pInBuffer, int *pPtr, int maxLen, int* pOffset );
+bool MsgWriteIpcFile(const char *pFileName, const char *pData, int DataSize);
+void MsgDeleteFile(const char *pFileName);
+bool MsgGetFileSize(const char *pFilePath, int* nSize);
+int MsgGetFileSize(const char *pFileName);
+FILE*  MsgOpenMMSFile(char *pFileName);
+bool MsgOpenCreateAndOverwriteFile(char *pFullPath, char *pBuff, int TotalLength);
+char* MsgOpenAndReadMmsFile(const char* szFilePath, int offset, int size, int* npSize );
+bool MsgWriteSmilFile(const char *pFilePath,char *pData, int DataSize);
+int    MsgReadSmilFile(const char *pFileName, char **ppData);
+void MsgDeleteSmilFile(const char *pFilePath);
+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);
+
+#endif // MSG_UTIL_FILE_H
+
diff --git a/include/utils/MsgUtilFunction.h b/include/utils/MsgUtilFunction.h
new file mode 100755 (executable)
index 0000000..3501a0e
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgStorageTypes.h"
+#include "MsgSettingTypes.h"
+#include "MsgFilterTypes.h"
+#include "MsgInternalTypes.h"
+#include "MsgCmdTypes.h"
+
+/*==================================================================================================
+                                       FUNCTION PROTOTYPES
+==================================================================================================*/
+
+// Encoders
+int MsgEncodeCountInfo(MSG_COUNT_INFO_S *pCountInfo, char **ppDest);
+
+int MsgEncodeCountByMsgType(int MsgCount, char **ppDest);
+
+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(MSG_MESSAGE_INFO_S *pMsgInfo,  MSG_SENDINGOPT_INFO_S* pSendOptInfo, char **ppDest);
+
+int MsgEncodeFolderViewList(msg_struct_list_s *pFolderViewList, char **ppDest);
+
+int MsgEncodeFolderList(msg_struct_list_s *pFolderList, char **ppDest);
+
+int MsgEncodeSetting(MSG_SETTING_S *pSetting, char **ppDest);
+
+int MsgEncodeFilterList(msg_struct_list_s *pFilterList, char **ppDest);
+
+int MsgEncodeFilterFlag(bool *pSetFlag, char **ppDest);
+
+int MsgEncodeMsgType(MSG_MESSAGE_TYPE_S *pMsgType, char **ppDest);
+
+int MsgEncodeThreadViewList(msg_struct_list_s *pThreadViewList, char **ppDest);
+
+int MsgEncodeConversationViewList(msg_struct_list_s *pConvViewList, char **ppDest);
+
+int MsgEncodeMsgGetContactCount(MSG_THREAD_COUNT_INFO_S *threadCountInfo, char **ppDest);
+
+int MsgEncodeMemSize(unsigned int *memsize, char **ppDest);
+
+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, int count, char **ppDest);
+
+int MsgEncodeThreadId(msg_thread_id_t *pThreadId, char **ppDest);
+
+int MsgEncodeThreadInfo(MSG_THREAD_VIEW_S *pThreadInfo, char **ppDest);
+
+
+// Decoders
+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,  MSG_SENDINGOPT_INFO_S* pSendOptInfo);
+
+void MsgDecodeFolderViewList(char *pSrc, msg_struct_list_s *pFolderViewList);
+
+void MsgDecodeRecipientList(char *pSrc, MSG_RECIPIENTS_LIST_S *pRecipientList);
+
+void MsgDecodeFolderList(char *pSrc, msg_struct_list_s *pFolderList);
+
+void MsgDecodeSetting(char *pSrc, MSG_SETTING_S *pSetting);
+
+void MsgDecodeFilterList(char *pSrc, msg_struct_list_s *pFilterList);
+
+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 MsgDecodeMemSize(char *pSrc, unsigned int *memsize);
+
+void MsgDecodeReportStatus(char *pSrc,  msg_struct_list_s *report_list);
+
+void MsgDecodeThreadId(char *pSrc, msg_thread_id_t *pThreadId);
+
+void MsgDecodeThreadInfo(char *pSrc, MSG_THREAD_VIEW_S *pThreadInfo);
+
+
+// Event Encoder
+int MsgMakeEvent(const void *pData, int DataSize, MSG_EVENT_TYPE_T MsgEvent, msg_error_t MsgError, void **ppEvent);
+
+
+int msg_verify_number(const char *raw, char *trimmed);
+
+int msg_verify_email(const char *raw);
+
+#endif // MSG_UTIL_FUNCTION_H
diff --git a/include/utils/MsgUtilStorage.h b/include/utils/MsgUtilStorage.h
new file mode 100755 (executable)
index 0000000..694c923
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define MSG_UTIL_STORAGE_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgInternalTypes.h"
+#include "MsgStorageTypes.h"
+#include "MsgSqliteWrapper.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 );
+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, msg_struct_list_s *pAddress);
+msg_error_t MsgStoGetAddressByConvId(MsgDbHandler *pDbHandle, msg_thread_id_t convId, int contactNameOrder, msg_struct_list_s *pAddrlist);
+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);
+bool MsgExistAddress(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsg, msg_thread_id_t *pConvId);
+
+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 MsgStoClearContactInfo(MsgDbHandler *pDbHandle, int ContactId);
+msg_error_t MsgStoClearContactInfo(MsgDbHandler *pDbHandle, int ContactId, const char *pNumber);
+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);
+msg_error_t MsgStoUpdateNetworkStatus(MsgDbHandler *pDbHandle, MSG_MESSAGE_INFO_S *pMsgInfo, msg_network_status_t status);
+char *MsgStoReplaceString(const char *org_str, const char *old_str, const char *new_str);
+void MsgConvertNumber(const char* pSrcNum, char* pDestNum);
+#endif // MSG_UTIL_STORAGE_H
+
diff --git a/include/utils/MsgVMessage.h b/include/utils/MsgVMessage.h
new file mode 100755 (executable)
index 0000000..c793dca
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+
diff --git a/mapi/CMakeLists.txt b/mapi/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..6af422f
--- /dev/null
@@ -0,0 +1,57 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6) 
+PROJECT(msg-server CXX)
+
+SET(CMAKE_SKIP_BUILD_RPATH TRUE)
+SET(VERSION_MAJOR 0)
+SET(VERSION "${VERSION_MAJOR}.1.0")
+
+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 MAPI   
+##########################################################
+
+SET(MAPI-SRCS 
+       ${CMAKE_SOURCE_DIR}/mapi/msg_svc.cpp
+       ${CMAKE_SOURCE_DIR}/mapi/msg_control.cpp
+       ${CMAKE_SOURCE_DIR}/mapi/msg_storage.cpp
+       ${CMAKE_SOURCE_DIR}/mapi/msg_transport.cpp
+       ${CMAKE_SOURCE_DIR}/mapi/msg_filter.cpp
+       ${CMAKE_SOURCE_DIR}/mapi/msg_message.cpp
+       ${CMAKE_SOURCE_DIR}/mapi/msg_mms.cpp
+       ${CMAKE_SOURCE_DIR}/mapi/msg_setting.cpp
+)
+
+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)
+
+FOREACH(flag ${mapi_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_LIBRARY(${MAPI-LIB} SHARED ${MAPI-SRCS})
+TARGET_LINK_LIBRARIES(${MAPI-LIB} ${mapi_pkgs_LDFLAGS} ${UTILS-LIB} ${TRANS-PROXY-LIB})
+SET_TARGET_PROPERTIES(${MAPI-LIB} PROPERTIES SOVERSION ${VERSION_MAJOR})
+SET_TARGET_PROPERTIES(${MAPI-LIB} PROPERTIES VERSION ${VERSION})
+
+INSTALL(TARGETS ${MAPI-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
+
diff --git a/mapi/msg_control.cpp b/mapi/msg_control.cpp
new file mode 100755 (executable)
index 0000000..7c0bcc7
--- /dev/null
@@ -0,0 +1,90 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgHandle.h"
+#include "MsgDebug.h"
+#include "MsgException.h"
+
+#include "msg_private.h"
+#include "msg.h"
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+EXPORT_API int msg_open_msg_handle(msg_handle_t *handle)
+{
+       if (handle == NULL)
+       {
+               MSG_FATAL("Input Paramter is NULL");
+               return -EINVAL;
+       }
+       MsgHandle* pHandle = new MsgHandle();
+
+       // Create MsgHandle
+       *handle = (msg_handle_t)pHandle;
+
+       if (*handle == NULL)
+               return -EINVAL;
+
+       try
+       {
+               // Connect to Socket
+               pHandle->openHandle();
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+
+               if (e.errorCode() == MsgException::SERVER_READY_ERROR)
+                       return MSG_ERR_SERVER_NOT_READY;
+               else
+                       return MSG_ERR_COMMUNICATION_ERROR;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+EXPORT_API int msg_close_msg_handle(msg_handle_t *handle)
+{
+       if (handle == NULL || *handle == NULL)
+       {
+               MSG_FATAL("Input Paramter is NULL");
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)(*handle);
+
+       try
+       {
+               // Disconnect to Socket
+               pHandle->closeHandle(pHandle);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_COMMUNICATION_ERROR;
+       }
+
+       // Destroy MsgHandle
+       delete (MsgHandle*)(*handle);
+       (*handle) = NULL;
+
+       return MSG_SUCCESS;
+}
+
diff --git a/mapi/msg_filter.cpp b/mapi/msg_filter.cpp
new file mode 100755 (executable)
index 0000000..a7a9d19
--- /dev/null
@@ -0,0 +1,353 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgDebug.h"
+#include "MsgHandle.h"
+#include "msg.h"
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+EXPORT_API int msg_add_filter(msg_handle_t handle, const msg_struct_t msg_struct_handle)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       // 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;
+       }
+
+       if(msg_struct->type != MSG_STRUCT_FILTER)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->addFilter((const MSG_FILTER_S *)msg_struct->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_FILTER_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_update_filter(msg_handle_t handle, const msg_struct_t msg_struct_handle)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       // 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;
+       }
+
+
+       if(msg_struct->type != MSG_STRUCT_FILTER)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->updateFilter((const MSG_FILTER_S *)msg_struct->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_FILTER_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_delete_filter(msg_handle_t handle, msg_filter_id_t filter_id)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->deleteFilter(filter_id);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_FILTER_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_get_filter_list(msg_handle_t handle, msg_struct_list_s *filter_list)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || filter_list == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getFilterList(filter_list);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_FILTER_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_set_filter_operation(msg_handle_t handle, bool set_flag)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setFilterOperation(set_flag);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_FILTER_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_get_filter_operation(msg_handle_t handle, bool *set_flag)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getFilterOperation(set_flag);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_FILTER_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_set_filter_active(msg_handle_t handle, msg_filter_id_t filter_id, bool active)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       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)
+{
+       if (!filter)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = 0;
+
+       MSG_FILTER_S *filter_data = (MSG_FILTER_S *)filter;
+
+       switch (field)
+       {
+       case MSG_FILTER_ID_INT :
+               ret = filter_data->filterId;
+               break;
+       case MSG_FILTER_TYPE_INT :
+               ret = filter_data->filterType;
+               break;
+       default :
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       return ret;
+}
+
+
+char *msg_get_filter_info_str(void *filter, int field)
+{
+       if (!filter)
+               return NULL;
+
+       char *ret_str = NULL;
+
+       MSG_FILTER_S *filter_data = (MSG_FILTER_S *)filter;
+
+       switch (field)
+       {
+       case MSG_FILTER_VALUE_STR :
+               ret_str = filter_data->filterValue;
+               break;
+       default :
+               return NULL;
+       }
+
+       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)
+               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_ID_INT :
+               filter_data->filterId = value;
+               break;
+       case MSG_FILTER_TYPE_INT :
+               filter_data->filterType = value;
+               break;
+       default :
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       return err;
+}
+
+int msg_set_filter_info_str(void *filter, int field, char *value, int size)
+{
+       if (!filter || !value)
+               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_VALUE_STR :
+       {
+               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;
+       }
+
+       return err;
+}
+
+
diff --git a/mapi/msg_message.cpp b/mapi/msg_message.cpp
new file mode 100755 (executable)
index 0000000..b78d7a3
--- /dev/null
@@ -0,0 +1,717 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgTypes.h"
+#include "MsgStorageTypes.h"
+#include "MsgInternalTypes.h"
+#include "MsgMmsMessage.h"
+
+#include "msg.h"
+#include "msg_private.h"
+
+void msg_message_create_struct(msg_struct_s *msg_struct)
+{
+       MSG_MESSAGE_HIDDEN_S *msg = (MSG_MESSAGE_HIDDEN_S *)new MSG_MESSAGE_HIDDEN_S;
+       memset(msg, 0x00, sizeof(MSG_MESSAGE_HIDDEN_S));
+
+       /* set default value to message*/
+       msg->msgId = 0;
+       msg->threadId = 0;
+       msg->folderId = MSG_DRAFT_ID;
+       msg->mainType= MSG_SMS_TYPE;
+       msg->subType = MSG_NORMAL_SMS;
+       msg->classType = MSG_CLASS_NONE;
+       msg->storageId = MSG_STORAGE_PHONE;
+       time_t curTime = time(NULL);
+       msg->displayTime = curTime;
+       msg->networkStatus = MSG_NETWORK_NOT_SEND;
+       msg->encodeType = MSG_ENCODE_AUTO;
+       msg->bRead = false;
+       msg->bProtected = false;
+       msg->bBackup = false;
+       msg->priority = MSG_MESSAGE_PRIORITY_NORMAL;
+       msg->direction = MSG_DIRECTION_TYPE_MO;
+       msg->bPortValid = false;
+       msg->dataSize = 0;
+       msg->pData = NULL;
+       msg->pMmsData = NULL;
+
+       /* 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;
+       }
+
+       msg->addr_list = addr_list;
+
+       msg_struct->data = (int *)msg;
+}
+
+int msg_message_release(msg_struct_s **msg_struct)
+{
+       MSG_MESSAGE_HIDDEN_S *msg = (MSG_MESSAGE_HIDDEN_S *)(*msg_struct)->data;
+
+       if (msg->pData) {
+               delete [] static_cast<char*>(msg->pData);
+               msg->pData = NULL;
+       }
+
+       if (msg->pMmsData) {
+               delete [] static_cast<char*>(msg->pMmsData);
+               msg->pMmsData = NULL;
+       }
+
+       // Memory Free
+       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];
+                       delete (MSG_ADDRESS_INFO_S *)addrInfo->data;
+                       addrInfo->data = NULL;
+                       delete (msg_struct_s *)msg->addr_list->msg_struct_info[i];
+                       msg->addr_list->msg_struct_info[i] = NULL;
+               }
+
+               delete [] msg->addr_list->msg_struct_info;
+
+               delete msg->addr_list;
+               msg->addr_list = NULL;
+       }
+
+       delete msg;
+       (*msg_struct)->data = NULL;
+
+       delete (msg_struct_s *)*msg_struct;
+       *msg_struct = NULL;
+
+       return MSG_SUCCESS;
+}
+
+int msg_message_get_int_value(void *data, int field, int *value)
+{
+       if (!data)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)data;
+
+       switch (field)
+       {
+       case MSG_MESSAGE_ID_INT :
+               *value = msg_data->msgId;
+               break;
+       case MSG_MESSAGE_THREAD_ID_INT :
+               *value = msg_data->threadId;
+               break;
+       case MSG_MESSAGE_FOLDER_ID_INT :
+               *value = msg_data->folderId;
+               break;
+       case MSG_MESSAGE_TYPE_INT :
+       {
+        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 if (msg_data->subType == MSG_ETWS_SMS)
+                               *value = MSG_TYPE_SMS_ETWS_PRIMARY;
+                       else
+                               *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;
+
+       break;
+       }
+       case MSG_MESSAGE_CLASS_TYPE_INT :
+               *value = msg_data->classType;
+               break;
+       case MSG_MESSAGE_STORAGE_ID_INT :
+               *value = msg_data->storageId;
+               break;
+       case MSG_MESSAGE_DISPLAY_TIME_INT :
+               *value = msg_data->displayTime;
+               break;
+       case MSG_MESSAGE_NETWORK_STATUS_INT :
+               *value = msg_data->networkStatus;
+               break;
+       case MSG_MESSAGE_ENCODE_TYPE_INT :
+               *value = msg_data->encodeType;
+               break;
+       case MSG_MESSAGE_PRIORITY_INT :
+               *value = msg_data->priority;
+               break;
+       case MSG_MESSAGE_DIRECTION_INT :
+               *value = msg_data->direction;
+               break;
+       case MSG_MESSAGE_DEST_PORT_INT :
+               *value = msg_data->dstPort;
+               break;
+       case MSG_MESSAGE_SRC_PORT_INT :
+               *value = msg_data->srcPort;
+               break;
+       case MSG_MESSAGE_ATTACH_COUNT_INT :
+               *value = msg_data->attachCount;
+               break;
+       case MSG_MESSAGE_DATA_SIZE_INT :
+               *value = msg_data->dataSize;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+int msg_message_get_bool_value(void *data, int field, bool *value)
+{
+       if (!data)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)data;
+
+       switch (field) {
+       case MSG_MESSAGE_READ_BOOL :
+               *value = msg_data->bRead;
+               break;
+       case MSG_MESSAGE_PROTECTED_BOOL :
+               *value = msg_data->bProtected;
+               break;
+       case MSG_MESSAGE_BACKUP_BOOL :
+               *value = msg_data->bBackup;
+               break;
+       case MSG_MESSAGE_PORT_VALID_BOOL :
+               *value = msg_data->bPortValid;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+int msg_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_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)data;
+
+       switch (field) {
+       case MSG_MESSAGE_REPLY_ADDR_STR :
+               strncpy(value, msg_data->replyAddress, size);
+               break;
+       case MSG_MESSAGE_SUBJECT_STR :
+               strncpy(value, msg_data->subject, size);
+               break;
+       case MSG_MESSAGE_THUMBNAIL_PATH_STR :
+               strncpy(value, msg_data->thumbPath, size);
+               break;
+       case MSG_MESSAGE_SMS_DATA_STR :
+       case MSG_MESSAGE_MMS_TEXT_STR :
+               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;
+       }
+
+       return ret;
+}
+
+int msg_message_get_struct_hnd(void *data, int field, void **value)
+{
+       if (!data)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       switch (field) {
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+int msg_message_get_list_hnd(void *data, int field, void **value)
+{
+       if (!data)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)data;
+
+       switch (field) {
+       case MSG_MESSAGE_ADDR_LIST_STRUCT :
+               *value = (void *)msg_data->addr_list;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+int msg_message_set_int_value(void *data, int field, int value)
+{
+       if (!data)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)data;
+
+       switch (field)
+       {
+       case MSG_MESSAGE_ID_INT :
+               msg_data->msgId = value;
+               break;
+       case MSG_MESSAGE_THREAD_ID_INT :
+               msg_data->threadId = value;
+               break;
+       case MSG_MESSAGE_FOLDER_ID_INT :
+               msg_data->folderId = 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;
+                       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_ETWS_PRIMARY) {
+                       msg_data->mainType = MSG_SMS_TYPE;
+                       msg_data->subType = MSG_ETWS_SMS;
+               }
+        break;
+       }
+       case MSG_MESSAGE_CLASS_TYPE_INT :
+               msg_data->classType = value;
+               break;
+       case MSG_MESSAGE_STORAGE_ID_INT :
+               msg_data->storageId = value;
+               break;
+       case MSG_MESSAGE_DISPLAY_TIME_INT :
+               msg_data->displayTime = value;
+               break;
+       case MSG_MESSAGE_NETWORK_STATUS_INT :
+               msg_data->networkStatus = value;
+               break;
+       case MSG_MESSAGE_ENCODE_TYPE_INT :
+               msg_data->encodeType = value;
+               break;
+       case MSG_MESSAGE_PRIORITY_INT :
+               msg_data->priority = value;
+               break;
+       case MSG_MESSAGE_DIRECTION_INT :
+               msg_data->direction = value;
+               break;
+       case MSG_MESSAGE_DEST_PORT_INT :
+               msg_data->dstPort = value;
+               break;
+       case MSG_MESSAGE_SRC_PORT_INT :
+               msg_data->srcPort = value;
+               break;
+       case MSG_MESSAGE_ATTACH_COUNT_INT :
+                msg_data->attachCount = value;
+               break;
+       case MSG_MESSAGE_DATA_SIZE_INT :
+               msg_data->dataSize = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+int msg_message_set_bool_value(void *data, int field, bool value)
+{
+       if (!data)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)data;
+
+       switch (field) {
+       case MSG_MESSAGE_READ_BOOL :
+               msg_data->bRead = value;
+               break;
+       case MSG_MESSAGE_PROTECTED_BOOL :
+               msg_data->bProtected = value;
+               break;
+       case MSG_MESSAGE_BACKUP_BOOL :
+               msg_data->bBackup = value;
+               break;
+       case MSG_MESSAGE_PORT_VALID_BOOL :
+               msg_data->bPortValid = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+int msg_message_set_str_value(void *data, int field, char *value, int size)
+{
+       if (!data || !value)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MESSAGE_HIDDEN_S *msg_data = (MSG_MESSAGE_HIDDEN_S *)data;
+
+       switch (field) {
+       case MSG_MESSAGE_REPLY_ADDR_STR :
+               snprintf(msg_data->replyAddress, sizeof(msg_data->replyAddress), "%s", value);
+               break;
+       case MSG_MESSAGE_SUBJECT_STR :
+               snprintf(msg_data->subject, sizeof(msg_data->subject), "%s",value);
+               break;
+       case MSG_MESSAGE_THUMBNAIL_PATH_STR :
+               snprintf(msg_data->thumbPath, sizeof(msg_data->thumbPath), "%s",value);
+               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);
+               ((char*) msg_data->pData)[msg_data->dataSize] = '\0';
+       }
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+int msg_message_set_struct_hnd(void *data, int field, void *value)
+{
+       if (!data)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       switch (field) {
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+void msg_message_copy_message(MSG_MESSAGE_HIDDEN_S *pSrc, MSG_MESSAGE_HIDDEN_S *pDst)
+{
+
+       pDst->msgId = pSrc->msgId;
+       pDst->threadId = pSrc->msgId;
+       pDst->folderId = pSrc->folderId;
+       pDst->mainType = pSrc->mainType;
+       pDst->subType = pSrc->subType;
+       pDst->classType = pSrc->classType;
+       pDst->storageId = pSrc->storageId;
+       pDst->displayTime = pSrc->displayTime;
+       pDst->networkStatus = pSrc->networkStatus;
+       pDst->encodeType = pSrc->encodeType;
+       pDst->bRead = pSrc->bRead;
+       pDst->bProtected = pSrc->bProtected;
+       pDst->bBackup = pSrc->bBackup;
+       pDst->priority = pSrc->priority;
+       pDst->direction = pSrc->direction;
+       pDst->bPortValid = pSrc->bPortValid;
+       pDst->dataSize = pSrc->dataSize;
+       memcpy(pDst->subject, pSrc->subject, sizeof(pDst->subject));
+       if(pSrc->dataSize)
+       {
+               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];
+                       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;
+
+       for(int i=0; i < MAX_TO_ADDRESS_CNT; ++i)
+       {
+               msg_struct_s *src_addr = (msg_struct_s *)src_addrlist->msg_struct_info[i];
+               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));
+       }
+
+}
+
+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 :
+                       {
+                               if ( cb_msg->type == MSG_ETWS_SMS )
+                                       *value = MSG_TYPE_SMS_ETWS_PRIMARY;
+                               else if ( cb_msg->type == MSG_CB_SMS )
+                                       *value = ((cb_msg->messageId & 0xFFF8) == 0x1100 ) ? MSG_TYPE_SMS_ETWS_SECONDARY : MSG_TYPE_SMS_CB;
+                               else
+                                       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)
+{
+       //TODO :: check message type is MMS
+       int ret = MSG_SUCCESS;
+       msg_struct_s *msg_struct = (msg_struct_s *)msg_struct_handle;
+       msg_struct_s *mms_struct = (msg_struct_s *)mms_struct_handle;
+
+       if (msg_struct == NULL || mms_struct == NULL) {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (msg_struct->data == NULL || mms_struct->data == NULL) {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (msg_struct->type != MSG_STRUCT_MESSAGE_INFO || mms_struct->type != MSG_STRUCT_MMS) {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       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));
+
+       _MsgMmsDeserializeMessageData(tmp_mms_data, (char*)msg_data->pMmsData);
+
+       convert_from_mmsdata(tmp_mms_data, mms_struct);
+
+       _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;
+}
+
+EXPORT_API int msg_set_mms_struct(msg_struct_t msg_struct_handle, msg_struct_t mms_struct_handle)
+{
+       //TODO :: check message type is MMS
+       int ret = MSG_SUCCESS;
+       msg_struct_s *msg_struct = (msg_struct_s *)msg_struct_handle;
+       msg_struct_s *mms_struct = (msg_struct_s *)mms_struct_handle;
+
+       if (msg_struct == NULL || mms_struct == NULL) {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (msg_struct->data == NULL || mms_struct->data == NULL) {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (msg_struct->type != MSG_STRUCT_MESSAGE_INFO || mms_struct->type != MSG_STRUCT_MMS) {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       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));
+
+       convert_to_mmsdata(mms_struct, tmp_mms_data);
+
+       msg_data->pMmsData = _MsgMmsSerializeMessageData(tmp_mms_data, &(msg_data->dataSize));
+
+       _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;
+}
+
diff --git a/mapi/msg_mms.cpp b/mapi/msg_mms.cpp
new file mode 100755 (executable)
index 0000000..c8b51fc
--- /dev/null
@@ -0,0 +1,1317 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <MsgHandle.h>
+#include <MsgException.h>
+#include "MsgTypes.h"
+#include "MsgMmsTypes.h"
+#include "MsgMmsMessage.h"
+#include "MsgDebug.h"
+
+#include "msg.h"
+#include "msg_private.h"
+
+//Internel Struct
+typedef struct _MMS_DATA_S
+{
+       GList                   *pagelist;
+       GList                   *regionlist;
+       GList                   *attachlist;
+       GList                   *transitionlist;
+       GList                   *metalist;
+       MMS_SMIL_ROOTLAYOUT     rootlayout;
+       MMS_APPID_INFO_S        msgAppId;
+} MMS_DATA_HIDDEN_S;
+
+typedef struct
+{
+       MmsSmilMediaType        mediatype; /**< Indicates the SMIL media type. see enum MmsSmilMediaType */
+
+       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 + 1];  /**< Indicates the fullpath of the DRM */
+       msg_struct_s *pText;
+       msg_struct_s *pAVI;
+} MMS_MEDIA_HIDDEN_S;
+
+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);
+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);
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+static inline void *get_msg_struct_data(msg_struct_s *msg_struct)
+{
+       if (msg_struct == NULL)
+               return NULL;
+
+       return msg_struct->data;
+}
+
+msg_struct_s *msg_mms_create_struct(int type)
+{
+       msg_struct_s *msg_struct = new msg_struct_s;
+       bzero(msg_struct, sizeof(msg_struct_s));
+
+       msg_struct->type = type;
+       msg_struct->data = msg_mms_create_struct_data(type);
+
+       return msg_struct;
+}
+
+void *msg_mms_create_struct_data(int field)
+{
+       void *data = NULL;
+
+       switch(field)
+       {
+       case MSG_STRUCT_MMS:
+               data = (void *)new MMS_DATA_HIDDEN_S;
+               bzero(data, sizeof(MMS_DATA_HIDDEN_S));
+               break;
+       case MSG_STRUCT_MMS_PAGE:
+               data = (void *)new MMS_PAGE_S;
+               bzero(data, sizeof(MMS_PAGE_S));
+               break;
+       case MSG_STRUCT_MMS_MEDIA:
+       {
+               MMS_MEDIA_HIDDEN_S *media = new MMS_MEDIA_HIDDEN_S;
+               bzero(media, sizeof(MMS_MEDIA_HIDDEN_S));
+
+               media->pText = msg_mms_create_struct(MSG_STRUCT_MMS_SMIL_TEXT);
+               media->pAVI = msg_mms_create_struct(MSG_STRUCT_MMS_SMIL_AVI);
+               data = (void *)media;
+       }
+               break;
+       case MSG_STRUCT_MMS_ATTACH:
+               data = (void *)new MMS_ATTACH_S;
+               bzero(data, sizeof(MMS_ATTACH_S));
+               break;
+       case MSG_STRUCT_MMS_REGION:
+               data = (void *)new MMS_SMIL_REGION;
+               bzero(data, sizeof(MMS_SMIL_REGION));
+               ((MMS_SMIL_REGION *)data)->fit = MMSUI_IMAGE_REGION_FIT_MEET;
+               break;
+       case MSG_STRUCT_MMS_TRANSITION:
+               data = (void *)new MMS_SMIL_TRANSITION;
+               bzero(data, sizeof(MMS_SMIL_TRANSITION));
+               break;
+       case MSG_STRUCT_MMS_META:
+               data = (void *)new MMS_SMIL_META;
+               bzero(data, sizeof(MMS_SMIL_META));
+               break;
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+               data = (void *)new MmsSmilText;
+               bzero(data, sizeof(MmsSmilText));
+               break;
+       case MSG_STRUCT_MMS_SMIL_AVI:
+               data = (void *)new MmsSmilAVI;
+               bzero(data, sizeof(MmsSmilAVI));
+               break;
+       }
+
+       return data;
+}
+
+void msg_mms_list_item_free_func(gpointer data)
+{
+       msg_struct_s *msg_struct = (msg_struct_s *)data;
+       if (msg_struct->type == MSG_STRUCT_MMS_MEDIA)  {
+               __msg_mms_release_media(msg_struct);
+       } else if (msg_struct->type == MSG_STRUCT_MMS_PAGE) {
+               __msg_mms_release_page(msg_struct);
+       } else if (msg_struct->type == MSG_STRUCT_MMS_ATTACH) {
+               __msg_mms_release_attach(msg_struct);
+       } else if (msg_struct->type == MSG_STRUCT_MMS_REGION) {
+               __msg_mms_release_region(msg_struct);
+       } else if (msg_struct->type == MSG_STRUCT_MMS_TRANSITION) {
+               __msg_mms_release_transition(msg_struct);
+       } else if (msg_struct->type == MSG_STRUCT_MMS_META) {
+               __msg_mms_release_meta(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);
+       }
+
+       delete (MMS_PAGE_S *)page;
+       page_struct->data = NULL;
+
+       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->pText)
+               msg_mms_release_struct(&media->pText);
+
+       if (media->pAVI)
+               msg_mms_release_struct(&media->pAVI);
+
+       delete (MMS_MEDIA_HIDDEN_S *)media;
+
+       media_struct->data = NULL;
+
+       delete media_struct;
+}
+
+void __msg_mms_release_attach(msg_struct_s *attach_struct)
+{
+       MMS_ATTACH_S *attach = (MMS_ATTACH_S *)attach_struct->data;
+
+       delete (MMS_ATTACH_S *)attach;
+
+       attach_struct->data = NULL;
+
+       delete attach_struct;
+}
+
+void __msg_mms_release_region(msg_struct_s *region_struct)
+{
+       MMS_SMIL_REGION *region = (MMS_SMIL_REGION *)region_struct->data;
+
+       delete (MMS_SMIL_REGION *)region;
+
+       region_struct->data = NULL;
+
+       delete region_struct;
+}
+
+void __msg_mms_release_transition(msg_struct_s *transition_struct)
+{
+       MMS_SMIL_TRANSITION *transition = (MMS_SMIL_TRANSITION *)transition_struct->data;
+
+       delete (MMS_SMIL_TRANSITION *)transition;
+
+       transition_struct->data = NULL;
+
+       delete transition_struct;
+}
+
+void __msg_mms_release_meta(msg_struct_s *meta_struct)
+{
+       MMS_SMIL_META *meta = (MMS_SMIL_META *)meta_struct->data;
+
+       delete (MMS_SMIL_META *)meta;
+
+       meta_struct->data = NULL;
+
+       delete meta_struct;
+}
+
+void __msg_mms_release_mms(msg_struct_s *mms_struct)
+{
+       MMS_DATA_HIDDEN_S *mms = (MMS_DATA_HIDDEN_S *)mms_struct->data;
+
+       if (mms->pagelist) {
+               g_list_free_full(mms->pagelist, msg_mms_list_item_free_func);
+               mms->pagelist = NULL;
+       }
+
+       if (mms->regionlist) {
+               g_list_free_full(mms->regionlist, msg_mms_list_item_free_func);
+               mms->regionlist = NULL;
+       }
+
+       if (mms->attachlist) {
+               g_list_free_full(mms->attachlist, msg_mms_list_item_free_func);
+               mms->attachlist = NULL;
+       }
+
+       if (mms->transitionlist) {
+               g_list_free_full(mms->transitionlist, msg_mms_list_item_free_func);
+               mms->transitionlist = NULL;
+       }
+
+       if (mms->metalist) {
+               g_list_free_full(mms->metalist, msg_mms_list_item_free_func);
+               mms->metalist = NULL;
+       }
+
+       delete (MMS_DATA_HIDDEN_S *)mms;
+
+       mms_struct->data = NULL;
+
+       delete mms_struct;
+}
+
+int msg_mms_release_struct(msg_struct_s **msg_struct_data)
+{
+       msg_struct_s *msg_struct = (msg_struct_s *)*msg_struct_data;
+       int type = msg_struct->type;
+
+       switch(type)
+       {
+       case MSG_STRUCT_MMS:
+               __msg_mms_release_mms(*msg_struct_data);
+               *msg_struct_data = NULL;
+               break;
+       case MSG_STRUCT_MMS_PAGE:
+               __msg_mms_release_page(*msg_struct_data);
+               *msg_struct_data = NULL;
+               break;
+       case MSG_STRUCT_MMS_MEDIA:
+               __msg_mms_release_media(*msg_struct_data);
+               *msg_struct_data = NULL;
+               break;
+       case MSG_STRUCT_MMS_ATTACH:
+               __msg_mms_release_attach(*msg_struct_data);
+               *msg_struct_data = NULL;
+               break;
+       case MSG_STRUCT_MMS_REGION:
+               __msg_mms_release_attach(*msg_struct_data);
+               *msg_struct_data = NULL;
+               break;
+       case MSG_STRUCT_MMS_TRANSITION:
+               __msg_mms_release_transition(*msg_struct_data);
+               *msg_struct_data = NULL;
+               break;
+       case MSG_STRUCT_MMS_META:
+               __msg_mms_release_meta(*msg_struct_data);
+               *msg_struct_data = NULL;
+               break;
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+               delete (MmsSmilText*)msg_struct->data;
+               delete msg_struct;
+               *msg_struct_data = NULL;
+               break;
+       case MSG_STRUCT_MMS_SMIL_AVI:
+               delete (MmsSmilAVI*)msg_struct->data;
+               delete msg_struct;
+               *msg_struct_data = NULL;
+               break;
+       }
+
+       return 0;
+}
+
+int msg_mms_get_int_value(msg_struct_s *msg_struct, int field, int *value)
+{
+       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_ROOTLAYOUT_WIDTH_INT)
+                       *value = mms_data->rootlayout.width.value;
+               else if (field == MSG_MMS_ROOTLAYOUT_HEIGHT_INT)
+                       *value = mms_data->rootlayout.height.value;
+               else if (field == MSG_MMS_ROOTLAYOUT_BGCOLOR_INT)
+                       *value = mms_data->rootlayout.bgColor;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_PAGE:
+       {
+               MMS_PAGE_S *mms_page_data = (MMS_PAGE_S *)msg_struct->data;
+               if (field == MSG_MMS_PAGE_PAGE_DURATION_INT)
+                       *value = mms_page_data->nDur;
+               else if (field == MSG_MMS_PAGE_BEGIN_TIME_INT)
+                       *value = mms_page_data->nBegin;
+               else if (field == MSG_MMS_PAGE_END_TIME_INT)
+                       *value = mms_page_data->nEnd;
+               else if (field == MSG_MMS_PAGE_MIN_INT)
+                       *value = mms_page_data->nMin;
+               else if (field == MSG_MMS_PAGE_MAX_INT)
+                       *value = mms_page_data->nMax;
+               else if (field == MSG_MMS_PAGE_REPEAT_INT)
+                       *value = mms_page_data->nRepeat;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_MEDIA:
+       {
+               MMS_MEDIA_S *mms_media_data = (MMS_MEDIA_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)
+                       *value = mms_media_data->drmType;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_ATTACH:
+       {
+               MMS_ATTACH_S *mms_attach_data = (MMS_ATTACH_S *)msg_struct->data;
+               if (field == MSG_MMS_ATTACH_MIME_TYPE_INT)
+                       *value = mms_attach_data->mediatype;
+               else if (field == MSG_MMS_ATTACH_FILESIZE_INT)
+                       *value = mms_attach_data->fileSize;
+               else if (field == MSG_MMS_ATTACH_DRM_TYPE_INT)
+                       *value = mms_attach_data->drmType;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_REGION:
+       {
+               MMS_SMIL_REGION *mms_region_data = (MMS_SMIL_REGION *)msg_struct->data;
+               if (field == MSG_MMS_REGION_LENGTH_LEFT_INT)
+                       *value = mms_region_data->nLeft.value;
+               else if (field == MSG_MMS_REGION_LENGTH_TOP_INT)
+                       *value = mms_region_data->nTop.value;
+               else if (field == MSG_MMS_REGION_LENGTH_WIDTH_INT)
+                       *value = mms_region_data->width.value;
+               else if (field == MSG_MMS_REGION_LENGTH_HEIGHT_INT)
+                       *value = mms_region_data->height.value;
+               else if (field == MSG_MMS_REGION_BGCOLOR_INT)
+                       *value = mms_region_data->bgColor;
+               else if (field == MSG_MMS_REGION_FIT_TYPE_INT)
+                       *value = mms_region_data->fit;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_TRANSITION:
+       {
+               MMS_SMIL_TRANSITION *mms_transition_data = (MMS_SMIL_TRANSITION *)msg_struct->data;
+               if (field == MSG_MMS_TRANSITION_TYPE_INT)
+                       *value = mms_transition_data->nType;
+               else if (field == MSG_MMS_TRANSITION_SUBTYPE_INT)
+                       *value = mms_transition_data->nSubType;
+               else if (field == MSG_MMS_TRANSITION_DURATION_INT)
+                       *value = mms_transition_data->nDur;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       {
+               MmsSmilText *mms_smil_text_data = (MmsSmilText *)msg_struct->data;
+               if (field == MSG_MMS_SMIL_TEXT_REPEAT_INT)
+                       *value = mms_smil_text_data->nRepeat;
+               else if (field == MSG_MMS_SMIL_TEXT_BEGIN_INT)
+                       *value = mms_smil_text_data->nBegin;
+               else if (field == MSG_MMS_SMIL_TEXT_END_INT)
+                       *value = mms_smil_text_data->nEnd;
+               else if (field == MSG_MMS_SMIL_TEXT_DURTIME_INT)
+                       *value = mms_smil_text_data->nDurTime;
+               else if (field == MSG_MMS_SMIL_TEXT_BGCOLOR_INT)
+                       *value = mms_smil_text_data->nBgColor;
+               else if (field == MSG_MMS_SMIL_TEXT_DIRECTION_TYPE_INT)
+                       *value = mms_smil_text_data->nDirection;
+               else if (field == MSG_MMS_SMIL_TEXT_SIZE_INT)
+                       *value = mms_smil_text_data->nSize;
+               else if (field == MSG_MMS_SMIL_TEXT_COLOR_INT)
+                       *value = mms_smil_text_data->nColor;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_SMIL_AVI:
+       {
+               MmsSmilAVI *mms_smil_avi_data = (MmsSmilAVI *)msg_struct->data;
+               if (field == MSG_MMS_SMIL_AVI_REPEAT_INT)
+                       *value = mms_smil_avi_data->nRepeat;
+               else if (field == MSG_MMS_SMIL_AVI_BEGIN_INT)
+                       *value = mms_smil_avi_data->nBegin;
+               else if (field == MSG_MMS_SMIL_AVI_END_INT)
+                       *value = mms_smil_avi_data->nEnd;
+               else if (field == MSG_MMS_SMIL_AVI_DURTIME_INT)
+                       *value = mms_smil_avi_data->nDurTime;
+               else if (field == MSG_MMS_SMIL_AVI_BGCOLOR_INT)
+                       *value = mms_smil_avi_data->nBgColor;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return MSG_SUCCESS;
+}
+
+int msg_mms_get_str_value(msg_struct_s *msg_struct, int field, char *value, int size)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       switch(msg_struct->type) {
+       case MSG_STRUCT_MMS_MEDIA:
+       {
+               MMS_MEDIA_S *mms_media_data = (MMS_MEDIA_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)
+                       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
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_ATTACH:
+       {
+               MMS_ATTACH_S *mms_attach_data = (MMS_ATTACH_S *)msg_struct->data;
+               if (field == MSG_MMS_ATTACH_FILENAME_STR)
+                       strncpy(value, mms_attach_data->szFileName, size);
+               else if (field == MSG_MMS_ATTACH_FILEPATH_STR)
+                       strncpy(value, mms_attach_data->szFilePath, size);
+               else if (field == MSG_MMS_ATTACH_DRM_FULLPATH_STR)
+                       strncpy(value, mms_attach_data->szDrm2FullPath, size);
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_REGION:
+       {
+               MMS_SMIL_REGION *mms_region_data = (MMS_SMIL_REGION *)msg_struct->data;
+               if (field == MSG_MMS_REGION_ID_STR)
+                       strncpy(value, mms_region_data->szID, size);
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_TRANSITION:
+       {
+               MMS_SMIL_TRANSITION *mms_transition_data = (MMS_SMIL_TRANSITION *)msg_struct->data;
+               if (field == MSG_MMS_TRANSITION_ID_STR)
+                       strncpy(value, mms_transition_data->szID, size);
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_META:
+       {
+               MMS_SMIL_META *mms_meta_data = (MMS_SMIL_META *)msg_struct->data;
+               if (field == MSG_MMS_META_ID_STR)
+                       strncpy(value, mms_meta_data->szID, size);
+               else if (field == MSG_MMS_META_NAME_STR)
+                       strncpy(value, mms_meta_data->szName, size);
+               else if (field == MSG_MMS_META_CONTENT_STR)
+                       strncpy(value, mms_meta_data->szContent, size);
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       {
+               MmsSmilText *mms_smil_text_data = (MmsSmilText *)msg_struct->data;
+               if (field == MSG_MMS_SMIL_TEXT_TRANSITION_IN_ID_STR)
+                       strncpy(value, mms_smil_text_data->szTransInId, size);
+               else if (field == MSG_MMS_SMIL_TEXT_TRANSITION_OUT_ID_STR)
+                       strncpy(value, mms_smil_text_data->szTransOutId, size);
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_SMIL_AVI:
+       {
+               MmsSmilAVI *mms_smil_avi_data = (MmsSmilAVI *)msg_struct->data;
+               if (field == MSG_MMS_SMIL_AVI_TRANSITION_IN_ID_STR)
+                       strncpy(value, mms_smil_avi_data->szTransInId, size);
+               else if (field == MSG_MMS_SMIL_AVI_TRANSITION_OUT_ID_STR)
+                       strncpy(value, mms_smil_avi_data->szTransOutId, size);
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       default :
+                       err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return MSG_SUCCESS;
+}
+
+int msg_mms_get_bool_value(msg_struct_s *msg_struct, int field, bool *value)
+{
+       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_ROOTLAYOUT_WIDTH_PERCENT_BOOL)
+                       *value = mms_data->rootlayout.width.bUnitPercent;
+               else if (field == MSG_MMS_ROOTLAYOUT_HEIGHT_PERCENT_BOOL)
+                       *value = mms_data->rootlayout.height.bUnitPercent;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_REGION:
+       {
+               MMS_SMIL_REGION *mms_region_data = (MMS_SMIL_REGION *)msg_struct->data;
+               if (field == MSG_MMS_REGION_LENGTH_LEFT_PERCENT_BOOL)
+                       *value = mms_region_data->nLeft.bUnitPercent;
+               else if (field == MSG_MMS_REGION_LENGTH_TOP_PERCENT_BOOL)
+                       *value = mms_region_data->nTop.bUnitPercent;
+               else if (field == MSG_MMS_REGION_LENGTH_WIDTH_PERCENT_BOOL)
+                       *value = mms_region_data->width.bUnitPercent;
+               else if (field == MSG_MMS_REGION_LENGTH_HEIGHT_PERCENT_BOOL)
+                       *value = mms_region_data->height.bUnitPercent;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       {
+               MmsSmilText *mms_smil_text_data = (MmsSmilText *)msg_struct->data;
+               if (field == MSG_MMS_SMIL_TEXT_BOLD_BOOL)
+                       *value = mms_smil_text_data->bBold;
+               else if (field == MSG_MMS_SMIL_TEXT_UNDERLINE_BOOL)
+                       *value = mms_smil_text_data->bUnderLine;
+               else if (field == MSG_MMS_SMIL_TEXT_ITALIC_BOOL)
+                       *value = mms_smil_text_data->bItalic;
+               else if (field == MSG_MMS_SMIL_TEXT_REVERSE_BOOL)
+                       *value = mms_smil_text_data->bReverse;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return MSG_SUCCESS;
+}
+
+int msg_mms_get_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s **value)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       switch(msg_struct->type) {
+       case MSG_STRUCT_MMS_MEDIA:
+       {
+               MMS_MEDIA_HIDDEN_S *mms_media_data = (MMS_MEDIA_HIDDEN_S *)msg_struct->data;
+               if (field == MSG_MMS_MEDIA_SMIL_TEXT_HND)
+                       *value = mms_media_data->pText;
+               else if (field == MSG_MMS_MEDIA_SMIL_AVI_HND)
+                       *value = mms_media_data->pAVI;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return MSG_SUCCESS;
+}
+
+int msg_mms_get_list_handle(msg_struct_s *msg_struct, int field, msg_list_handle_t *value)
+{
+       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_PAGE_LIST_HND)
+                       *value = (msg_list_handle_t)mms_data->pagelist;
+               else if (field == MSG_MMS_REGION_LIST_HND)
+                       *value = (msg_list_handle_t)mms_data->regionlist;
+               else if (field == MSG_MMS_ATTACH_LIST_HND)
+                       *value = (msg_list_handle_t)mms_data->attachlist;
+               else if (field == MSG_MMS_TRANSITION_LIST_HND)
+                       *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
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_PAGE:
+       {
+               MMS_PAGE_S *mms_page_data = (MMS_PAGE_S *)msg_struct->data;
+               if (field == MSG_MMS_PAGE_MEDIA_LIST_HND)
+                       *value = (msg_list_handle_t)mms_page_data->medialist;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return MSG_SUCCESS;
+}
+/*SET*/
+int msg_mms_set_int_value(msg_struct_s *msg_struct, int field, int value)
+{
+       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_ROOTLAYOUT_WIDTH_INT)
+                       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)
+                       mms_data->rootlayout.bgColor = value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_PAGE:
+       {
+               MMS_PAGE_S *mms_page_data = (MMS_PAGE_S *)msg_struct->data;
+               if (field == MSG_MMS_PAGE_PAGE_DURATION_INT)
+                       mms_page_data->nDur = value;
+               else if (field == MSG_MMS_PAGE_BEGIN_TIME_INT)
+                       mms_page_data->nBegin = value;
+               else if (field == MSG_MMS_PAGE_END_TIME_INT)
+                       mms_page_data->nEnd = value;
+               else if (field == MSG_MMS_PAGE_MIN_INT)
+                       mms_page_data->nMin = value;
+               else if (field == MSG_MMS_PAGE_MAX_INT)
+                       mms_page_data->nMax = value;
+               else if (field == MSG_MMS_PAGE_REPEAT_INT)
+                       mms_page_data->nRepeat = value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_MEDIA:
+       {
+               MMS_MEDIA_S *mms_media_data = (MMS_MEDIA_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)
+                       mms_media_data->drmType = (MsgDrmType)value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_ATTACH:
+       {
+               MMS_ATTACH_S *mms_attach_data = (MMS_ATTACH_S *)msg_struct->data;
+               if (field == MSG_MMS_ATTACH_MIME_TYPE_INT)
+                       mms_attach_data->mediatype = (MimeType)value;
+               else if (field == MSG_MMS_ATTACH_FILESIZE_INT)
+                       mms_attach_data->fileSize = value;
+               else if (field == MSG_MMS_ATTACH_DRM_TYPE_INT)
+                       mms_attach_data->drmType = (MsgDrmType)value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_REGION:
+       {
+               MMS_SMIL_REGION *mms_region_data = (MMS_SMIL_REGION *)msg_struct->data;
+               if (field == MSG_MMS_REGION_LENGTH_LEFT_INT)
+                       mms_region_data->nLeft.value = value;
+               else if (field == MSG_MMS_REGION_LENGTH_TOP_INT)
+                       mms_region_data->nTop.value = value;
+               else if (field == MSG_MMS_REGION_LENGTH_WIDTH_INT)
+                       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)
+                       mms_region_data->bgColor = value;
+               else if (field == MSG_MMS_REGION_FIT_TYPE_INT)
+                       mms_region_data->fit = (REGION_FIT_TYPE_T)value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_TRANSITION:
+       {
+               MMS_SMIL_TRANSITION *mms_transition_data = (MMS_SMIL_TRANSITION *)msg_struct->data;
+               if (field == MSG_MMS_TRANSITION_TYPE_INT)
+                       mms_transition_data->nType = (MmsSmilTransType)value;
+               else if (field == MSG_MMS_TRANSITION_SUBTYPE_INT)
+                       mms_transition_data->nSubType = (MmsSmilTransSubType)value;
+               else if (field == MSG_MMS_TRANSITION_DURATION_INT)
+                       mms_transition_data->nDur = value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       {
+               MmsSmilText *mms_smil_text_data = (MmsSmilText *)msg_struct->data;
+               if (field == MSG_MMS_SMIL_TEXT_REPEAT_INT)
+                       mms_smil_text_data->nRepeat = value;
+               else if (field == MSG_MMS_SMIL_TEXT_BEGIN_INT)
+                       mms_smil_text_data->nBegin = value;
+               else if (field == MSG_MMS_SMIL_TEXT_END_INT)
+                       mms_smil_text_data->nEnd = value;
+               else if (field == MSG_MMS_SMIL_TEXT_DURTIME_INT)
+                       mms_smil_text_data->nDurTime = value;
+               else if (field == MSG_MMS_SMIL_TEXT_BGCOLOR_INT)
+                       mms_smil_text_data->nBgColor = value;
+               else if (field == MSG_MMS_SMIL_TEXT_DIRECTION_TYPE_INT)
+                       mms_smil_text_data->nDirection = (MmsTextDirection)value;
+               else if (field == MSG_MMS_SMIL_TEXT_SIZE_INT)
+                       mms_smil_text_data->nSize = value;
+               else if (field == MSG_MMS_SMIL_TEXT_COLOR_INT)
+                       mms_smil_text_data->nColor = value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_SMIL_AVI:
+       {
+               MmsSmilAVI *mms_smil_avi_data = (MmsSmilAVI *)msg_struct->data;
+               if (field == MSG_MMS_SMIL_AVI_REPEAT_INT)
+                       mms_smil_avi_data->nRepeat = value;
+               else if (field == MSG_MMS_SMIL_AVI_BEGIN_INT)
+                       mms_smil_avi_data->nBegin = value;
+               else if (field == MSG_MMS_SMIL_AVI_END_INT)
+                       mms_smil_avi_data->nEnd = value;
+               else if (field == MSG_MMS_SMIL_AVI_DURTIME_INT)
+                       mms_smil_avi_data->nDurTime = value;
+               else if (field == MSG_MMS_SMIL_AVI_BGCOLOR_INT)
+                       mms_smil_avi_data->nBgColor = value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return MSG_SUCCESS;
+}
+
+int msg_mms_set_str_value(msg_struct_s *msg_struct, int field, char *value, int size)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       switch(msg_struct->type) {
+       case MSG_STRUCT_MMS_MEDIA:
+       {
+               MMS_MEDIA_S *mms_media_data = (MMS_MEDIA_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) {
+                               MSG_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)
+                       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
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_ATTACH:
+       {
+               MMS_ATTACH_S *mms_attach_data = (MMS_ATTACH_S *)msg_struct->data;
+               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) {
+                       char *filename = NULL;
+                       char *filepath = value;
+
+                       if (filepath != NULL) {
+                               MSG_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
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_REGION:
+       {
+               MMS_SMIL_REGION *mms_region_data = (MMS_SMIL_REGION *)msg_struct->data;
+               if (field == MSG_MMS_REGION_ID_STR)
+                       strncpy(mms_region_data->szID, value, MAX_SMIL_REGION_ID);
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_TRANSITION:
+       {
+               MMS_SMIL_TRANSITION *mms_transition_data = (MMS_SMIL_TRANSITION *)msg_struct->data;
+               if (field == MSG_MMS_TRANSITION_ID_STR)
+                       strncpy(mms_transition_data->szID, value, MAX_SMIL_TRANSITION_ID);
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_META:
+       {
+               MMS_SMIL_META *mms_meta_data = (MMS_SMIL_META *)msg_struct->data;
+               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->szName, value, MAX_SMIL_META_NAME);
+               else if (field == MSG_MMS_META_CONTENT_STR)
+                       strncpy(mms_meta_data->szContent, value, MAX_SMIL_META_CONTENT);
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       {
+               MmsSmilText *mms_smil_text_data = (MmsSmilText *)msg_struct->data;
+               if (field == MSG_MMS_SMIL_TEXT_TRANSITION_IN_ID_STR)
+                       strncpy(mms_smil_text_data->szTransInId, value, MAX_SMIL_TRANSIN_ID);
+               else if (field == MSG_MMS_SMIL_TEXT_TRANSITION_OUT_ID_STR)
+                       strncpy(mms_smil_text_data->szTransOutId, value, MAX_SMIL_TRANSOUT_ID);
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_SMIL_AVI:
+       {
+               MmsSmilAVI *mms_smil_avi_data = (MmsSmilAVI *)msg_struct->data;
+               if (field == MSG_MMS_SMIL_AVI_TRANSITION_IN_ID_STR)
+                       strncpy(mms_smil_avi_data->szTransInId, value, MAX_SMIL_TRANSIN_ID);
+               else if (field == MSG_MMS_SMIL_AVI_TRANSITION_OUT_ID_STR)
+                       strncpy(mms_smil_avi_data->szTransOutId, value, MAX_SMIL_TRANSOUT_ID);
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       default :
+                       err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return MSG_SUCCESS;
+}
+
+int msg_mms_set_bool_value(msg_struct_s *msg_struct, int field, bool value)
+{
+       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_ROOTLAYOUT_WIDTH_PERCENT_BOOL)
+                       mms_data->rootlayout.width.bUnitPercent = value;
+               else if (field == MSG_MMS_ROOTLAYOUT_HEIGHT_PERCENT_BOOL)
+                       mms_data->rootlayout.height.bUnitPercent = value;
+               else
+                       err  = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_REGION:
+       {
+               MMS_SMIL_REGION *mms_region_data = (MMS_SMIL_REGION *)msg_struct->data;
+               if (field == MSG_MMS_REGION_LENGTH_LEFT_PERCENT_BOOL)
+                       mms_region_data->nLeft.bUnitPercent = value;
+               else if (field == MSG_MMS_REGION_LENGTH_TOP_PERCENT_BOOL)
+                       mms_region_data->nTop.bUnitPercent = value;
+               else if (field == MSG_MMS_REGION_LENGTH_WIDTH_PERCENT_BOOL)
+                       mms_region_data->width.bUnitPercent = value;
+               else if (field == MSG_MMS_REGION_LENGTH_HEIGHT_PERCENT_BOOL)
+                       mms_region_data->height.bUnitPercent = value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       {
+               MmsSmilText *mms_smil_text_data = (MmsSmilText *)msg_struct->data;
+               if (field == MSG_MMS_SMIL_TEXT_BOLD_BOOL)
+                       mms_smil_text_data->bBold = value;
+               else if (field == MSG_MMS_SMIL_TEXT_UNDERLINE_BOOL)
+                       mms_smil_text_data->bUnderLine = value;
+               else if (field == MSG_MMS_SMIL_TEXT_ITALIC_BOOL)
+                       mms_smil_text_data->bItalic = value;
+               else if (field == MSG_MMS_SMIL_TEXT_REVERSE_BOOL)
+                       mms_smil_text_data->bReverse = value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return MSG_SUCCESS;
+}
+
+int msg_mms_set_struct_handle(msg_struct_s *msg_struct, int field, msg_struct_s *value)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       switch(msg_struct->type) {
+       case MSG_STRUCT_MMS_MEDIA:
+       {
+               MMS_MEDIA_HIDDEN_S *mms_media_data = (MMS_MEDIA_HIDDEN_S *)msg_struct->data;
+
+               if (field == MSG_MMS_MEDIA_SMIL_TEXT_HND)
+                       memcpy(mms_media_data->pText->data, value->data, sizeof(MmsSmilText));
+               else if (field == MSG_MMS_MEDIA_SMIL_AVI_HND)
+                       memcpy(mms_media_data->pAVI->data, value->data, sizeof(MmsSmilAVI));
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return MSG_SUCCESS;
+}
+
+int msg_mms_set_list_handle(msg_struct_s *msg_struct, int field, msg_list_handle_t value)
+{
+       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_PAGE_LIST_HND)
+                       mms_data->pagelist = (GList *)value;
+               else if (field == MSG_MMS_REGION_LIST_HND)
+                       mms_data->regionlist = (GList *)value;
+               else if (field == MSG_MMS_ATTACH_LIST_HND)
+                       mms_data->attachlist = (GList *)value;
+               else if (field == MSG_MMS_TRANSITION_LIST_HND)
+                       mms_data->transitionlist = (GList *)value;
+               else if (field == MSG_MMS_META_LIST_HND)
+                       mms_data->metalist = (GList *)value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       case MSG_STRUCT_MMS_PAGE:
+       {
+               MMS_PAGE_S *mms_page_data = (MMS_PAGE_S *)msg_struct->data;
+               if (field == MSG_MMS_PAGE_MEDIA_LIST_HND)
+                       mms_page_data->medialist = (GList *)value;
+               else
+                       err = MSG_ERR_INVALID_PARAMETER;
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return MSG_SUCCESS;
+}
+
+EXPORT_API int msg_mms_add_item(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;
+       switch(msg_struct->type) {
+       case MSG_STRUCT_MMS:
+       {
+
+               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);
+                       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);
+                       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);
+                       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);
+                       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);
+                       mms_data->metalist = g_list_append(mms_data->metalist, msg_struct_item);
+                       *item = (msg_struct_t)msg_struct_item;
+               } else {
+                       err = MSG_ERR_INVALID_PARAMETER;
+               }
+       }
+       break;
+       case MSG_STRUCT_MMS_PAGE:
+       {
+
+               MMS_PAGE_S *mms_page_data = (MMS_PAGE_S *)msg_struct->data;
+
+               if (field == MSG_STRUCT_MMS_MEDIA) {
+                       msg_struct_item = msg_mms_create_struct(field);
+                       mms_page_data->medialist = g_list_append(mms_page_data->medialist, msg_struct_item);
+                       *item = (msg_struct_t)msg_struct_item;
+               } else {
+                       err = MSG_ERR_INVALID_PARAMETER;
+               }
+       }
+       break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+void convert_to_media_data(const msg_struct_s *pSrc, MMS_MEDIA_S *pDest)
+{
+       const MMS_MEDIA_HIDDEN_S *src_media = (MMS_MEDIA_HIDDEN_S *)pSrc->data;
+       MMS_MEDIA_S *dst_media = pDest;
+
+       dst_media->mediatype = src_media->mediatype;
+       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);
+       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);
+       dst_media->drmType = src_media->drmType;
+
+       if (src_media->mediatype == MMS_SMIL_MEDIA_TEXT) {
+               msg_struct_s *smil_struct = (msg_struct_s *)src_media->pText;
+               MmsSmilText *smiltext = (MmsSmilText *)smil_struct->data;
+               memcpy(&dst_media->sMedia.sText, smiltext, sizeof(MmsSmilText));
+       } else {
+               msg_struct_s *smil_struct = (msg_struct_s *)src_media->pAVI;
+               MmsSmilAVI *smilavi = (MmsSmilAVI *)smil_struct->data;
+               memcpy(&dst_media->sMedia.sAVI, smilavi, sizeof(MmsSmilAVI));
+       }
+}
+
+void convert_from_media_data(const MMS_MEDIA_S *pSrc, msg_struct_s *pDest)
+{
+       const MMS_MEDIA_S *src_media = pSrc;
+       MMS_MEDIA_HIDDEN_S *dst_media = (MMS_MEDIA_HIDDEN_S *)pDest->data;
+
+       dst_media->mediatype = src_media->mediatype;
+       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);
+       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);
+       dst_media->drmType = src_media->drmType;
+
+       if (src_media->mediatype == MMS_SMIL_MEDIA_TEXT) {
+               msg_struct_s *dst_smil_struct = (msg_struct_s *)dst_media->pText;
+               MmsSmilText *dst_smiltext = (MmsSmilText *)dst_smil_struct->data;
+               memcpy(dst_smiltext, &src_media->sMedia.sText, sizeof(MmsSmilText));
+       } else {
+               msg_struct_s *dst_smil_struct = (msg_struct_s *)dst_media->pAVI;
+               MmsSmilAVI *dst_smilavi = (MmsSmilAVI *)dst_smil_struct->data;
+               memcpy(dst_smilavi, &src_media->sMedia.sAVI, sizeof(MmsSmilAVI));
+       }
+}
+
+void convert_to_mmsdata(const msg_struct_s *pSrc, 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));
+               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);
+
+                       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));
+               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));
+               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));
+               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));
+               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));
+}
+
+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++)
+               {
+                       msg_struct_s *dst_media_s = msg_mms_create_struct(MSG_STRUCT_MMS_MEDIA);
+
+                       MMS_MEDIA_S *src_media = (MMS_MEDIA_S *)g_list_nth_data(src_page->medialist, j);
+
+                       convert_from_media_data(src_media, dst_media_s);
+
+                       page->medialist = g_list_append(page->medialist, dst_media_s);
+               }
+
+               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;
+
+               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));
+}
diff --git a/mapi/msg_setting.cpp b/mapi/msg_setting.cpp
new file mode 100755 (executable)
index 0000000..0db861a
--- /dev/null
@@ -0,0 +1,1826 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgHandle.h"
+#include "MsgDebug.h"
+
+#include "msg_private.h"
+#include "msg.h"
+
+/*******************************************************************************
+ *                                                                      SMSC                                                                  *
+ *******************************************************************************/
+
+int msg_setting_get_int_value(msg_struct_s *msg_struct, int field, int *value)
+{
+       int err = MSG_SUCCESS;
+
+       switch (msg_struct->type) {
+       case MSG_STRUCT_SETTING_SMSC_OPT :
+               *value = msg_get_smsc_opt_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_SMSC_INFO :
+               *value = msg_get_smsc_info_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_CB_OPT :
+               *value = msg_get_cb_option_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+               *value = msg_get_cb_channel_info_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_SMS_SEND_OPT :
+               *value = msg_get_sms_send_opt_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_MMS_SEND_OPT :
+               *value = msg_get_mms_send_opt_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_MMS_RECV_OPT :
+               *value = msg_get_mms_recv_opt_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
+               *value = msg_get_push_msg_opt_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_GENERAL_OPT :
+               *value = msg_get_general_opt_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_MSGSIZE_OPT :
+               *value = msg_get_msgsize_opt_int(msg_struct->data, field);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+int msg_setting_get_str_value(msg_struct_s *msg_struct, int field, char *src, int size)
+{
+       int err = MSG_SUCCESS;
+       char *ret_str = NULL;
+
+       switch (msg_struct->type)
+       {
+       case MSG_STRUCT_SETTING_SMSC_INFO :
+               ret_str = msg_get_smsc_info_str(msg_struct->data, field);
+               if (ret_str == NULL)
+                       err = MSG_ERR_UNKNOWN;
+               else
+                       strncpy(src, ret_str, size);
+               break;
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+               ret_str = msg_get_cb_channel_info_str(msg_struct->data, field);
+               if (ret_str == NULL)
+                       err = MSG_ERR_UNKNOWN;
+               else
+                       strncpy(src, ret_str, size);
+               break;
+       case MSG_STRUCT_SETTING_VOICE_MSG_OPT :
+               ret_str = msg_get_voice_msg_opt_str(msg_struct->data, field);
+               if (ret_str == NULL)
+                       err = MSG_ERR_UNKNOWN;
+               else
+                       strncpy(src, ret_str, size);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+int msg_setting_get_bool_value(msg_struct_s *msg_struct, int field, bool *value)
+{
+       int err = MSG_SUCCESS;
+
+       switch (msg_struct->type) {
+       case MSG_STRUCT_SETTING_CB_OPT :
+               *value = msg_get_cb_option_bool(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+               *value = msg_get_cb_channel_info_bool(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_SMS_SEND_OPT :
+               *value = msg_get_sms_send_opt_bool(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_MMS_SEND_OPT :
+               *value = msg_get_mms_send_opt_bool(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_MMS_RECV_OPT :
+               *value = msg_get_mms_recv_opt_bool(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
+               *value = msg_get_push_msg_opt_bool(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SETTING_GENERAL_OPT :
+               *value = msg_get_general_opt_bool(msg_struct->data, field);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+int msg_setting_get_list_handle(msg_struct_s *msg_struct, int field, void **value)
+{
+       int err = MSG_SUCCESS;
+
+       switch (msg_struct->type) {
+       case MSG_STRUCT_SETTING_SMSC_OPT :
+               err = msg_get_smsc_opt_list(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_CB_OPT :
+               err = msg_get_cb_option_list(msg_struct->data, field, value);
+               break;
+       default :
+               break;
+       }
+
+       return err;
+}
+
+int msg_setting_set_int_value(msg_struct_s *msg_struct, int field, int value)
+{
+       int err = MSG_SUCCESS;
+
+       switch (msg_struct->type) {
+       case MSG_STRUCT_SETTING_SMSC_OPT :
+               err = msg_set_smsc_opt_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_SMSC_INFO :
+               err = msg_set_smsc_info_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_CB_OPT :
+               err = msg_set_cb_option_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+               err = msg_set_cb_channel_info_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_SMS_SEND_OPT :
+               err = msg_set_sms_send_opt_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_MMS_SEND_OPT :
+               err = msg_set_mms_send_opt_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_MMS_RECV_OPT :
+               err = msg_set_mms_recv_opt_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
+               err = msg_set_push_msg_opt_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_GENERAL_OPT :
+               err = msg_set_general_opt_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_MSGSIZE_OPT :
+               err = msg_set_msgsize_opt_int(msg_struct->data, field, value);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+int msg_setting_set_str_value(msg_struct_s *msg_struct, int field, char *value, int size)
+{
+       int err = MSG_SUCCESS;
+
+       switch (msg_struct->type)
+       {
+       case MSG_STRUCT_SETTING_SMSC_INFO :
+               err = msg_set_smsc_info_str(msg_struct->data, field, value, size);
+               break;
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+               err = msg_set_cb_channel_info_str(msg_struct->data, field, value, size);
+               break;
+       case MSG_STRUCT_SETTING_VOICE_MSG_OPT :
+               err = msg_set_voice_msg_opt_str(msg_struct->data, field, value, size);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+int msg_setting_set_bool_value(msg_struct_s *msg_struct, int field, bool value)
+{
+       int err = MSG_SUCCESS;
+
+       switch (msg_struct->type) {
+       case MSG_STRUCT_SETTING_CB_OPT :
+               err = msg_set_cb_option_bool(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+               err = msg_set_cb_channel_info_bool(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_SMS_SEND_OPT :
+               err = msg_set_sms_send_opt_bool(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_MMS_SEND_OPT :
+               err = msg_set_mms_send_opt_bool(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_MMS_RECV_OPT :
+               err = msg_set_mms_recv_opt_bool(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
+               err = msg_set_push_msg_opt_bool(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SETTING_GENERAL_OPT :
+               err = msg_set_general_opt_bool(msg_struct->data, field, value);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_get_smsc_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getSMSCOption(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_smsc_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_struct == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setSMSCOption(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+int msg_get_smsc_opt_list(void *smsc_opt, int field, void **value)
+{
+       if (!smsc_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_SMSC_LIST_HIDDEN_S *smsc_opt_data = (MSG_SMSC_LIST_HIDDEN_S *)smsc_opt;
+
+       int ret = MSG_SUCCESS;
+
+       switch (field)
+       {
+       case MSG_SMSC_LIST_STRUCT :
+               *value = (void *)smsc_opt_data->smsc_list;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_get_smsc_opt_int(void *smsc_opt, int field)
+{
+       if (!smsc_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_SMSC_LIST_HIDDEN_S *smsc_opt_data = (MSG_SMSC_LIST_HIDDEN_S *)smsc_opt;
+
+       switch (field)
+       {
+       case MSG_SMSC_SELECTED_ID_INT :
+               ret = smsc_opt_data->selected;
+               break;
+       default :
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       return ret;
+}
+
+int msg_set_smsc_opt_int(void *smsc_opt, int field, int value)
+{
+       if (!smsc_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_SMSC_LIST_HIDDEN_S *smsc_opt_data = (MSG_SMSC_LIST_HIDDEN_S *)smsc_opt;
+
+       switch (field)
+       {
+       case MSG_SMSC_SELECTED_ID_INT :
+               smsc_opt_data->selected = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+int msg_get_smsc_info_int(void *smsc_info, int field)
+{
+       if (!smsc_info)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_SMSC_DATA_S *smsc_data = (MSG_SMSC_DATA_S *)smsc_info;
+
+       switch (field)
+       {
+       case MSG_SMSC_ADDR_TON_INT :
+               ret = smsc_data->smscAddr.ton;
+               break;
+       case MSG_SMSC_ADDR_NPI_INT :
+               ret = smsc_data->smscAddr.npi;
+               break;
+       case MSG_SMSC_PID_INT :
+               ret = smsc_data->pid;
+               break;
+       case MSG_SMSC_VAL_PERIOD_INT :
+               ret = smsc_data->valPeriod;
+               break;
+       default :
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       return ret;
+}
+
+int msg_set_smsc_info_int(void *smsc_info, int field, int value)
+{
+       if (!smsc_info)
+               return MSG_ERR_NULL_POINTER;
+
+       int err = MSG_SUCCESS;
+
+       MSG_SMSC_DATA_S *smsc_data = (MSG_SMSC_DATA_S *)smsc_info;
+
+       switch (field)
+       {
+       case MSG_SMSC_ADDR_TON_INT :
+               smsc_data->smscAddr.ton = value;
+               break;
+       case MSG_SMSC_ADDR_NPI_INT :
+               smsc_data->smscAddr.npi = value;
+               break;
+       case MSG_SMSC_PID_INT :
+               smsc_data->pid = value;
+               break;
+       case MSG_SMSC_VAL_PERIOD_INT :
+               smsc_data->valPeriod = value;
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+char *msg_get_smsc_info_str(void *smsc_info, int field)
+{
+       if (!smsc_info)
+               return NULL;
+
+       char *ret_str = NULL;
+
+       MSG_SMSC_DATA_S *smsc_data = (MSG_SMSC_DATA_S *)smsc_info;
+
+       switch (field)
+       {
+       case MSG_SMSC_ADDR_STR :
+               ret_str = smsc_data->smscAddr.address;
+               break;
+       case MSG_SMSC_NAME_STR :
+               ret_str = smsc_data->name;
+               break;
+       default :
+               return NULL;
+       }
+
+       return ret_str;
+}
+
+int msg_set_smsc_info_str(void *smsc_info, int field, char *val, int size)
+{
+       if (!smsc_info)
+               return MSG_ERR_NULL_POINTER;
+
+       int err = MSG_SUCCESS;
+
+       MSG_SMSC_DATA_S *smsc_data = (MSG_SMSC_DATA_S *)smsc_info;
+
+       switch (field)
+       {
+       case MSG_SMSC_ADDR_STR :
+               bzero(smsc_data->smscAddr.address, sizeof(smsc_data->smscAddr.address));
+               snprintf(smsc_data->smscAddr.address, sizeof(smsc_data->smscAddr.address), "%s", val);
+               break;
+       case MSG_SMSC_NAME_STR :
+               bzero(smsc_data->name, sizeof(smsc_data->name));
+               snprintf(smsc_data->name, sizeof(smsc_data->name), "%s", val);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_get_cb_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getCBOption(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_cb_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_struct == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setCBOption(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+int msg_get_cb_option_int(void *cb_opt, int field)
+{
+       if (!cb_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_CBMSG_OPT_HIDDEN_S *cb_opt_data = (MSG_CBMSG_OPT_HIDDEN_S *)cb_opt;
+
+       switch (field)
+       {
+       case MSG_CB_MAX_SIM_COUNT_INT :
+               ret = cb_opt_data->maxSimCnt;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_cb_option_int(void *cb_opt, int field, int value)
+{
+       if (!cb_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_CBMSG_OPT_HIDDEN_S *cb_opt_data = (MSG_CBMSG_OPT_HIDDEN_S *)cb_opt;
+
+       switch (field)
+       {
+       case MSG_CB_MAX_SIM_COUNT_INT :
+               cb_opt_data->maxSimCnt = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+
+bool msg_get_cb_option_bool(void *cb_opt, int field)
+{
+       if (!cb_opt)
+               return false;
+
+       bool ret = false;
+
+       MSG_CBMSG_OPT_HIDDEN_S *cb_opt_data = (MSG_CBMSG_OPT_HIDDEN_S *)cb_opt;
+
+       switch (field)
+       {
+       case MSG_CB_RECEIVE_BOOL :
+               ret = cb_opt_data->bReceive;
+               break;
+       case MSG_CB_LANGUAGE_TYPE_ALL_BOOL :
+               ret = cb_opt_data->bLanguage[MSG_CBLANG_TYPE_ALL];
+               break;
+       case MSG_CB_LANGUAGE_TYPE_ENG_BOOL :
+               ret = cb_opt_data->bLanguage[MSG_CBLANG_TYPE_ENG];
+               break;
+       case MSG_CB_LANGUAGE_TYPE_GER_BOOL :
+               ret = cb_opt_data->bLanguage[MSG_CBLANG_TYPE_GER];
+               break;
+       case MSG_CB_LANGUAGE_TYPE_FRE_BOOL :
+               ret = cb_opt_data->bLanguage[MSG_CBLANG_TYPE_FRE];
+               break;
+       case MSG_CB_LANGUAGE_TYPE_ITA_BOOL :
+               ret = cb_opt_data->bLanguage[MSG_CBLANG_TYPE_ITA];
+               break;
+       case MSG_CB_LANGUAGE_TYPE_NED_BOOL :
+               ret = cb_opt_data->bLanguage[MSG_CBLANG_TYPE_NED];
+               break;
+       case MSG_CB_LANGUAGE_TYPE_SPA_BOOL :
+               ret = cb_opt_data->bLanguage[MSG_CBLANG_TYPE_SPA];
+               break;
+       case MSG_CB_LANGUAGE_TYPE_POR_BOOL :
+               ret = cb_opt_data->bLanguage[MSG_CBLANG_TYPE_POR];
+               break;
+       case MSG_CB_LANGUAGE_TYPE_SWE_BOOL :
+               ret = cb_opt_data->bLanguage[MSG_CBLANG_TYPE_SWE];
+               break;
+       case MSG_CB_LANGUAGE_TYPE_TUR_BOOL :
+               ret = cb_opt_data->bLanguage[MSG_CBLANG_TYPE_TUR];
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_cb_option_bool(void *cb_opt, int field, bool value)
+{
+       if (!cb_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_CBMSG_OPT_HIDDEN_S *cb_opt_data = (MSG_CBMSG_OPT_HIDDEN_S *)cb_opt;
+
+       switch (field)
+       {
+       case MSG_CB_RECEIVE_BOOL :
+               cb_opt_data->bReceive = value;
+               break;
+       case MSG_CB_LANGUAGE_TYPE_ALL_BOOL :
+               cb_opt_data->bLanguage[MSG_CBLANG_TYPE_ALL] = value;
+               break;
+       case MSG_CB_LANGUAGE_TYPE_ENG_BOOL :
+               cb_opt_data->bLanguage[MSG_CBLANG_TYPE_ENG] = value;
+               break;
+       case MSG_CB_LANGUAGE_TYPE_GER_BOOL :
+               cb_opt_data->bLanguage[MSG_CBLANG_TYPE_GER] = value;
+               break;
+       case MSG_CB_LANGUAGE_TYPE_FRE_BOOL :
+               cb_opt_data->bLanguage[MSG_CBLANG_TYPE_FRE] = value;
+               break;
+       case MSG_CB_LANGUAGE_TYPE_ITA_BOOL :
+               cb_opt_data->bLanguage[MSG_CBLANG_TYPE_ITA] = value;
+               break;
+       case MSG_CB_LANGUAGE_TYPE_NED_BOOL :
+               cb_opt_data->bLanguage[MSG_CBLANG_TYPE_NED] = value;
+               break;
+       case MSG_CB_LANGUAGE_TYPE_SPA_BOOL :
+               cb_opt_data->bLanguage[MSG_CBLANG_TYPE_SPA] = value;
+               break;
+       case MSG_CB_LANGUAGE_TYPE_POR_BOOL :
+               cb_opt_data->bLanguage[MSG_CBLANG_TYPE_POR] = value;
+               break;
+       case MSG_CB_LANGUAGE_TYPE_SWE_BOOL :
+               cb_opt_data->bLanguage[MSG_CBLANG_TYPE_SWE] = value;
+               break;
+       case MSG_CB_LANGUAGE_TYPE_TUR_BOOL :
+               cb_opt_data->bLanguage[MSG_CBLANG_TYPE_TUR] = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+int msg_get_cb_option_list(void *cb_opt, int field, void **value)
+{
+       if (!cb_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_CBMSG_OPT_HIDDEN_S *cb_opt_data = (MSG_CBMSG_OPT_HIDDEN_S *)cb_opt;
+
+       int ret = MSG_SUCCESS;
+
+       switch (field)
+       {
+       case MSG_CB_CHANNEL_LIST_STRUCT :
+               *value = (void *)cb_opt_data->channelData;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_get_cb_channel_info_int(void *cb_ch_info, int field)
+{
+       if (!cb_ch_info)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_ERR_INVALID_PARAMETER;
+
+       MSG_CB_CHANNEL_INFO_S *cb_ch_data = (MSG_CB_CHANNEL_INFO_S *)cb_ch_info;
+
+       switch (field)
+       {
+       case MSG_CB_CHANNEL_ID_FROM_INT :
+               ret = cb_ch_data->from;
+               break;
+       case MSG_CB_CHANNEL_ID_TO_INT :
+               ret = cb_ch_data->to;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_cb_channel_info_int(void *cb_ch_info, int field, int value)
+{
+       if (!cb_ch_info)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_CB_CHANNEL_INFO_S *cb_ch_data = (MSG_CB_CHANNEL_INFO_S *)cb_ch_info;
+
+       switch (field)
+       {
+       case MSG_CB_CHANNEL_ID_FROM_INT :
+               cb_ch_data->from = value;
+               break;
+       case MSG_CB_CHANNEL_ID_TO_INT :
+               cb_ch_data->to = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+bool msg_get_cb_channel_info_bool(void *cb_ch_info, int field)
+{
+       if (!cb_ch_info)
+               return false;
+
+       bool ret = false;
+
+       MSG_CB_CHANNEL_INFO_S *cb_ch_data = (MSG_CB_CHANNEL_INFO_S *)cb_ch_info;
+
+       switch (field)
+       {
+       case MSG_CB_CHANNEL_ACTIVATE_BOOL :
+               ret = cb_ch_data->bActivate;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_cb_channel_info_bool(void *cb_ch_info, int field, bool value)
+{
+       if (!cb_ch_info)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_CB_CHANNEL_INFO_S *cb_ch_data = (MSG_CB_CHANNEL_INFO_S *)cb_ch_info;
+
+       switch (field)
+       {
+       case MSG_CB_CHANNEL_ACTIVATE_BOOL :
+               cb_ch_data->bActivate = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+char *msg_get_cb_channel_info_str(void *cb_ch_info, int field)
+{
+       if (!cb_ch_info)
+               return NULL;
+
+       char *ret_str = NULL;
+
+       MSG_CB_CHANNEL_INFO_S *cb_ch_data = (MSG_CB_CHANNEL_INFO_S *)cb_ch_info;
+
+       switch (field)
+       {
+       case MSG_CB_CHANNEL_NAME_STR :
+               ret_str = cb_ch_data->name;
+               break;
+       default :
+               break;
+       }
+
+       return ret_str;
+}
+
+int msg_set_cb_channel_info_str(void *cb_ch_info, int field, char *val, int size)
+{
+       if (!cb_ch_info)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_CB_CHANNEL_INFO_S *cb_ch_data = (MSG_CB_CHANNEL_INFO_S *)cb_ch_info;
+
+       switch (field)
+       {
+       case MSG_CB_CHANNEL_NAME_STR :
+               bzero(cb_ch_data->name, sizeof(cb_ch_data->name));
+               snprintf(cb_ch_data->name, sizeof(cb_ch_data->name), "%s", val);
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+EXPORT_API int msg_get_sms_send_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getSmsSendOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_sms_send_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_struct == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setSmsSendOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+int msg_get_sms_send_opt_int(void *sms_send_opt, int field)
+{
+       if (!sms_send_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_ERR_INVALID_PARAMETER;
+
+       MSG_SMS_SENDOPT_S *send_opt = (MSG_SMS_SENDOPT_S *)sms_send_opt;
+
+       switch (field)
+       {
+       case MSG_SMS_SENDOPT_ENCODE_TYPE_INT :
+               ret = send_opt->dcs;
+               break;
+       case MSG_SMS_SENDOPT_NETWORK_MODE_INT :
+               ret = send_opt->netMode;
+               break;
+       case MSG_SMS_SENDOPT_SAVE_STORAGE_INT :
+               ret = send_opt->saveStorage;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_sms_send_opt_int(void *sms_send_opt, int field, int value)
+{
+       if (!sms_send_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_SMS_SENDOPT_S *send_opt = (MSG_SMS_SENDOPT_S *)sms_send_opt;
+
+       switch (field)
+       {
+       case MSG_SMS_SENDOPT_ENCODE_TYPE_INT :
+               send_opt->dcs = value;
+               break;
+       case MSG_SMS_SENDOPT_NETWORK_MODE_INT :
+               send_opt->netMode = value;
+               break;
+       case MSG_SMS_SENDOPT_SAVE_STORAGE_INT :
+               send_opt->saveStorage = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+bool msg_get_sms_send_opt_bool(void *sms_send_opt, int field)
+{
+       if (!sms_send_opt)
+               return false;
+
+       bool ret = false;
+
+       MSG_SMS_SENDOPT_S *send_opt = (MSG_SMS_SENDOPT_S *)sms_send_opt;
+
+       switch (field)
+       {
+       case MSG_SMS_SENDOPT_REPLY_PATH_BOOL :
+               ret = send_opt->bReplyPath;
+               break;
+       case MSG_SMS_SENDOPT_DELIVERY_REPORT_BOOL :
+               ret = send_opt->bDeliveryReport;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_sms_send_opt_bool(void *sms_send_opt, int field, bool value)
+{
+       if (!sms_send_opt)
+               return false;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_SMS_SENDOPT_S *send_opt = (MSG_SMS_SENDOPT_S *)sms_send_opt;
+
+       switch (field)
+       {
+       case MSG_SMS_SENDOPT_REPLY_PATH_BOOL :
+               send_opt->bReplyPath = value;
+               break;
+       case MSG_SMS_SENDOPT_DELIVERY_REPORT_BOOL :
+               send_opt->bDeliveryReport = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+EXPORT_API int msg_get_mms_send_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getMmsSendOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_mms_send_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_struct == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setMmsSendOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+
+int msg_get_mms_send_opt_int(void *mms_send_opt, int field)
+{
+       if (!mms_send_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_ERR_INVALID_PARAMETER;
+
+       MSG_MMS_SENDOPT_S *send_opt = (MSG_MMS_SENDOPT_S *)mms_send_opt;
+
+       switch (field)
+       {
+       case MSG_MMS_SENDOPT_CLASS_TYPE_INT :
+               ret = send_opt->msgClass;
+               break;
+       case MSG_MMS_SENDOPT_PRIORITY_TYPE_INT :
+               ret = send_opt->priority;
+               break;
+       case MSG_MMS_SENDOPT_EXPIRY_TIME_INT :
+               ret = send_opt->expiryTime;
+               break;
+       case MSG_MMS_SENDOPT_DELIVERY_TIME_INT :
+               ret = send_opt->deliveryTime;
+               break;
+       case MSG_MMS_SENDOPT_CUSTOM_DELIVERY_TIME_INT :
+               ret = send_opt->customDeliveryTime;
+               break;
+       case MSG_MMS_SENDOPT_REPLY_CHARGING_INT :
+               ret = send_opt->replyCharging;
+               break;
+       case MSG_MMS_SENDOPT_REPLY_CHARGING_DEADLINE_INT :
+               ret = send_opt->replyChargingDeadline;
+               break;
+       case MSG_MMS_SENDOPT_REPLY_CHARGING_SIZE_INT :
+               ret = send_opt->replyChargingSize;
+               break;
+       case MSG_MMS_SENDOPT_CREATION_MODE_INT :
+               ret = send_opt->creationMode;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_mms_send_opt_int(void *mms_send_opt, int field, int value)
+{
+       if (!mms_send_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MMS_SENDOPT_S *send_opt = (MSG_MMS_SENDOPT_S *)mms_send_opt;
+
+       switch (field)
+       {
+       case MSG_MMS_SENDOPT_CLASS_TYPE_INT :
+               send_opt->msgClass = value;
+               break;
+       case MSG_MMS_SENDOPT_PRIORITY_TYPE_INT :
+               send_opt->priority = value;
+               break;
+       case MSG_MMS_SENDOPT_EXPIRY_TIME_INT :
+               send_opt->expiryTime = value;
+               break;
+       case MSG_MMS_SENDOPT_DELIVERY_TIME_INT :
+               send_opt->deliveryTime = value;
+               break;
+       case MSG_MMS_SENDOPT_CUSTOM_DELIVERY_TIME_INT :
+               send_opt->customDeliveryTime = value;
+               break;
+       case MSG_MMS_SENDOPT_REPLY_CHARGING_INT :
+               send_opt->replyCharging = value;
+               break;
+       case MSG_MMS_SENDOPT_REPLY_CHARGING_DEADLINE_INT :
+               send_opt->replyChargingDeadline = value;
+               break;
+       case MSG_MMS_SENDOPT_REPLY_CHARGING_SIZE_INT :
+               send_opt->replyChargingSize = value;
+               break;
+       case MSG_MMS_SENDOPT_CREATION_MODE_INT :
+               send_opt->creationMode = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+bool msg_get_mms_send_opt_bool(void *mms_send_opt, int field)
+{
+       if (!mms_send_opt)
+               return false;
+
+       bool ret = false;
+
+       MSG_MMS_SENDOPT_S *send_opt = (MSG_MMS_SENDOPT_S *)mms_send_opt;
+
+       switch (field)
+       {
+       case MSG_MMS_SENDOPT_SENDER_VISIBILITY_BOOL :
+               ret = send_opt->bSenderVisibility;
+               break;
+       case MSG_MMS_SENDOPT_DELIVERY_REPORT_BOOL :
+               ret = send_opt->bDeliveryReport;
+               break;
+       case MSG_MMS_SENDOPT_READ_REPLY_BOOL :
+               ret = send_opt->bReadReply;
+               break;
+       case MSG_MMS_SENDOPT_KEEP_COPY_BOOL :
+               ret = send_opt->bKeepCopy;
+               break;
+       case MSG_MMS_SENDOPT_BODY_REPLYING_BOOL :
+               ret = send_opt->bBodyReplying;
+               break;
+       case MSG_MMS_SENDOPT_HIDE_RECIPIENTS_BOOL :
+               ret = send_opt->bHideRecipients;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_mms_send_opt_bool(void *mms_send_opt, int field, bool value)
+{
+       if (!mms_send_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MMS_SENDOPT_S *send_opt = (MSG_MMS_SENDOPT_S *)mms_send_opt;
+
+       switch (field)
+       {
+       case MSG_MMS_SENDOPT_SENDER_VISIBILITY_BOOL :
+               send_opt->bSenderVisibility = value;
+               break;
+       case MSG_MMS_SENDOPT_DELIVERY_REPORT_BOOL :
+               send_opt->bDeliveryReport = value;
+               break;
+       case MSG_MMS_SENDOPT_READ_REPLY_BOOL :
+               send_opt->bReadReply = value;
+               break;
+       case MSG_MMS_SENDOPT_KEEP_COPY_BOOL :
+               send_opt->bKeepCopy = value;
+               break;
+       case MSG_MMS_SENDOPT_BODY_REPLYING_BOOL :
+               send_opt->bBodyReplying = value;
+               break;
+       case MSG_MMS_SENDOPT_HIDE_RECIPIENTS_BOOL :
+               send_opt->bHideRecipients = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+EXPORT_API int msg_get_mms_recv_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getMmsRecvOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_mms_recv_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_struct == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setMmsRecvOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+int msg_get_mms_recv_opt_int(void *mms_recv_opt, int field)
+{
+       if (!mms_recv_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_ERR_INVALID_PARAMETER;
+
+       MSG_MMS_RECVOPT_S *recv_opt = (MSG_MMS_RECVOPT_S *)mms_recv_opt;
+
+       switch (field)
+       {
+       case MSG_MMS_RECVOPT_HOME_RETRIEVE_TYPE_INT :
+               ret = recv_opt->homeNetwork;
+               break;
+       case MSG_MMS_RECVOPT_ABROAD_RETRIEVE_TYPE_INT :
+               ret = recv_opt->abroadNetwok;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_mms_recv_opt_int(void *mms_recv_opt, int field, int value)
+{
+       if (!mms_recv_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MMS_RECVOPT_S *recv_opt = (MSG_MMS_RECVOPT_S *)mms_recv_opt;
+
+       switch (field)
+       {
+       case MSG_MMS_RECVOPT_HOME_RETRIEVE_TYPE_INT :
+               recv_opt->homeNetwork = value;
+               break;
+       case MSG_MMS_RECVOPT_ABROAD_RETRIEVE_TYPE_INT :
+               recv_opt->abroadNetwok = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+bool msg_get_mms_recv_opt_bool(void *mms_recv_opt, int field)
+{
+       if (!mms_recv_opt)
+               return false;
+
+       bool ret = false;
+
+       MSG_MMS_RECVOPT_S *recv_opt = (MSG_MMS_RECVOPT_S *)mms_recv_opt;
+
+       switch (field)
+       {
+       case MSG_MMS_RECVOPT_READ_REPORT_BOOL :
+               ret = recv_opt->readReceipt;
+               break;
+       case MSG_MMS_RECVOPT_DELIVERY_REPORT_BOOL :
+               ret = recv_opt->bDeliveryReceipt;
+               break;
+       case MSG_MMS_RECVOPT_REJECT_UNKNOWN_BOOL :
+               ret = recv_opt->bRejectUnknown;
+               break;
+       case MSG_MMS_RECVOPT_REJECT_ADVERTISEMENT_BOOL :
+               ret = recv_opt->bRejectAdvertisement;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_mms_recv_opt_bool(void *mms_recv_opt, int field, bool value)
+{
+       if (!mms_recv_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MMS_RECVOPT_S *recv_opt = (MSG_MMS_RECVOPT_S *)mms_recv_opt;
+
+       switch (field)
+       {
+       case MSG_MMS_RECVOPT_READ_REPORT_BOOL :
+               recv_opt->readReceipt = value;
+               break;
+       case MSG_MMS_RECVOPT_DELIVERY_REPORT_BOOL :
+               recv_opt->bDeliveryReceipt = value;
+               break;
+       case MSG_MMS_RECVOPT_REJECT_UNKNOWN_BOOL :
+               recv_opt->bRejectUnknown = value;
+               break;
+       case MSG_MMS_RECVOPT_REJECT_ADVERTISEMENT_BOOL :
+               recv_opt->bRejectAdvertisement = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+EXPORT_API int msg_get_push_msg_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getPushMsgOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_push_msg_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_struct == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setPushMsgOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+int msg_get_push_msg_opt_int(void *push_msg_opt, int field)
+{
+       if (!push_msg_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_ERR_INVALID_PARAMETER;
+
+       MSG_PUSHMSG_OPT_S *push_opt = (MSG_PUSHMSG_OPT_S *)push_msg_opt;
+
+       switch (field)
+       {
+       case MSG_PUSHMSG_SERVICE_TYPE_INT :
+               ret = push_opt->serviceType;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_push_msg_opt_int(void *push_msg_opt, int field, int value)
+{
+       if (!push_msg_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_PUSHMSG_OPT_S *push_opt = (MSG_PUSHMSG_OPT_S *)push_msg_opt;
+
+       switch (field)
+       {
+       case MSG_PUSHMSG_SERVICE_TYPE_INT :
+               push_opt->serviceType = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+bool msg_get_push_msg_opt_bool(void *push_msg_opt, int field)
+{
+       if (!push_msg_opt)
+               return false;
+
+       bool ret = false;
+
+       MSG_PUSHMSG_OPT_S *push_opt = (MSG_PUSHMSG_OPT_S *)push_msg_opt;
+
+       switch (field)
+       {
+       case MSG_PUSHMSG_RECEIVE_BOOL :
+               ret = push_opt->bReceive;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_push_msg_opt_bool(void *push_msg_opt, int field, bool value)
+{
+       if (!push_msg_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_PUSHMSG_OPT_S *push_opt = (MSG_PUSHMSG_OPT_S *)push_msg_opt;
+
+       switch (field)
+       {
+       case MSG_PUSHMSG_RECEIVE_BOOL :
+               push_opt->bReceive = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+EXPORT_API int msg_get_voice_msg_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getVoiceMsgOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_voice_msg_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_struct == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setVoiceMsgOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+char *msg_get_voice_msg_opt_str(void *voice_msg_opt, int field)
+{
+       if (!voice_msg_opt)
+               return NULL;
+
+       char *ret_str = NULL;
+
+       MSG_VOICEMAIL_OPT_S *voice_opt = (MSG_VOICEMAIL_OPT_S *)voice_msg_opt;
+
+       switch (field)
+       {
+       case MSG_VOICEMSG_ADDRESS_STR :
+               ret_str = voice_opt->mailNumber;
+               break;
+       default :
+               break;
+       }
+
+       return ret_str;
+}
+
+int msg_set_voice_msg_opt_str(void *voice_msg_opt, int field, char *val, int size)
+{
+       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_ADDRESS_STR :
+               bzero(voice_opt->mailNumber, sizeof(voice_opt->mailNumber));
+               snprintf(voice_opt->mailNumber, sizeof(voice_opt->mailNumber), "%s", val);
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+EXPORT_API int msg_get_general_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getGeneralOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_general_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_struct == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setGeneralOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+int msg_get_general_opt_int(void *general_opt, int field)
+{
+       if (!general_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_ERR_INVALID_PARAMETER;
+
+       MSG_GENERAL_OPT_S *opt = (MSG_GENERAL_OPT_S *)general_opt;
+
+       switch (field)
+       {
+       case MSG_GENERAL_ALERT_TONE_INT :
+               ret = opt->alertTone;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_general_opt_int(void *general_opt, int field, int value)
+{
+       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_ALERT_TONE_INT :
+               opt->alertTone = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+bool msg_get_general_opt_bool(void *general_opt, int field)
+{
+       if (!general_opt)
+               return false;
+
+       int ret = false;
+
+       MSG_GENERAL_OPT_S *opt = (MSG_GENERAL_OPT_S *)general_opt;
+
+       switch (field)
+       {
+       case MSG_GENERAL_KEEP_COPY_BOOL :
+               ret = opt->bKeepCopy;
+               break;
+       case MSG_GENERAL_AUTO_ERASE_BOOL :
+               ret = opt->bAutoErase;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_general_opt_bool(void *general_opt, int field, bool value)
+{
+       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_KEEP_COPY_BOOL :
+               opt->bKeepCopy = value;
+               break;
+       case MSG_GENERAL_AUTO_ERASE_BOOL :
+               opt->bAutoErase = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
+
+EXPORT_API int msg_get_msgsize_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getMsgSizeOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_msgsize_opt(msg_handle_t handle, msg_struct_t msg_struct)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_struct == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->setMsgSizeOpt(msg_struct);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_SET_READ_ERROR;
+       }
+
+       return err;
+}
+
+int msg_get_msgsize_opt_int(void *size_opt, int field)
+{
+       if (!size_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_ERR_INVALID_PARAMETER;
+
+       MSG_MSGSIZE_OPT_S *msg_opt = (MSG_MSGSIZE_OPT_S *)size_opt;
+
+       switch (field)
+       {
+       case MSG_MESSAGE_SIZE_INT :
+               ret = msg_opt->nMsgSize;
+               break;
+       default :
+               break;
+       }
+
+       return ret;
+}
+
+int msg_set_msgsize_opt_int(void *size_opt, int field, int value)
+{
+       if (!size_opt)
+               return MSG_ERR_NULL_POINTER;
+
+       int ret = MSG_SUCCESS;
+
+       MSG_MSGSIZE_OPT_S *msg_opt = (MSG_MSGSIZE_OPT_S *)size_opt;
+
+       switch (field)
+       {
+       case MSG_MESSAGE_SIZE_INT :
+               msg_opt->nMsgSize = value;
+               break;
+       default :
+               ret = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return ret;
+}
diff --git a/mapi/msg_storage.cpp b/mapi/msg_storage.cpp
new file mode 100755 (executable)
index 0000000..0c91d73
--- /dev/null
@@ -0,0 +1,2657 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgHandle.h"
+#include "MsgDebug.h"
+#include "MsgException.h"
+
+#include "msg.h"
+#include "msg_private.h"
+#include "msg_storage.h"
+
+
+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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || opq_msg == NULL || send_opt == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       msg_struct_s *pMsgStruct = (msg_struct_s *)opq_msg;
+       msg_struct_s *pStruct = (msg_struct_s *)send_opt;
+
+       try
+       {
+               err = pHandle->addMessage((MSG_MESSAGE_HIDDEN_S *)pMsgStruct->data, (MSG_SENDINGOPT_S *)pStruct->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_add_syncml_message(msg_handle_t handle, const msg_struct_t syncml_msg)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || syncml_msg == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+       msg_struct_s *pStruct = (msg_struct_s *)syncml_msg;
+
+       try
+       {
+               err = pHandle->addSyncMLMessage((MSG_SYNCML_MESSAGE_S *)pStruct->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_update_message(msg_handle_t handle, const msg_struct_t opq_msg, const msg_struct_t send_opt)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || opq_msg == NULL || send_opt == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+       msg_struct_s *pMsgStruct = (msg_struct_s *)opq_msg;
+       msg_struct_s* pStruct = (msg_struct_s *)send_opt;
+
+       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);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_update_read_status(msg_handle_t handle, msg_message_id_t msg_id, bool read)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->updateReadStatus(msg_id, read);
+       }
+       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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->updateProtectedStatus(msg_id, is_protected);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_delete_message(msg_handle_t handle, msg_message_id_t msg_id)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->deleteMessage(msg_id);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_delete_all_msgs_in_folder(msg_handle_t handle, msg_folder_id_t folder_id, bool bOnlyDB)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->deleteAllMessagesInFolder(folder_id, bOnlyDB);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_delete_msgs_by_list(msg_handle_t handle, msg_id_list_s *msg_id_list)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->moveMessageToFolder(msg_id, dest_folder_id);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_move_msg_to_storage(msg_handle_t handle, msg_message_id_t msg_id, msg_storage_id_t storage_id)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       if (storage_id != MSG_STORAGE_PHONE && storage_id != MSG_STORAGE_SIM)
+       {
+               MSG_FATAL("unsupported storage [%d]", storage_id);
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->moveMessageToStorage(msg_id, storage_id);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_count_message(msg_handle_t handle, msg_folder_id_t folder_id, msg_struct_t count_info)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+       msg_struct_s *pStruct = (msg_struct_s *)count_info;
+       try
+       {
+               err = pHandle->countMessage(folder_id, (MSG_COUNT_INFO_S *)pStruct->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_count_msg_by_type(msg_handle_t handle, msg_message_type_t msg_type, int *msg_count)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       MSG_MESSAGE_TYPE_S msgType = {0};
+
+       if (msg_type == MSG_TYPE_SMS)
+       {
+               msgType.mainType = MSG_SMS_TYPE;
+               msgType.subType = MSG_NORMAL_SMS;
+       }
+       else if (msg_type == MSG_TYPE_SMS_WAPPUSH)
+       {
+               msgType.mainType = MSG_SMS_TYPE;
+               msgType.subType = MSG_WAP_SI_SMS;
+       }
+       else if (msg_type == MSG_TYPE_MMS)
+       {
+               msgType.mainType = MSG_MMS_TYPE;
+               msgType.subType = MSG_SENDREQ_MMS;
+       }
+
+       try
+       {
+               err = pHandle->countMsgByType(&msgType, msg_count);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || addr_info == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+       msg_struct_s *pAddr = (msg_struct_s *)addr_info;
+       msg_struct_s *pCount = (msg_struct_s *)msg_thread_count_list;
+
+       try
+       {
+               err = pHandle->countMsgByContact((MSG_THREAD_LIST_INDEX_INFO_S *)pAddr->data, (MSG_THREAD_COUNT_INFO_S *)pCount->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+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)
+{
+       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 *pMsgStruct = (msg_struct_s *)opq_msg;
+       msg_struct_s *pStruct = (msg_struct_s *)send_opt;
+
+       try
+       {
+               err = pHandle->getMessage(msg_id, (MSG_MESSAGE_HIDDEN_S *)pMsgStruct->data, (MSG_SENDINGOPT_S *)pStruct->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_get_vobject_data(msg_handle_t handle, msg_message_id_t msg_id, void** result_data)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || result_data == NULL)
+       {
+               MSG_FATAL("handle or result_data is NULL");
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getVobject(msg_id, result_data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+EXPORT_API int msg_get_conversation(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_t conv)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || !conv)
+       {
+               MSG_FATAL("handle or opq_msg is NULL");
+               return -EINVAL;
+       }
+
+       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)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+       msg_struct_s *pStruct = (msg_struct_s *)sort_rule;
+
+       try
+       {
+               if (sort_rule == NULL)
+               {
+                       MSG_SORT_RULE_S sortRule = {0};
+
+                       sortRule.sortType = MSG_SORT_BY_READ_STATUS;
+                       sortRule.bAscending = true;
+
+                       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);
+       }
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+       msg_struct_s *pStruct =(msg_struct_s *)sort_rule;
+
+       try
+       {
+               if (sort_rule == NULL)
+               {
+                       MSG_SORT_RULE_S sortRule = {0};
+
+                       sortRule.sortType = MSG_SORT_BY_THREAD_DATE;
+                       sortRule.bAscending = false;
+
+                       err = pHandle->getThreadViewList(&sortRule, msg_thread_view_list);
+               }
+               else
+               {
+                       err = pHandle->getThreadViewList((MSG_SORT_RULE_S *)pStruct->data, msg_thread_view_list);
+               }
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getConversationViewList(thread_id, msg_conv_view_list);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_delete_thread_message_list(msg_handle_t handle, msg_thread_id_t thread_id, bool include_protected_msg)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->deleteThreadMessageList(thread_id, include_protected_msg);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_add_folder(msg_handle_t handle, const msg_struct_t folder_info)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || folder_info == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+       msg_struct_s *pStruct = (msg_struct_s *)folder_info;
+
+       try
+       {
+               err = pHandle->addFolder((MSG_FOLDER_INFO_S *)pStruct->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_update_folder(msg_handle_t handle, const msg_struct_t folder_info)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || folder_info == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+       msg_struct_s *pStruct = (msg_struct_s *)folder_info;
+
+       try
+       {
+               err = pHandle->updateFolder((MSG_FOLDER_INFO_S *)pStruct->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_delete_folder(msg_handle_t handle, msg_folder_id_t folder_id)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->deleteFolder(folder_id);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_get_folder_list(msg_handle_t handle, msg_struct_list_s *folder_list)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getFolderList(folder_list);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+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)
+{
+       if (handle == NULL)
+       {
+               MSG_DEBUG("Handle is NULL");
+               return -EINVAL;
+       }
+
+       if (folder_id >= MSG_MAX_FOLDER_ID)
+       {
+               MSG_DEBUG("folderId is invalid [%d]", folder_id);
+               return -EINVAL;
+       }
+
+       MSG_DEBUG("type : %d, folder : %d, num_msg : %d", msg_type, folder_id, num_msg);
+
+       int err = 0;
+       MSG_SENDINGOPT_S sendingOpt = {0};
+       sendingOpt.bSetting = false;
+
+       char strMsg[20] = {0};
+       char prefix[10] ="0103001";
+//     int postfix = 8111;
+       int postfix = 0;
+
+       srand(getpid());
+
+       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++)
+       {
+               msg_s = (msg_struct_s *)msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
+               msgInfo = (MSG_MESSAGE_HIDDEN_S *)msg_s->data;
+
+               msgInfo->folderId = folder_id;
+
+               if (msg_type == MSG_TYPE_MMS)
+               {
+                       msgInfo->mainType = MSG_MMS_TYPE;
+                       msgInfo->subType = MSG_SENDREQ_MMS;
+               }
+               else
+               {
+                       msgInfo->mainType = MSG_SMS_TYPE;
+                       msgInfo->subType = MSG_NORMAL_SMS;
+
+                       snprintf(strMsg, sizeof(strMsg), "test msg %d", i);
+                       msgInfo->dataSize = strlen(strMsg);
+                       msgInfo->pData = (void*)new char[msgInfo->dataSize+1];
+            memcpy((char *)msgInfo->pData, strMsg, msgInfo->dataSize);
+            ((char*) msgInfo->pData)[msgInfo->dataSize] = '\0';
+               }
+
+               msgInfo->storageId = MSG_STORAGE_PHONE;
+
+               msgInfo->addr_list->nCount = 1;
+
+               addr_s = (msg_struct_s *)msgInfo->addr_list->msg_struct_info[0];
+
+               addrInfo = (MSG_ADDRESS_INFO_S *)addr_s->data;
+
+               addrInfo->addressType = MSG_ADDRESS_TYPE_PLMN;
+               postfix = rand()%10000;
+               snprintf(addrInfo->addressVal, MAX_ADDRESS_VAL_LEN+1, "%s%04d", prefix, postfix);
+
+               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;
+
+               if (folder_id == MSG_OUTBOX_ID || folder_id == MSG_SENTBOX_ID)
+                       msgInfo->direction = MSG_DIRECTION_TYPE_MO;
+               else
+                       msgInfo->direction = MSG_DIRECTION_TYPE_MT;
+
+               if (msg_type == MSG_TYPE_MMS)
+               {
+                       snprintf(msgInfo->subject, MAX_SUBJECT_LEN+1, "subject %d", i);
+
+                       if(folder_id == MSG_INBOX_ID) msgInfo->networkStatus = MSG_NETWORK_RETRIEVE_SUCCESS;
+
+                       //MMS_MESSAGE_DATA_S* mms_data;
+                       //MMS_PAGE_S* page[2];
+                       //MMS_MEDIA_S* media[5];
+
+//                     mms_data = msg_mms_create_message();
+
+//                     msg_mms_set_rootlayout(mms_data, 100, 100, 0xffffff);
+//                     msg_mms_add_region(mms_data, "Image", 0, 50, 100, 50, 0xffffff);
+//                     msg_mms_add_region(mms_data, "Text", 0, 0, 100, 50, 0xffffff);
+
+                       //------------>  1st Slide Composing
+//                     page[0] = msg_mms_add_page(mms_data, 5440);
+
+//                     media[0] = msg_mms_add_media(page[0], MMS_SMIL_MEDIA_IMG, "Image", (char*)"/opt/etc/msg-service/P091120_104633.jpg");
+//                     media[1] = msg_mms_add_media(page[0], MMS_SMIL_MEDIA_AUDIO, NULL, (char*)"/opt/etc/msg-service/audio.amr");
+//                     media[2] = msg_mms_add_media(page[0], MMS_SMIL_MEDIA_TEXT, "Text", (char*)"/opt/etc/msg-service/Temp0_2.txt");
+//                     media[2]->sMedia.sText.nColor = 0x000000;
+//                     media[2]->sMedia.sText.nSize = MMS_SMIL_FONT_SIZE_NORMAL;
+//                     media[2]->sMedia.sText.bBold = true;
+
+                       //------------>  2nd Slide Composing
+//                     page[1] = msg_mms_add_page(mms_data, 4544);
+
+//                     media[3] = msg_mms_add_media(page[1], MMS_SMIL_MEDIA_TEXT, "Text", (char*)"/opt/etc/msg-service/Temp1_0.txt");
+//                     media[3]->sMedia.sText.nColor = 0x000000;
+//                     media[3]->sMedia.sText.nSize = MMS_SMIL_FONT_SIZE_NORMAL;
+//                     media[3]->sMedia.sText.bItalic = true;
+//                     media[4] = msg_mms_add_media(page[1], MMS_SMIL_MEDIA_VIDEO, "Text", (char*)"/opt/etc/msg-service/V091120_104905.3gp");
+//                     strncpy(media[4]->szAlt, "Video Load Fail", MAX_SMIL_ALT_LEN-1);
+
+                       //FIXME msg_mms_set_message_body((msg_message_t)&msgInfo, mms_data);
+
+//                     msg_mms_destroy_message(mms_data);
+               }
+
+               //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());
+                       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;
+               }
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+EXPORT_API int msg_generate_sms(msg_handle_t handle, msg_folder_id_t folder_id, unsigned int num_msg)
+{
+       MSG_DEBUG("folder %d, num_msg %d", folder_id, num_msg);
+
+       if (handle == NULL)
+       {
+               MSG_DEBUG("Handle is NULL");
+               return -EINVAL;
+       }
+
+       if (folder_id >= MSG_MAX_FOLDER_ID)
+       {
+               MSG_DEBUG("folderId is invalid");
+               return -EINVAL;
+       }
+
+       int err = 0;
+       char strMsg[20] = {0};
+       char prefix[10] ="0103001";
+       int postfix = 0;
+
+       MSG_SENDINGOPT_S sendingOpt = {0};
+       sendingOpt.bSetting = false;
+
+       srand(getpid());
+
+       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++)
+       {
+               msg_s = (msg_struct_s *)msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
+               msgInfo = (MSG_MESSAGE_HIDDEN_S *)msg_s->data;
+
+               msgInfo->msgId  = 0; // It should be set 0
+               msgInfo->folderId = folder_id;
+
+               msgInfo->mainType = MSG_SMS_TYPE;
+               msgInfo->subType = 0;
+
+               msgInfo->storageId = MSG_STORAGE_PHONE;
+
+               snprintf(strMsg, sizeof(strMsg), "test %d", i);
+               msgInfo->dataSize = strlen(strMsg);
+               msgInfo->pData = strMsg;
+
+               msgInfo->addr_list->nCount = 1;
+
+               addr_s = (msg_struct_s *)msgInfo->addr_list->msg_struct_info[0];
+
+               addrInfo = (MSG_ADDRESS_INFO_S *)addr_s->data;
+
+               addrInfo->addressType = MSG_ADDRESS_TYPE_PLMN;
+               postfix = rand()%10000;
+               snprintf(addrInfo->addressVal, MAX_ADDRESS_VAL_LEN+1, "%s%04d", prefix, postfix);
+
+               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());
+                       msg_release_struct((msg_struct_t *)&msg_s);
+                       return MSG_ERR_STORAGE_ERROR;
+               }
+
+               msg_release_struct((msg_struct_t *)&msg_s);
+
+               if (err < 0)
+               {
+                       MSG_DEBUG("err [%d]", err);
+                       return err;
+               }
+       }
+
+       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;
+
+       try
+       {
+               err = pHandle->getQuickPanelData(type, (MSG_MESSAGE_HIDDEN_S *)pMsg->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_reset_database(msg_handle_t handle)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->resetDatabase();
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_get_mem_size(msg_handle_t handle, unsigned int* memsize)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getMemSize(memsize);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+
+}
+
+EXPORT_API int msg_backup_message(msg_handle_t handle, msg_message_backup_type_t type, const char *backup_filepath)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || backup_filepath == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->backupMessage(type, backup_filepath);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_restore_message(msg_handle_t handle, const char *backup_filepath)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || backup_filepath == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->restoreMessage(backup_filepath);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || search_string == NULL)
+       {
+               return -EINVAL;
+       }
+
+       if (strlen(search_string) <= 0 || strlen(search_string) > MAX_MSG_TEXT_LEN)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->searchMessage(search_string, msg_thread_view_list);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_search_conditions == NULL)
+       {
+               return -EINVAL;
+       }
+
+       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);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getRejectMsgList(phone_num, msg_reject_msg_list);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_reg_storage_change_callback(msg_handle_t handle, msg_storage_change_cb cb, void *user_param)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || cb == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regStorageChangeCallback(cb, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_CALLBACK_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_get_report_status(msg_handle_t handle, msg_message_id_t msg_id, msg_struct_list_s *report_list)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_id < 1 || report_list == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getReportStatus(msg_id, report_list);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getAddressList(thread_id, msg_address_list);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_address_list->nCount < 1)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getThreadIdByAddress(msg_address_list, thread_id);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_get_thread(msg_handle_t handle, msg_thread_id_t thread_id, msg_struct_t msg_thread)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msg_thread == NULL ) {
+               MSG_FATAL("handle or msg_thread is NULL");
+               return -EINVAL;
+       }
+
+       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->getThread(thread_id, pThreadInfo);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL) {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->getMessageList(folder_id, thread_id, msg_type, storage_id, msg_list);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       return err;
+}
+
+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;
+       }
+       else if (mainType == MSG_MMS_TYPE)
+       {
+               if (subType == MSG_NOTIFICATIONIND_MMS)
+                       return MSG_TYPE_MMS_NOTI;
+               else if (subType == MSG_SENDREQ_JAVA_MMS)
+                       return MSG_TYPE_MMS_JAVA;
+               else
+                       return MSG_TYPE_MMS;
+       }
+       else
+               return MSG_TYPE_INVALID;
+}
+
+
+int msg_syncml_info_get_int(void *syncml_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_SYNCML_MESSAGE_S *pSync = (MSG_SYNCML_MESSAGE_S *)syncml_info;
+       switch(field)
+       {
+       case MSG_SYNCML_INFO_EXTID_INT:
+               result = pSync->extId;
+               break;
+       case MSG_SYNCML_INFO_PINCODE_INT:
+               result = pSync->pinCode;
+               break;
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return result;
+}
+
+int msg_count_info_get_int(void *count_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_COUNT_INFO_S *pCount = (MSG_COUNT_INFO_S *)count_info;
+       switch(field)
+       {
+       case MSG_COUNT_INFO_READ_INT:
+               result = pCount->nReadCnt;
+               break;
+       case MSG_COUNT_INFO_UNREAD_INT:
+               result = pCount->nUnreadCnt;
+               break;
+       case MSG_COUNT_INFO_SMS_INT:
+               result = pCount->nSms;
+               break;
+       case MSG_COUNT_INFO_MMS_INT:
+               result = pCount->nMms;
+               break;
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return result;
+}
+
+int msg_thread_count_get_int(void *count_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_THREAD_COUNT_INFO_S *pCount = (MSG_THREAD_COUNT_INFO_S *)count_info;
+       switch(field)
+       {
+       case MSG_THREAD_COUNT_TOTAL_INT:
+               result = pCount->totalCount;
+               break;
+       case MSG_THREAD_COUNT_UNREAD_INT:
+               result = pCount->unReadCount;
+               break;
+       case MSG_THREAD_COUNT_SMS_INT:
+               result = pCount->smsMsgCount;
+               break;
+       case MSG_THREAD_COUNT_MMS_INT:
+               result = pCount->mmsMsgCount;
+               break;
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return result;
+}
+
+int msg_thread_index_get_int(void *index_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_THREAD_LIST_INDEX_S *pIndex = (MSG_THREAD_LIST_INDEX_S *)index_info;
+       switch(field)
+       {
+       case MSG_THREAD_LIST_INDEX_CONTACTID_INT:
+               result = pIndex->contactId;
+               break;
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return result;
+}
+
+int msg_sortrule_get_int(void *sort_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_SORT_RULE_S *pSort = (MSG_SORT_RULE_S *)sort_info;
+       switch(field)
+       {
+       case MSG_SORT_RULE_SORT_TYPE_INT:
+               result = pSort->sortType;
+               break;
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return result;
+}
+
+int msg_folder_info_get_int(void *folder_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_FOLDER_INFO_S *pFolder = (MSG_FOLDER_INFO_S *)folder_info;
+       switch(field)
+       {
+       case MSG_FOLDER_INFO_ID_INT:
+               result = pFolder->folderId;
+               break;
+       case MSG_FOLDER_INFO_TYPE_INT:
+               result = pFolder->folderType;
+               break;
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return result;
+}
+
+int msg_thread_info_get_int(void *data, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_THREAD_VIEW_S *pThread = (MSG_THREAD_VIEW_S *)data;
+
+       switch(field)
+       {
+       case MSG_THREAD_ID_INT :
+               result = pThread->threadId;
+               break;
+       case MSG_THREAD_MSG_TYPE_INT :
+               result = msg_get_msg_type(pThread->mainType, pThread->subType);
+               break;
+       case MSG_THREAD_MSG_TIME_INT :
+               result = pThread->threadTime;
+               break;
+       case MSG_THREAD_DIRECTION_INT :
+               result = pThread->direction;
+               break;
+       case MSG_THREAD_UNREAD_COUNT_INT :
+               result = pThread->unreadCnt;
+               break;
+       case MSG_THREAD_SMS_COUNT_INT :
+               result = pThread->smsCnt;
+               break;
+       case MSG_THREAD_MMS_COUNT_INT :
+               result = pThread->mmsCnt;
+               break;
+       default:
+               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;
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return result;
+}
+
+
+int msg_search_condition_get_int(void *condition_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_SEARCH_CONDITION_S *pCond = (MSG_SEARCH_CONDITION_S *)condition_info;
+       switch(field)
+       {
+       case MSG_SEARCH_CONDITION_FOLDERID_INT:
+               result = pCond->folderId;
+               break;
+       case MSG_SEARCH_CONDITION_MSGTYPE_INT:
+               result = pCond->msgType;
+               break;
+       case MSG_SEARCH_CONDITION_RESERVED_INT:
+               result = pCond->reserved;
+               break;
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       return result;
+}
+
+int msg_report_status_get_int(void *report_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_REPORT_STATUS_INFO_S *pReport = (MSG_REPORT_STATUS_INFO_S *)report_info;
+       switch(field)
+       {
+       case MSG_REPORT_TYPE_INT:
+               result = pReport->type;
+               break;
+       case MSG_REPORT_STATUS_INT:
+               result = pReport->status;
+               break;
+       case MSG_REPORT_TIME_INT:
+               result = pReport->statusTime;
+               break;
+
+       default:
+               result = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+       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:
+               break;
+       }
+       return result;
+}
+
+char* msg_folder_info_get_str(void *folder_info, int field)
+{
+       char *result = NULL;
+       MSG_FOLDER_INFO_S *pFolder = (MSG_FOLDER_INFO_S *)folder_info;
+       switch(field)
+       {
+       case MSG_FOLDER_INFO_NAME_STR:
+               result = pFolder->folderName;
+               break;
+       default:
+               result = NULL;
+               break;
+       }
+       return result;
+}
+
+char *msg_thread_info_get_str(void *data, int field)
+{
+       char *ret_str = NULL;
+       MSG_THREAD_VIEW_S *pThread = (MSG_THREAD_VIEW_S *)data;
+
+       switch(field)
+       {
+       case MSG_THREAD_NAME_STR :
+               ret_str = pThread->threadName;
+               break;
+       case MSG_THREAD_MSG_DATA_STR :
+               ret_str = pThread->threadData;
+               break;
+       default:
+               break;
+       }
+
+       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;
+       default:
+               break;
+       }
+
+       return ret_str;
+}
+
+
+char* msg_search_condition_get_str(void *condition_info, int field, int size)
+{
+       char *result = NULL;
+       MSG_SEARCH_CONDITION_S *search_cond = (MSG_SEARCH_CONDITION_S *)condition_info;
+       switch(field)
+       {
+       case MSG_SEARCH_CONDITION_ADDRESS_VALUE_STR:
+               result = search_cond->pAddressVal;
+               break;
+       case MSG_SEARCH_CONDITION_SEARCH_VALUE_STR:
+               result = search_cond->pSearchVal;
+               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->bSetting;
+               break;
+       case MSG_SEND_OPT_KEEPCOPY_BOOL:
+               result = sendopt->bKeepCopy;
+               break;
+       case MSG_SEND_OPT_DELIVER_REQ_BOOL:
+               result = sendopt->bDeliverReq;
+               break;
+       default:
+               break;
+       }
+       return result;
+}
+
+bool msg_sortrule_get_bool(void *sort_rule, int field)
+{
+       bool result = false;
+       MSG_SORT_RULE_S *pSort = (MSG_SORT_RULE_S *)sort_rule;
+       switch(field)
+       {
+       case MSG_SORT_RULE_ACSCEND_BOOL:
+               result = pSort->bAscending;
+               break;
+       default:
+               break;
+       }
+       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;
+       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;
+       if(!msg_struct || !value)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_SENDINGOPT_S *sendopt = (MSG_SENDINGOPT_S *)msg_struct->data;
+
+       switch(field)
+       {
+       case MSG_SEND_OPT_MMS_OPT_HND:
+               *value = (void *)sendopt->mmsSendOpt;
+               break;
+       case MSG_SEND_OPT_SMS_OPT_HND:
+               *value = (void *)sendopt->smsSendOpt;
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+       }
+       return err;
+}
+
+int msg_syncml_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_SYNCML_MESSAGE_S *pSync = (MSG_SYNCML_MESSAGE_S *)msg_struct->data;
+       switch(field)
+       {
+       case MSG_SYNCML_INFO_MESSAGE_HND:
+               *value = (void *)pSync->msg;
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+
+       }
+       return err;
+}
+
+int msg_thread_index_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_THREAD_LIST_INDEX_INFO_S *pIndex = (MSG_THREAD_LIST_INDEX_INFO_S *)msg_struct->data;
+       switch(field)
+       {
+       case MSG_SYNCML_INFO_MESSAGE_HND:
+               *value = (void *)pIndex->msgAddrInfo;
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+
+       }
+       return err;
+}
+
+int msg_address_info_get_int(void *addr_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_ADDRESS_INFO_S *pAddr = (MSG_ADDRESS_INFO_S *)addr_info;
+       switch(field)
+       {
+       case MSG_ADDRESS_INFO_ADDRESS_TYPE_INT:
+               result = pAddr->addressType;
+               break;
+       case MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT:
+               result = pAddr->recipientType;
+               break;
+       case MSG_ADDRESS_INFO_CONTACT_ID_INT:
+               result = pAddr->contactId;
+               break;
+       default:
+               break;
+       }
+       return result;
+}
+int msg_mms_sendopt_get_int(void *opt_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MMS_SENDINGOPT_S *pOpt = (MMS_SENDINGOPT_S *)opt_info;
+       switch(field)
+       {
+       case MSG_MMS_SENDOPTION_EXPIRY_TIME_INT:
+               result = pOpt->expiryTime;
+               break;
+       case MSG_MMS_SENDOPTION_DELIVERY_TIME_INT:
+               result = pOpt->deliveryTime;
+               break;
+       case MSG_MMS_SENDOPTION_PRIORITY_INT:
+               result = pOpt->priority;
+               break;
+       default:
+               break;
+       }
+       return result;
+}
+
+int msg_reject_message_get_int(void *msg_info, int field)
+{
+       int result = MSG_ERR_INVALID_PARAMETER;
+       MSG_REJECT_MSG_INFO_S *pMsg = (MSG_REJECT_MSG_INFO_S *)msg_info;
+       switch(field)
+       {
+       case MSG_REJECT_MESSAGE_MSGID_INT:
+               result = pMsg->msgId;
+               break;
+       case MSG_REJECT_MESSAGE_DISPLAY_TIME_INT:
+               result = pMsg->displayTime;
+               break;
+       default:
+               break;
+       }
+       return result;
+}
+
+char* msg_address_info_get_str(void *addr_info, int field, int size)
+{
+       char *result = NULL;
+       MSG_ADDRESS_INFO_S *pAddr = (MSG_ADDRESS_INFO_S *)addr_info;
+       switch(field)
+       {
+       case MSG_ADDRESS_INFO_ADDRESS_VALUE_STR:
+               result = pAddr->addressVal;
+               break;
+       case MSG_ADDRESS_INFO_DISPLAYNAME_STR:
+               result = pAddr->displayName;
+               break;
+
+       default:
+               result = NULL;
+               break;
+       }
+       return result;
+}
+
+char* msg_reject_message_get_str(void *msg_info, int field, int size)
+{
+       char *result = NULL;
+       MSG_REJECT_MSG_INFO_S *pMsg = (MSG_REJECT_MSG_INFO_S *)msg_info;
+       switch(field)
+       {
+       case MSG_REJECT_MESSAGE_MSGTEXT_STR:
+               result = pMsg->msgText;
+               break;
+       default:
+               result = NULL;
+               break;
+       }
+       return result;
+}
+
+bool msg_mms_sendopt_get_bool(void *opt_info, int field)
+{
+       bool result = false;
+       MMS_SENDINGOPT_S *pOpt = (MMS_SENDINGOPT_S *)opt_info;
+       switch(field)
+       {
+       case MSG_MMS_SENDOPTION_READ_REQUEST_BOOL:
+               result = pOpt->bReadReq;
+               break;
+       case MSG_MMS_SENDOPTION_DELIVERY_CUSTOMTIME_BOOL:
+               result = pOpt->bUseDeliveryCustomTime;
+               break;
+       default:
+               break;
+       }
+       return result;
+}
+
+bool msg_sms_sendopt_get_bool(void *opt_info, int field)
+{
+       bool result = false;
+       SMS_SENDINGOPT_S *pOpt = (SMS_SENDINGOPT_S *)opt_info;
+       switch(field)
+       {
+       case MSG_SMS_SENDOPT_REPLYPATH_BOOL:
+               result = pOpt->bReplyPath;
+               break;
+       default:
+               break;
+       }
+       return result;
+}
+
+int msg_syncml_info_set_int(void *syncml_info, int field, int value)
+{
+
+       msg_error_t err =  MSG_SUCCESS;
+       if(!syncml_info)
+               return MSG_ERR_NULL_POINTER;
+
+    MSG_SYNCML_MESSAGE_S *pSync = (MSG_SYNCML_MESSAGE_S *)syncml_info;
+    switch(field)
+    {
+    case MSG_SYNCML_INFO_EXTID_INT:
+               pSync->extId = value;
+               break;
+    case MSG_SYNCML_INFO_PINCODE_INT:
+               pSync->pinCode = value;
+               break;
+    default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+    }
+
+       return err;
+}
+
+int msg_count_info_set_int(void *count_info, int field, int value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!count_info)
+               return MSG_ERR_NULL_POINTER;
+
+    MSG_COUNT_INFO_S *pCount = (MSG_COUNT_INFO_S *)count_info;
+
+    switch(field)
+    {
+    case MSG_COUNT_INFO_READ_INT:
+               pCount->nReadCnt = value;
+               break;
+    case MSG_COUNT_INFO_UNREAD_INT:
+               pCount->nUnreadCnt = value;
+               break;
+    case MSG_COUNT_INFO_SMS_INT:
+               pCount->nSms = value;
+               break;
+    case MSG_COUNT_INFO_MMS_INT:
+               pCount->nMms = value;
+               break;
+    default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+    }
+       return err;
+}
+
+int msg_thread_count_set_int(void *count_info, int field, int value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!count_info)
+               return MSG_ERR_NULL_POINTER;
+
+    MSG_THREAD_COUNT_INFO_S *pCount = (MSG_THREAD_COUNT_INFO_S *)count_info;
+    switch(field)
+    {
+    case MSG_THREAD_COUNT_TOTAL_INT:
+               pCount->totalCount = value;
+               break;
+    case MSG_THREAD_COUNT_UNREAD_INT:
+               pCount->unReadCount = value;
+               break;
+    case MSG_THREAD_COUNT_SMS_INT:
+               pCount->smsMsgCount = value;
+               break;
+    case MSG_THREAD_COUNT_MMS_INT:
+               pCount->mmsMsgCount = value;
+               break;
+    default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+    }
+       return err;
+}
+
+int msg_thread_index_set_int(void *index_info, int field, int value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!index_info)
+               return MSG_ERR_NULL_POINTER;
+
+    MSG_THREAD_LIST_INDEX_S *pIndex = (MSG_THREAD_LIST_INDEX_S *)index_info;
+    switch(field)
+    {
+    case MSG_THREAD_LIST_INDEX_CONTACTID_INT:
+               pIndex->contactId = value;
+               break;
+    default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+    }
+
+       return err;
+}
+
+int msg_sortrule_set_int(void *sort_info, int field, int value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if(!sort_info)
+               return MSG_ERR_NULL_POINTER;
+
+    MSG_SORT_RULE_S *pSort = (MSG_SORT_RULE_S *)sort_info;
+    switch(field)
+    {
+    case MSG_SORT_RULE_SORT_TYPE_INT:
+               pSort->sortType = value;
+               break;
+    default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+    }
+       return err;
+}
+
+int msg_folder_info_set_int(void *folder_info, int field, int value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!folder_info)
+               return MSG_ERR_NULL_POINTER;
+
+    MSG_FOLDER_INFO_S *pFolder = (MSG_FOLDER_INFO_S *)folder_info;
+    switch(field)
+    {
+    case MSG_FOLDER_INFO_ID_INT:
+               pFolder->folderId = value;
+               break;
+    case MSG_FOLDER_INFO_TYPE_INT:
+               pFolder->folderType = value;
+               break;
+    default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+    }
+
+       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:
+               pCond->folderId = value;
+               break;
+    case MSG_SEARCH_CONDITION_MSGTYPE_INT:
+               pCond->msgType = value;
+               break;
+    case MSG_SEARCH_CONDITION_RESERVED_INT:
+               pCond->reserved = 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;
+}
+
+int msg_folder_info_set_str(void *folder_info, int field, char *value, int size)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!folder_info || !value)
+               return MSG_ERR_NULL_POINTER;
+    MSG_FOLDER_INFO_S *pFolder = (MSG_FOLDER_INFO_S *)folder_info;
+    int _len = 0;
+    (size > MAX_FOLDER_NAME_SIZE)? _len = MAX_FOLDER_NAME_SIZE : _len = size;
+    switch(field)
+    {
+    case MSG_FOLDER_INFO_NAME_STR:
+               strncpy(pFolder->folderName, value, _len);
+               break;
+    default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+    }
+
+       return err;
+}
+
+int msg_search_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_SEARCH_CONDITION_S *search_cond = (MSG_SEARCH_CONDITION_S *)condition_info;
+
+    switch(field)
+    {
+    case MSG_SEARCH_CONDITION_ADDRESS_VALUE_STR:
+               search_cond->pAddressVal = value;
+               break;
+    case MSG_SEARCH_CONDITION_SEARCH_VALUE_STR:
+               search_cond->pSearchVal = 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;
+       if(!send_opt)
+               return MSG_ERR_NULL_POINTER;
+
+    MSG_SENDINGOPT_S *sendopt = (MSG_SENDINGOPT_S *)send_opt;
+    switch(field)
+    {
+    case MSG_SEND_OPT_SETTING_BOOL:
+               sendopt->bSetting = value;
+               break;
+    case MSG_SEND_OPT_KEEPCOPY_BOOL:
+               sendopt->bKeepCopy = value;
+               break;
+    case MSG_SEND_OPT_DELIVER_REQ_BOOL:
+               sendopt->bDeliverReq = value;
+               break;
+    default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+    }
+       return err;
+}
+
+int msg_sortrule_set_bool(void *sort_rule, int field, bool value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       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:
+               pSort->bAscending = 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;
+       if(!msg_struct || !value)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_SENDINGOPT_S *sendopt = (MSG_SENDINGOPT_S *)msg_struct->data;
+       msg_struct_s *pTmp = NULL;
+
+       switch(field)
+       {
+       case MSG_SEND_OPT_MMS_OPT_HND:
+               pTmp = (msg_struct_s *)sendopt->mmsSendOpt;
+               memcpy(pTmp->data, value->data, sizeof(MMS_SENDINGOPT_INFO_S));
+               break;
+       case MSG_SEND_OPT_SMS_OPT_HND:
+               pTmp = (msg_struct_s *)sendopt->smsSendOpt;
+               memcpy(pTmp->data, value->data, sizeof(SMS_SENDINGOPT_INFO_S));
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+       }
+       return err;
+}
+
+int msg_syncml_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_SYNCML_MESSAGE_S *pSync = (MSG_SYNCML_MESSAGE_S *)msg_struct->data;
+       msg_struct_s *pTmp = NULL;
+
+       switch(field)
+       {
+       case MSG_SYNCML_INFO_MESSAGE_HND:
+       {
+               pTmp = (msg_struct_s *)pSync->msg;
+               MSG_MESSAGE_HIDDEN_S *pSrc = (MSG_MESSAGE_HIDDEN_S *)value->data;
+               MSG_MESSAGE_HIDDEN_S *pDst = (MSG_MESSAGE_HIDDEN_S *)pTmp->data;
+               msg_message_copy_message(pSrc, pDst);
+               break;
+       }
+       default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+
+       }
+       return err;
+}
+
+int msg_thread_index_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_THREAD_LIST_INDEX_INFO_S *pIndex = (MSG_THREAD_LIST_INDEX_INFO_S *)msg_struct->data;
+       msg_struct_s *pTmp = NULL;
+
+       switch(field)
+       {
+       case MSG_THREAD_LIST_INDEX_ADDR_INFO_HND:
+               pTmp = (msg_struct_s *)pIndex->msgAddrInfo;
+               memcpy(pTmp->data, value->data, sizeof(MSG_ADDRESS_INFO_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;
+       if(!addrinfo)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_ADDRESS_INFO_S *pAddr = (MSG_ADDRESS_INFO_S *)addrinfo;
+       switch(field)
+       {
+       case MSG_ADDRESS_INFO_ADDRESS_TYPE_INT:
+               pAddr->addressType = value;
+               break;
+       case MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT:
+               pAddr->recipientType = value;
+               break;
+       case MSG_ADDRESS_INFO_CONTACT_ID_INT:
+               pAddr->contactId = value;
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+       break;
+       }
+
+       return err;
+}
+
+
+int msg_mms_sendopt_set_int(void *opt_info, int field, int value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!opt_info)
+               return MSG_ERR_NULL_POINTER;
+
+       MMS_SENDINGOPT_S *pOpt = (MMS_SENDINGOPT_S *)opt_info;
+       switch(field)
+       {
+       case MSG_MMS_SENDOPTION_EXPIRY_TIME_INT:
+               pOpt->expiryTime = value;
+               break;
+       case MSG_MMS_SENDOPTION_DELIVERY_TIME_INT:
+               pOpt->deliveryTime = value;
+               break;
+       case MSG_MMS_SENDOPTION_PRIORITY_INT:
+               pOpt->priority = value;
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+       break;
+       }
+
+       return err;
+}
+
+int msg_reject_message_set_int(void *msg_info, int field, int value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!msg_info)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_REJECT_MSG_INFO_S *pMsg = (MSG_REJECT_MSG_INFO_S *)msg_info;
+       switch(field)
+       {
+       case MSG_REJECT_MESSAGE_MSGID_INT:
+               pMsg->msgId = value;
+               break;
+       case MSG_REJECT_MESSAGE_DISPLAY_TIME_INT:
+               pMsg->displayTime = value;
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+       break;
+       }
+
+       return err;
+}
+
+int msg_address_info_set_str(void *addr_info, int field, char *value, int size)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!addr_info || !value)
+               return MSG_ERR_NULL_POINTER;
+    MSG_ADDRESS_INFO_S *pAddr = (MSG_ADDRESS_INFO_S *)addr_info;
+    int _len = 0;
+
+    switch(field)
+    {
+    case MSG_ADDRESS_INFO_ADDRESS_VALUE_STR:
+        (size > MAX_ADDRESS_VAL_LEN)? _len = MAX_ADDRESS_VAL_LEN : _len = size;
+        memset(pAddr->addressVal, 0x00, sizeof(pAddr->addressVal));
+               strncpy(pAddr->addressVal, value, _len);
+               break;
+    case MSG_ADDRESS_INFO_DISPLAYNAME_STR:
+        (size > MAX_DISPLAY_NAME_LEN)? _len = MAX_DISPLAY_NAME_LEN : _len = size;
+        memset(pAddr->displayName, 0x00, sizeof(pAddr->displayName));
+               strncpy(pAddr->displayName, 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;
+       if(!msg_info || !value)
+               return MSG_ERR_NULL_POINTER;
+    MSG_REJECT_MSG_INFO_S *pMsg = (MSG_REJECT_MSG_INFO_S *)msg_info;
+    int _len = 0;
+    (size > MAX_MSG_TEXT_LEN)? _len = MAX_MSG_TEXT_LEN : _len = size;
+    switch(field)
+    {
+    case MSG_REJECT_MESSAGE_MSGTEXT_STR:
+               strncpy(pMsg->msgText, value, _len);
+               break;
+    default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+    }
+
+       return err;
+}
+
+int msg_mms_sendopt_set_bool(void *option, int field, bool value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!option)
+               return MSG_ERR_NULL_POINTER;
+
+    MMS_SENDINGOPT_S *pOpt = (MMS_SENDINGOPT_S *)option;
+    switch(field)
+    {
+    case MSG_MMS_SENDOPTION_READ_REQUEST_BOOL:
+               pOpt->bReadReq = value;
+               break;
+    case MSG_MMS_SENDOPTION_DELIVERY_CUSTOMTIME_BOOL:
+               pOpt->bUseDeliveryCustomTime = value;
+               break;
+    default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+    }
+       return err;
+}
+
+int msg_sms_sendopt_set_bool(void *option, int field, bool value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!option)
+               return MSG_ERR_NULL_POINTER;
+
+    SMS_SENDINGOPT_S *pOpt = (SMS_SENDINGOPT_S *)option;
+    switch(field)
+    {
+    case MSG_SMS_SENDOPT_REPLYPATH_BOOL:
+               pOpt->bReplyPath = value;
+               break;
+    default:
+       err = MSG_ERR_UNKNOWN;
+               break;
+    }
+       return err;
+}
+
+EXPORT_API int msg_add_push_event(msg_handle_t handle, const msg_struct_t push_event)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || push_event == NULL)
+       {
+               return -EINVAL;
+       }
+
+       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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || push_event == NULL)
+       {
+               return -EINVAL;
+       }
+
+       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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || src_event == NULL || dst_event == NULL)
+       {
+               return -EINVAL;
+       }
+
+       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;
+}
diff --git a/mapi/msg_svc.cpp b/mapi/msg_svc.cpp
new file mode 100755 (executable)
index 0000000..e8e85ee
--- /dev/null
@@ -0,0 +1,1462 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "msg_private.h"
+#include "msg.h"
+
+#define MSG_TYPE_CHECK(a, b) \
+               ({\
+                       if(a != (b & 0xff00)) return MSG_ERR_INVALID_PARAMETER; \
+               })\
+
+
+
+EXPORT_API msg_struct_t msg_create_struct(int field)
+{
+       msg_struct_s *msg_struct = new msg_struct_s;
+       memset(msg_struct, 0x00, sizeof(msg_struct_s));
+
+       msg_struct->type = field;
+
+       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;
+               memset(msg_struct->data, 0x00, sizeof(MSG_FILTER_S));
+               break;
+       }
+       case MSG_STRUCT_THREAD_INFO:
+       {
+               msg_struct->data = (void *)new MSG_THREAD_VIEW_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_THREAD_VIEW_S));
+               break;
+       }
+       case MSG_STRUCT_SENDOPT:
+       {
+               MSG_SENDINGOPT_S *pOpt = (MSG_SENDINGOPT_S *)new MSG_SENDINGOPT_S;
+               memset(pOpt, 0x00, sizeof(MSG_SENDINGOPT_S));
+               msg_struct->data = pOpt;
+
+               msg_struct_s *pSms = new msg_struct_s;
+               msg_struct_s *pMms = new msg_struct_s;
+
+               pOpt->mmsSendOpt = (msg_struct_t)pMms;
+               pOpt->smsSendOpt = (msg_struct_t)pSms;
+
+               pMms->type = MSG_STRUCT_MMS_SENDOPT;
+               pMms->data = new MMS_SENDINGOPT_S;
+               memset(pMms->data, 0x00, sizeof(MMS_SENDINGOPT_S));
+
+               pSms->type = MSG_STRUCT_SMS_SENDOPT;
+               pSms->data = new SMS_SENDINGOPT_S;
+               memset(pSms->data, 0x00, sizeof(SMS_SENDINGOPT_S));
+               break;
+       }
+       case MSG_STRUCT_SYNCML_INFO:
+       {
+               MSG_SYNCML_MESSAGE_S *pSyncML= (MSG_SYNCML_MESSAGE_S *)new MSG_SYNCML_MESSAGE_S;
+               memset(pSyncML, 0x00, sizeof(MSG_SYNCML_MESSAGE_S));
+               msg_struct->data = pSyncML;
+
+               msg_struct_s *pStruct = new msg_struct_s;
+               pSyncML->msg = (msg_struct_t)pStruct;
+               pStruct->type = MSG_STRUCT_MESSAGE_INFO;
+               msg_message_create_struct(pStruct);
+
+               break;
+       }
+       case MSG_STRUCT_COUNT_INFO:
+       {
+               msg_struct->data = new MSG_COUNT_INFO_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_COUNT_INFO_S));
+               break;
+       }
+       case MSG_STRUCT_THREAD_COUNT_INFO:
+       {
+               msg_struct->data = new MSG_THREAD_COUNT_INFO_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_THREAD_COUNT_INFO_S));
+               break;
+       }
+       case MSG_STRUCT_THREAD_LIST_INDEX:
+       {
+               MSG_THREAD_LIST_INDEX_INFO_S * pThread = (MSG_THREAD_LIST_INDEX_INFO_S *)new MSG_THREAD_LIST_INDEX_INFO_S;
+               memset(pThread, 0x00, sizeof(MSG_THREAD_LIST_INDEX_INFO_S));
+
+               msg_struct->data = (void *)pThread;
+
+               msg_struct_s *pStruct = new msg_struct_s;
+               pThread->msgAddrInfo = (msg_struct_t)pStruct;
+
+               pStruct->type = MSG_STRUCT_ADDRESS_INFO;
+               pStruct->data = new MSG_ADDRESS_INFO_S;
+               memset(pStruct->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+
+               break;
+       }
+       case MSG_STRUCT_SORT_RULE:
+       {
+               msg_struct->data = new MSG_SORT_RULE_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_SORT_RULE_S));
+               break;
+       }
+       case MSG_STRUCT_FOLDER_INFO:
+       {
+               msg_struct->data = new MSG_FOLDER_INFO_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_FOLDER_INFO_S));
+               break;
+       }
+       case MSG_STRUCT_SEARCH_CONDITION:
+       {
+               msg_struct->data = new MSG_SEARCH_CONDITION_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_SEARCH_CONDITION_S));
+               break;
+       }
+       case MSG_STRUCT_REPORT_STATUS_INFO:
+       {
+               msg_struct->data = new MSG_REPORT_STATUS_INFO_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_REPORT_STATUS_INFO_S));
+               break;
+       }
+       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_SMSC_LIST_HIDDEN_S *pTmp = (MSG_SMSC_LIST_HIDDEN_S *)msg_struct->data;
+
+        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;
+
+        smsc_list->msg_struct_info = (msg_struct_t *)new char[sizeof(msg_struct_t)*SMSC_LIST_MAX];
+
+        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;
+        }
+               break;
+       }
+       case MSG_STRUCT_SETTING_SMSC_INFO :
+       {
+               msg_struct->data = new MSG_SMSC_DATA_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_SMSC_DATA_S));
+               break;
+       }
+       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_CBMSG_OPT_HIDDEN_S *pTmp = (MSG_CBMSG_OPT_HIDDEN_S *)msg_struct->data;
+
+        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];
+
+        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;
+        }
+
+               break;
+       }
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+       {
+               msg_struct->data = new MSG_CB_CHANNEL_INFO_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_CB_CHANNEL_INFO_S));
+               break;
+       }
+       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));
+               break;
+       }
+       case MSG_STRUCT_SETTING_MMS_SEND_OPT :
+       {
+               msg_struct->data = new MSG_MMS_SENDOPT_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_MMS_SENDOPT_S));
+               break;
+       }
+       case MSG_STRUCT_SETTING_MMS_RECV_OPT :
+       {
+               msg_struct->data = new MSG_MMS_RECVOPT_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_MMS_RECVOPT_S));
+               break;
+       }
+       case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
+       {
+               msg_struct->data = new MSG_PUSHMSG_OPT_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_PUSHMSG_OPT_S));
+               break;
+       }
+       case MSG_STRUCT_SETTING_VOICE_MSG_OPT :
+       {
+               msg_struct->data = new MSG_VOICEMAIL_OPT_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_VOICEMAIL_OPT_S));
+               break;
+       }
+       case MSG_STRUCT_SETTING_GENERAL_OPT :
+       {
+               msg_struct->data = new MSG_GENERAL_OPT_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_GENERAL_OPT_S));
+               break;
+       }
+       case MSG_STRUCT_SETTING_MSGSIZE_OPT :
+       {
+               msg_struct->data = new MSG_MSGSIZE_OPT_S;
+               memset(msg_struct->data, 0x00, sizeof(MSG_MSGSIZE_OPT_S));
+               break;
+       }
+       case MSG_STRUCT_SMS_SENDOPT:
+       {
+               msg_struct->data = new SMS_SENDINGOPT_S;
+               memset(msg_struct->data, 0x00, sizeof(SMS_SENDINGOPT_S));
+               break;
+       }
+       case MSG_STRUCT_MMS_SENDOPT:
+       {
+               msg_struct->data = new MMS_SENDINGOPT_S;
+               memset(msg_struct->data, 0x00, sizeof(MMS_SENDINGOPT_S));
+               break;
+       }
+       case MSG_STRUCT_REQUEST_INFO:
+       {
+               MSG_REQUEST_S *pRequest = (MSG_REQUEST_S *)new MSG_REQUEST_S;
+               memset(pRequest, 0x00, sizeof(MSG_REQUEST_S));
+               msg_struct->data = pRequest;
+
+               msg_struct_s *pMsg = (msg_struct_s *)new msg_struct_s;
+               msg_struct_s *pOpt = (msg_struct_s *)new msg_struct_s;
+
+               pRequest->msg = (msg_struct_t)pMsg;
+               pRequest->sendOpt = (msg_struct_t)pOpt;
+
+               pMsg->type = MSG_STRUCT_MESSAGE_INFO;
+               msg_message_create_struct(pMsg);
+
+               pOpt->type = MSG_STRUCT_SENDOPT;
+               pOpt->data = new MSG_SENDINGOPT_S;
+               memset(pOpt->data, 0x00, sizeof(MSG_SENDINGOPT_S));
+               msg_struct_s *pSms = new msg_struct_s;
+               msg_struct_s *pMms = new msg_struct_s;
+
+               MSG_SENDINGOPT_S *sendOpt = (MSG_SENDINGOPT_S *)pOpt->data;
+
+               sendOpt->mmsSendOpt = (msg_struct_t)pMms;
+               sendOpt->smsSendOpt = (msg_struct_t)pSms;
+
+               pMms->type = MSG_STRUCT_MMS_SENDOPT;
+               pMms->data = new MMS_SENDINGOPT_S;
+               memset(pMms->data, 0x00, sizeof(MMS_SENDINGOPT_S));
+
+               pSms->type = MSG_STRUCT_SMS_SENDOPT;
+               pSms->data = new SMS_SENDINGOPT_S;
+               memset(pSms->data, 0x00, sizeof(SMS_SENDINGOPT_S));
+               break;
+       }
+       case MSG_STRUCT_MMS:
+       case MSG_STRUCT_MMS_PAGE:
+       case MSG_STRUCT_MMS_MEDIA:
+       case MSG_STRUCT_MMS_ATTACH:
+       case MSG_STRUCT_MMS_REGION:
+       case MSG_STRUCT_MMS_TRANSITION:
+       case MSG_STRUCT_MMS_META:
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       case MSG_STRUCT_MMS_SMIL_AVI:
+               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;
+       }
+
+       return (msg_struct_t) msg_struct;
+}
+
+
+EXPORT_API int msg_release_struct(msg_struct_t *msg_struct_handle)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_handle == NULL || *msg_struct_handle == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_struct_s *msg_struct = (msg_struct_s *)*msg_struct_handle;
+
+       switch(msg_struct->type)
+       {
+       case MSG_STRUCT_MESSAGE_INFO :
+       {
+               msg_message_release(&msg_struct);
+
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_FILTER:
+       {
+               delete (MSG_FILTER_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_CONV_INFO:
+       {
+               MSG_CONVERSATION_VIEW_S *pConv = (MSG_CONVERSATION_VIEW_S*)(msg_struct->data);
+
+               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);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_SENDOPT:
+       {
+               MSG_SENDINGOPT_S *pOpt = (MSG_SENDINGOPT_S*)(msg_struct->data);
+               delete (MMS_SENDINGOPT_S *)(((msg_struct_s *)pOpt->mmsSendOpt)->data);
+               ((msg_struct_s *)pOpt->mmsSendOpt)->data = NULL;
+               delete (msg_struct_s *)pOpt->mmsSendOpt;
+               pOpt->mmsSendOpt = NULL;
+
+               delete (SMS_SENDINGOPT_S *)(((msg_struct_s *)pOpt->smsSendOpt)->data);
+               ((msg_struct_s *)pOpt->smsSendOpt)->data = NULL;
+               delete (msg_struct_s *)pOpt->smsSendOpt;
+               pOpt->smsSendOpt = NULL;
+
+               delete pOpt;
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+
+               break;
+       }
+       case MSG_STRUCT_SYNCML_INFO:
+       {
+               MSG_SYNCML_MESSAGE_S *pSyncML = (MSG_SYNCML_MESSAGE_S*)(msg_struct->data);
+               msg_struct_s *msg = (msg_struct_s *)pSyncML->msg;
+               msg_message_release(&msg);
+
+               delete pSyncML;
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_COUNT_INFO:
+       {
+               delete (MSG_COUNT_INFO_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_THREAD_COUNT_INFO:
+       {
+               delete (MSG_THREAD_COUNT_INFO_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+
+               break;
+       }
+       case MSG_STRUCT_THREAD_LIST_INDEX:
+       {
+               MSG_THREAD_LIST_INDEX_INFO_S *pThread = (MSG_THREAD_LIST_INDEX_INFO_S*)(msg_struct->data);
+               delete (MSG_ADDRESS_INFO_S *)(((msg_struct_s *)pThread->msgAddrInfo)->data);
+               ((msg_struct_s *)pThread->msgAddrInfo)->data = NULL;
+               delete (msg_struct_s *)pThread->msgAddrInfo;
+               pThread->msgAddrInfo = NULL;
+               delete pThread;
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+
+               break;
+       }
+       case MSG_STRUCT_SORT_RULE:
+       {
+               delete (MSG_SORT_RULE_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+
+               break;
+       }
+       case MSG_STRUCT_FOLDER_INFO:
+       {
+               delete (MSG_FOLDER_INFO_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+
+               break;
+       }
+       case MSG_STRUCT_SEARCH_CONDITION:
+       {
+               delete (MSG_SEARCH_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);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+
+               break;
+       }
+       case MSG_STRUCT_SMS_SENDOPT:
+       {
+               delete (SMS_SENDINGOPT_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+
+               break;
+       }
+       case MSG_STRUCT_MMS_SENDOPT:
+       {
+               delete (MMS_SENDINGOPT_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+
+               break;
+       }
+       case MSG_STRUCT_REQUEST_INFO:
+       {
+               MSG_REQUEST_S *pRequest = (MSG_REQUEST_S*)(msg_struct->data);
+
+               MSG_SENDINGOPT_S *pSendingOpt = (MSG_SENDINGOPT_S *)(((msg_struct_s *)pRequest->sendOpt)->data);
+
+               msg_struct_s *pMmsOpt = (msg_struct_s *)pSendingOpt->mmsSendOpt;
+               msg_struct_s *pSmsOpt = (msg_struct_s *)pSendingOpt->smsSendOpt;
+
+               delete (MMS_SENDINGOPT_S *)(pMmsOpt->data);
+               pMmsOpt->data = NULL;
+               delete (msg_struct_s *)pSendingOpt->mmsSendOpt;
+               pSendingOpt->mmsSendOpt = NULL;
+               delete (MMS_SENDINGOPT_S *)(pSmsOpt->data);
+               pSmsOpt->data = NULL;
+               delete (msg_struct_s *)pSendingOpt->smsSendOpt;
+               pSendingOpt->smsSendOpt = NULL;
+
+               delete (MSG_SENDINGOPT_S *)pSendingOpt;
+               ((msg_struct_s *)pRequest->sendOpt)->data = NULL;
+               delete (msg_struct_s *)pRequest->sendOpt;
+               pRequest->sendOpt = NULL;
+
+               msg_struct_s *msg = (msg_struct_s *)pRequest->msg;
+               msg_message_release(&msg);
+
+               delete pRequest;
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_MMS:
+       case MSG_STRUCT_MMS_PAGE:
+       case MSG_STRUCT_MMS_MEDIA:
+       case MSG_STRUCT_MMS_ATTACH:
+       case MSG_STRUCT_MMS_REGION:
+       case MSG_STRUCT_MMS_TRANSITION:
+       case MSG_STRUCT_MMS_META:
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       case MSG_STRUCT_MMS_SMIL_AVI:
+       {
+               msg_mms_release_struct(&msg_struct);
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_SETTING_SMSC_OPT :
+       {
+               msg_struct_list_s *smsc_list = NULL;
+               msg_struct_s *smsc_info = NULL;
+               MSG_SMSC_LIST_HIDDEN_S *pTmp = NULL;
+
+               pTmp = (MSG_SMSC_LIST_HIDDEN_S *)msg_struct->data;
+               smsc_list = (msg_struct_list_s *)pTmp->smsc_list;
+
+               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 [] smsc_list->msg_struct_info;
+
+               delete [] (MSG_SMSC_LIST_HIDDEN_S*)pTmp;
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+       {
+               delete (MSG_CB_CHANNEL_INFO_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_SETTING_CB_OPT :
+       {
+               msg_struct_list_s *cb_list = NULL;
+               msg_struct_s *cb_info = NULL;
+               MSG_CBMSG_OPT_HIDDEN_S *pTmp = NULL;
+
+               pTmp = (MSG_CBMSG_OPT_HIDDEN_S *)msg_struct->data;
+               cb_list = (msg_struct_list_s *)pTmp->channelData;
+
+               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 [] cb_list->msg_struct_info;
+
+               delete [] (MSG_CBMSG_OPT_HIDDEN_S*)pTmp;
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_SETTING_SMS_SEND_OPT :
+       {
+               delete (MSG_SMS_SENDOPT_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_SETTING_MMS_SEND_OPT :
+       {
+               delete (MSG_MMS_SENDOPT_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_SETTING_MMS_RECV_OPT :
+       {
+               delete (MSG_MMS_RECVOPT_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
+       {
+               delete (MSG_PUSHMSG_OPT_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_SETTING_VOICE_MSG_OPT :
+       {
+               delete (MSG_VOICEMAIL_OPT_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_SETTING_GENERAL_OPT :
+       {
+               delete (MSG_GENERAL_OPT_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *msg_struct_handle = NULL;
+               break;
+       }
+       case MSG_STRUCT_SETTING_MSGSIZE_OPT :
+       {
+               delete (MSG_MSGSIZE_OPT_S*)(msg_struct->data);
+               msg_struct->data = NULL;
+
+               delete msg_struct;
+               *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;
+       }
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+int msg_release_list_struct(msg_struct_list_s *msg_struct_list)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_list == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       if (msg_struct_list->msg_struct_info == NULL) {
+               if (msg_struct_list->nCount > 0)
+                       msg_struct_list->nCount = 0;
+               return err;
+       }
+
+       if(msg_struct_list->nCount > 0) {
+               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++) {
+                       msg_release_struct(&(msg_struct_list->msg_struct_info[i]));
+               }
+       }
+
+       //free peer info list
+       delete [] msg_struct_list->msg_struct_info;
+       msg_struct_list->msg_struct_info = NULL;
+
+       return err;
+}
+
+EXPORT_API int msg_get_int_value(msg_struct_t msg_struct_handle, int field, int *value)
+{
+
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_handle == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
+       MSG_TYPE_CHECK(msg_struct->type, field);
+
+       if (msg_struct->data == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       switch (msg_struct->type)
+       {
+       case MSG_STRUCT_MESSAGE_INFO :
+               err = msg_message_get_int_value(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_FILTER:
+               *value = msg_get_filter_info_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SYNCML_INFO :
+               *value = msg_syncml_info_get_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_COUNT_INFO :
+               *value = msg_count_info_get_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_THREAD_COUNT_INFO :
+               *value = msg_thread_count_get_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_THREAD_LIST_INDEX :
+               *value = msg_thread_index_get_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SORT_RULE :
+               *value = msg_sortrule_get_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_FOLDER_INFO :
+               *value = msg_folder_info_get_int(msg_struct->data, field);
+               break;
+       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_REPORT_STATUS_INFO :
+               *value = msg_report_status_get_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_ADDRESS_INFO :
+               *value = msg_address_info_get_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_MMS_SENDOPT :
+               *value = msg_mms_sendopt_get_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_REJECT_MSG_INFO :
+               *value = msg_reject_message_get_int(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_REQUEST_INFO :
+               *value = msg_request_get_int(msg_struct->data, field);
+               break;
+       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:
+       case MSG_STRUCT_MMS_ATTACH:
+       case MSG_STRUCT_MMS_REGION:
+       case MSG_STRUCT_MMS_TRANSITION:
+       case MSG_STRUCT_MMS_META:
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       case MSG_STRUCT_MMS_SMIL_AVI:
+               err = msg_mms_get_int_value(msg_struct, field, value);
+               break;
+       case MSG_STRUCT_SETTING_SMSC_OPT :
+       case MSG_STRUCT_SETTING_SMSC_INFO :
+       case MSG_STRUCT_SETTING_CB_OPT :
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+       case MSG_STRUCT_SETTING_SMS_SEND_OPT :
+       case MSG_STRUCT_SETTING_MMS_SEND_OPT :
+       case MSG_STRUCT_SETTING_MMS_RECV_OPT :
+       case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
+       case MSG_STRUCT_SETTING_GENERAL_OPT :
+       case MSG_STRUCT_SETTING_MSGSIZE_OPT :
+               err = msg_setting_get_int_value(msg_struct, field, value);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_get_str_value(msg_struct_t msg_struct_handle, int field, char *src, int size)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_handle == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
+
+       if (msg_struct->data == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       char *ret_str = NULL;
+
+       switch (msg_struct->type)
+       {
+       case MSG_STRUCT_MESSAGE_INFO :
+               err = msg_message_get_str_value(msg_struct->data, field, src, size);
+               break;
+       case MSG_STRUCT_FILTER:
+               ret_str = msg_get_filter_info_str(msg_struct->data, field);
+                       if (ret_str == NULL)
+                               err = MSG_ERR_UNKNOWN;
+                       else
+                               strncpy(src, ret_str, size);
+               break;
+       case MSG_STRUCT_FOLDER_INFO :
+               ret_str = msg_folder_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_THREAD_INFO :
+               ret_str = msg_thread_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_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)
+                       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);
+               if (ret_str == NULL)
+                       err = MSG_ERR_UNKNOWN;
+               else
+                       strncpy(src, ret_str, size);
+               break;
+
+       case MSG_STRUCT_REJECT_MSG_INFO :
+               ret_str = msg_reject_message_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:
+       case MSG_STRUCT_MMS_ATTACH:
+       case MSG_STRUCT_MMS_REGION:
+       case MSG_STRUCT_MMS_TRANSITION:
+       case MSG_STRUCT_MMS_META:
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       case MSG_STRUCT_MMS_SMIL_AVI:
+               err = msg_mms_get_str_value(msg_struct, field, src, size);
+               break;
+       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;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_get_bool_value(msg_struct_t msg_struct_handle, int field, bool *value)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_handle == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
+
+       if (msg_struct->data == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       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_MMS_SENDOPT:
+               *value = msg_mms_sendopt_get_bool(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_SMS_SENDOPT:
+               *value = msg_sms_sendopt_get_bool(msg_struct->data, field);
+               break;
+       case MSG_STRUCT_MMS:
+       case MSG_STRUCT_MMS_PAGE:
+       case MSG_STRUCT_MMS_MEDIA:
+       case MSG_STRUCT_MMS_ATTACH:
+       case MSG_STRUCT_MMS_REGION:
+       case MSG_STRUCT_MMS_TRANSITION:
+       case MSG_STRUCT_MMS_META:
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       case MSG_STRUCT_MMS_SMIL_AVI:
+               err = msg_mms_get_bool_value(msg_struct, field, value);
+               break;
+       case MSG_STRUCT_SETTING_CB_OPT :
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+       case MSG_STRUCT_SETTING_SMS_SEND_OPT :
+       case MSG_STRUCT_SETTING_MMS_SEND_OPT :
+       case MSG_STRUCT_SETTING_MMS_RECV_OPT :
+       case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
+       case MSG_STRUCT_SETTING_GENERAL_OPT :
+               err = msg_setting_get_bool_value(msg_struct, field, value);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_get_struct_handle(msg_struct_t msg_struct_handle, int field, msg_struct_t *value)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_handle == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
+
+       if (msg_struct->data == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       switch (msg_struct->type)
+       {
+       case MSG_STRUCT_MESSAGE_INFO :
+               err = msg_message_get_struct_hnd(msg_struct->data, field, (void **)value);
+               break;
+       case MSG_STRUCT_SENDOPT:
+               err = msg_sendopt_get_struct_handle(msg_struct, field, (void **)value);
+               break;
+       case MSG_STRUCT_SYNCML_INFO:
+               err = msg_syncml_get_struct_handle(msg_struct, field, (void **)value);
+               break;
+       case MSG_STRUCT_THREAD_LIST_INDEX:
+               err = msg_thread_index_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;
+       case MSG_STRUCT_REQUEST_INFO:
+               err = msg_request_get_struct_handle(msg_struct, field, (void **)value);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_get_list_handle(msg_struct_t msg_struct_handle, int field, void **value)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_handle == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
+
+       if (msg_struct->data == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       switch (msg_struct->type)
+       {
+       case MSG_STRUCT_MESSAGE_INFO :
+               err = msg_message_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);
+               break;
+       case MSG_STRUCT_SETTING_CB_OPT :
+       case MSG_STRUCT_SETTING_SMSC_OPT :
+               err = msg_setting_get_list_handle(msg_struct, field, value);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_int_value(msg_struct_t msg_struct_handle, int field, int value)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_handle == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
+
+       if (msg_struct->data == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       switch (msg_struct->type)
+       {
+       case MSG_STRUCT_MESSAGE_INFO :
+               err = msg_message_set_int_value(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_FILTER :
+               err = msg_set_filter_info_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SYNCML_INFO :
+               err = msg_syncml_info_set_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_COUNT_INFO :
+               err = msg_count_info_set_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_THREAD_COUNT_INFO :
+               err = msg_thread_count_set_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_THREAD_LIST_INDEX :
+               err = msg_thread_index_set_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SORT_RULE :
+               err = msg_sortrule_set_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_FOLDER_INFO :
+               err = msg_folder_info_set_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SEARCH_CONDITION :
+               err = msg_search_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;
+       case MSG_STRUCT_ADDRESS_INFO :
+               err = msg_address_info_set_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_MMS_SENDOPT :
+               err = msg_mms_sendopt_set_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_REJECT_MSG_INFO :
+               err = msg_reject_message_set_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_REQUEST_INFO :
+               err = msg_request_set_int(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_MMS:
+       case MSG_STRUCT_MMS_PAGE:
+       case MSG_STRUCT_MMS_MEDIA:
+       case MSG_STRUCT_MMS_ATTACH:
+       case MSG_STRUCT_MMS_REGION:
+       case MSG_STRUCT_MMS_TRANSITION:
+       case MSG_STRUCT_MMS_META:
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       case MSG_STRUCT_MMS_SMIL_AVI:
+               err = msg_mms_set_int_value(msg_struct, field, value);
+               break;
+       case MSG_STRUCT_SETTING_SMSC_OPT :
+       case MSG_STRUCT_SETTING_SMSC_INFO :
+       case MSG_STRUCT_SETTING_CB_OPT :
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+       case MSG_STRUCT_SETTING_SMS_SEND_OPT :
+       case MSG_STRUCT_SETTING_MMS_SEND_OPT :
+       case MSG_STRUCT_SETTING_MMS_RECV_OPT :
+       case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
+       case MSG_STRUCT_SETTING_GENERAL_OPT :
+       case MSG_STRUCT_SETTING_MSGSIZE_OPT :
+               err = msg_setting_set_int_value(msg_struct, field, value);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_str_value(msg_struct_t msg_struct_handle, int field, char *value, int size)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_handle == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
+
+       if (msg_struct->data == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       switch (msg_struct->type)
+       {
+       case MSG_STRUCT_MESSAGE_INFO :
+               err = msg_message_set_str_value(msg_struct->data, field, value, size);
+               break;
+       case MSG_STRUCT_FILTER :
+               err = msg_set_filter_info_str(msg_struct->data, field, value, size);
+               break;
+       case MSG_STRUCT_FOLDER_INFO :
+               err = msg_folder_info_set_str(msg_struct->data, field, value, size);
+               break;
+       case MSG_STRUCT_SEARCH_CONDITION :
+               err = msg_search_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;
+       case MSG_STRUCT_REJECT_MSG_INFO :
+               err = msg_reject_message_set_str(msg_struct->data, field, value, size);
+               break;
+       case MSG_STRUCT_MMS:
+       case MSG_STRUCT_MMS_PAGE:
+       case MSG_STRUCT_MMS_MEDIA:
+       case MSG_STRUCT_MMS_ATTACH:
+       case MSG_STRUCT_MMS_REGION:
+       case MSG_STRUCT_MMS_TRANSITION:
+       case MSG_STRUCT_MMS_META:
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       case MSG_STRUCT_MMS_SMIL_AVI:
+               err = msg_mms_set_str_value(msg_struct, field, value, size);
+               break;
+       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;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_bool_value(msg_struct_t msg_struct_handle, int field, bool value)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_handle == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
+
+       if (msg_struct->data == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       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;
+       case MSG_STRUCT_SENDOPT:
+               err = msg_sendopt_set_bool(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_SORT_RULE:
+               err = msg_sortrule_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;
+       case MSG_STRUCT_SMS_SENDOPT:
+               err = msg_sms_sendopt_set_bool(msg_struct->data, field, value);
+               break;
+       case MSG_STRUCT_MMS:
+       case MSG_STRUCT_MMS_PAGE:
+       case MSG_STRUCT_MMS_MEDIA:
+       case MSG_STRUCT_MMS_ATTACH:
+       case MSG_STRUCT_MMS_REGION:
+       case MSG_STRUCT_MMS_TRANSITION:
+       case MSG_STRUCT_MMS_META:
+       case MSG_STRUCT_MMS_SMIL_TEXT:
+       case MSG_STRUCT_MMS_SMIL_AVI:
+               err = msg_mms_set_bool_value(msg_struct, field, value);
+               break;
+       case MSG_STRUCT_SETTING_CB_OPT :
+       case MSG_STRUCT_SETTING_CB_CHANNEL_INFO :
+       case MSG_STRUCT_SETTING_SMS_SEND_OPT :
+       case MSG_STRUCT_SETTING_MMS_SEND_OPT :
+       case MSG_STRUCT_SETTING_MMS_RECV_OPT :
+       case MSG_STRUCT_SETTING_PUSH_MSG_OPT :
+       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;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_struct_handle(msg_struct_t msg_struct_handle, int field, msg_struct_t value)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_handle == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
+
+       if (msg_struct->data == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       switch (msg_struct->type)
+       {
+       case MSG_STRUCT_MESSAGE_INFO :
+               err = msg_message_set_struct_hnd(msg_struct->data, field, (void *)value);
+               break;
+       case MSG_STRUCT_SENDOPT:
+               err = msg_sendopt_set_struct_handle(msg_struct, field, (msg_struct_s *)value);
+               break;
+       case MSG_STRUCT_SYNCML_INFO:
+               err = msg_syncml_set_struct_handle(msg_struct, field, (msg_struct_s *)value);
+               break;
+       case MSG_STRUCT_THREAD_LIST_INDEX:
+               err = msg_thread_index_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;
+       case MSG_STRUCT_REQUEST_INFO:
+               err = msg_request_set_struct_handle(msg_struct, field, (msg_struct_s *)value);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               break;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_set_list_handle(msg_struct_t msg_struct_handle, int field, void *value)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (msg_struct_handle == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       msg_struct_s *msg_struct = (msg_struct_s *) msg_struct_handle;
+
+       if (msg_struct->data == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       switch (msg_struct->type)
+       {
+       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)
+{
+       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)
+{
+       return (int)g_list_length((GList *)list_handle);
+}
+
+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)
+{
+       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 = (160*MAX_SEGMENT_NUM) + 1;
+       int textSize = 0;
+
+       bool bAbnormal = false;
+
+       textSize = strlen(msg_text);
+
+       unsigned char decodeData[bufSize];
+       memset(decodeData, 0x00, sizeof(decodeData));
+
+       MsgTextConvert textCvt;
+
+       *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 :
+               decodeLen = textCvt.convertUTF8ToAuto(decodeData, bufSize, (const unsigned char*)msg_text, textSize, &encodeType);
+               break;
+       default :
+               err = MSG_ERR_INVALID_PARAMETER;
+               return err;
+               break;
+       }
+
+       // calculate segment size.
+       int headerLen = 1;
+       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;
+//     }
+
+       if (msg_encode_type_to == MSG_ENCODE_GSM7BIT || encodeType == MSG_ENCODE_GSM7BIT) {
+               MSG_DEBUG("MSG_ENCODE_GSM7BIT");
+
+//             if (((decodeLen+headerSize)/160) > 1)
+//                     segSize = ((140*8) - ((headerLen + concat + headerSize)*8)) / 7;
+               if(decodeLen > 160)
+                       segSize = ((140*8) - ((headerLen + concat)*8)) / 7;
+               else
+                       segSize = 160;
+
+               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)
+                       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;
+       }
+
+       *text_size = decodeLen;
+       *segment_size = segSize;
+
+       return err;
+}
diff --git a/mapi/msg_transport.cpp b/mapi/msg_transport.cpp
new file mode 100755 (executable)
index 0000000..e680a61
--- /dev/null
@@ -0,0 +1,821 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgHandle.h"
+#include "MsgDebug.h"
+#include "MsgException.h"
+#include "MsgUtilFunction.h"
+
+#include "msg.h"
+#include "msg_private.h"
+#include "msg_transport.h"
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+EXPORT_API int msg_submit_req(msg_handle_t handle, msg_struct_t req)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL ||req == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       msg_struct_s *pStruct = (msg_struct_s *)req;
+
+       try
+       {
+               err = pHandle->submitReq((MSG_REQUEST_S *)pStruct->data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_TRANSPORT_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_reg_sent_status_callback(msg_handle_t handle, msg_sent_status_cb cb, void *user_param)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || cb == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regSentStatusCallback(cb, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_CALLBACK_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_reg_sms_message_callback(msg_handle_t handle, msg_sms_incoming_cb cb, unsigned short port, void *user_param)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || cb == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regSmsMessageCallback(cb, port, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_CALLBACK_ERROR;
+       }
+
+       return err;
+}
+
+
+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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || cb == NULL)
+       {
+               return -EINVAL;
+       }
+
+       if (app_id && strlen(app_id) > MAX_MMS_JAVA_APPID_LEN)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regMmsConfMessageCallback(cb, app_id, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_CALLBACK_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_reg_syncml_message_callback(msg_handle_t handle,  msg_syncml_msg_incoming_cb cb, void *user_param)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || cb == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regSyncMLMessageCallback(cb, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_CALLBACK_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_reg_lbs_message_callback(msg_handle_t handle, msg_lbs_msg_incoming_cb cb, void *user_param)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || cb == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regLBSMessageCallback(cb, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_CALLBACK_ERROR;
+       }
+
+       return err;
+}
+
+
+EXPORT_API int msg_reg_syncml_message_operation_callback(msg_handle_t handle,  msg_syncml_msg_operation_cb cb, void *user_param)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || cb == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regSyncMLMessageOperationCallback(cb, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || cb == NULL)
+       {
+               return -EINVAL;
+       }
+
+       if (app_id && strlen(app_id) > MAX_WAPPUSH_ID_LEN)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regPushMessageCallback(cb, app_id, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               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)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || cb == NULL)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->regCBMessageCallback(cb, bsave, user_param);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_CALLBACK_ERROR;
+       }
+
+       return err;
+}
+
+EXPORT_API int msg_syncml_message_operation(msg_handle_t handle,  msg_message_id_t msgId)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || msgId < 1)
+       {
+               return -EINVAL;
+       }
+
+       MsgHandle* pHandle = (MsgHandle*)handle;
+
+       try
+       {
+               err = pHandle->operateSyncMLMessage(msgId);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_TRANSPORT_ERROR;
+       }
+
+       return err;
+}
+
+
+static msg_handle_t msgHandle = NULL;
+static msg_simple_sent_status_cb sentStatusCallback = NULL;
+
+static void sent_status_cb_func(msg_handle_t handle, msg_struct_t sent_status, void *user_param)
+{
+//     MSG_DEBUG("Sent Status [%d]", sent_status->status);
+
+       msg_simple_sent_status_cb pfunc = sentStatusCallback;
+// TODO : Fixme
+       pfunc((msg_struct_t)sent_status, user_param);
+
+       MSG_DEBUG("After entering callback function.");
+
+       // Close control handle instance
+       //      msg_close_msg_handle(&msgHandle);
+
+       //      MSG_DEBUG("After msg_close_msg_handle.");
+
+}
+
+
+static int msg_send_single_sms(const char *phone_num, const char *sms_text, msg_simple_sent_status_cb cb, void *user_param)
+{
+       if (phone_num == NULL || sms_text == NULL || cb == NULL)
+       {
+               MSG_DEBUG("Invalid parameter [%s] [%s] [%s]", phone_num, sms_text, cb);
+               return -EINVAL;
+       }
+
+       if (strlen(phone_num) > MAX_PHONE_NUMBER_LEN)
+       {
+               MSG_DEBUG("Phone Number is too long [%s]", phone_num);
+               return -EINVAL;
+       }
+
+       msg_struct_s req = {0,};
+       MSG_REQUEST_S msgReq = {0};
+
+       req.type = MSG_STRUCT_REQUEST_INFO;
+       req.data = (void *)&msgReq;
+
+       msg_error_t retVal = MSG_SUCCESS;
+
+       // Open control handle instance
+       if ((retVal = msg_open_msg_handle(&msgHandle)) != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgOpenMsgHandle is failed. Error Code = %d", retVal);
+               return retVal;
+       }
+
+       //msgReq.msg = msg_new_message();
+       MSG_MESSAGE_HIDDEN_S msg_info = {0,};
+       msg_struct_s msg = {0,};
+
+       msg.type = MSG_STRUCT_MESSAGE_INFO;
+       msg.data = &msg_info;
+
+       /* when sending SMS */
+       msg_info.mainType = MSG_SMS_TYPE;
+       msg_info.subType = MSG_NORMAL_SMS;
+       msg_info.msgId = 0;
+       msg_info.folderId = MSG_OUTBOX_ID;
+
+       /* fill the destination number in msgReq */
+       msg_struct_list_s addr_list = {0,};
+
+       addr_list.nCount = 1;
+
+       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_ADDRESS_INFO_S address[addr_list.nCount];
+       memset(address, 0, sizeof(MSG_ADDRESS_INFO_S) * addr_list.nCount);
+
+       for (int i = 0; i < addr_list.nCount; i++) {
+               addr_info[i].type = MSG_STRUCT_ADDRESS_INFO;
+               addr_info[i].data = (void *)&address[i];
+
+               address[i].addressType = MSG_ADDRESS_TYPE_PLMN;
+               snprintf(address[i].addressVal, MAX_ADDRESS_VAL_LEN+1, "%s", phone_num);
+
+               address[i].recipientType = MSG_RECIPIENTS_TYPE_TO;
+       }
+
+       msg_info.addr_list = &addr_list;
+
+       msg_info.bPortValid = false;
+
+       /* 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);
+
+       sentStatusCallback = cb;
+
+       // register sent status callback
+       retVal = msg_reg_sent_status_callback(msgHandle, sent_status_cb_func, user_param);
+
+       if (retVal != MSG_SUCCESS)
+       {
+               MSG_DEBUG("msg_reg_sent_status_callback() is failed. Error Code = %d", retVal);
+               msg_close_msg_handle(&msgHandle);
+               return retVal;
+       }
+
+       // sending message request
+       msgReq.msg = (msg_struct_t)&msg;
+
+       retVal = msg_submit_req(msgHandle, (msg_struct_t)&req);
+
+       if (retVal != MSG_SUCCESS)
+       {
+               MSG_DEBUG("msg_submit_req() is failed. Error Code = %d", retVal);
+               msg_close_msg_handle(&msgHandle);
+               return retVal;
+       }
+
+       return MSG_SUCCESS;
+}
+
+EXPORT_API int msg_sms_send(const char *phone_num_list, const char *sms_text, msg_simple_sent_status_cb cb, void *user_param)
+{
+       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;
+       }
+
+       char trimmed_num[strlen(phone_num_list)+1];
+       bzero(trimmed_num, strlen(phone_num_list)+1);
+
+       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,", "))
+       {
+               if (strlen(cur_num) > MAX_PHONE_NUMBER_LEN)
+               {
+                       MSG_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);
+               retVal = msg_send_single_sms(cur_num, sms_text, cb, user_param);
+
+               if (retVal != MSG_SUCCESS)
+                       return retVal;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+EXPORT_API int msg_sms_send_message(msg_handle_t handle, msg_struct_t req)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || !req) {
+               MSG_FATAL("handle or req is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       msg_struct_s *req_s = (msg_struct_s *)req;
+       MSG_REQUEST_S *pReq = (MSG_REQUEST_S *)req_s->data;
+
+       pReq->reqId = 1;
+
+       msg_struct_s *msg_s = (msg_struct_s *)pReq->msg;
+
+       MSG_MESSAGE_HIDDEN_S *reqmsg = (MSG_MESSAGE_HIDDEN_S*)msg_s->data;
+
+       if (reqmsg->dataSize <= 0) {
+               MSG_FATAL("msg size is invalid : [%d]", reqmsg->dataSize);
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (reqmsg->mainType != MSG_SMS_TYPE) {
+               MSG_DEBUG("mainType is not SMS [%d]", reqmsg->mainType);
+               reqmsg->mainType = MSG_SMS_TYPE;
+       }
+
+       if (reqmsg->subType > MSG_CONCAT_SIM_SMS) {
+               MSG_DEBUG("subType is not SMS [%d]", reqmsg->subType);
+               reqmsg->subType = MSG_NORMAL_SMS;
+       }
+
+       reqmsg->folderId = MSG_OUTBOX_ID; // outbox fixed
+       reqmsg->networkStatus = MSG_NETWORK_SENDING;
+
+       err = msg_submit_req(handle, req);
+
+       if (err == MSG_SUCCESS)
+               MSG_DEBUG("Sending Message is OK!");
+       else
+               MSG_DEBUG("Sending Message is failed! [%d]", err);
+
+       return err;
+}
+
+
+EXPORT_API int msg_mms_send_message(msg_handle_t handle, msg_struct_t req)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || !req)
+       {
+               MSG_FATAL("handle or req is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       msg_struct_s *req_s = (msg_struct_s *)req;
+       MSG_REQUEST_S *pReq = (MSG_REQUEST_S *)req_s->data;
+
+       pReq->reqId = 1;
+
+       msg_struct_s *msg_s = (msg_struct_s *)pReq->msg;
+
+       MSG_MESSAGE_HIDDEN_S *reqmsg = (MSG_MESSAGE_HIDDEN_S*)msg_s->data;
+
+       if (reqmsg->dataSize <= 0)
+       {
+               MSG_FATAL("MMS data size is invalid");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       reqmsg->mainType = MSG_MMS_TYPE;
+       reqmsg->subType = MSG_SENDREQ_MMS;
+       reqmsg->folderId = MSG_OUTBOX_ID; // outbox fixed
+       reqmsg->networkStatus = MSG_NETWORK_SENDING;
+
+       err = msg_submit_req(handle, req);
+
+       if (err == MSG_SUCCESS)
+               MSG_DEBUG("Sending Message is OK!");
+       else
+               MSG_DEBUG("Sending Message is failed! [%d]", err);
+
+       return err;
+}
+
+
+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)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (handle == NULL)
+       {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       msg_struct_t req_t = msg_create_struct(MSG_STRUCT_REQUEST_INFO);
+
+       msg_struct_s *req_s = (msg_struct_s *)req_t;
+       MSG_REQUEST_S *req = (MSG_REQUEST_S *)req_s->data;
+       msg_struct_s *msg_s = (msg_struct_s *)req->msg;
+       MSG_MESSAGE_HIDDEN_S *reqmsg = (MSG_MESSAGE_HIDDEN_S *)msg_s->data;
+       void *read_report_data = NULL;
+       size_t read_report_datasize;
+
+       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;
+       }
+
+       MSG_DEBUG("mms_read_status [%d]", mms_read_status);
+       memcpy(read_report_data, &mms_read_status, read_report_datasize);
+
+       req->reqId = 1;
+
+       reqmsg->bPortValid = false;
+       reqmsg->msgId = msgId;
+       reqmsg->folderId = MSG_OUTBOX_ID; // outbox fixed
+       reqmsg->mainType = MSG_MMS_TYPE;
+       reqmsg->subType = MSG_READREPLY_MMS;
+
+       reqmsg->dataSize = read_report_datasize;
+       reqmsg->pMmsData = read_report_data;
+
+       err = msg_submit_req(handle, req_t);
+       if (err == MSG_SUCCESS)
+               MSG_DEBUG("Sending Message is OK!");
+       else
+               MSG_DEBUG("Sending Message is failed!");
+
+       free(read_report_data);
+       read_report_data = NULL;
+       reqmsg->pMmsData = NULL;
+
+       msg_release_struct(&req_t);
+
+       return err;
+}
+
+
+EXPORT_API int msg_mms_forward_message(msg_handle_t handle, msg_struct_t req)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       if (handle == NULL || !req )
+       {
+               MSG_FATAL("handle or req is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       msg_struct_s *req_s = (msg_struct_s *)req;
+       MSG_REQUEST_S *pReq = (MSG_REQUEST_S *)req_s->data;
+
+       pReq->reqId = 1;
+
+       msg_struct_s *msg_s = (msg_struct_s *)pReq->msg;
+
+       MSG_MESSAGE_HIDDEN_S *reqmsg = (MSG_MESSAGE_HIDDEN_S*)msg_s->data;
+
+       reqmsg->mainType = MSG_MMS_TYPE;
+       reqmsg->subType = MSG_FORWARD_MMS;
+       reqmsg->folderId = MSG_OUTBOX_ID; // outbox fixed
+       reqmsg->networkStatus = MSG_NETWORK_SENDING;
+
+       err = msg_submit_req(handle, req);
+
+       if (err == MSG_SUCCESS)
+               MSG_DEBUG("Sending Message is OK!");
+       else
+               MSG_DEBUG("Sending Message is failed!");
+
+       return err;
+}
+
+
+EXPORT_API int msg_mms_retrieve_message(msg_handle_t handle, msg_struct_t req)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if ( handle == NULL|| !req)
+       {
+               MSG_FATAL("handle or req is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       msg_struct_s *req_s = (msg_struct_s *)req;
+       MSG_REQUEST_S *pReq = (MSG_REQUEST_S *)req_s->data;
+
+       msg_struct_s *msg_s = (msg_struct_s *)pReq->msg;
+       MSG_MESSAGE_HIDDEN_S *reqmsg = (MSG_MESSAGE_HIDDEN_S*)msg_s->data;
+
+       reqmsg->mainType = MSG_MMS_TYPE;
+       reqmsg->subType = MSG_RETRIEVE_MMS;
+       reqmsg->folderId = MSG_OUTBOX_ID; // outbox fixed
+       reqmsg->networkStatus = MSG_NETWORK_RETRIEVING;
+
+       err = msg_submit_req(handle, req);
+
+       if (err == MSG_SUCCESS)
+               MSG_DEBUG("Sending Message is OK!");
+       else
+               MSG_DEBUG("Sending Message is failed!");
+
+       return err;
+}
+
+
+/* reject_msg_support */
+EXPORT_API int msg_mms_reject_message(msg_handle_t handle, msg_struct_t req)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (handle == NULL || !req )
+       {
+               MSG_FATAL("handle or req is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       msg_struct_s *req_s = (msg_struct_s *)req;
+       MSG_REQUEST_S *pReq = (MSG_REQUEST_S *)req_s->data;
+
+       msg_struct_s *msg_s = (msg_struct_s *)pReq->msg;
+       MSG_MESSAGE_HIDDEN_S *reqmsg = (MSG_MESSAGE_HIDDEN_S*)msg_s->data;
+
+       reqmsg->mainType = MSG_MMS_TYPE;
+       reqmsg->subType = MSG_NOTIFYRESPIND_MMS;
+       reqmsg->folderId = MSG_OUTBOX_ID; // outbox fixed
+       reqmsg->networkStatus = MSG_NETWORK_SENDING;
+
+       err = msg_submit_req(handle, req);
+
+       if (err == MSG_SUCCESS)
+               MSG_DEBUG("Sending Message is OK!");
+       else
+               MSG_DEBUG("Sending Message is failed!");
+
+       return err;
+}
+/* reject_msg_support */
+
+
+int msg_request_get_int(void *request_info, int field)
+{
+       int result = -1;
+       MSG_REQUEST_S *pRequest = (MSG_REQUEST_S *)request_info;
+       switch(field)
+       {
+       case MSG_REQUEST_REQUESTID_INT:
+               result = pRequest->reqId;
+               break;
+
+       default:
+               break;
+       }
+       return result;
+}
+
+
+int msg_request_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_REQUEST_S *pRequest = (MSG_REQUEST_S *)msg_struct->data;
+       switch(field)
+       {
+       case MSG_REQUEST_MESSAGE_HND:
+               *value = (void *)pRequest->msg;
+               break;
+       case MSG_REQUEST_SENDOPT_HND:
+               *value = (void *)pRequest->sendOpt;
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+
+       }
+       return err;
+}
+
+int msg_request_set_int(void *request_info, int field, int value)
+{
+       msg_error_t err =  MSG_SUCCESS;
+       if(!request_info)
+               return MSG_ERR_NULL_POINTER;
+
+       MSG_REQUEST_S *pRequest = (MSG_REQUEST_S *)request_info;
+       switch(field)
+       {
+       case MSG_REQUEST_REQUESTID_INT:
+               pRequest->reqId = value;
+               break;
+       default:
+               err = MSG_ERR_UNKNOWN;
+       break;
+       }
+
+       return err;
+}
+
+int msg_request_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_REQUEST_S *pRequest = (MSG_REQUEST_S *)msg_struct->data;
+       msg_struct_s *pTmp = NULL;
+
+
+       switch(field)
+       {
+       case MSG_REQUEST_MESSAGE_HND:
+       {
+               pTmp = (msg_struct_s *)pRequest->msg;
+               MSG_MESSAGE_HIDDEN_S *pSrc = (MSG_MESSAGE_HIDDEN_S *)value->data;
+               MSG_MESSAGE_HIDDEN_S *pDst = (MSG_MESSAGE_HIDDEN_S *)pTmp->data;
+               msg_message_copy_message(pSrc, pDst);
+               break;
+       }
+       case MSG_REQUEST_SENDOPT_HND:
+       {
+               pTmp = (msg_struct_s *)pRequest->sendOpt;
+               MSG_SENDINGOPT_S *pSrc = (MSG_SENDINGOPT_S *)value->data;
+               MSG_SENDINGOPT_S *pDst = (MSG_SENDINGOPT_S *)pTmp->data;
+               pDst->bDeliverReq = pSrc->bDeliverReq;
+               pDst->bKeepCopy = pSrc->bKeepCopy;
+               pDst->bSetting = pSrc->bSetting;
+
+               msg_struct_s *tmpDstMmsSendOpt = (msg_struct_s *)pDst->mmsSendOpt;
+               msg_struct_s *tmpDstSmsSendOpt = (msg_struct_s *)pDst->smsSendOpt;
+
+               msg_struct_s *tmpSrcMmsSendOpt = (msg_struct_s *)pDst->mmsSendOpt;
+               msg_struct_s *tmpSrcSmsSendOpt = (msg_struct_s *)pDst->smsSendOpt;
+
+               tmpDstMmsSendOpt->type = tmpSrcMmsSendOpt->type;
+               memcpy(tmpDstMmsSendOpt->data, tmpSrcMmsSendOpt->data, sizeof(MMS_SENDINGOPT_S));
+
+               tmpDstSmsSendOpt->type = tmpSrcSmsSendOpt->type;
+               memcpy(tmpDstSmsSendOpt->data, tmpSrcSmsSendOpt->data, sizeof(SMS_SENDINGOPT_S));
+
+               break;
+       }
+       default:
+               err = MSG_ERR_UNKNOWN;
+               break;
+       }
+       return err;
+}
+
+
+int msg_sent_status_get_int(MSG_SENT_STATUS_S *sent_status_info, int field)
+{
+       int result = -1;
+
+       switch(field)
+       {
+       case MSG_SENT_STATUS_REQUESTID_INT:
+               result = sent_status_info->reqId;
+               break;
+       case MSG_SENT_STATUS_NETWORK_STATUS_INT:
+               result = sent_status_info->status;
+               break;
+       default:
+               break;
+       }
+       return result;
+}
diff --git a/mms-plugin.manifest b/mms-plugin.manifest
new file mode 100755 (executable)
index 0000000..8f7d470
--- /dev/null
@@ -0,0 +1,7 @@
+<manifest>
+  <request>
+    <domain name="_"/>
+  </request>
+</manifest>
+
+
diff --git a/msg-server b/msg-server
new file mode 100755 (executable)
index 0000000..0c9ab19
--- /dev/null
@@ -0,0 +1,7 @@
+#!/bin/sh
+## A script for running msg-server in booting time.
+
+if [ ! -e /opt/etc/.hib_capturing ]; then
+/usr/bin/msg-server &
+fi
+
diff --git a/msg-service-tools.manifest b/msg-service-tools.manifest
new file mode 100755 (executable)
index 0000000..d75f53e
--- /dev/null
@@ -0,0 +1,12 @@
+<manifest>
+       <request>
+               <domain name="msg-service"/>
+       </request>
+        
+       <assign>
+                <filesystem path="/etc/rc.d/init.d/msg-server" label="_" exec_label="none"/>
+                <filesystem path="/etc/rc.d/rc3.d/S70msg-server" label="_" exec_label="none"/>
+                <filesystem path="/etc/rc.d/rc5.d/S70msg-server" label="_" exec_label="none"/>
+        </assign>
+
+</manifest>
diff --git a/msg-service.manifest b/msg-service.manifest
new file mode 100755 (executable)
index 0000000..5fef746
--- /dev/null
@@ -0,0 +1,23 @@
+<manifest>
+       <define>
+               <domain name="msg-service" policy="restricted" plist="msg-service-tools"/>
+               <provide>
+                       <label name="msg-service::db"/>
+               </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.pc.in b/msg-service.pc.in
new file mode 100755 (executable)
index 0000000..5d04123
--- /dev/null
@@ -0,0 +1,10 @@
+prefix=/usr
+libdir=${prefix}/lib
+includedir=${prefix}/include
+
+Name: MESSAGE-FRAMEWORK
+Version: @VERSION@
+Description: Messaging Framework
+Requires: glib-2.0
+Libs: -L${libdir} -lmsg_mapi
+Cflags: -I${includedir} -I${includedir}/msg-service
diff --git a/msg_helper/CMakeLists.txt b/msg_helper/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..ad060c3
--- /dev/null
@@ -0,0 +1,48 @@
+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 mm-fileinfo mm-player mm-sound sensor feedback)
+
+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/MsgSensorWrapper.cpp b/msg_helper/MsgSensorWrapper.cpp
new file mode 100755 (executable)
index 0000000..e284ae9
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <sensor.h>
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+int sensorHandler = -1;
+
+msg_sensor_cb cbFunction = NULL;
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+
+void MsgSensorCB(unsigned int event_type, sensor_event_data_t *event_data , void *data)
+{
+       int *my_event_data;
+
+       my_event_data = (int *)(event_data->event_data);
+
+       if (event_type == MOTION_ENGINE_EVENT_TOP_TO_BOTTOM)
+               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();
+               }
+}
+
+
+msg_error_t MsgSensorConnect()
+{
+       sensorHandler = sf_connect(MOTION_SENSOR);
+       if (sensorHandler < 0) {
+               MSG_DEBUG("sensor attach fail.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+void MsgSensorDisconnect()
+{
+       if(cbFunction != NULL)
+               cbFunction = NULL;
+
+       if (sensorHandler < 0)
+               return;
+
+       try
+       {
+               sf_stop(sensorHandler);
+       }
+       catch(int exception)
+       {
+               MSG_FATAL("sf_stop error[%d]", exception);
+       }
+       sf_disconnect(sensorHandler);
+}
+
+
+msg_error_t MsgRegSensorCB(msg_sensor_cb cb)
+{
+       int resultCondition = -1;
+
+       if (sensorHandler < 0) {
+               MSG_DEBUG("Not connected to sensor FW.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       if(cb != NULL) {
+               // regist cb.
+               cbFunction = cb;
+       } else {
+               MSG_DEBUG("cb is NULL.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       resultCondition = sf_register_event(sensorHandler, MOTION_ENGINE_EVENT_TOP_TO_BOTTOM , NULL , MsgSensorCB,NULL);
+       if (resultCondition < 0) {
+               MSG_DEBUG("SLP_sensor_register_cb fail to gather data.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       MSG_DEBUG("Start SF.");
+       resultCondition = sf_start(sensorHandler, 0);
+       if (resultCondition < 0) {
+               MSG_DEBUG("SLP_sensor_start fail.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       return MSG_SUCCESS;
+}
diff --git a/msg_helper/MsgSoundPlayer.cpp b/msg_helper/MsgSoundPlayer.cpp
new file mode 100755 (executable)
index 0000000..1879fd2
--- /dev/null
@@ -0,0 +1,419 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <mm_error.h>
+#include <mm_player.h>
+#include <mm_session_private.h>
+#include <mm_sound.h>
+#include <feedback.h>
+
+extern void worker_done();
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+static MMHandleType hPlayerHandle = 0;
+static bool bPlaying = false;
+static bool bVibrating = false;
+
+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 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;
+
+       bool isEmergency = false;
+
+       if (data)
+               isEmergency = (bool)data;
+
+       char *msg_tone_file_path = NULL;
+       AutoPtr<char> buf(&msg_tone_file_path);
+
+       msg_tone_file_path = new char[MAX_SOUND_FILE_LEN];
+
+       if (isEmergency) {
+       } else {
+               char *tmpFileFath = NULL;
+
+               tmpFileFath = MsgSettingGetString(VCONFKEY_SETAPPL_NOTI_MSG_RINGTONE_PATH_STR);
+
+               if (tmpFileFath == NULL || MsgGetFileSize(tmpFileFath) < 1) {
+                       strncpy(msg_tone_file_path, DEFAULT_FILE, MAX_SOUND_FILE_LEN-1);
+               } else {
+                       strncpy(msg_tone_file_path, tmpFileFath, MAX_SOUND_FILE_LEN-1);
+                       free(tmpFileFath);
+                       tmpFileFath = NULL;
+               }
+       }
+
+       MSG_DEBUG("Emergency=[%d], Sound File [%s]", isEmergency, msg_tone_file_path);
+
+       MsgSettingGetBool(VCONFKEY_SETAPPL_SOUND_STATUS_BOOL, &bSoundOn);
+       MsgSettingGetBool(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, &bVibrationOn);
+
+       int err = MM_ERROR_NONE;
+
+       if (isEmergency)
+               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);
+
+       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)
+                               MsgSoundPlayDtmf();
+               } else if (alertOnCall == 2) {
+                       MSG_DEBUG("Call is active & Alert on Call - Vibration");
+
+                       if (bVibrationOn)
+                               MsgSoundPlayVibration(true);
+               }
+       } else{
+               MSG_DEBUG("Call is not active");
+
+               if (bVibrationOn) {
+                       MSG_DEBUG("Play vibration.");
+                       MsgSoundPlayVibration(false);
+               }
+
+               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(bool isEmergency)
+{
+       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*)isEmergency) == 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, 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");
+               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(bool isOnCall)
+{
+       MSG_BEGIN();
+
+       int ret = 0;
+
+       ret = feedback_initialize();
+
+       if (ret != FEEDBACK_ERROR_NONE) {
+               MSG_DEBUG("Fail to feedback_initialize : [%d]", ret);
+               return;
+       }
+
+       if (isOnCall)
+               ret = feedback_play_type(FEEDBACK_TYPE_VIBRATION, FEEDBACK_PATTERN_MESSAGE_ON_CALL);
+       else
+               ret = feedback_play_type(FEEDBACK_TYPE_VIBRATION, FEEDBACK_PATTERN_MESSAGE);
+
+       if (ret != FEEDBACK_ERROR_NONE)
+               MSG_DEBUG("Fail to feedback_play_type");
+
+       ret = feedback_deinitialize();
+
+       if (ret != FEEDBACK_ERROR_NONE) {
+               MSG_DEBUG("Fail to feedback_deinitialize : [%d]", ret);
+               return;
+       }
+
+       MSG_END();
+}
+
+void 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\n");
+       } else {
+               MSG_DEBUG("play tone success\n");
+       }
+
+       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
new file mode 100755 (executable)
index 0000000..2d8392a
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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(g_strcmp0(argv[0], MSG_NORMAL_SOUND_START) == 0)
+       {
+               MsgSoundPlayStart(false);
+               notEnd = true;
+       }
+       if(g_strcmp0(argv[0], MSG_EMERGENCY_SOUND_START) == 0)
+       {
+               MsgSoundPlayStart(true);
+               notEnd = true;
+       }
+       else if(g_strcmp0(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-service.service b/packaging/msg-service.service
new file mode 100644 (file)
index 0000000..cd27b1b
--- /dev/null
@@ -0,0 +1,10 @@
+
+[Unit]
+Description=Start the msg-server
+
+[Service]
+ExecStart=/usr/bin/msg-server
+
+[Install]
+WantedBy=tizen-middleware.target
+
diff --git a/packaging/msg-service.spec b/packaging/msg-service.spec
new file mode 100755 (executable)
index 0000000..1db3975
--- /dev/null
@@ -0,0 +1,660 @@
+Name:           msg-service
+Version:        0.9.2
+Release:        1
+License:        Samsung
+Summary:        Messaging Framework Library
+Group:          System/Libraries
+Source0:        %{name}-%{version}.tar.gz
+Source101:      msg-service.service
+
+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(capi-appfw-application)
+BuildRequires: pkgconfig(contacts-service2)
+BuildRequires: pkgconfig(db-util)
+BuildRequires: pkgconfig(dlog)
+BuildRequires: pkgconfig(drm-client)
+BuildRequires: pkgconfig(glib-2.0)
+BuildRequires: pkgconfig(libcurl)
+BuildRequires: pkgconfig(libsystemd-daemon)
+BuildRequires: pkgconfig(libxml-2.0)
+BuildRequires: pkgconfig(libwbxml2)
+BuildRequires: pkgconfig(media-thumbnail)
+BuildRequires: pkgconfig(mm-fileinfo)
+BuildRequires: pkgconfig(mm-player)
+BuildRequires: pkgconfig(mm-session)
+BuildRequires: pkgconfig(mm-sound)
+BuildRequires: pkgconfig(network)
+BuildRequires: pkgconfig(notification)
+BuildRequires: pkgconfig(pmapi)
+BuildRequires: pkgconfig(mmutil-imgp)
+BuildRequires: pkgconfig(mmutil-jpeg)
+BuildRequires: pkgconfig(security-server)
+BuildRequires: pkgconfig(sensor)
+BuildRequires: pkgconfig(svi)
+BuildRequires: pkgconfig(tapi)
+BuildRequires: pkgconfig(vconf)
+BuildRequires: pkgconfig(feedback)
+
+%description
+Description: Messaging Framework Library
+
+
+%package devel
+License:        Flora License v1.0
+Summary:        Messaging Framework Library (development)
+Requires:       %{name} = %{version}-%{release}
+Group:          Development/Libraries
+
+%description devel
+Description: Messaging Framework Library (development)
+
+
+%package tools
+License:        Flora License v1.0
+Summary:        Messaging server application
+Requires:       %{name} = %{version}-%{release}
+Group:          TO_BU / FILL_IN
+Requires(post): /usr/bin/sqlite3
+Requires(post): /usr/bin/vconftool
+Requires(post): /sbin/ldconfig
+Requires(postun): /sbin/ldconfig
+
+%description tools
+Description:  Messaging server application
+
+
+%package -n sms-plugin
+License:        Flora License v1.0
+Summary:        SMS plugin library
+Requires:       %{name} = %{version}-%{release}
+Group:          System/Libraries
+Requires(post): /sbin/ldconfig
+Requires(postun): /sbin/ldconfig
+
+%description -n sms-plugin
+Description: SMS plugin library
+
+%package -n mms-plugin
+License:        Flora License v1.0
+Summary:        MMS plugin library
+Requires:       %{name} = %{version}-%{release}
+Group:          System/Libraries
+Requires(post): /sbin/ldconfig
+Requires(postun): /sbin/ldconfig
+
+%description -n mms-plugin
+Description: MMS plugin library
+
+%prep
+%setup -q
+
+
+%build
+cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix}
+make %{?jobs:-j%jobs}
+
+%install
+rm -rf %{buildroot}
+mkdir -p %{buildroot}/usr/share/license
+
+%make_install
+
+mkdir -p %{buildroot}%{_libdir}/systemd/user/tizen-middleware.target.wants
+install -m 0644 %SOURCE101 %{buildroot}%{_libdir}/systemd/user/
+ln -s ../msg-service.service %{buildroot}%{_libdir}/systemd/user/tizen-middleware.target.wants/msg-service.service
+
+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}/opt/usr/data/msg-service
+
+%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/usr/dbspace/.msg_service.db ]
+then
+    mkdir -p /opt/usr/dbspace/
+    sqlite3 /opt/usr/dbspace/.msg_service.db "PRAGMA journal_mode = PERSIST;
+
+    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 ,
+       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 ,
+       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 PRIMARY KEY ,
+       SIM_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 ,
+       HREF TEXT ,
+       CONTENT TEXT ,
+       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 ,
+       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 ,
+       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 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_REPORT_TABLE (
+       MSG_ID INTEGER NOT NULL ,
+       ADDRESS_VAL TEXT ,
+       STATUS_TYPE INTEGER ,
+       STATUS INTEGER DEFAULT 0 ,
+       TIME DATETIME );
+
+    CREATE TABLE MSG_PUSHCFG_TABLE (
+       PUSH_ID INTEGER PRIMARY KEY ,
+       CONTENT_TYPE TEXT,
+       APP_ID TEXT,
+       PKG_NAME TEXT,
+       LAUNCH INTEGER,
+       APPCODE INTEGER,
+       SECURE INTEGER );
+
+    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);
+
+    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 (31, 'text/vnd.wap.emn+xml', 'X-Wap-Application-Id: x-wap-application:emn.ua', '', 0, 32, 0);
+       INSERT INTO MSG_PUSHCFG_TABLE VALUES (32, 'application/vnd.wap.emn+wbxml', 'X-Wap-Application-Id: x-wap-application:emn.ua', '', 0, 33, 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_PUSHCFG_TABLE VALUES (35, 'application/vnd.wap.emn+wbxml', 'X-oma-docomo:xmd.mail.ua', '', 0, 45, 1);"
+fi
+
+chown :6011 /opt/usr/dbspace/.msg_service.db
+chown :6011 /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 /opt/usr/data/msg-service
+chgrp db_msg_service /opt/usr/data/msg-service
+
+if [ -f /usr/lib/rpm-plugins/msm.so ]
+then
+       chsmack -a 'msg-service::db' /opt/usr/dbspace/.msg_service.db*
+        chsmack -a "_" -e "_" /etc/rc.d/init.d/msg-server
+        chsmack -a "_" -e "_" /etc/rc.d/rc3.d/S70msg-server
+        chsmack -a "_" -e "_" /etc/rc.d/rc5.d/S70msg-server
+fi
+
+########## Setting Config Value (Internal keys) ##########
+vcuid=5000
+# Message Server Status
+vconftool set -t bool memory/msg/ready 0 -i -g 5000 -u $vcuid
+
+# SMS Send Options
+vconftool set -t int db/msg/network_mode 2 -u $vcuid
+
+# New Message Count
+vconftool set -t int db/msg/recv_sms 0 -u $vcuid
+vconftool set -t int db/msg/recv_mms 0 -u $vcuid
+
+########## Setting Config Value (Private keys) ##########
+# General Options
+vconftool set -t bool db/private/msg-service/general/keep_copy 1 -u $vcuid
+vconftool set -t bool db/private/msg-service/general/auto_erase 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/general/block_msg 0 -u $vcuid
+vconftool set -t int db/private/msg-service/general/contact_sync_time 0 -u $vcuid
+
+# SMS Send Options
+vconftool set -t int db/private/msg-service/sms_send/dcs 3 -u $vcuid
+vconftool set -t bool db/private/msg-service/sms_send/reply_path 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/sms_send/delivery_report 0 -u $vcuid
+vconftool set -t int db/private/msg-service/sms_send/save_storage 1 -u $vcuid
+
+# SMSC
+vconftool set -t int db/private/msg-service/smsc/total_count 1 -u $vcuid
+vconftool set -t int db/private/msg-service/smsc/selected 0 -u $vcuid
+
+vconftool set -t int db/private/msg-service/smsc/pid/0 1 -u $vcuid
+vconftool set -t int db/private/msg-service/smsc/val_period/0 255 -u $vcuid
+vconftool set -t string db/private/msg-service/smsc/name/0 "" -u $vcuid
+vconftool set -t int db/private/msg-service/smsc/ton/0 1 -u $vcuid
+vconftool set -t int db/private/msg-service/smsc/npi/0 1 -u $vcuid
+vconftool set -t string db/private/msg-service/smsc/address/0 "" -u $vcuid
+
+vconftool set -t int db/private/msg-service/smsc/pid/1 0 -u $vcuid
+vconftool set -t int db/private/msg-service/smsc/val_period/1 0 -u $vcuid
+vconftool set -t string db/private/msg-service/smsc/name/1 "" -u $vcuid
+vconftool set -t int db/private/msg-service/smsc/ton/1 0 -u $vcuid
+vconftool set -t int db/private/msg-service/smsc/npi/1 0 -u $vcuid
+vconftool set -t string db/private/msg-service/smsc/address/1 "" -u $vcuid
+
+vconftool set -t int db/private/msg-service/smsc/pid/2 0 -u $vcuid
+vconftool set -t int db/private/msg-service/smsc/val_period/2 0 -u $vcuid
+vconftool set -t string db/private/msg-service/smsc/name/2 "" -u $vcuid
+vconftool set -t int db/private/msg-service/smsc/ton/2 0 -u $vcuid
+vconftool set -t int db/private/msg-service/smsc/npi/2 0 -u $vcuid
+vconftool set -t string db/private/msg-service/smsc/address/2 "" -u $vcuid
+
+# MMS Send Options
+vconftool set -t int db/private/msg-service/mms_send/msg_class 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_send/priority 1 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_send/expiry_time 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_send/custom_delivery 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_send/sender_visibility 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_send/delivery_report 1 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_send/read_reply 1 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_send/keep_copy 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_send/body_replying 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_send/hide_recipients 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_send/report_allowed 1 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_send/reply_charging 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_send/reply_charging_deadline 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_send/reply_charging_size 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_send/delivery_time 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_send/creation_mode 2 -u $vcuid
+
+# MMS Receive Options
+vconftool set -t int db/private/msg-service/mms_recv/home_network 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_recv/abroad_network 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_recv/read_receipt 1 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_recv/delivery_receipt 1 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_recv/reject_unknown 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_recv/reject_advertisement 0 -u $vcuid
+
+# MMS Receive Options
+vconftool set -t int db/private/msg-service/mms_style/font_size 30 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_style/font_style/bold 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_style/font_style/italic 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/mms_style/font_style/underline 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_style/font_color/red 255 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_style/font_color/green 255 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_style/font_color/blue 255 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_style/font_color/hue 255 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_style/bg_color/red 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_style/bg_color/green 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_style/bg_color/blue 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_style/bg_color/hue 255 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_style/page_dur 2 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_style/page_custom_dur 0 -u $vcuid
+vconftool set -t int db/private/msg-service/mms_style/page_dur_manual 0 -u $vcuid
+
+# Push Msg Options
+vconftool set -t bool db/private/msg-service/push_msg/recv_option 1 -u $vcuid
+vconftool set -t int db/private/msg-service/push_msg/service_load 1 -u $vcuid
+
+# CB Msg Options
+vconftool set -t bool db/private/msg-service/cb_msg/receive 1 -f -u $vcuid
+vconftool set -t bool db/private/msg-service/cb_msg/save 1 -f -u $vcuid
+vconftool set -t int db/private/msg-service/cb_msg/max_sim_count 0 -u $vcuid
+vconftool set -t int db/private/msg-service/cb_msg/channel_count 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/cb_msg/language/0 1 -f -u $vcuid
+vconftool set -t bool db/private/msg-service/cb_msg/language/1 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/cb_msg/language/2 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/cb_msg/language/3 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/cb_msg/language/4 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/cb_msg/language/5 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/cb_msg/language/6 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/cb_msg/language/7 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/cb_msg/language/8 0 -u $vcuid
+vconftool set -t bool db/private/msg-service/cb_msg/language/9 0 -u $vcuid
+
+# Voice Mail Options
+vconftool set -t string db/private/msg-service/voice_mail/voice_mail_number "5500" -f -u $vcuid
+vconftool set -t int db/private/msg-service/voice_mail/voice_mail_count 0 -u $vcuid
+
+# MMS Size Options
+vconftool set -t int db/private/msg-service/size_opt/msg_size 300 -u $vcuid
+
+# SIM message count
+vconftool set -t int db/private/msg-service/sim_count/used_cnt 0 -u $vcuid
+vconftool set -t int db/private/msg-service/sim_count/total_cnt 0 -u $vcuid
+
+# SIM information
+vconftool set -t int memory/private/msg-service/sim_changed 0 -i -u $vcuid
+vconftool set -t string memory/private/msg-service/sim_imsi "" -i -u $vcuid
+vconftool set -t bool memory/private/msg-service/national_sim 0 -i -u $vcuid
+vconftool set -t string memory/private/msg-service/msisdn "" -i -u $vcuid
+
+vconftool set -t int db/private/msg-service/notification_priv_id 0 -u $vcuid
+
+/sbin/ldconfig
+/bin/systemctl daemon-reload
+if [ "$1" = "1" ]; then
+    systemctl stop msg-service.service
+fi
+
+%postun -p /sbin/ldconfig
+
+%postun tools -p /sbin/ldconfig
+%postun -n sms-plugin -p /sbin/ldconfig
+%postun -n mms-plugin -p /sbin/ldconfig
+
+%files
+%manifest msg-service.manifest
+%defattr(-,root,root,-)
+%dir %attr(775,root,db_msg_service) /opt/usr/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_transaction_proxy.so
+%{_libdir}/libmsg_vobject.so
+/usr/share/license/msg-service/LICENSE.Flora
+
+%files devel
+%defattr(-,root,root,-)
+%{_libdir}/libmsg_mapi.so
+%{_libdir}/pkgconfig/msg-service.pc
+%{_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
+%{_sysconfdir}/rc.d/init.d/msg-server
+%{_sysconfdir}/rc.d/rc3.d/S70msg-server
+%{_sysconfdir}/rc.d/rc5.d/S70msg-server
+%{_libdir}/systemd/user/msg-service.service
+%{_libdir}/systemd/user/tizen-middleware.target.wants/msg-service.service
+/usr/share/license/msg-service/LICENSE.Flora
+
+%files -n sms-plugin
+%manifest sms-plugin.manifest
+%defattr(-,root,root,-)
+%{_libdir}/libmsg_sms_plugin.so
+/usr/share/license/msg-service/LICENSE.Flora
+
+%files -n mms-plugin
+%manifest mms-plugin.manifest
+%defattr(-,root,root,-)
+%{_libdir}/libmsg_mms_plugin.so
+/usr/share/license/msg-service/LICENSE.Flora
+
+%changelog
+* Wed Oct 25 2012 Sangkoo Kim <sangkoo.kim@samsung.com>
+- New release version
+
+* 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)
diff --git a/plugin/mms_plugin/CMakeLists.txt b/plugin/mms_plugin/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..a9a0742
--- /dev/null
@@ -0,0 +1,68 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT(mms-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}")
+
+
+##########################################################
+# 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
+       MmsPluginAvCodec.cpp
+       MmsPluginConnManWrapper.cpp
+       MmsPluginUserAgent.cpp
+       MmsPluginHttp.cpp
+       MmsPluginInternal.cpp
+       MmsPluginSmil.cpp
+       MmsPluginSMILValidate.cpp
+       MmsPluginDrm.cpp
+       MmsPluginUtil.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/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)
+
+FOREACH(flag ${mms_plugin_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}\"")
+ADD_DEFINITIONS("-DFEATURE_JAVA_MMS")
+ADD_DEFINITIONS("-D__SUPPORT_DRM__")
+
+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} ${UTILS-LIB})
+
+INSTALL(TARGETS ${MMS-PLUGIN-LIB} LIBRARY DESTINATION lib)
+
diff --git a/plugin/mms_plugin/MmsPluginAvCodec.cpp b/plugin/mms_plugin/MmsPluginAvCodec.cpp
new file mode 100755 (executable)
index 0000000..ce342b8
--- /dev/null
@@ -0,0 +1,211 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MmsPluginAvCodec.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/MmsPluginCodecCommon.cpp b/plugin/mms_plugin/MmsPluginCodecCommon.cpp
new file mode 100755 (executable)
index 0000000..66817e7
--- /dev/null
@@ -0,0 +1,1974 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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"
+
+#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-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}
+       }
+};
+
+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;
+}
+
+// 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;
+}
+
+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;
+}
+
+
+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     nTemp = 0;
+       char *pReturnStr = 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;
+
+                       /* fixme: charset problem
+                        * pDecStart ~ pDecQ : charSet & MSG_CHARSET_USC2 ~ MSG_CHARSET_UTF8 & LATIN
+                        */
+
+                       *pDecQ = '\0';
+                       nCharset = _MsgGetCode(MSG_CHARSET, pDecStart + 2);
+                       if(nCharset < 0)
+                               goto __CATCH;
+                       *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 = strdup(pSrc);
+       nTemp = strlen(pSrc);
+
+       {//temp brace;
+               const char *pToCharSet = "UTF-8";
+
+               UINT16 charset_code =  MmsGetBinaryValue(MmsCodeCharSet, nCharset);
+
+               const char *pFromCharSet = MmsPluginTextConvertGetCharSet(charset_code);
+
+               if (pFromCharSet != NULL && strcmp(pFromCharSet, pToCharSet) != 0) {//Not UTF-8
+                       char *pDest = NULL;
+                       int destLen = 0;
+
+                       if (MmsPluginTextConvert(pToCharSet, pFromCharSet, pTemp, nTemp, &pDest, &destLen) == false) {
+                               MSG_DEBUG("MmsPluginTextConvert Fail");
+                       }
+
+                       if (pDest) {
+                               free(pTemp);
+                               pTemp = strdup(pDest);
+                               nTemp = destLen;
+                               free(pDest);
+                       }
+               }
+
+       }
+
+       pReturnStr = (char *)malloc(nTemp + 1);
+
+       if (pReturnStr == NULL) {
+               goto __CATCH;
+       }
+
+       memset(pReturnStr, 0, nTemp + 1);
+
+       if (pTemp) {
+               memcpy(pReturnStr, pTemp, nTemp);
+               free(pTemp);
+               pTemp = NULL;
+       }
+
+       if(pRe) {
+               free(pRe);
+               pRe = NULL;
+       }
+
+       if (pSrc != NULL && pSrc != szTempBuf) {
+               free(pSrc);
+               pSrc = NULL;
+       }
+
+       return pReturnStr;
+
+__CATCH:
+
+       if(pRe) {
+               free(pRe);
+               pRe = NULL;
+       }
+
+       if (pSrc != NULL && pSrc != szTempBuf) {
+               free(pSrc);
+               pSrc = NULL;
+       }
+
+       if (pTemp) {
+               free(pTemp);
+               pTemp = NULL;
+       }
+
+       return NULL;
+}
+
+
+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_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_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);
+       }
+}
+
+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__
+       MmsInitMsgDRMInfo(&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)
+{
+       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;
+}
+
+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;
+}
+
+#ifdef __SUPPORT_DRM__
+bool MmsInitMsgDRMInfo(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;
+
+       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;
+}
+
+#endif
+
+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) {
+#ifdef __SUPPORT_DRM__
+                                       MmsReleaseMsgDRMInfo(&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;
+                       }
+
+                       MmsInitMsgType(&pBody->presentationType);
+
+                       break;
+               }
+
+       default:
+               /* Any single part */
+               if (pBody->body.pBinary) {
+                       free(pBody->body.pBinary);
+                       pBody->body.pBinary = 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));
+       }
+}
diff --git a/plugin/mms_plugin/MmsPluginConnManWrapper.cpp b/plugin/mms_plugin/MmsPluginConnManWrapper.cpp
new file mode 100755 (executable)
index 0000000..e034a69
--- /dev/null
@@ -0,0 +1,450 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MmsPluginConnManWrapper.h"
+#include "MmsPluginDebug.h"
+
+void network_print_profile(net_profile_info_t *ProfInfo)
+{
+       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);
+       } else {
+               MSG_DEBUG("Error!!! Invalid profile type\n");
+               return;
+       }
+
+       MSG_DEBUG("**************************************************************************************************");
+
+       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");
+
+               MSG_DEBUG("Profile Type = [pdp]\n");
+
+       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");
+
+       MSG_DEBUG("Profile APN = [%s]\n", ProfInfo->ProfileInfo.Pdp.Apn);
+
+       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]);
+       }
+
+       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");
+       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");
+       else
+               MSG_DEBUG("Proxy Method = [unknown]\n");
+
+       MSG_DEBUG("Profile Proxy = [%s]\n", net_info->ProxyAddr);
+
+       MSG_DEBUG("**************************************************************************************************");
+}
+
+
+
+void network_evt_cb (net_event_info_t *event_cb, void *user_data)
+{
+       MSG_BEGIN();
+
+       MmsPluginCmAgent::instance()->processCBdatas(event_cb, user_data);
+
+       MSG_END();
+}
+
+
+MmsPluginCmAgent *MmsPluginCmAgent::pInstance = NULL;
+
+MmsPluginCmAgent *MmsPluginCmAgent::instance()
+{
+       if (!pInstance)
+               pInstance = new MmsPluginCmAgent();
+
+       return pInstance;
+}
+
+MmsPluginCmAgent::MmsPluginCmAgent()
+{
+       MSG_BEGIN();
+
+       isCmOpened = false;
+       bzero(&mmsProfile, sizeof (net_profile_info_t));
+
+       MSG_END();
+}
+
+MmsPluginCmAgent::~MmsPluginCmAgent()
+{
+
+}
+
+bool MmsPluginCmAgent::registration()
+{
+       MSG_BEGIN();
+
+       bool registResult = true;
+
+       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;
+       }
+
+       MSG_END();
+
+       return registResult;
+}
+
+bool MmsPluginCmAgent::open()
+{
+       MSG_BEGIN();
+
+       if (!isCmOpened) {
+               if (!registration())
+                       return false;
+
+               int netOpenResult = NET_ERR_NONE;
+               net_service_type_t service_type = NET_SERVICE_MMS;
+
+               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;
+               }
+
+               MSG_DEBUG("WAITING UNTIL Network Connection Open.");
+
+               lock();
+
+               int time_ret = 0;
+               time_ret = cv.timedwait(mx.pMutex(), 50);
+
+               unlock();
+
+               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;
+                       }
+               }
+       } else {
+               MSG_DEBUG("Network is already opened.");
+               return false;
+       }
+
+       MSG_END();
+
+       return isCmOpened;
+}
+
+
+void MmsPluginCmAgent::close()
+{
+       MSG_BEGIN();
+
+       if (isCmOpened) {
+               int netOpenResult = NET_ERR_NONE;
+
+               netOpenResult = net_close_connection(mmsProfile.ProfileName);
+               if (netOpenResult != NET_ERR_NONE) {
+                       MSG_DEBUG("Error!! net_close_connection() failed.\n");
+                       deregistration();
+                       return;
+               }
+
+               MSG_DEBUG("WAITING UNTIL Network Connection Close.");
+
+               lock();
+
+               int time_ret = 0;
+               time_ret = cv.timedwait(mx.pMutex(), 50);
+
+               unlock();
+
+               if (time_ret == ETIMEDOUT) {
+                       MSG_DEBUG("Network Connection Close Timed Out.");
+               }
+
+               deregistration();
+               isCmOpened = false;
+       } else {
+               MSG_DEBUG ("Network Connection is not opened.");
+               return;
+       }
+}
+
+
+void MmsPluginCmAgent::deregistration()
+{
+       MSG_BEGIN();
+
+       int netOpenResult = NET_ERR_NONE;
+
+       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_END();
+}
+
+
+void MmsPluginCmAgent::processCBdatas(net_event_info_t *event_cb, void *user_data)
+{
+       MSG_BEGIN();
+
+       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);
+               }
+               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;
+
+               /*Successful PDP Activation*/
+               if (event_cb->Error == NET_ERR_NONE || event_cb->Error == NET_ERR_ACTIVE_CONNECTION_EXISTS) {
+                       network_print_profile(prof_info);
+
+                       lock();
+
+                       memcpy(&mmsProfile, prof_info, sizeof(net_profile_info_t));
+                       isCmOpened = true;
+                       signal();
+
+                       unlock();
+               } else {
+                       MSG_DEBUG("Activation Failed %d \n", event_cb->Error); // open failed
+                       lock();
+                       isCmOpened = false;
+                       signal();
+                       unlock();
+               }
+               break;
+
+       case NET_EVENT_CLOSE_RSP:
+               MSG_DEBUG("Got Close RSP\n");
+
+               lock();
+
+               bzero(&mmsProfile, sizeof(net_profile_info_t));
+               isCmOpened = false;
+               signal();
+
+               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();
+}
+
+
+bool MmsPluginCmAgent::getDeviceName(char *deviceName)
+{
+       if (!isCmOpened)
+               return false;
+
+       int deviceNameLength = strlen(mmsProfile.ProfileInfo.Pdp.net_info.DevName);
+
+       if (deviceNameLength > 0) {
+               strncpy(deviceName, mmsProfile.ProfileInfo.Pdp.net_info.DevName, deviceNameLength);
+               deviceName[deviceNameLength] = '\0';
+               return true;
+       }
+
+       return false;
+}
+
+
+bool MmsPluginCmAgent::getHomeURL(char *homeURL)
+{
+       if (!isCmOpened)
+               return false;
+
+       int homeURLLength = strlen(mmsProfile.ProfileInfo.Pdp.HomeURL);
+
+       if (homeURLLength > 0) {
+               strncpy(homeURL, mmsProfile.ProfileInfo.Pdp.HomeURL, homeURLLength);
+               homeURL[homeURLLength] = '\0';
+               return true;
+       }
+
+       return false;
+}
+
+
+bool MmsPluginCmAgent::getProxyAddr(char *proxyAddr)
+{
+       if (!isCmOpened)
+               return false;
+
+       int proxyAddrLength = strlen(mmsProfile.ProfileInfo.Pdp.net_info.ProxyAddr);
+
+       if (proxyAddrLength > 0) {
+               if (strchr(mmsProfile.ProfileInfo.Pdp.net_info.ProxyAddr, ':') == NULL)
+                       return false;
+
+               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 false;
+}
+
+
+int MmsPluginCmAgent::getProxyPort()
+{
+       if (!isCmOpened)
+               return -1;
+
+       int proxyAddrLength = strlen(mmsProfile.ProfileInfo.Pdp.net_info.ProxyAddr);
+
+       if (proxyAddrLength > 0) {
+               char *pPort = strchr(mmsProfile.ProfileInfo.Pdp.net_info.ProxyAddr, ':') + 1;
+               if (pPort)
+                       return atoi(pPort);
+               else
+                       return -1;
+       }
+
+       return -1;
+}
+
diff --git a/plugin/mms_plugin/MmsPluginDecode.cpp b/plugin/mms_plugin/MmsPluginDecode.cpp
new file mode 100755 (executable)
index 0000000..4fd1dca
--- /dev/null
@@ -0,0 +1,7447 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <stdlib.h>
+#include <errno.h>
+
+#include "MsgUtilFile.h"
+
+#include "MmsPluginDebug.h"
+#include "MmsPluginDecode.h"
+#include "MmsPluginCodecCommon.h"
+#include "MmsPluginStorage.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginMIME.h"
+#include "MmsPluginAvCodec.h"
+#include "MmsPluginSmil.h"
+#include "MmsPluginTextConvert.h"
+#include "MmsPluginUtil.h"
+
+#ifdef __SUPPORT_DRM__
+#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 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 __MmsBinaryDecodeCharset(FILE *pFile, UINT32 *nCharSet, int *pCharSetLen, int totalLength);
+static int __MmsDecodeGetFilename(FILE *pFile, char *szBuff, int bufLen, int totalLength);
+static MsgHeaderAddress *__MmsDecodeEncodedAddress(FILE *pFile, int totalLength);
+
+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 int __MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength);
+
+#ifdef __SUPPORT_DRM__
+static bool __MmsBinaryDecodeDRMContent(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, unsigned int bodyLength, int totalLength);
+#endif
+
+//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 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 MsgMultipart *__MsgAllocMultipart(void);
+
+static char *__MsgConvertLatin2UTF8FileName(char *pSrc);
+static bool __MsgIsUTF8String(unsigned char *szSrc, int nChar);
+static bool __MsgIsPercentSign(char *pSrc);
+static bool __MsgIsMultipartRelated(int type);
+static bool __MsgIsPresentablePart(int type);
+static bool __MsgIsText(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 __MsgLatin5code2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar);
+static int __MsgGetLatin52UTFCodeSize(unsigned char *szSrc, int nChar);
+static int __MsgLatin2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar);
+static int __MsgLatin7code2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar);
+static int __MsgGetLatin72UTFCodeSize(unsigned char *szSrc, int nChar);
+static int __MsgUnicode2UTF(unsigned char *des, int outBufSize, unsigned short *szSrc, int nChar);
+static int __MsgGetUnicode2UTFCodeSize(unsigned short *szSrc, int nChar);
+static bool __MmsAddrUtilCheckEmailAddress(char *pszAddr);
+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);
+
+#ifndef        __SUPPORT_DRM__
+static bool __MsgMakeFileName(int iMsgType, char *szFileName, int nUntitleIndex);
+#else
+static bool __MsgMakeFileName(int iMsgType, char *szFileName, MsgDrmType drmType, int nUntitleIndex);
+#endif
+
+static bool __MmsDebugPrintMulitpartEntry(MsgMultipart *pMultipart, int index);
+
+static char gszMmsLoadBuf1[MSG_MMS_DECODE_BUFFER_MAX + 1] = {0, };
+static char gszMmsLoadBuf2[MSG_MMS_DECODE_BUFFER_MAX + 1] = {0, };
+
+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 char *gpMmsDecodeBuf1 = NULL;
+static char *gpMmsDecodeBuf2 = NULL;
+
+MmsHeader      mmsHeader =
+{
+       false,                                                                  //bActive
+       NULL,                                                                   //pszOwner
+       -1,                                                                             //msgID
+
+       (MmsMsgType)MMS_MSGTYPE_ERROR,                  //MmsMsgType                    iType;
+       "",                                                                             //char[]                                szTrID;
+       //"",                                                                           //short int                             version;
+       0,                                                                              //short int                             version;
+       0,                                                                              //UINT32                                date;
+
+       NULL,                                                                   //MsgHeaderAddress*             pFrom;
+       NULL,                                                                   //MsgHeaderAddress*             pTo;
+       NULL,                                                                   //MsgHeaderAddress*             pCc;
+       NULL,                                                                   //MsgHeaderAddress*             pBcc;
+       "",                                                                             //char[]                                szSubject;
+       (MmsResponseStatus)MMS_RESPSTATUS_OK,   //MmsResponseStatus             iResponseStatus;
+       (MmsRetrieveStatus)MMS_RETRSTATUS_OK,   //MmsRetrieveStatus             iRetrieveStatus;
+       "",                                                                             //char[]                                szResponseText;
+       "",                                                                             //char[]                                szRetrieveText;
+
+
+       /* has default value in specification */
+
+       (MmsMsgClass)MMS_MSGCLASS_PERSONAL,             //MmsMsgClass                   msgClass;
+       {MMS_TIMETYPE_RELATIVE, 0},                             //MmsTimeStruct                 expiryTime;
+       {MMS_TIMETYPE_RELATIVE, 0},                             //MmsTimeStruct                 deliveryTime;
+       (MmsPriority)MMS_PRIORITY_NORMAL,               //MmsPriority                   priority;               // Refer [OMA-MMS-ENC-v1_2-20030915-C]
+       (MmsSenderVisible)MMS_SENDER_SHOW,              //MmsSenderVisible              senderVisible;
+       (MmsReport)MMS_REPORT_NO,                               //MmsReport                             deliveryReport;
+       (MmsReport)MMS_REPORT_NO,                               //MmsReport                             readReply;
+       (MmsReportAllowed)MMS_REPORTALLOWED_NO,//MmsReportAllowed               iReportAllowed;
+       "",                                                                             //char[]                                szContentLocation;
+
+
+       /* there is no right default value */
+
+       (msg_delivery_report_status_t)MSG_DELIVERY_REPORT_NONE,         //MmsMsgStatus                  iMsgStatus;
+       (msg_read_report_status_t)MSG_READ_REPORT_NONE,         //MmsReadStatus                 readStatus;
+
+       /* MMS v1.1 ReplyCharge */
+       {
+               (MmsReplyChargeType)MMS_REPLY_NONE,     //MmsReplyChargeType    chargeType;
+               {MMS_TIMETYPE_RELATIVE, 0},                     //MmsTimeStruct                 deadLine;
+               0,                                                                      //int                                   chargeSize;
+               "" ,                                                            //char                                  szChargeID;
+       },
+
+       "",                                                                             //char[]                                szMsgID;
+       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
+
+static bool __MmsDecodeInitialize(void)
+{
+       MmsInitMsgType(&mmsHeader.msgType);
+       MmsInitMsgBody(&mmsHeader.msgBody);
+       return true;
+}
+
+void MmsInitHeader()
+{
+       mmsHeader.type = MMS_MSGTYPE_ERROR;
+
+       memset(mmsHeader.szTrID, 0, MMS_TR_ID_LEN + 1);
+       mmsHeader.version = MMS_VERSION;
+       mmsHeader.date = 0;
+
+       __MsgFreeHeaderAddress(mmsHeader.pFrom);
+       __MsgFreeHeaderAddress(mmsHeader.pTo);
+       __MsgFreeHeaderAddress(mmsHeader.pCc);
+       __MsgFreeHeaderAddress(mmsHeader.pBcc);
+
+       mmsHeader.pFrom = NULL;
+       mmsHeader.pTo = NULL;
+       mmsHeader.pCc = NULL;
+       mmsHeader.pBcc = NULL;
+
+       memset(mmsHeader.szSubject, 0, MSG_LOCALE_SUBJ_LEN + 1);
+
+       mmsHeader.responseStatus = (MmsResponseStatus)MMS_RESPSTATUS_OK;
+       mmsHeader.retrieveStatus = (MmsRetrieveStatus)MMS_RETRSTATUS_OK;
+       memset(mmsHeader.szResponseText, 0, MMS_LOCALE_RESP_TEXT_LEN + 1);
+       memset(mmsHeader.szRetrieveText, 0, MMS_LOCALE_RESP_TEXT_LEN + 1);
+
+
+       mmsHeader.msgClass = (MmsMsgClass)MMS_MSGCLASS_PERSONAL;
+       mmsHeader.expiryTime.type = MMS_TIMETYPE_RELATIVE;
+       mmsHeader.expiryTime.time = 0;
+       mmsHeader.deliveryTime.type     = MMS_TIMETYPE_RELATIVE;
+       mmsHeader.deliveryTime.time     = 0;
+       mmsHeader.priority = (MmsPriority)MMS_PRIORITY_NORMAL;  // Refer [OMA-MMS-ENC-v1_2-20030915-C]
+       mmsHeader.hideAddress =(MmsSenderVisible)MMS_SENDER_SHOW;
+       mmsHeader.deliveryReport = (MmsReport)MMS_REPORT_NO;
+       mmsHeader.readReply = (MmsReport)MMS_REPORT_NO;
+       mmsHeader.reportAllowed = (MmsReportAllowed)MMS_REPORTALLOWED_YES;
+       memset(mmsHeader.szContentLocation, 0, MMS_LOCATION_LEN + 1);
+
+
+       mmsHeader.msgStatus = (msg_delivery_report_status_t)MSG_DELIVERY_REPORT_NONE;
+       mmsHeader.readStatus = (msg_read_report_status_t)MSG_READ_REPORT_NONE;
+
+       mmsHeader.replyCharge.chargeType = (MmsReplyChargeType)MMS_REPLY_NONE;
+       mmsHeader.replyCharge.chargeSize = 0;
+       mmsHeader.replyCharge.deadLine.type = MMS_TIMETYPE_RELATIVE;
+       mmsHeader.replyCharge.deadLine.time = 0;
+       memset(mmsHeader.replyCharge.szChargeID, 0, MMS_MSG_ID_LEN + 1);
+
+
+       memset(mmsHeader.szMsgID, 0, MMS_MSG_ID_LEN + 1);
+       mmsHeader.msgSize = 0;
+#ifdef __SUPPORT_DRM__
+       mmsHeader.drmType = MSG_DRM_TYPE_NONE;
+#endif
+
+       __MmsDecodeInitialize();
+}
+
+static void __MmsCleanDecodeBuff(void)
+{
+       memset(gpMmsDecodeBuf1, 0, gMmsDecodeMaxLen + 1);
+       memset(gpMmsDecodeBuf2, 0, gMmsDecodeMaxLen + 1);
+       gpCurMmsDecodeBuff = NULL;
+       gCurMmsDecodeBuffPos = 0;
+       gMmsDecodeBufLen = 0;
+}
+
+void MmsRegisterDecodeBuffer()
+{
+       gpMmsDecodeBuf1 = gszMmsLoadBuf1;
+       gpMmsDecodeBuf2 = gszMmsLoadBuf2;
+       gpCurMmsDecodeBuff = NULL;
+       gCurMmsDecodeBuffPos = 0;
+       gMmsDecodeMaxLen = MSG_MMS_DECODE_BUFFER_MAX;
+       gMmsDecodeCurOffset = 0;
+       gMmsDecodeBufLen = 0;
+}
+
+void MmsUnregisterDecodeBuffer(void)
+{
+       gpMmsDecodeBuf1 = NULL;
+       gpMmsDecodeBuf2 = NULL;
+       gpCurMmsDecodeBuff = NULL;
+       gCurMmsDecodeBuffPos = 0;
+       gMmsDecodeMaxLen = 0;
+       gMmsDecodeCurOffset = 0;
+       gMmsDecodeBufLen = 0;
+}
+
+
+static int __MmsGetDecodeOffset(void)
+{
+       return (gMmsDecodeCurOffset - gMmsDecodeBufLen + gCurMmsDecodeBuffPos);
+}
+
+static bool __MmsBinaryDecodeCheckAndDecreaseLength(int *pLength, int valueLength)
+{
+       if (*pLength <= valueLength) {
+               gCurMmsDecodeBuffPos -= valueLength;
+               gCurMmsDecodeBuffPos += *pLength;
+               return false;
+       }
+
+       *pLength -= valueLength;
+
+       return true;
+}
+
+
+/* ==========================================================
+
+          B  I  N  A  R  Y         D  E  C  O  D  I  N  G
+
+   ==========================================================*/
+
+/*
+ * Binary Encoded Message Format
+ *
+ *             < Single Part Body Message >
+ * -----------------------------------
+ * |           Header Fields                    |
+ * -----------------------------------
+ * | Content Type:start=xxx;type=xxx | ->(ex) Text/Plain, Text/Html, ....
+ * -----------------------------------
+ * |           Single Part Body                 |
+ * -----------------------------------
+ *
+ *             < Multi Part Body Message >
+ * -----------------------------------
+ * |           Header Fields                    |
+ * -----------------------------------
+ * | Content Type:start=xxx;type=xxx | -> (ex) Application/vnd.wap.multipart.mixed(related), multipart/mixed(related)
+ * -----------------------------------
+ * |   # of Entries (body parts)        |
+ * -----------------------------------                         < Each Entry >
+ * |                   Entry 1                          |      ->      -----------------------------
+ * -----------------------------------         |               header Length           |
+ * |                   Entry 2                          |              -----------------------------
+ * -----------------------------------         |               Data Length                     |
+ * |                   ......                           |              -----------------------------  -
+ * -----------------------------------         |               Content-Type            |  |
+ * |                   Entry n                          |              -----------------------------  | Header Length
+ * -----------------------------------         |                       Header                  |  |
+ *                                                                                     -----------------------------  -
+ *                                                                                     |                       Data                    |  | Data Length
+ *                                                                                     -----------------------------  -
+ */
+bool MmsBinaryDecodeMsgHeader(FILE *pFile, int totalLength)
+{
+       UINT16 fieldCode = 0xffff;
+       UINT16 fieldValue = 0xffff;
+       UINT8 oneByte = 0xff;
+
+       MsgHeaderAddress *pAddr = NULL;
+       MsgHeaderAddress *pLastTo = NULL;
+       MsgHeaderAddress *pLastCc = NULL;
+       MsgHeaderAddress *pLastBcc = NULL;
+
+       UINT32 valueLength = 0;
+       UINT32 tmpInteger = 0;
+       int     tmpIntLen = 0;
+
+       int offset = 0;
+
+       char szGarbageBuff[MSG_STDSTR_LONG]     = {0, };
+       char *pLimitData = NULL;
+       int nRead = 0;
+
+       MSG_DEBUG("pFile=%d, total len=%d\n", pFile, totalLength);
+
+       __MmsCleanDecodeBuff();
+
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos,
+                                                                  &gMmsDecodeCurOffset, gpMmsDecodeBuf1, gpMmsDecodeBuf2,
+                                                                  gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+               MSG_DEBUG("fail to load to buffer \n");
+               goto __CATCH;
+       }
+
+       while (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength)) {
+               fieldCode = oneByte & 0x7f;
+
+               switch (MmsGetBinaryType(MmsCodeFieldCode, fieldCode)) {
+               case MMS_CODE_RESPONSESTATUS:
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("responseStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       fieldValue = MmsGetBinaryType(MmsCodeResponseStatus, (UINT16)(oneByte & 0x7F));
+
+                       if (fieldValue == 0xFFFF) {
+                               MSG_DEBUG("responseStatus error\n");
+                               goto __CATCH;
+                       }
+
+                       if (fieldValue >= 0x0044 && fieldValue <= 0x005F) {
+                               fieldValue = 0x0040;
+                       } else if (fieldValue >= 0x006A && fieldValue <= 0x007F) {
+                               fieldValue = 0x0060;
+                       }
+
+                       mmsHeader.responseStatus = (MmsResponseStatus)fieldValue;
+
+                       MSG_DEBUG("response status = %s\n", MmsDebugGetResponseStatus(mmsHeader.responseStatus));
+
+                       break;
+
+               case MMS_CODE_RETRIEVESTATUS:
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("retrieveStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       fieldValue = MmsGetBinaryType(MmsCodeRetrieveStatus, (UINT16)(oneByte & 0x7F));
+
+                       if (fieldValue == 0xFFFF) {
+                               MSG_DEBUG("retrieveStatus error\n");
+                               goto __CATCH;
+                       }
+
+                       if (fieldValue >= 0x0043 && fieldValue <= 0x005F) {
+                               fieldValue = 0x0040; // 192; Error-transient-failure
+                       } else if (fieldValue >= 0x0064 && fieldValue <= 0x007F) {
+                               fieldValue = 0x0060; //224; Error-permanent-failure
+                       }
+
+                       mmsHeader.retrieveStatus = (MmsRetrieveStatus)fieldValue;
+
+                       MSG_DEBUG("retrieve status = %s\n",
+                                                                                                                       MmsDebugGetRetrieveStatus(mmsHeader.retrieveStatus));
+
+                       break;
+
+               case MMS_CODE_RESPONSETEXT:
+
+                       if (__MmsBinaryDecodeEncodedString(pFile, mmsHeader.szResponseText, MMS_LOCALE_RESP_TEXT_LEN + 1, totalLength) == false) {
+                               MSG_DEBUG("invalid MMS_CODE_RESPONSETEXT \n");
+                               goto __CATCH;
+                       }
+
+                       MSG_DEBUG("response text = %s\n", mmsHeader.szResponseText);
+                       break;
+
+               case MMS_CODE_RETRIEVETEXT:
+
+                       if (__MmsBinaryDecodeEncodedString(pFile, mmsHeader.szRetrieveText, MMS_LOCALE_RESP_TEXT_LEN + 1, totalLength) == false) {
+                               MSG_DEBUG("invalid MMS_CODE_RETRIEVETEXT \n");
+                               goto __CATCH;
+                       }
+
+                       MSG_DEBUG("retrieve text = %s\n", mmsHeader.szResponseText);
+                       break;
+
+               case MMS_CODE_MSGID:
+
+                       if (__MmsBinaryDecodeText(pFile, mmsHeader.szMsgID, MMS_MSG_ID_LEN + 1, totalLength) < 0) {
+                               MSG_DEBUG("MMS_CODE_MSGID is invalid\n");
+                               goto __CATCH;
+                       }
+
+                       MSG_DEBUG("msg id = %s\n", mmsHeader.szMsgID);
+
+                       if (MsgStrlen (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("invalid MMS_CODE_SUBJECT \n");
+                               goto __CATCH;
+                       }
+
+                       pLimitData = (char *)malloc(MSG_LOCALE_SUBJ_LEN + 1);
+
+                       if (pLimitData == NULL) {
+                               MSG_DEBUG("pLimitData malloc fail \n");
+                               goto __CATCH;
+                       }
+
+                       nRead = __MsgCutUTFString((unsigned char*)pLimitData, MSG_LOCALE_SUBJ_LEN + 1, (unsigned char*)mmsHeader.szSubject, MSG_SUBJ_LEN);
+                       MSG_DEBUG("Subject edit.. \n");
+
+                       if (nRead > MSG_LOCALE_SUBJ_LEN) {
+                               memset(mmsHeader.szSubject, 0 , sizeof(mmsHeader.szSubject));
+                               strncpy(mmsHeader.szSubject, pLimitData, MSG_SUBJ_LEN);
+                       } else {
+                               memset(mmsHeader.szSubject, 0 , sizeof(mmsHeader.szSubject));
+                               strncpy(mmsHeader.szSubject, pLimitData, MSG_LOCALE_SUBJ_LEN);
+                       }
+
+                       if (pLimitData) {
+                               free(pLimitData);
+                               pLimitData = NULL;
+                       }
+
+                       MSG_DEBUG("subject = %s\n", mmsHeader.szSubject);
+                       break;
+
+               case MMS_CODE_FROM:
+
+                       /* Value-length (Address-present-token Encoded-string-value | Insert-address-token) */
+
+                       if (__MmsDecodeValueLength(pFile, &valueLength, totalLength) <= 0) {
+                               MSG_DEBUG("MMS_CODE_FROM is invalid\n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("MMS_CODE_FROM GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       // DRM_TEMPLATE - start
+
+                       valueLength--;
+
+                       if (oneByte == (MmsGetBinaryValue(MmsCodeAddressType, MMS_ADDRESS_PRESENT_TOKEN)|0x80)) {
+                               if (valueLength > 0) {
+                                       mmsHeader.pFrom = __MmsDecodeEncodedAddress(pFile, totalLength);
+                                       if (mmsHeader.pFrom == NULL) {
+                                               MSG_DEBUG("MMS_CODE_FROM __MmsDecodeEncodedAddress fail\n");
+                                               goto __CATCH;
+                                       }
+                               } else {
+                                       mmsHeader.pFrom = (MsgHeaderAddress *)malloc(sizeof(MsgHeaderAddress));
+                                       if (mmsHeader.pFrom == NULL)
+                                               goto __CATCH;
+
+                                       mmsHeader.pFrom->szAddr = (char *)malloc(1);
+                                       if (mmsHeader.pFrom->szAddr == NULL) {
+                                               free(mmsHeader.pFrom);
+                                               mmsHeader.pFrom = NULL;
+                                               goto __CATCH;
+                                       }
+
+                                       mmsHeader.pFrom->szAddr[0] = '\0';
+                                       mmsHeader.pFrom->pNext = NULL;
+                               }
+
+                               MSG_DEBUG("from = %s\n", mmsHeader.pFrom->szAddr);
+                               // DRM_TEMPLATE - end
+                       } else if (oneByte == (MmsGetBinaryValue(MmsCodeAddressType, MMS_INSERT_ADDRESS_TOKEN)|0x80)) {
+                               /* Present Token only */
+                               MSG_DEBUG("MMS_CODE_FROM insert token\n");
+                       } else {
+                               /* from data broken */
+                               MSG_DEBUG("from addr broken\n");
+                               gCurMmsDecodeBuffPos--;
+                               goto __CATCH;
+                       }
+                       break;
+
+               case MMS_CODE_TO:
+
+                       pAddr = __MmsDecodeEncodedAddress(pFile, totalLength);
+                       if (pAddr == NULL) {
+                               MSG_DEBUG("MMS_CODE_TO __MmsDecodeEncodedAddress fail\n");
+                               goto __CATCH;
+                       }
+
+                       if (mmsHeader.pTo == NULL) {
+                               /* the first TO */
+                               pLastTo = mmsHeader.pTo = pAddr;
+                       } else {
+                               if (pLastTo)
+                                       pLastTo->pNext = pAddr;
+                               pLastTo = pAddr;
+                       }
+
+                       MSG_DEBUG("to = %s\n", mmsHeader.pTo->szAddr);
+                       break;
+
+               case MMS_CODE_BCC:
+
+                       pAddr = __MmsDecodeEncodedAddress(pFile, totalLength);
+                       if (pAddr == NULL) {
+                               MSG_DEBUG("MMS_CODE_BCC __MmsDecodeEncodedAddress fail\n");
+                               goto __CATCH;
+                       }
+
+                       if (mmsHeader.pBcc == NULL) {
+                               /* the first Bcc */
+                               pLastBcc = mmsHeader.pBcc = pAddr;
+                       } else {
+                               if (pLastBcc)
+                                       pLastBcc->pNext = pAddr;
+                               pLastBcc = pAddr;
+                       }
+
+                       MSG_DEBUG("bcc = %s\n", mmsHeader.pBcc->szAddr);
+                       break;
+
+               case MMS_CODE_CC:
+
+                       pAddr = __MmsDecodeEncodedAddress(pFile, totalLength);
+                       if (pAddr == NULL) {
+                               MSG_DEBUG("MMS_CODE_CC __MmsDecodeEncodedAddress fail\n");
+                               goto __CATCH;
+                       }
+
+                       if (mmsHeader.pCc == NULL) {
+                               /* the first Cc */
+                               pLastCc = mmsHeader.pCc = pAddr;
+                       } else {
+                               if (pLastCc)
+                                       pLastCc->pNext = pAddr;
+                               pLastCc = pAddr;
+                       }
+                       MSG_DEBUG("cc = %s\n", mmsHeader.pCc->szAddr);
+                       break;
+
+               case MMS_CODE_CONTENTLOCATION:
+
+                       if (__MmsBinaryDecodeText(pFile, mmsHeader.szContentLocation, MMS_LOCATION_LEN + 1, totalLength) < 0) {
+                               MSG_DEBUG("MMS_CODE_CONTENTLOCATION is invalid\n");
+                               goto __CATCH;
+                       }
+                       MSG_DEBUG("content location = %s\n", mmsHeader.szContentLocation);
+                       break;
+
+               case MMS_CODE_DATE:
+
+                       if (__MmsDecodeLongInteger(pFile, (UINT32*)&mmsHeader.date, totalLength) == false) {
+                               MSG_DEBUG("MMS_CODE_DATE is invalid\n");
+                               goto __CATCH;
+                       }
+                       MSG_DEBUG("date = %d\n", mmsHeader.date);
+                       break;
+
+               case MMS_CODE_DELIVERYREPORT:
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("deliveryReport GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       fieldValue = MmsGetBinaryType(MmsCodeDeliveryReport, (UINT16)(oneByte & 0x7F));
+
+                       if (fieldValue == 0xFFFF) {
+                               MSG_DEBUG("deliveryReport error\n");
+                               goto __CATCH;
+                       }
+
+                       mmsHeader.deliveryReport = (MmsReport)fieldValue;
+
+                       MSG_DEBUG("delivery report=%s\n", MmsDebugGetMmsReport(mmsHeader.deliveryReport));
+                       break;
+
+               case MMS_CODE_DELIVERYTIME:
+
+                       /* value_length (absolute-token Long-integer | Relative-token Long-integer) */
+
+                       if (__MmsDecodeValueLength(pFile, &valueLength, totalLength) <= 0) {
+                               MSG_DEBUG("invalid MMS_CODE_DELIVERYTIME \n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("delivery time GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       //DRM_TEMPLATE - start
+                       valueLength--;
+
+                       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("invalid MMS_CODE_DELIVERYTIME\n");
+                                               goto __CATCH;
+                                       }
+                               }
+                       // DRM_TEMPLATE - end
+                       } else {
+                               mmsHeader.deliveryTime.type = MMS_TIMETYPE_RELATIVE;
+
+                               if (__MmsBinaryDecodeInteger(pFile, (UINT32*)&mmsHeader.deliveryTime.time, &tmpIntLen, totalLength) == false) {
+                                       MSG_DEBUG("__MmsBinaryDecodeInteger fail...\n");
+                                       goto __CATCH;
+                               }
+                       }
+                       MSG_DEBUG("delivery type=%d, time=%d\n", mmsHeader.deliveryTime.type, mmsHeader.deliveryTime.time);
+                       break;
+
+               case MMS_CODE_EXPIRYTIME:
+
+                       /* value_length(absolute-token Long-integer | Relative-token Long-integer) */
+
+                       if (__MmsDecodeValueLength(pFile, &valueLength, totalLength) <= 0) {
+                               MSG_DEBUG("invalid MMS_CODE_EXPIRYTIME \n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("expiry time GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       // DRM_TEMPLATE - start
+                       valueLength--;
+
+                       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("MMS_CODE_EXPIRYTIME is invalid\n");
+                                               goto __CATCH;
+                                       }
+                               }
+                       // DRM_TEMPLATE - end
+                       } else {
+                               mmsHeader.expiryTime.type = MMS_TIMETYPE_RELATIVE;
+
+                               if (__MmsBinaryDecodeInteger(pFile, (UINT32*)&mmsHeader.expiryTime.time, &tmpIntLen, totalLength) == false) {
+                                       MSG_DEBUG("__MmsBinaryDecodeInteger fail...\n");
+                                       goto __CATCH;
+                               }
+                       }
+                       MSG_DEBUG("expiry = %d\n", mmsHeader.expiryTime.time);
+                       break;
+
+               case MMS_CODE_MSGCLASS:
+
+                       /* Class-value = Class-identifier | Token Text */
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgClass GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       if (oneByte > 0x7f) {
+                               /* Class-identifier */
+                               mmsHeader.msgClass = (MmsMsgClass)MmsGetBinaryType(MmsCodeMsgClass, (UINT16)(oneByte & 0x7F));
+                       } else {
+                               if (__MmsBinaryDecodeText(pFile, szGarbageBuff, MSG_STDSTR_LONG, totalLength) < 0) {
+                                       MSG_DEBUG("1. __MmsBinaryDecodeText fail. (class)\n");
+                                       goto __CATCH;
+                               }
+                       }
+                       MSG_DEBUG("msg class=%s\n", MmsDebugGetMsgClass(mmsHeader.msgClass));
+                       break;
+
+               case MMS_CODE_MSGSIZE:
+
+                       if (__MmsDecodeLongInteger(pFile, (UINT32*)&mmsHeader.msgSize, totalLength) == false) {
+                               MSG_DEBUG("MMS_CODE_MSGSIZE is invalid\n");
+                               goto __CATCH;
+                       }
+                       MSG_DEBUG("msg size = %d\n", mmsHeader.msgSize);
+                       break;
+
+               case MMS_CODE_MSGSTATUS:
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       mmsHeader.msgStatus =  (msg_delivery_report_status_t)MmsGetBinaryType(MmsCodeMsgStatus, (UINT16)(oneByte & 0x7F));
+                       MSG_DEBUG("msg status=%s \n", MmsDebugGetMsgStatus(mmsHeader.msgStatus)) ;
+                       break;
+
+               case MMS_CODE_MSGTYPE:
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       mmsHeader.type = (MmsMsgType)MmsGetBinaryType(MmsCodeMsgType, (UINT16)(oneByte & 0x7F));
+                       MSG_DEBUG("msg type=%s\n", MmsDebugGetMsgType(mmsHeader.type));
+                       break;
+
+               case MMS_CODE_PRIORITY:
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+                       mmsHeader.priority = (MmsPriority)MmsGetBinaryType(MmsCodePriority, (UINT16)(oneByte & 0x7F));
+                       MSG_DEBUG("priority=%d\n", mmsHeader.priority);
+                       break;
+
+               case MMS_CODE_READREPLY:
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+                       mmsHeader.readReply = (MmsReport)MmsGetBinaryType(MmsCodeReadReply, (UINT16)(oneByte & 0x7F));
+                       MSG_DEBUG("read reply=%s \n", MmsDebugGetMmsReport(mmsHeader.readReply));
+                       break;
+
+               case MMS_CODE_REPORTALLOWED:
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+                       mmsHeader.reportAllowed =  (MmsReportAllowed)MmsGetBinaryType(MmsCodeReportAllowed, (UINT16)(oneByte & 0x7F));
+                       MSG_DEBUG("mmsHeader.reportAllowed=%d\n", MmsDebugGetMmsReportAllowed(mmsHeader.reportAllowed));
+                       break;
+
+               case MMS_CODE_SENDERVISIBILLITY:
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+                       mmsHeader.hideAddress= (MmsSenderVisible)!(MmsGetBinaryType(MmsCodeSenderVisibility, (UINT16)(oneByte &0x7F)));
+                       MSG_DEBUG("sender visible=%d \n", 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");
+                               goto __CATCH;
+                       }
+                       MSG_DEBUG("trID = %s\n", mmsHeader.szTrID);
+                       break;
+
+               case MMS_CODE_VERSION:
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+                       mmsHeader.version = oneByte;
+
+                       MSG_DEBUG("ver = 0x%x\n", mmsHeader.version);
+                       break;
+
+               case MMS_CODE_CONTENTTYPE:
+
+                       /*
+                        * Content-type is the last header field of SendRequest and RetrieveConf.
+                        * It's required to decrease pointer by one and return,
+                        * to parse this field in MmsBinaryDecodeContentType().
+                        */
+                       goto __RETURN;
+
+
+               /* ----------- Add by MMSENC v1.1 ----------- */
+
+               case MMS_CODE_READSTATUS:
+
+                       /* Read-status-value = Read | Deleted without being read */
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       mmsHeader.readStatus =  (msg_read_report_status_t)MmsGetBinaryType(MmsCodeReadStatus, (UINT16)(oneByte & 0x7F));
+                       MSG_DEBUG("read status=%s\n", 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("msgStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       mmsHeader.replyCharge.chargeType =  (MmsReplyChargeType)MmsGetBinaryType(MmsCodeReplyCharging, (UINT16)(oneByte & 0x7F));
+                       MSG_DEBUG("mmsHeader.reply charge=%d\n", mmsHeader.replyCharge.chargeType);
+                       break;
+
+               case MMS_CODE_REPLYCHARGINGDEADLINE:
+
+                       /* Reply-charging-deadline-value = Value-length (Absolute-token Date-value | Relative-token Delta-seconds-value) */
+
+                       if (__MmsDecodeValueLength(pFile, &valueLength, totalLength) <= 0) {
+                               MSG_DEBUG("invalid MMS_CODE_REPLYCHARGINGDEADLINE \n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("msgStatus GetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       if (oneByte == (MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_ABSOLUTE) | 0x80)) {
+                               mmsHeader.replyCharge.deadLine.type = MMS_TIMETYPE_ABSOLUTE;
+                       } else {
+                               mmsHeader.replyCharge.deadLine.type = MMS_TIMETYPE_RELATIVE;
+                       }
+
+                       // DRM_TEMPLATE - start
+                       valueLength--;
+
+                       if (valueLength > 0) {
+                               if (__MmsDecodeLongInteger(pFile, (UINT32*)&mmsHeader.replyCharge.deadLine.time, totalLength) == false) {
+                                       MSG_DEBUG("MMS_CODE_REPLYCHARGINGDEADLINE is invalid\n");
+                                       goto __CATCH;
+                               }
+                       }
+                       // 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("1. __MmsBinaryDecodeText fail. (szReplyChargingID)\n");
+                               goto __CATCH;
+                       }
+                       break;
+
+               case MMS_CODE_REPLYCHARGINGSIZE:
+
+                       /* Reply-charging-size-value = Long-integer */
+
+                       if (__MmsDecodeLongInteger(pFile, (UINT32*)&mmsHeader.replyCharge.chargeSize, totalLength) == false) {
+                               MSG_DEBUG("MMS_CODE_REPLYCHARGINGSIZE is invalid\n");
+                               goto __CATCH;
+                       }
+                       break;
+
+               case MMS_CODE_PREVIOUSLYSENTBY:
+
+                       /*
+                        * Previously-sent-by-value = Value-length Forwarded-count-value Encoded-string-value
+                        * Forwarded-count-value = Integer-value
+                        * 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("1. invalid MMS_CODE_PREVIOUSLYSENTBY \n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeInteger(pFile, &tmpInteger, &tmpIntLen, totalLength) == false) {
+                               MSG_DEBUG("2. invalid MMS_CODE_PREVIOUSLYSENTBY \n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeEncodedString(pFile, szGarbageBuff, MSG_STDSTR_LONG, totalLength) == false) {
+                               MSG_DEBUG("invalid MMS_CODE_RETRIEVETEXT \n");
+                               goto __CATCH;
+                       }
+                       break;
+
+               case MMS_CODE_PREVIOUSLYSENTDATE:
+
+                       /*
+                        * Previously-sent-date-value = Value-length Forwarded-count-value Date-value
+                        * Forwarded-count-value = Integer-value
+                        * 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("1. invalid MMS_CODE_PREVIOUSLYSENTDATE \n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeInteger(pFile, &tmpInteger, &tmpIntLen, totalLength) == false) {
+                               MSG_DEBUG("2. invalid MS_CODE_PREVIOUSLYSENTDATE \n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsDecodeLongInteger(pFile, (UINT32*)&tmpInteger, totalLength) == false) {
+                               MSG_DEBUG("3. invalid MMS_CODE_PREVIOUSLYSENTDATE \n");
+                               goto __CATCH;
+                       }
+                       break;
+
+               default:
+
+                       /*
+                        * Application-header             = Token-text Application-specific-value
+                        * Token-text                             = Token End-of-string
+                        * Application-specific-value = Text -string
+                        *
+                        * OR unknown header field - Just ignore these fields.
+                        *
+                        * Read one byte and check the value >= 0x80
+                        * (check these value can be field code)
+                        */
+                       {
+                               int             remainLength = 0;
+
+                               oneByte = 0x00;
+
+                               offset = __MmsGetDecodeOffset();
+                               if (offset >= totalLength)
+                                       goto __RETURN;
+
+                               remainLength = totalLength - offset;
+
+                               while ((oneByte < 0x80) && (remainLength > 0)) {
+                                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&remainLength, 1) == false) {
+                                               MSG_DEBUG("__MmsBinaryDecodeCheckAndDecreaseLength fail\n");
+                                               goto __CATCH;
+                                       }
+                                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                                               MSG_DEBUG("responseStatus GetOneByte fail\n");
+                                               goto __CATCH;
+                                       }
+                               }
+
+                               gCurMmsDecodeBuffPos--;
+                       }
+
+                       break;
+               }       /* switch */
+
+               offset = __MmsGetDecodeOffset();
+               if (offset >= totalLength)
+                       goto __RETURN;
+
+       }       /* while */
+
+
+__RETURN:
+
+       if (mmsHeader.pTo == NULL && pLastTo) {
+               free(pLastTo);
+       }
+
+       if (mmsHeader.pCc == NULL && pLastCc) {
+               free(pLastCc);
+       }
+
+       if (mmsHeader.pBcc == NULL && pLastBcc) {
+               free(pLastBcc);
+       }
+
+       MSG_DEBUG("success\n");
+       return true;
+
+
+__CATCH:
+
+       if (mmsHeader.pTo == NULL && pLastTo) {
+               free(pLastTo);
+       }
+
+       if (mmsHeader.pCc == NULL && pLastCc) {
+               free(pLastCc);
+       }
+
+       if (mmsHeader.pBcc == NULL && pLastBcc) {
+               free(pLastBcc);
+       }
+
+       MSG_DEBUG("failed\n");
+
+       return false;
+}
+
+bool MmsBinaryDecodeMsgBody(FILE *pFile, char *szFilePath, int totalLength)
+{
+       MSG_BEGIN();
+
+       int length = 0;
+       int offset = 0;
+
+       if (szFilePath != NULL)
+               strncpy(mmsHeader.msgType.szOrgFilePath, szFilePath , strlen(szFilePath));
+
+       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,
+                                                                       &gMmsDecodeCurOffset, gpMmsDecodeBuf1, gpMmsDecodeBuf2,
+                                                                       gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+               MSG_DEBUG("fail to load to buffer \n");
+               goto __CATCH;
+       }
+
+       // msg's type [ex] related, mixed, single part (jpg, amr and etc)
+       length = __MmsBinaryDecodeContentType(pFile, &mmsHeader.msgType, totalLength);
+       if (length == -1) {
+               MSG_DEBUG("MMS_CODE_CONTENTTYPE is fail\n");
+               goto __CATCH;
+       }
+
+       mmsHeader.msgType.size   = length + 1; // + Content-Type code value
+       mmsHeader.msgBody.offset = __MmsGetDecodeOffset();
+
+       switch (mmsHeader.msgType.type) {
+       case MIME_APPLICATION_VND_WAP_MULTIPART_MIXED:
+       case MIME_APPLICATION_VND_WAP_MULTIPART_RELATED:
+       case MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC:
+       case MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE:
+       case MIME_MULTIPART_REPORT:
+       case MIME_MULTIPART_MIXED:
+       case MIME_MULTIPART_RELATED:
+       case MIME_MULTIPART_ALTERNATIVE:
+       case MIME_APPLICATION_VND_OMA_DRM_MESSAGE:
+       case MIME_APPLICATION_VND_OMA_DRM_CONTENT:
+
+               MSG_DEBUG("Decode multipart\n");
+
+               offset = __MmsGetDecodeOffset();
+               if (offset >= totalLength)
+                       goto __RETURN;
+
+               if (__MmsBinaryDecodeMultipart(pFile, szFilePath, &mmsHeader.msgType, &mmsHeader.msgBody, totalLength) == false) {
+                       MSG_DEBUG("MmsBinaryDecodeMultipart is fail.\n");
+                       goto __CATCH;
+               }
+               break;
+
+       default:
+
+               /* Single part message ---------------------------------------------- */
+               if (szFilePath != NULL)
+                       strcpy(mmsHeader.msgBody.szOrgFilePath, szFilePath);
+
+               offset = __MmsGetDecodeOffset();
+               if (offset >= totalLength)
+                       goto __RETURN;
+
+               if (__MmsBinaryDecodePartBody(pFile, totalLength - mmsHeader.msgBody.offset, totalLength) == false) {
+                       MSG_DEBUG("MmsBinaryDecodePartBody is fail.(Single Part)\n");
+                       goto __CATCH;
+               }
+
+               mmsHeader.msgBody.size = totalLength - mmsHeader.msgBody.offset;
+               mmsHeader.msgType.contentSize = totalLength - mmsHeader.msgBody.offset;
+
+               break;
+       }
+
+#ifdef __SUPPORT_DRM__
+       mmsHeader.drmType = MsgGetDRMType(&mmsHeader.msgType, &mmsHeader.msgBody);
+#endif
+
+__RETURN:
+       MSG_END();
+       return true;
+
+__CATCH:
+       return false;
+}
+
+static bool __MmsBinaryDecodeParameter(FILE *pFile, MsgType *pMsgType, int valueLength, int totalLength)
+{
+       UINT8 oneByte = 0;
+       int charSetLen = 0;
+       char *szTypeString = NULL;
+       char *szTypeValue = NULL;
+       UINT8 paramCode = 0xff;
+       UINT32 integer = 0;
+       int intLen = 0;
+       int length = 0;
+       int textLength = 0;
+
+       /*
+        * Parameter = Typed-parameter | Untyped-parameter
+        * WAP-230-WSP-20010118-p, Proposed Version 18 January 2001 (pp.107)
+        */
+
+       MSG_BEGIN();
+
+       while (valueLength > 0) {
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                       MSG_DEBUG("paramCode _MmsBinaryDecodeGetOneByte fail\n");
+                       goto __CATCH;
+               }
+
+               paramCode = oneByte;
+               valueLength--;
+
+               switch (paramCode) {
+               case 0x81: // charset
+
+                       if (__MmsBinaryDecodeCharset(pFile, (UINT32*)&(pMsgType->param.charset), &charSetLen, totalLength) == false) {
+                               MSG_DEBUG("MmsBinaryDecodeContentType : __MmsBinaryDecodeCharset fail.\n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, charSetLen) == false)
+                               goto __RETURN;
+
+                       break;
+
+               case 0x85: //name = Text-string
+               case 0x97: //name = Text-value  = No-value | Token-text | Quoted-string
+                       memset(pMsgType->param.szName, 0, sizeof(pMsgType->param.szName));
+                       length = __MmsDecodeGetFilename(pFile,  pMsgType->param.szName,
+                                                                                        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");
+                               goto __CATCH;
+                       }
+
+                       if (__MsgCheckFileNameHasInvalidChar(pMsgType->param.szName)) {
+                               __MsgReplaceInvalidFileNameChar(pMsgType->param.szName, '_');
+                       }
+
+                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, length) == false)
+                               goto __RETURN;
+
+                       break;
+
+               case 0x86: //filename = Text-string
+               case 0x98: //filename = Text-value  = No-value | Token-text | Quoted-string
+                       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");
+                               goto __CATCH;
+                       }
+
+                       if (__MsgCheckFileNameHasInvalidChar(pMsgType->param.szFileName)) {
+                               __MsgReplaceInvalidFileNameChar(pMsgType->param.szFileName, '_');
+                       }
+
+                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, length) == false)
+                               goto __RETURN;
+
+                       break;
+
+               case 0x89: //type = Constrained-encoding = Extension-Media | Short-integer
+
+                       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                               MSG_DEBUG("type _MmsBinaryDecodeGetOneByte fail\n");
+                               goto __CATCH;
+                       }
+
+                       if (oneByte > 0x7f) {
+                               pMsgType->param.type = MmsGetBinaryType(MmsCodeContentType,
+                                                                                                                 (UINT16)(oneByte & 0x7f));
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, 1) == false)
+                                       goto __RETURN;
+                       } else {
+                               gCurMmsDecodeBuffPos--;
+
+                               textLength = 0;
+                               szTypeString = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+                               pMsgType->param.type = MmsGetTextType(MmsCodeContentType, szTypeString);
+
+                               if (szTypeString) {
+                                       free(szTypeString);
+                                       szTypeString = NULL;
+                               }
+
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, textLength) == false)
+                                       goto __RETURN;
+                       }
+
+                       break;
+
+               case 0x8A: //start encoding version 1.2
+               case 0x99: //start encoding version 1.4
+
+                       textLength       = 0;
+                       szTypeString = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+                       if (szTypeString) {
+                               memset(pMsgType->param.szStart, 0, MMS_CONTENT_ID_LEN + 1);
+                               strncpy(pMsgType->param.szStart, szTypeString, MMS_CONTENT_ID_LEN);
+                               free(szTypeString);
+                               szTypeString = NULL;
+
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, textLength) == false)
+                                       goto __RETURN;
+                       }
+
+                       break;
+
+               case 0x8B: //startInfo encoding version 1.2
+               case 0x9A: //startInfo encoding version 1.4
+
+                       textLength       = 0;
+                       szTypeString = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+
+                       if (szTypeString) {
+                               memset(pMsgType->param.szStartInfo, 0, MMS_CONTENT_ID_LEN + 1);
+                               strncpy(pMsgType->param.szStartInfo, szTypeString, MMS_CONTENT_ID_LEN);
+
+                               free(szTypeString);
+                               szTypeString = NULL;
+
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, textLength) == false)
+                                       goto __RETURN;
+                       }
+
+                       break;
+
+               default:
+
+                       if (paramCode > 0x7F) {
+                               MSG_DEBUG("Unsupported parameter\n");
+
+                               // In case of the last byte of Parameter field, it should be returned without decreasing the gCurMmsDecodeBuffPos value.
+                               valueLength++;
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, 1) == false)
+                                       goto __RETURN;
+                       } else {
+                               /*
+                                * Untyped Parameter = Token-text Untyped-value
+                                * Token-text            = Token End-of-string
+                                * Untyped-value         = Integer-value | Text-value
+                                * Text-value            = No-value | Token-text | Quoted-string
+                                *
+                                * Just increase pointer!!!
+                                */
+
+
+                               /* Token-text */
+
+                               gCurMmsDecodeBuffPos--;
+                               valueLength++;
+
+                               textLength        = 0;
+                               szTypeString  = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, textLength) == false)
+                                       goto __RETURN;
+
+
+                               /* Text-value */
+
+                               if (__MmsBinaryDecodeInteger(pFile, &integer, &intLen, totalLength) == true) {
+                                       MSG_DEBUG("Unsupported parameter(%d)\n", integer);
+                                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, intLen) == false)
+                                               goto __RETURN;
+                               } else {
+                                       textLength        = 0;
+                                       szTypeValue  = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+
+                                       if (szTypeValue) {
+                                               /* checkMe:  forwardLock needs boudary string */
+                                               if (strcasecmp(szTypeString, "boundary") == 0) {
+                                                       memset(pMsgType->param.szBoundary, 0, MSG_BOUNDARY_LEN + 1);
+                                                       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);
+                                               } 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);
+#endif
+                                               }
+                                               free(szTypeValue);
+                                               szTypeValue = NULL;
+
+                                               MSG_DEBUG("Unsupported parameter(%s)\n", szTypeValue);
+                                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&valueLength, textLength) == false)
+                                                       goto __RETURN;
+                                       }
+                               }
+
+                               if (szTypeString) {
+                                       MSG_DEBUG("Unsupported parameter(%s)\n", szTypeString);
+                                       free(szTypeString);
+                                       szTypeString = NULL;
+                               }
+                       }
+
+                       break;
+               }
+       }       /*end of while loop*/
+
+
+__RETURN:
+
+       if (szTypeString) {
+               free(szTypeString);
+               szTypeString = NULL;
+       }
+
+       return true;
+
+__CATCH:
+
+       return false;
+}
+
+/**
+ * Decode Encoded Content type
+ *
+ * @param      pEncodedData    [in] ContentType encoded data
+ * @param      pMsgType                [out] Decoded MsgType
+ * @return     Decoded address list
+ */
+static int __MmsBinaryDecodeContentType(FILE *pFile, MsgType *pMsgType, int totalLength)
+{
+       UINT8 oneByte = 0;
+       char *szTypeString = NULL;
+       int valueLength = 0;
+       int length = 0;
+       int textLength = 0;
+
+
+       /*
+        * Content-type-value             : [WAPWSP 8.4.2.24]
+        * Preassigned content-types  : [WAPWSP Appendix A, Table 40]
+        * The use of start-parameter : [RFC2387] and SHOULD be encoded according to [WAPWSP].
+        *
+        * Content-type-value   = Constrained-media | Content-general-form
+        * Content-general-form = Value-length Media-type
+        * Media-type                   = (Well-known-media | Extension-Media) *(Parameter)
+        */
+
+       MSG_DEBUG("decoding content type..\n");
+
+       length = __MmsDecodeValueLength(pFile, (UINT32*)&valueLength, totalLength);
+       if (length <= 0) {
+               /*
+                * Constrained-media or Single part message
+                * Constrained-media = Constrained-encoding = Extension-Media | Short-integer
+                * Extension-media   = *TEXT End-of-string
+                * Short-integer     = OCTET(1xxx xxxx)
+                */
+
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                       MSG_DEBUG("Constrained-media _MmsBinaryDecodeGetOneByte fail\n");
+                       goto __CATCH;
+               }
+
+               if (oneByte > 0x7F) {
+                       /* Short-integer */
+                       pMsgType->type = MmsGetBinaryType(MmsCodeContentType, (UINT16)(oneByte & 0x7F));
+                       length = 1;
+               } else {
+                       char *pszTemp = NULL;
+
+                       /* Extension-Media */
+                       gCurMmsDecodeBuffPos--;
+
+                       textLength = 0;
+                       szTypeString = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+
+                       if (szTypeString && (strchr(szTypeString, ';')) != NULL) {
+                               pszTemp = __MsgGetStringUntilDelimiter(szTypeString, ';');
+                               if (pszTemp) {
+                                       free(szTypeString);
+                                       szTypeString = pszTemp;
+                               }
+                       }
+
+                       pMsgType->type = MmsGetTextType(MmsCodeContentType, szTypeString);
+
+                       length = textLength;
+
+                       if (szTypeString) {
+                               free(szTypeString);
+                               szTypeString = NULL;
+                       }
+               }
+       } else {
+               /*
+                * Content-general-form = Value-length Media-type
+                * Media-type                   = (Well-known-media | Extension-Media)*(Parameter)
+                */
+
+               length += valueLength;
+
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                       MSG_DEBUG("Well-known-media _MmsBinaryDecodeGetOneByte fail\n");
+                       goto __CATCH;
+               }
+
+               if (oneByte > 0x7F) {
+                       /* Well-known-media */
+                       pMsgType->type = MmsGetBinaryType(MmsCodeContentType, (UINT16)(oneByte & 0x7F));
+                       valueLength--;
+               } else {
+                       /* Extension-Media */
+                       gCurMmsDecodeBuffPos--;
+
+                       textLength = 0;
+                       szTypeString = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+                       pMsgType->type = MmsGetTextType(MmsCodeContentType, szTypeString);
+                       valueLength -= textLength;
+
+                       if (szTypeString) {
+                               free(szTypeString);
+                               szTypeString = NULL;
+                       }
+               }
+
+               MSG_DEBUG("content type=%s\n", MmsDebugGetMimeType((MimeType)pMsgType->type));
+
+
+               if (__MmsBinaryDecodeParameter(pFile, pMsgType, valueLength, totalLength) == false) {
+                       MSG_DEBUG("Content-Type parameter fail\n");
+                       goto __CATCH;
+               }
+       }
+
+       return length;
+
+__CATCH:
+       return -1;
+}
+
+static bool __MmsBinaryDecodePartHeader(FILE *pFile, MsgType *pMsgType, int headerLen, int totalLength)
+{
+       UINT8 fieldCode = 0xff;
+       int length = 0;
+       UINT32 valueLength = 0;
+       char *pCode = NULL;
+       char *pValue = NULL;
+       char *pParam = NULL;
+       char ch = '\0';
+       UINT8 oneByte = 0;
+       int     textLength = 0;
+       int tmpInt = 0;
+       int tmpIntLen = 0;
+       char *pLatinBuff = NULL;
+       char *szSrc = NULL;
+       char *szTemp = NULL;
+
+
+       if (pFile == NULL || pMsgType == NULL)
+               return false;
+
+       /*
+        * Message-header                         = Well-known-header | Application-header
+        * Well-known-header              = Well-known-field-name Wap-value
+        * Application-header             = Token-text Application-specific-value
+        * Well-known-field-name          = Short-integer
+        * Application-specific-value = Text-string
+        */
+
+       while (headerLen > 0) {
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                       MSG_DEBUG("field code GetOneByte fail\n");
+                       goto __CATCH;
+               }
+
+               if (0x80 <= oneByte && oneByte <= 0xC7) {
+                       /* Well-known-header = Well-known-field-name Wap-value (0x00 ~ 0x47) */
+
+                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, 1) == false)
+                               goto __RETURN;
+
+                       fieldCode = oneByte & 0x7f;
+
+                       switch (fieldCode) {
+                       case 0x0E:      //Content-Location
+                       case 0x04:      //Content-Location
+
+                               pLatinBuff = (char *)malloc(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");
+                                       goto __CATCH;
+                               }
+
+                               szSrc = MsgChangeHexString(pLatinBuff);
+
+                               if (szSrc) {
+                                       strcpy(pLatinBuff, szSrc);
+                                       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("MsgLatin2UTF fail \n");
+                                       goto __CATCH;
+                               }
+
+                               free(pLatinBuff);
+                               pLatinBuff = NULL;
+
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, length) == false)
+                                       goto __RETURN;
+
+                               break;
+
+                       case 0x40:      // Content-ID
+
+                               pLatinBuff = (char *)malloc(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");
+                                       goto __CATCH;
+                               }
+
+                               szSrc = MsgChangeHexString(pLatinBuff);
+
+                               if (szSrc) {
+                                       strcpy(pLatinBuff, szSrc);
+                                       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("MsgLatin2UTF fail \n");
+                                       goto __CATCH;
+                               }
+                               free(pLatinBuff);
+                               pLatinBuff = NULL;
+
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, length) == false)
+                                       goto __RETURN;
+
+                               break;
+
+                       case 0x2E:      // Content-Disposition
+                       case 0x45:      // Content-Disposition
+
+                               /*
+                                * Content-disposition-value = Value-length Disposition *(Parameter)
+                                * Disposition = Form-data | Attachment | Inline | Token-text
+                                *                               Form-data = <Octet 128> : 0x80
+                                *                               Attachment = <Octet 129> : 0x81
+                                *                               Inline = <Octet 130> : 0x82
+                                */
+
+                               length = __MmsDecodeValueLength2(pFile, &valueLength, totalLength);
+
+                               if (length > 0) {
+                                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, length) == false)
+                                               goto __RETURN;
+
+                               }
+
+                               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                                       MSG_DEBUG("Disposition value GetOneByte fail\n");
+                                       goto __CATCH;
+                               }
+
+                               if (length > 0)
+                                       valueLength--;
+
+                               if (oneByte >= 0x80) {
+                                       pMsgType->disposition = MmsGetBinaryType(MmsCodeMsgDisposition, (UINT16)(oneByte & 0x7F));
+
+                                       if (pMsgType->disposition == INVALID_HOBJ) {
+                                               MSG_DEBUG("MmsBinaryDecodePartHeader : Content-Disposition MmsGetBinaryType fail.\n");
+                                               pMsgType->disposition = MSG_DISPOSITION_ATTACHMENT;             // default
+                                       }
+
+                                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, 1) == false)
+                                               goto __RETURN;
+
+                                       if (__MmsBinaryDecodeParameter(pFile, pMsgType, valueLength, totalLength) == false) {
+                                               MSG_DEBUG("Disposition parameter fail\n");
+                                               goto __CATCH;
+                                       }
+
+                                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, valueLength) == false)
+                                               goto __RETURN;
+                               } else {
+
+                                       gCurMmsDecodeBuffPos--;
+                                       valueLength++;
+
+                                       pLatinBuff = (char *)malloc(MSG_FILENAME_LEN_MAX);
+                                       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");
+                                               goto __CATCH;
+                                       }
+                                       free(pLatinBuff);
+                                       pLatinBuff = NULL;
+
+                                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, textLength) == false)
+                                               goto __RETURN;
+
+                                       valueLength -= textLength;
+
+                                       if (__MmsBinaryDecodeParameter(pFile, pMsgType, valueLength, totalLength) == false)
+                                       {
+                                               MSG_DEBUG("Disposition parameter fail\n");
+                                               goto __CATCH;
+                                       }
+
+                                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, valueLength) == false)
+                                               goto __RETURN;
+
+                               }
+
+                               break;
+
+                       case 0x0B:      //Content-Encoding
+
+                               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                                       MSG_DEBUG("Disposition value GetOneByte fail\n");
+                                       goto __CATCH;
+                               }
+
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, 1) == false)
+                                       goto __RETURN;
+
+                               break;
+
+                       case 0x0C:      //Content-Language
+
+                               if (__MmsBinaryDecodeInteger(pFile, (UINT32*)&tmpInt, &tmpIntLen, totalLength) == true) {
+                                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, tmpIntLen) == false)
+                                               goto __RETURN;
+                               } else {
+                                       char* cTemp = NULL;
+
+                                       cTemp = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+
+                                       if (cTemp == NULL) {
+                                               MSG_DEBUG("MmsBinaryDecodePartHeader : __MmsBinaryDecodeText2 fail...\n");
+                                               goto __CATCH;
+                                       }
+
+                                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, textLength) == false) {
+                                               if (cTemp) {
+                                                       free(cTemp);
+                                               }
+                                               goto __RETURN;
+                                       }
+
+                                       if (cTemp)
+                                               free(cTemp);
+                               }
+
+                               break;
+
+                       case 0x0D:      //Content-Length
+
+                               if (__MmsBinaryDecodeInteger(pFile, (UINT32*)&tmpInt, &tmpIntLen, totalLength) == false) {
+                                       MSG_DEBUG("MmsBinaryDecodePartHeader : __MmsBinaryDecodeInteger fail...\n");
+                                       goto __CATCH;
+                               }
+
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, tmpIntLen) == false)
+                                       goto __RETURN;
+
+                               break;
+
+                       case 0x30:      //X-Wap-Content-URI skip this value
+
+                               MSG_DEBUG("MmsBinaryDecodePartHeader : X-Wap-Content-URI header.\n");
+                               pLatinBuff = (char *)malloc(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");
+                                       goto __CATCH;
+                               }
+
+                               MSG_DEBUG("MmsBinaryDecodePartHeader : 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");
+
+                               break;
+
+                       case 0x01:      // Accept-charset
+                               //if (NvGetInt(NV_SI_ADM_GCF_STATE) == 1)
+                               {
+                                       /*      WAP-230-WSP-200010705-a.pdf
+                                               8.4.2.8 Accept charset field
+                                               The following rules are used to encode accept character set values.
+                                               Accept-charset-value = Constrained-charset | Accept-charset-general-form
+                                               Accept-charset-general-form = Value-length (Well-known-charset | Token-text) [Q-value]
+                                               Constrained-charset = Any-charset | Constrained-encoding
+                                               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     charset = 0;
+                                       int charSetLen = 0;
+
+                                       MSG_DEBUG("MmsBinaryDecodePartHeader : Accept-charset. \n");
+
+                                       length = __MmsDecodeValueLength(pFile, &valueLength, totalLength);
+                                       if (length > 0) {
+                                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, length) == false)
+                                                       goto __RETURN;
+
+                                       }
+
+                                       if (__MmsBinaryDecodeInteger(pFile, (UINT32*)&charset, &charSetLen, totalLength) == false) {
+                                               // We only support the well-known-charset format
+                                               MSG_DEBUG("MmsBinaryDecodePartHeader : __MmsBinaryDecodeInteger fail...\n");
+                                               goto __CATCH;
+                                       }
+
+                                       if (charset > 0)
+                                               MmsGetBinaryType(MmsCodeCharSet, (UINT16)charset);
+
+                                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, charSetLen) == false)
+                                               goto __RETURN;
+
+                                       break;
+                               }
+
+                       default:
+
+                               /* Other Content-xxx headers : Have valueLength */
+
+                               MSG_DEBUG("MmsBinaryDecodePartHeader : unknown Value = 0x%x\n", oneByte);
+
+                               length = __MmsDecodeValueLength(pFile, &valueLength, totalLength);
+                               if (length <= 0) {
+                                       MSG_DEBUG("MmsBinaryDecodePartHeader : 1. invalid MMS_CODE_PREVIOUSLYSENTDATE \n");
+                                       goto __CATCH;
+                               }
+
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, length) == false)
+                                       goto __RETURN;
+
+                               szTemp = (char *)malloc(valueLength);
+                               if (szTemp == NULL)
+                                       goto __CATCH;
+
+                               if (__MmsBinaryDecodeGetBytes(pFile, szTemp, valueLength, totalLength) == false) {
+                                       MSG_DEBUG("MmsBinaryDecodePartHeader : default _MmsBinaryDecodeGetBytes() fail\n");
+                                       if (szTemp) {
+                                               free(szTemp);
+                                               szTemp = NULL;
+                                       }
+                                       goto __CATCH;
+                               }
+
+                               if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, valueLength) == false)
+                                       goto __RETURN;
+
+                               break;
+                       }
+               } else {
+                       /*
+                        * Application-header  = Token-text Application-specific-value
+                        * Application-specific-value = Text-string
+                        */
+
+                       MSG_DEBUG(" Application-header = Token-text Application-specific-value \n");
+
+                       gCurMmsDecodeBuffPos--;
+
+                       /* Token-text */
+
+                       textLength = 0;
+                       pCode = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+                       if (pCode == NULL) {
+                               MSG_DEBUG("pCode is null\n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, textLength) == false)
+                               goto __RETURN;
+
+                       MSG_DEBUG(" Token-text (%s) \n", pCode);
+
+
+                       /* Application-specific-value */
+
+                       textLength = 0;
+                       pValue = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+                       if (pValue == NULL) {
+                               MSG_DEBUG("pValue is null\n");
+                               goto __CATCH;
+                       }
+
+                       MSG_DEBUG(" Application-specific-value (%s) \n", pValue);
+
+
+                       pParam = strchr(pValue, MSG_CH_ADDR_DELIMETER);
+                       if (pParam) {
+                               ch = *pParam;
+                               *pParam = '\0';
+                       }
+
+                       switch (MmsGetTextType(MmsCodeMsgBodyHeaderCode, pCode)) {
+                       case MMS_BODYHDR_TRANSFERENCODING:              // Content-Transfer-Encoding
+                               pMsgType->encoding = MmsGetTextType(MmsCodeContentTransferEncoding, pValue);
+                               break;
+
+                       case MMS_BODYHDR_CONTENTID:                             // Content-ID
+
+                               pLatinBuff = (char *)malloc(MMS_CONTENT_ID_LEN + 1);
+                               if (pLatinBuff == NULL)
+                               {
+                                       goto __CATCH;
+                               }
+
+                               __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)
+                               {
+                                       MSG_DEBUG("MsgLatin2UTF fail \n");
+                                       goto __CATCH;
+                               }
+
+                               free(pLatinBuff);
+                               pLatinBuff = NULL;
+                               break;
+
+                       case MMS_BODYHDR_CONTENTLOCATION:               // Content-Location
+
+                               pLatinBuff = (char *)malloc(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("MsgLatin2UTF fail \n");
+                                       goto __CATCH;
+                               }
+
+                               free(pLatinBuff);
+                               pLatinBuff = NULL;
+                               break;
+
+                       case MMS_BODYHDR_DISPOSITION:                   // Content-Disposition
+                               pMsgType->disposition = MmsGetTextType(MmsCodeMsgDisposition, pValue);
+                               break;
+
+                       case MMS_BODYHDR_X_OMA_DRM_SEPARATE_DELIVERY:   // DRM RO WAITING
+                                       break;
+
+                       default:
+                               MSG_DEBUG("Unknown Field : %s, Value: %s\n", pCode, pValue);
+                               break;
+                       }
+
+                       if (pParam) {
+                               __MsgParseParameter(pMsgType, pParam + 1);
+                               *pParam = ch;
+                       }
+                       if (pCode) {
+                               free(pCode);
+                               pCode = NULL;
+                       }
+                       if (pValue) {
+                               free(pValue);
+                               pValue = NULL;
+                       }
+
+                       if (__MmsBinaryDecodeCheckAndDecreaseLength(&headerLen, textLength) == false)
+                               goto __RETURN;
+
+               }
+       }       //while
+
+__RETURN:
+
+       if (pLatinBuff) {
+               free(pLatinBuff);
+               pLatinBuff = NULL;
+       }
+
+       if (szTemp) {
+               free(szTemp);
+               szTemp = NULL;
+       }
+
+       if (pCode) {
+               free(pCode);
+               pCode = NULL;
+       }
+
+       return true;
+
+__CATCH:
+
+       if (pLatinBuff) {
+               free(pLatinBuff);
+               pLatinBuff = NULL;
+       }
+       if (pCode) {
+               free(pCode);
+               pCode = NULL;
+       }
+       if (pValue) {
+               free(pValue);
+               pValue = NULL;
+       }
+
+       if (szTemp) {
+               free(szTemp);
+               szTemp = NULL;
+       }
+
+       return false;
+}
+
+static bool __MmsBinaryDecodeEntries(FILE *pFile, UINT32 *npEntries, int totalLength)
+{
+       int length = 0;
+
+       length = __MmsBinaryDecodeUintvar(pFile, npEntries, totalLength);
+       if (length <= 0) {
+               goto __CATCH;
+       }
+
+       MSG_DEBUG("Number of Entries = %d\n", *npEntries);
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+static bool __MmsBinaryDecodePartBody(FILE *pFile, UINT32 bodyLength, int totalLength)
+{
+       int offset = 0;
+
+       /*
+        * Currently, offset and size is
+        * the only information used with msgBody.
+        * If you need, add here more information
+        */
+       MSG_BEGIN();
+
+       offset = __MmsGetDecodeOffset();
+       offset += bodyLength;
+
+       if (MsgFseek(pFile, offset, SEEK_SET) < 0) {
+               MSG_DEBUG("fail to seek file pointer \n");
+               goto __CATCH;
+       }
+
+       __MmsCleanDecodeBuff();
+
+       gMmsDecodeCurOffset = offset;
+
+       if (offset >= totalLength)
+               goto __RETURN;
+
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                  gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+               MSG_DEBUG("fail to load to buffer \n");
+               goto __CATCH;
+       }
+
+       return true;
+
+__RETURN:
+       return true;
+
+__CATCH:
+       return false;
+}
+
+static bool __MmsBinaryDecodeMovePointer(FILE *pFile, int offset, int totalLength)
+{
+       if (offset > totalLength)
+               goto __RETURN;
+
+       if (MsgFseek(pFile, offset, SEEK_SET) < 0) {
+               MSG_DEBUG("fail to seek file pointer \n");
+               goto __CATCH;
+       }
+
+       __MmsCleanDecodeBuff();
+
+       gMmsDecodeCurOffset = offset;
+
+       if (offset == totalLength)
+               goto __RETURN;
+
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                       gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+               MSG_DEBUG("fail to load to buffer \n");
+               goto __CATCH;
+       }
+
+__RETURN:
+       return true;
+
+__CATCH:
+       return false;
+}
+
+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;
+       int offset = 0;
+       int     index = 0;
+
+       MsgPresentationFactor factor = MSG_PRESENTATION_NONE;
+       MsgPresentaionInfo presentationInfo;
+
+       MSG_DEBUG("total length=%d\n", totalLength);
+
+       presentationInfo.factor = MSG_PRESENTATION_NONE;
+       presentationInfo.pCurPresentation = NULL;
+       presentationInfo.pPrevPart = NULL;
+
+       if (__MmsBinaryDecodeEntries(pFile, &nEntries, totalLength) == false) {
+               MSG_DEBUG("MmsBinaryDecodeEntries is fail.\n");
+               goto __CATCH;
+       }
+
+       if (pMsgBody->body.pMultipart != NULL)
+               pLastMultipart = pMsgBody->body.pMultipart;
+
+       while (nEntries) {
+               MSG_DEBUG("decoding %dth multipart\n", index);
+
+               offset = __MmsGetDecodeOffset();
+               if (offset >= totalLength)
+                       goto __RETURN;
+
+               if ((pMultipart = __MsgAllocMultipart()) == NULL) {
+                       MSG_DEBUG("MsgAllocMultipart Fail \n");
+                       goto __CATCH;
+               }
+
+               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);
+               } 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.pCurPresentation = pMultipart;
+               }
+
+               if (pLastMultipart == NULL) {
+                       /* first multipart */
+                       pMsgBody->body.pMultipart = pMultipart;
+                       pLastMultipart = pMultipart;
+                       pPreMultipart = NULL;
+               } else {
+                       pLastMultipart->pNext = pMultipart;
+                       pLastMultipart = pMultipart;
+                       pPreMultipart = pMultipart;
+               }
+
+               pMsgType->contentSize += pMultipart->pBody->size;
+
+               nEntries--;
+
+               __MmsDebugPrintMulitpartEntry(pMultipart, index++);
+
+       }
+
+       pMsgBody->size = totalLength - pMsgBody->offset;
+
+#ifdef __SUPPORT_DRM__
+       if (MmsDrm2GetConvertState() != MMS_DRM2_CONVERT_REQUIRED)
+#endif
+               __MsgConfirmPresentationPart(pMsgType, pMsgBody, &presentationInfo);
+
+       if (__MsgResolveNestedMultipart(pMsgType, pMsgBody) == false) {
+               MSG_DEBUG("MmsBinaryDecodeMultipart : MsgResolveNestedMultipart failed \n");
+               goto __CATCH;
+       }
+
+__RETURN:
+       return true;
+
+__CATCH:
+       if (pMultipart) {
+               if (pMultipart->pBody) {
+                       free(pMultipart->pBody);
+                       pMultipart->pBody = NULL;
+               }
+
+               free(pMultipart);
+               pMultipart = NULL;
+       }
+
+       return false;
+}
+
+static bool __MmsBinaryDecodeEachPart(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, int totalLength)
+{
+       int     length = 0;
+       bool bSuccess = false;
+       UINT32 headerLength = 0;
+       UINT32 bodyLength = 0;
+       int offset = 0;
+
+       MSG_DEBUG("MmsBinaryDecodeEachPart: total length=%d\n", totalLength);
+
+       /* header length */
+
+       if (__MmsBinaryDecodeUintvar(pFile, &headerLength, totalLength) <= 0) {
+               MSG_DEBUG("MmsBinaryDecodeEachPart: Get header length fail \n");
+               goto __CATCH;
+       }
+
+       offset = __MmsGetDecodeOffset();
+       if (offset >= totalLength)
+               goto __RETURN;
+
+
+       /* body length */
+
+       if (__MmsBinaryDecodeUintvar(pFile, &bodyLength, totalLength) <= 0) {
+               MSG_DEBUG("MmsBinaryDecodeEachPart: Get body length fail\n");
+               goto __CATCH;
+       }
+
+
+       offset = __MmsGetDecodeOffset();
+       if (offset >= totalLength)
+               goto __RETURN;
+
+
+       /* Content Type */
+       if (szFilePath != NULL)
+               strncpy(pMsgType->szOrgFilePath, szFilePath, strlen(szFilePath));
+
+       pMsgType->offset = __MmsGetDecodeOffset();
+       pMsgType->size = headerLength;
+       pMsgType->contentSize = bodyLength;
+
+       if (pMsgType->offset > totalLength)
+               goto __RETURN;
+
+       length = __MmsBinaryDecodeContentType(pFile, pMsgType, totalLength);
+       if (length <= 0) {
+               MSG_DEBUG("MmsBinaryDecodeEachPart: Decode contentType Fail \n");
+               goto __CATCH;
+       }
+
+       offset = __MmsGetDecodeOffset();
+       if (offset >= totalLength)
+               goto __RETURN;
+
+
+       /* Part Header */
+
+       if (__MmsBinaryDecodePartHeader(pFile, pMsgType, headerLength - length, totalLength) == false) {
+               MSG_DEBUG("MmsBinaryDecodeEachPart: Decode contentHeader Fail \n");
+               goto __CATCH;
+       }
+
+       offset = __MmsGetDecodeOffset();
+       if (offset >= totalLength)
+               goto __RETURN;
+
+       /* Part Body */
+
+       if (szFilePath != NULL)
+               strncpy(pMsgBody->szOrgFilePath, szFilePath, strlen(szFilePath));
+
+       pMsgBody->offset = __MmsGetDecodeOffset();
+       pMsgBody->size   = bodyLength;
+
+       if (pMsgBody->offset > totalLength)
+               goto __RETURN;
+
+       switch (pMsgType->type) {
+       case MIME_APPLICATION_VND_WAP_MULTIPART_MIXED:
+       case MIME_APPLICATION_VND_WAP_MULTIPART_RELATED:
+       case MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC:
+       case MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE:
+       case MIME_MULTIPART_REPORT:
+       case MIME_MULTIPART_MIXED:
+       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");
+                       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();
+               if (offset >= totalLength)
+                       goto __RETURN;
+
+               break;
+#endif
+
+       default:
+               MSG_DEBUG("MmsBinaryDecodeEachPart: Other normal Part \n");
+
+               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;
+       }
+
+       return true;
+
+__RETURN:
+
+       return true;
+
+__CATCH:
+
+       return false;
+}
+
+#ifdef __SUPPORT_DRM__
+static bool __MmsBinaryDecodeDRMContent(FILE *pFile, char *szFilePath, MsgType *pMsgType, MsgBody *pMsgBody, unsigned int bodyLength, 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();
+
+       if (offset >= totalLength)
+               goto __RETURN;
+
+       if (szFilePath != NULL)
+               strncpy(pMsgBody->szOrgFilePath, szFilePath, strlen(szFilePath));
+       if (szFilePath != NULL)
+               strncpy(pMsgType->szOrgFilePath, szFilePath, strlen(szFilePath));
+
+       pRawData = (char *)malloc(bodyLength);
+       if (pRawData == NULL) {
+               MSG_DEBUG("pRawData alloc FAIL \n");
+               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;
+       }
+
+       isFileCreated = true;
+       MSG_DEBUG("MmsDrm2GetConvertState() [%d]", MmsDrm2GetConvertState());
+
+       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");
+                       goto __CATCH;
+               }
+       }
+
+       if(remove(szTempFilePath) != 0)
+               MSG_DEBUG("remove fail");
+       isFileCreated = false;
+
+       if (__MmsBinaryDecodeMovePointer(pFile, offset + bodyLength, totalLength) == false)
+               goto __CATCH;
+
+__RETURN:
+
+       if (pRawData) {
+               free(pRawData);
+               pRawData = NULL;
+       }
+
+       return true;
+
+__CATCH:
+       if (isFileCreated)
+               if(remove(szTempFilePath) != 0)
+                       MSG_DEBUG("remove fail");
+
+       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;
+                       }
+               }
+       }
+
+       return length;
+}
+
+static bool __MmsDrm2BinaryEncodeUintvar(UINT32 integer, int length, char *pszOutput)
+{
+       const char ZERO = 0x00;
+       int i = 2;
+       char szReverse[MSG_STDSTR_LONG] = {0, };
+
+       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];
+
+       return true;
+}
+
+static int __MmsDrm2GetEntriesValueLength(FILE *pFile, int orgOffset)
+{
+       char szEntries[5] = {0, };
+       UINT8 oneByte   = 0;
+       int j = 0;                      //j is the length of nEntries value
+
+       if (MsgReadFile(szEntries, sizeof(char), 4, pFile) != (size_t)4) {
+               MSG_DEBUG("__MmsDrm2GetEntriesValueLength: FmReadFile() returns false \n");
+               return false;
+       }
+
+       while (true) {
+               oneByte = szEntries[j++];
+
+               if (oneByte <= 0x7f)
+                       break;
+       }
+
+       //move file pointer to point nEntries
+       if (MsgFseek(pFile, orgOffset, SEEK_SET) < 0) {
+               MSG_DEBUG("__MmsDrm2GetEntriesValueLength: fail to seek file pointer\n");
+               return false;
+       }
+
+       return j;
+}
+
+static bool __MmsDrm2WriteDataToConvertedFile(FILE *pSrcFile, FILE *pDestinationFile, char *pszMmsLoadTempBuf, int length, int bufLen)
+{
+       int loadLen = 0, totalLoadLen = 0, nRead = 0;
+
+       for (int i=0; i<(length/bufLen)+1; i++) {
+               loadLen = (length-totalLoadLen < bufLen) ? length-totalLoadLen : bufLen;
+
+               memset(pszMmsLoadTempBuf, 0, MMS_DRM2_CONVERT_BUFFER_MAX + 1);
+
+               if (MsgReadFile(pszMmsLoadTempBuf, sizeof(char), loadLen, pSrcFile) != (size_t)loadLen) {
+                       MSG_DEBUG("__MmsDrm2WriteDataToConvertedFile: FmReadFile() returns false \n");
+                       return false;
+               }
+
+               if (MsgWriteFile(pszMmsLoadTempBuf, sizeof(char), loadLen, pDestinationFile) != (size_t)loadLen) {
+                       MSG_DEBUG("__MmsDrm2WriteDataToConvertedFile: File Writing is failed.\n");
+                       return false;
+               }
+
+               totalLoadLen += nRead;
+       }
+
+       return true;
+}
+
+/*************************************************************************
+ * 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)
+{
+       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;
+
+       MSG_DEBUG("start convert~~~~~~\n");
+
+       pFile = MsgOpenFile(szOriginFilePath, "rb");
+       if (pFile == NULL) {
+               MSG_DEBUG("Open decode temporary file fail\n");
+               goto __CATCH;
+       }
+
+       hConvertedFile = MsgOpenFile(MMS_DECODE_DRM_CONVERTED_TEMP_FILE, "wb+");
+       if (hConvertedFile == NULL) {
+               MSG_DEBUG("Open decode temporary file fail\n");
+               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);
+
+       // MMS Header  copy
+       length = mmsHeader.msgBody.offset;
+       if (__MmsDrm2WriteDataToConvertedFile(pFile, hConvertedFile, pszMmsLoadTempBuf, length, bufLen) == false) {
+               MSG_DEBUG("Write header data fail\n");
+               goto __CATCH;
+       }
+
+       curOffset += length;    //change offset
+
+       // MMS Body copy
+       if (MsgIsMultipart(mmsHeader.msgType.type) == true)
+       {
+               // nEntries copy
+               length = __MmsDrm2GetEntriesValueLength(pFile, curOffset);      // getting nEntries value's length
+
+               if (__MmsDrm2WriteDataToConvertedFile(pFile, hConvertedFile, pszMmsLoadTempBuf, length, bufLen) == false) {
+                       MSG_DEBUG("Write nEntries fail\n");
+                       goto __CATCH;
+               }
+
+               curOffset += length;    //change offset
+
+               // each Multipart entry copy
+               pMultipart = mmsHeader.msgBody.body.pMultipart;
+
+               while (pMultipart) {
+                       if (pMultipart->type.type == MIME_APPLICATION_VND_OMA_DRM_MESSAGE) {
+                               int orgDataLen = pMultipart->pBody->size;
+                               int nSize = 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);
+
+                               // 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 (MsgReadFile(pszOrgData, sizeof(char), orgDataLen, pFile) != (size_t)orgDataLen) {
+                                       MSG_DEBUG("FmReadFile() returns false for orgData\n");
+                                       goto __CATCH;
+                               }
+
+                               if((hFile = MsgOpenFile(szTempFile, "wb+")) == NULL) {
+                                       MSG_DEBUG("file open failed [%s]", szTempFile);
+                                       goto __CATCH;
+                               }
+
+                               if (MsgWriteFile(pszOrgData, sizeof(char), orgDataLen, hFile) != (size_t)orgDataLen) {
+                                       MSG_DEBUG("File write error");
+                                       goto __CATCH;
+                               }
+
+                               if (pszOrgData) {
+                                       free(pszOrgData);
+                                       pszOrgData = NULL;
+                               }
+
+                               MsgFflush(hFile);
+                               MsgCloseFile(hFile);
+
+                               hFile = NULL;
+
+                               // --> invoking drm agent api, converting data part start
+                               MSG_DEBUG("start data part convert by callling drm agent api\n");
+
+                               int ret = 0;
+                               ret = MsgDrmConvertDmtoDcfType(szTempFile, szTempFilePath);
+                               MSG_DEBUG("MsgDrmConvertDmtoDcfType returned %s", ret ? "true": "false");
+
+                               if (MsgGetFileSize(szTempFilePath, &nSize) == false) {
+                                       MSG_DEBUG("MsgGetFileSize error");
+                                       goto __CATCH;
+                               }
+                               MSG_DEBUG("end data part convert(converted data len = %d)\n", nSize);
+
+                               // 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;
+                               }
+
+                               // 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;
+                               }
+
+                               curOffset += length;
+
+                               // change dataLen based on converted data
+                               {
+                                       UINT8   oneByte = 0;
+                                       int             j = 0;
+                                       int             encodeLen = 0;
+                                       char    szOutput[MSG_STDSTR_LONG] = {0, };
+
+                                       while (true) {
+                                               oneByte = pszMmsLoadTempBuf[j++];
+
+                                               if (oneByte <= 0x7f)
+                                                       break;
+                                       }
+
+                                       encodeLen = __MmsDrm2BinaryEncodeUintvarLen((UINT32)nSize);
+                                       __MmsDrm2BinaryEncodeUintvar((UINT32)nSize, encodeLen, szOutput);
+
+                                       strncpy(&(pszMmsLoadTempBuf[j]), szOutput, encodeLen);
+                                       pszMmsLoadTempBuf[j+encodeLen] = '\0';
+
+                                       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;
+                               }
+
+                               curOffset += length;
+
+                               // write converted data
+                               hTempFile = MsgOpenFile(szTempFilePath, "rb");
+                               if (hTempFile == NULL) {
+                                       MSG_DEBUG("Open decode temporary file fail\n");
+                                       goto __CATCH;
+                               }
+
+                               length = nSize;
+
+                               if (__MmsDrm2WriteDataToConvertedFile(hTempFile, hConvertedFile, pszMmsLoadTempBuf, length, bufLen) == false) {
+                                       MSG_DEBUG("Write converted data fail\n");
+                                       goto __CATCH;
+                               }
+
+                               if (hTempFile != NULL) {
+                                       MsgCloseFile(hTempFile);
+                                       hTempFile = NULL;
+                               }
+
+                               curOffset += pMultipart->pBody->size;
+
+                               // 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");
+
+                               length = pMultipart->pBody->offset + pMultipart->pBody->size - curOffset;
+
+                               if (__MmsDrm2WriteDataToConvertedFile(pFile, hConvertedFile, pszMmsLoadTempBuf, length, bufLen) == false) {
+                                       MSG_DEBUG("Write multipart data fail \n");
+                                       goto __CATCH;
+                               }
+
+                               curOffset += length;
+                       }
+
+                       pMultipart = pMultipart->pNext;
+               }
+       }
+
+       MSG_DEBUG("end convert~~~~~~\n");
+
+       if (pFile != NULL) {
+               MsgCloseFile(pFile);
+               pFile = NULL;
+       }
+
+       if (hConvertedFile != NULL) {
+               MsgCloseFile(hConvertedFile);
+               hConvertedFile = NULL;
+       }
+
+       if (pszMmsLoadTempBuf) {
+               free(pszMmsLoadTempBuf);
+               pszMmsLoadTempBuf = NULL;
+       }
+
+       if(remove(szTempFile) != 0)
+               MSG_DEBUG("remove fail");
+       if(remove(szTempFilePath) != 0)
+               MSG_DEBUG("remove fail");
+
+       return true;
+
+__CATCH:
+
+       if (pFile != NULL) {
+               MsgCloseFile(pFile);
+               pFile = NULL;
+       }
+
+       if (hConvertedFile != NULL) {
+               MsgCloseFile(hConvertedFile);
+               hConvertedFile = NULL;
+       }
+
+       if (hTempFile != NULL) {
+               MsgCloseFile(hTempFile);
+               hTempFile = NULL;
+       }
+
+       if (pszMmsLoadTempBuf) {
+               free(pszMmsLoadTempBuf);
+               pszMmsLoadTempBuf = NULL;
+       }
+
+       if (pszOrgData) {
+               free(pszOrgData);
+               pszOrgData = NULL;
+       }
+
+       if (hFile != NULL)
+       {
+               MsgCloseFile(hFile);
+               hFile = NULL;
+       }
+
+       if (remove(szTempFile) != 0)
+               MSG_DEBUG("remove fail");
+
+       if (remove(szTempFilePath) != 0)
+               MSG_DEBUG("remove fail");
+
+       if (remove(MMS_DECODE_DRM_CONVERTED_TEMP_FILE) != 0)
+               MSG_DEBUG("remove fail");       //remove convertin result if it goes to __CATCH
+
+       return false;
+}
+
+/*************************************************************************
+ * description : Function for decoding a converted file
+ * argument : void
+ * return value
+    - bool :  result of converting
+**************************************************************************/
+
+bool MmsDrm2ReadMsgConvertedBody(MSG_MESSAGE_INFO_S *pMsg, bool bSavePartsAsTempFiles, bool bRetrieved, char *retrievedPath)
+{
+       MmsMsg *pMmsMsg;
+       MmsPluginStorage::instance()->getMmsMessage(&pMmsMsg);
+       MmsUnregisterDecodeBuffer();
+#ifdef __SUPPORT_DRM__
+       MmsReleaseMsgDRMInfo(&pMmsMsg->msgType.drmInfo);
+#endif
+       MmsReleaseMsgBody(&pMmsMsg->msgBody, pMmsMsg->msgType.type);
+
+       if (MmsReadMsgBody(pMsg->msgId, bSavePartsAsTempFiles, bRetrieved, retrievedPath) == false) {
+               MSG_DEBUG("MmsDrm2ReadMsgConvertedBody: _MmsReadMsgBody with converted file is failed\n");
+               return false;
+       }
+
+       return true;
+}
+
+#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)
+{
+       int length = gMmsDecodeMaxLen - gCurMmsDecodeBuffPos;
+
+       if (pFile == NULL || pOneByte == NULL)
+       {
+               MSG_DEBUG("_MmsBinaryDecodeGetOneByte: invalid file or buffer\n");
+               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;
+               }
+       }
+
+       *pOneByte = gpCurMmsDecodeBuff[gCurMmsDecodeBuffPos++];
+
+       return true;
+
+__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");
+                       goto __CATCH;
+               }
+       }
+
+       for (i = 0; i < bufLen - 1; i++)
+               szBuff[i] = gpCurMmsDecodeBuff[gCurMmsDecodeBuffPos++];
+
+
+       gCurMmsDecodeBuffPos++; //NULL
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+bool __MmsBinaryDecodeGetLongBytes(FILE *pFile, char *szBuff, int bufLen, int totalLength)
+{
+       int iPos = 0;
+
+       if (pFile == NULL || szBuff == NULL || bufLen == 0)
+               goto __CATCH;
+
+       memset(szBuff, 0, bufLen);
+
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                  gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+               MSG_DEBUG("_MmsBinaryDecodeGetLongBytes: fail to load to buffer \n");
+               goto __CATCH;
+       }
+
+       while ((bufLen - iPos) >= gMmsDecodeMaxLen) {
+               if (__MmsBinaryDecodeGetBytes(pFile, szBuff + iPos, gMmsDecodeMaxLen, totalLength) == false) {
+                       MSG_DEBUG("_MmsBinaryDecodeGetLongBytes: 1. _MmsBinaryDecodeGetBytes fail \n");
+                       goto __CATCH;
+               }
+
+               iPos += gMmsDecodeMaxLen;
+       }
+
+       if ((bufLen - iPos) > 0) {
+               if (__MmsBinaryDecodeGetBytes(pFile, szBuff + iPos, (bufLen - iPos), totalLength) == false) {
+                       MSG_DEBUG("_MmsBinaryDecodeGetLongBytes: 2. _MmsBinaryDecodeGetBytes fail \n");
+                       goto __CATCH;
+               }
+
+               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");
+                       goto __CATCH;
+               }
+       }
+
+       while (true) {
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false)
+                       goto __CATCH;
+
+               if (oneByte > 0x7f)     {
+                       iBuff[count++] = oneByte;
+               } else {
+                       iBuff[count++] = oneByte;
+                       break;
+               }
+
+               if (count > 4) {
+                       MSG_DEBUG("__MmsBinaryDecodeUintvar : legnth is too long\n");
+                       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;
+
+       if (length == 1)
+       {
+               if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+                       MSG_DEBUG("__MmsHeaderDecodeIntegerByLength: _MmsBinaryDecodeGetOneByte fail\n");
+                       return oneByte;
+               }
+
+               if (oneByte > 0x7f) {
+                       return (oneByte & 0x7f);
+               } else {
+                       return oneByte;
+               }
+       }
+
+       if (length == 0)
+               return 0;
+
+       pData = (char *)malloc(length + 1);
+       if (pData == NULL) {
+               MSG_DEBUG("__MmsHeaderDecodeIntegerByLength: pData alloc fail\n");
+               goto __CATCH;
+       }
+       memset(pData, 0, length + 1);
+
+       if (__MmsBinaryDecodeGetBytes(pFile, pData, length + 1, totalLength) == false) {
+               MSG_DEBUG("__MmsHeaderDecodeIntegerByLength: _MmsBinaryDecodeGetOneByte fail\n");
+               goto __CATCH;
+       }
+
+       gCurMmsDecodeBuffPos--; // - NULL
+
+       for (i= 0; i < length; i++)
+               returner.seg[length - (i+1)] = pData[i];
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       return returner.integer;
+
+__CATCH:
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       return returner.integer;
+}
+
+/**
+ * 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)
+{
+       UINT8 oneByte   = 0;
+       char *pData     = NULL;
+       union {
+               UINT32  integer;
+               UINT8   seg[4];
+       } returner;
+
+
+       if (pInteger == NULL)
+               return false;
+
+       returner.integer = 0;
+       *pIntLen                 = 0;
+
+       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+               MSG_DEBUG("__MmsBinaryDecodeInteger: GetOneByte fail\n");
+               return false;
+       }
+
+       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");
+                       goto __CATCH;
+               }
+               memset(pData, 0, oneByte + 1);
+
+               // Even NULL is copied in the _MmsBinaryDecodeGetBytes
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, oneByte + 1, totalLength) == false) {
+                       MSG_DEBUG("__MmsBinaryDecodeInteger: GetBytes fail\n");
+                       goto __CATCH;
+               }
+
+               gCurMmsDecodeBuffPos--; // - NULL
+
+               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];
+
+               *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;
+       }
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       return true;
+
+__CATCH:
+
+       gCurMmsDecodeBuffPos--;
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       return false;
+}
+
+/**
+ * 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)
+{
+       int length = 0;
+       UINT32 uintvar = 0;
+       UINT8 oneByte = 0;
+
+
+       /*
+        * value-length = short-length | (Length-quote Length)
+        *                              = 0~30             | 31 + Uintvar-length
+        */
+
+       if (pFile == NULL || pValueLength == NULL)
+               goto __CATCH;
+
+       *pValueLength = 0;
+
+       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+               gCurMmsDecodeBuffPos--;
+               goto __CATCH;
+       }
+
+       if (0x00 < oneByte && oneByte < 0x1F) {
+               /* short-length */
+
+               *pValueLength = oneByte;
+               length = 1;
+       } else if (oneByte == 0x1F) {
+               /* Length-quote = 0x1F */
+
+               length = __MmsBinaryDecodeUintvar(pFile, &uintvar, totalLength);
+               if (length == -1) {
+                       MSG_DEBUG("__MmsDecodeValueLength: __MmsBinaryDecodeUintvar fail..\n");
+                       goto __CATCH;
+               }
+               length ++;                                      // + length-quote
+               *pValueLength = uintvar;
+       } else {
+               MSG_DEBUG("__MmsDecodeValueLength: not a value length type data\n");
+               gCurMmsDecodeBuffPos--;
+               return 0;
+       }
+
+       return length;
+
+__CATCH:
+       MSG_DEBUG("__MmsDecodeValueLength: getting data fail\n");
+       return -1;
+}
+
+/**
+ * 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;
+
+
+       /*
+        * value-length = short-length | (Length-quote Length)
+        *                              = 0~30             | 31 + Uintvar-length
+        */
+
+       if (pFile == NULL || pValueLength == NULL)
+               goto __CATCH;
+
+       *pValueLength = 0;
+
+       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false) {
+               gCurMmsDecodeBuffPos--;
+               goto __CATCH;
+       }
+
+       if (0x00 < oneByte && oneByte < 0x1F) {
+               /* short-length */
+
+               *pValueLength = oneByte;
+               length = 1;
+       } else if (oneByte == 0x1F) {
+               /* Length-quote = 0x1F */
+
+               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;
+
+__CATCH:
+       MSG_DEBUG("__MmsDecodeValueLength2: getting data fail\n");
+       return -1;
+}
+
+/**
+ * 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;
+
+       /*
+        * 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);
+
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                        gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+               MSG_DEBUG("__MmsBinaryDecodeQuotedString: 1. fail to load to buffer \n");
+               goto __CATCH;
+       }
+
+       length = strlen(gpCurMmsDecodeBuff) + 1;        // + NULL
+
+       if (length == 0)
+               goto __RETURN;
+
+       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;
+               }
+
+               pData = (char *)malloc(gMmsDecodeBufLen + 1);
+               if (pData == NULL)
+                       goto __CATCH;
+
+               memset(pData, 0, gMmsDecodeBufLen + 1);
+
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, gMmsDecodeBufLen, totalLength) == false)
+                       goto __CATCH;
+
+               returnLength += gMmsDecodeBufLen;
+
+               if ((bufLen - iPos) > 0) {
+                       readBytes = (gMmsDecodeBufLen < (bufLen - iPos)) ? gMmsDecodeBufLen : (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);
+                               iPos += readBytes;
+                       }
+               }
+
+               if (pData) {
+                       free(pData);
+                       pData = NULL;
+               }
+
+               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;
+
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, length, totalLength) == false)
+                       goto __CATCH;
+
+               returnLength += 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;
+                       }
+               }
+
+               if (pData) {
+                       free(pData);
+                       pData = NULL;
+               }
+       }
+
+       szBuff[bufLen - 1] = '\0';
+
+       return returnLength;
+
+__RETURN:
+
+       return length;
+
+__CATCH:
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       return -1;
+}
+
+/**
+ * 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;
+
+       /*
+        * Text-String = [QUOTE]*TEXT end_of_string
+        *                               [QUOTE]*(128~255)\0
+        *                               *(32~126)\0
+        */
+
+       if (pFile == NULL || szBuff == NULL || bufLen <= 0)
+               return -1;
+
+       offset = __MmsGetDecodeOffset();
+       if (offset >= totalLength)
+               goto __RETURN;
+
+       memset(szBuff, 0, bufLen);
+
+       if (__MsgLoadDataToDecodeBuffer(pFile, &gpCurMmsDecodeBuff, &gCurMmsDecodeBuffPos, &gMmsDecodeCurOffset,
+                                                                       gpMmsDecodeBuf1, gpMmsDecodeBuf2, gMmsDecodeMaxLen, &gMmsDecodeBufLen, totalLength) == false) {
+               MSG_DEBUG("__MmsBinaryDecodeText: 1. fail to load to buffer \n");
+               goto __CATCH;
+       }
+
+       length = strlen(gpCurMmsDecodeBuff) + 1;        // + NULL
+
+       if (length == 0)
+               goto __RETURN;
+
+       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;
+               }
+
+               pData = (char *)malloc(gMmsDecodeBufLen + 1);
+               if (pData == NULL)
+                       goto __CATCH;
+
+               memset(pData, 0, gMmsDecodeBufLen + 1);
+
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, gMmsDecodeBufLen, totalLength) == false)
+                       goto __CATCH;
+
+               if ((bufLen - iPos) > 0) {
+                       readBytes = (gMmsDecodeBufLen < (bufLen - iPos)) ? gMmsDecodeBufLen : (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);
+                               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 */
+
+                               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 (pData) {
+                       free(pData);
+                       pData = NULL;
+               }
+
+               returnLength += length;         // + NULL
+       }
+
+       szBuff[bufLen - 1] = '\0';
+
+       return returnLength;
+
+__RETURN:
+
+       szBuff[0] = '\0';
+       length = 0;
+
+       __MmsBinaryDecodeMovePointer(pFile, offset, totalLength);
+
+       return length;
+
+__CATCH:
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       return -1;
+}
+
+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;
+
+       *pLength = 0;
+       offset = __MmsGetDecodeOffset();
+       if (offset >= totalLength)
+               goto __RETURN;
+
+       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;
+
+       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;
+               }
+
+               pData = (char *)malloc(gMmsDecodeBufLen + 1);
+               if (pData == NULL)
+                       goto __CATCH;
+
+               memset(pData, 0, gMmsDecodeBufLen + 1);
+
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, gMmsDecodeBufLen, totalLength) == false)
+                       goto __CATCH;
+
+               if (szBuff == NULL)     {
+                       szBuff = (char *)malloc(gMmsDecodeBufLen + 1);
+               } else {
+                       szTempPtr = (char *)realloc(szBuff, curLen + gMmsDecodeBufLen + 1);
+
+                       //NULL pointer check for realloc
+                       if (szTempPtr == NULL) {
+                               goto __CATCH;
+                       } else {
+                               szBuff = szTempPtr;
+                       }
+               }
+               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 (pData) {
+                       free(pData);
+                       pData = NULL;
+               }
+
+               *pLength += 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;
+       }       /* while */
+
+       if (length > 0) {
+               pData = (char *)malloc(length);
+               if (pData == NULL) {
+                       goto __CATCH;
+               }
+
+               if (__MmsBinaryDecodeGetBytes(pFile, pData, length, totalLength) == false) {
+                       goto __CATCH;
+               }
+
+               if (szBuff == NULL) {
+                       szBuff = (char *)malloc(length);
+               } else {
+                       szTempPtr = (char *)realloc(szBuff, curLen + length);
+
+                       //NULL pointer check for realloc
+                       if (szTempPtr == NULL)
+                               goto __CATCH;
+                       else
+                               szBuff = szTempPtr;
+               }
+
+               if (szBuff == NULL) {
+                       goto __CATCH;
+               }
+
+               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;
+               }
+
+               if (pData) {
+                       free(pData);
+                       pData = NULL;
+               }
+
+               *pLength += length;             // + NULL
+       }
+
+       return szBuff;
+
+__RETURN:
+
+       *pLength = 1;
+
+       __MmsBinaryDecodeMovePointer(pFile, offset, totalLength);
+
+       return szBuff;
+
+__CATCH:
+
+       if (szBuff) {
+               free(szBuff);
+               szBuff = NULL;
+       }
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       return NULL;
+}
+
+/**
+ * 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)
+{
+       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 (pFile == NULL || nCharSet == NULL || pCharSetLen == NULL)
+               return false;
+
+       if (__MmsBinaryDecodeInteger(pFile, &integer, pCharSetLen, totalLength) == false) {
+               MSG_DEBUG("__MmsBinaryDecodeCharset : __MmsBinaryDecodeInteger fail...\n");
+               goto __CATCH;
+       }
+
+       if (integer == 0) {
+               /* AnyCharSet : return MSG_CHARSET_UTF8 */
+               *nCharSet = MSG_CHARSET_UTF8;
+               return true;
+       }
+
+       *nCharSet = MmsGetBinaryType(MmsCodeCharSet, (UINT16)integer);
+
+       if (*nCharSet == MIME_UNKNOWN) {
+               MSG_DEBUG("__MmsBinaryDecodeCharset : MmsGetBinaryType fail..\n");
+               *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("__MmsBinaryDecodeEncodedString: decode string..\n");
+
+       if (pFile == NULL || szBuff == NULL || bufLen <= 0) {
+               MSG_DEBUG("__MmsBinaryDecodeEncodedString: invalid file or buffer\n");
+               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("__MmsBinaryDecodeEncodedString : 1. __MmsBinaryDecodeText fail.\n");
+                       goto __CATCH;
+               }
+               break;
+
+       default:
+
+               /* Value-length Charset Text_string */
+
+               if (__MmsBinaryDecodeCharset(pFile, &charSet, &charSetLen, totalLength) == false) {
+                       MSG_DEBUG("__MmsBinaryDecodeEncodedString : __MmsBinaryDecodeCharset error\n");
+                       goto __CATCH;                   /* (valueLength + valueLengthLen) */
+               }
+
+               nTemp = __MmsBinaryDecodeText(pFile, szBuff, bufLen, totalLength);
+               if (nTemp < 0) {
+                       /* There can be some error in data - no NULL -> try again with value length */
+
+                       pData = (char *)malloc(valueLength - charSetLen);
+                       if (pData == NULL) {
+                               MSG_DEBUG("__MmsBinaryDecodeEncodedString : pData alloc fail.\n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryDecodeGetLongBytes(pFile, pData, valueLength - charSetLen, totalLength) == false) {
+                               MSG_DEBUG("__MmsBinaryDecodeEncodedString : _MmsBinaryDecodeGetLongBytes fail.\n");
+                               goto __CATCH;
+                       }
+
+                       strncpy(szBuff, pData, bufLen - 1);
+               }
+
+               {//temp brace
+
+                       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, "%s", pDest);
+                       }
+               }
+       }
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       return true;
+
+__CATCH:
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       return false;
+}
+
+
+
+/**
+ * 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)
+{
+       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;
+       }
+
+       /*
+        * 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;
+
+       case 0:
+
+               /* Text-string = [Quote]*TEXT End-of-string */
+
+               textLength = 0;
+               pAddrStr   = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+               if (pAddrStr == NULL) {
+                       MSG_DEBUG("__MmsDecodeEncodedAddress : 1. __MmsBinaryDecodeText2 fail.\n");
+                       goto __CATCH;
+               }
+               break;
+
+       default:
+
+               /* Value-length Charset Text_string */
+
+               if (__MmsBinaryDecodeCharset(pFile, &charSet, &charSetLen, totalLength) == false) {
+                       MSG_DEBUG("__MmsDecodeEncodedAddress : __MmsBinaryDecodeCharset error\n");
+                       goto __CATCH;
+               }
+
+               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;
+                       }
+               }
+
+               /* fixme: charset transformation */
+
+               break;
+       }
+
+       pAddr = (MsgHeaderAddress *)malloc(sizeof(MsgHeaderAddress));
+       if (pAddr == NULL)
+               goto __CATCH;
+
+       memset(pAddr, 0, sizeof(MsgHeaderAddress));
+       pAddr->szAddr = pAddrStr;
+
+       return pAddr;
+
+__CATCH:
+
+       if (pAddrStr) {
+               free(pAddrStr);
+               pAddrStr = 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)
+{
+       UINT8 oneByte = 0;
+
+       /*
+        * Long-integer = Short-length Multi-octet-integer
+        *                                Short-length = 0~30
+        *                                Multi-octet-integer
+        */
+
+       if (pFile == NULL || pLongInteger == NULL)
+               return false;
+
+       *pLongInteger = 0;
+
+       if (__MmsBinaryDecodeGetOneByte(pFile, &oneByte, totalLength) == false)
+               goto __CATCH;
+
+       if (oneByte > 31)
+               goto __CATCH;
+
+       *pLongInteger = __MmsHeaderDecodeIntegerByLength(pFile, oneByte, totalLength);
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+
+/*
+ * @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)
+{
+       char *pUTF8Buff = NULL;
+       char *pLatinBuff = NULL;
+       char *pExt = NULL;
+       char *szSrc = NULL;
+       char *szSrc2 = NULL;
+       int length = 0;
+       int textLength = 0;
+
+       char *pTmpBuff = NULL;
+
+       memset (szBuff, 0, bufLen);
+
+       textLength = 0;
+       pLatinBuff  = __MmsBinaryDecodeText2(pFile, totalLength, &textLength);
+
+       //remove ""
+       if (pLatinBuff) {
+               szSrc = MsgRemoveQuoteFromFilename(pLatinBuff);
+               if (szSrc) {
+                       strcpy(pLatinBuff, szSrc);
+                       free(szSrc);
+                       szSrc = NULL;
+               }
+
+               szSrc2 = MsgChangeHexString(pLatinBuff);
+               if (szSrc2) {
+                       strcpy(pLatinBuff, szSrc2);
+                       free(szSrc2);
+                       szSrc2 = NULL;
+               }
+
+               if (__MsgIsUTF8String((unsigned char*)pLatinBuff, strlen(pLatinBuff)) == false) {
+                       length = strlen(pLatinBuff);
+
+                       int             utf8BufSize = 0;
+                       utf8BufSize = __MsgGetLatin2UTFCodeSize((unsigned char*)pLatinBuff, length);
+                       if (utf8BufSize < 3)
+                               utf8BufSize = 3;//min value
+
+                       pUTF8Buff = (char *)malloc(utf8BufSize + 1);
+                       if (pUTF8Buff == NULL) {
+                               MSG_DEBUG("__MmsDecodeGetFilename: pUTF8Buff alloc fail \n");
+                               goto __CATCH;
+                       }
+
+                       if (__MsgLatin2UTF ((unsigned char*)pUTF8Buff, utf8BufSize + 1, (unsigned char*)pLatinBuff, length) < 0) {
+                               MSG_DEBUG("__MmsDecodeGetFilename: MsgLatin2UTF fail \n");
+                               goto __CATCH;
+                       }
+                       free(pLatinBuff);
+                       pLatinBuff = NULL;
+               } else {
+                       pTmpBuff = MsgDecodeText(pLatinBuff);
+                       pUTF8Buff = pTmpBuff;
+                       free (pLatinBuff);
+                       pLatinBuff = NULL;
+               }
+       }
+
+       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);
+               } else {
+                       strncpy(szBuff, pUTF8Buff, bufLen - 1);
+               }
+               free(pUTF8Buff);
+               pUTF8Buff = NULL;
+
+               return textLength;
+       }
+
+__CATCH:
+
+       if (pLatinBuff) {
+               free(pLatinBuff);
+               pLatinBuff = NULL;
+       }
+
+       if (pUTF8Buff) {
+               free(pUTF8Buff);
+               pUTF8Buff = NULL;
+       }
+
+       return -1;
+}
+
+/* ==========================================================
+
+          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 (bRetrieved && (retrievedPath != NULL)) {
+               strncpy(szFullPath, retrievedPath, (strlen(retrievedPath) > MSG_FILEPATH_LEN_MAX ? MSG_FILEPATH_LEN_MAX:strlen(retrievedPath)));
+       } else {
+               MmsPluginStorage::instance()->getMmsRawFilePath(msgID, szFullPath);
+       }
+
+       pMsg->msgID = msgID;
+
+       /*      read from MMS raw file  */
+       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();
+
+       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;
+       }
+#endif
+
+       /* Set mmsHeader.msgType & msgBody to pMsg ----------- */
+
+       pMsg->mmsAttrib.contentType = (MimeType)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;
+
+       }
+
+       MsgCloseFile(pFile);
+       pFile = NULL;
+
+       /* nPartCount */
+       pMsg->nPartCount = 0;
+
+       if (MsgIsMultipart(mmsHeader.msgType.type) == true) {
+               pMultipart = pMsg->msgBody.body.pMultipart;
+               while (pMultipart) {
+                       pMsg->nPartCount++;
+
+                       if (pMultipart->type.type == MIME_TEXT_PLAIN)
+                               attachmax++;
+
+                       if ((mmsHeader.msgType.type == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED)||(mmsHeader.msgType.type == MIME_MULTIPART_MIXED)) {
+                               if ((pMsg->nPartCount >= attachmax)&&(pMultipart->pNext != NULL)) {
+                                       MmsReleaseMsgBody(pMultipart->pNext->pBody, pMultipart->pNext->type.type);
+
+                                       free(pMultipart->pNext->pBody);
+                                       pMultipart->pNext->pBody= NULL;
+
+                                       free(pMultipart->pNext);
+
+                                       pMultipart->pNext = NULL;
+                                       break;
+                               }
+                       }
+                       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);
+
+       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__
+       MmsReleaseMsgDRMInfo(&pMsg->msgType.drmInfo);
+#endif
+
+       MmsReleaseMsgBody(&pMsg->msgBody, pMsg->msgType.type);
+       MSG_DEBUG("_MmsReadMsgBody:    E  N  D    (fail)    ******************** \n");
+
+       return false;
+}
+
+static 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;
+}
+
+static 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;
+}
+
+static 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;
+}
+
+static 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;
+}
+
+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;
+               }
+
+               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_LOCALE_FILENAME_LEN_MAX-1) < strlen(pUTF8Buff)) {
+                                                       nameLen = (MSG_LOCALE_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_LOCALE_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;
+}
+
+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;
+               }
+       }
+}
+
+static 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;
+}
+
+static 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);
+               if (utf8BufSize < 3)
+                       utf8BufSize = 3; //min value
+
+               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;
+       }
+
+       return NULL;
+}
+
+static 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;
+}
+
+static 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';
+       }
+}
+
+static 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;
+}
+
+static bool __MsgIsPercentSign(char *pSrc)
+{
+       char *pCh = NULL;
+       bool bRet = false;
+
+       pCh = strchr(pSrc , '%');
+
+       if (pCh != NULL) {
+               bRet = true;
+       } else {
+               bRet = false;
+       }
+
+       return bRet;
+}
+
+static 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;
+       }
+
+       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;
+}
+
+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;
+
+       // 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;
+               }
+       }
+}
+
+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;
+               }
+
+               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__
+                                       MmsReleaseMsgDRMInfo(&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) {
+                                       MmsReleaseMsgBody(pRemovePart->pBody, pRemovePart->type.type);
+                                       free(pRemovePart->pBody);
+                                       pRemovePart->pBody = NULL;
+                               }
+
+                               free(pRemovePart);
+                               pRemovePart = NULL;
+                       }
+               } else {
+#ifdef __SUPPORT_DRM__
+                       MmsReleaseMsgDRMInfo(&pMsgBody->presentationType.drmInfo);
+#endif
+                       MmsInitMsgType(&pMsgBody->presentationType);
+                       pMsgBody->pPresentationBody = NULL;
+               }
+       }
+       MSG_END();
+}
+
+static bool __MsgIsMultipartRelated(int type)
+{
+       if (type == MIME_MULTIPART_RELATED || type == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
+               return true;
+       } else {
+               return false;
+       }
+}
+
+static 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__
+
+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
+
+static 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;
+       }
+}
+
+
+
+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;
+
+       switch (pPartType->type) {
+       case MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE:
+       case MIME_MULTIPART_ALTERNATIVE:
+
+               /* 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.
+                */
+
+               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__
+                       MmsReleaseMsgDRMInfo(&pRemoveList->type.drmInfo);
+#endif
+                       MmsReleaseMsgBody(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__
+                       MmsReleaseMsgDRMInfo(&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__
+                                       MmsReleaseMsgDRMInfo(&pSelectedPart->type.drmInfo);
+#endif
+                                       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);
+
+                               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__
+                               MmsReleaseMsgDRMInfo(&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");
+
+                       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;
+                       }
+
+                       pSelectedPart->pNext = NULL;
+                       pPartBody->body.pMultipart = pSelectedPart;
+               }
+
+               pTmpMultipart = pRemoveList;
+
+               while (pTmpMultipart) {
+#ifdef __SUPPORT_DRM__
+                       MmsReleaseMsgDRMInfo(&pTmpMultipart->type.drmInfo);
+#endif
+                       MmsReleaseMsgBody(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 != NULL) {
+
+                       if (pSelectedPart->pBody != NULL)
+                               memcpy(pPartBody, pSelectedPart->pBody, sizeof(MsgBody));
+
+#ifdef __SUPPORT_DRM__
+                       MmsReleaseMsgDRMInfo(&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:
+
+       return NULL;
+}
+
+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;
+       }
+}
+
+
+static 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;
+}
+
+static 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;
+
+       return ResultChar;
+}
+
+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;
+       }
+}
+
+static bool __MsgCopyNestedMsgType(MsgType *pMsgType1, MsgType *pMsgType2)
+{
+       if(!pMsgType1 || !pMsgType2)
+               return false;
+
+       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);
+                       }
+               }
+       } 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);
+               }
+       }
+#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;
+
+       pMsgType1->contentSize = pMsgType2->contentSize;
+       pMsgType1->offset = pMsgType2->offset;
+       pMsgType1->size = pMsgType2->size;
+       pMsgType1->type = pMsgType2->type;
+
+       __MsgCopyNestedMsgParam(&(pMsgType1->param), &(pMsgType2->param));
+
+       if (pMsgType1->param.szName[0]) {
+#ifdef __SUPPORT_DRM__
+               pMsgType1->drmInfo.szContentName = MsgStrCopy(pMsgType2->param.szName);
+#endif
+       }
+
+       return true;
+}
+
+static bool __MsgCopyNestedMsgParam(MsgContentParam *pParam1, MsgContentParam *pParam2)
+{
+       if (pParam1->charset == MSG_CHARSET_UNKNOWN)
+               pParam1->charset = pParam2->charset;
+
+       if (pParam1->type == MIME_UNKNOWN)
+               pParam1->type = pParam2->type;
+
+       /* Don't copy pParam2->pPresentation */
+
+       /* For alternative: copy the boundary string */
+       if (pParam2->szBoundary[0] !='\0')
+               strcpy(pParam1->szBoundary, pParam2->szBoundary);
+
+       if (pParam1->szFileName[0] =='\0')
+               strcpy(pParam1->szFileName, pParam2->szFileName);
+
+       if (pParam1->szName[0] =='\0')
+               strcpy(pParam1->szName, pParam2->szName);
+
+       if (pParam1->szStart[0] =='\0')
+               strcpy(pParam1->szStart, pParam2->szStart);
+
+       if (pParam1->szStartInfo[0] =='\0')
+               strcpy(pParam1->szStartInfo, pParam2->szStartInfo);
+
+       return true;
+}
+
+static bool __MsgIsMultipartMixed(int type)
+{
+       if (type == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED || type == MIME_MULTIPART_MIXED) {
+               return true;
+       } else {
+               return false;
+       }
+}
+
+bool MmsGetMsgAttrib(MmsMsgID msgID, MmsAttrib* pAttrib)
+{
+       MmsMsg *pMsg = NULL;
+
+       memset(pAttrib, 0, sizeof(MmsAttrib));
+       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+       memcpy(pAttrib, &(pMsg->mmsAttrib), sizeof(MmsAttrib));
+
+       MSG_DEBUG("MmsGetMsgAttrib: msgID = %lu ---------------------\n", msgID);
+
+       if ('\0' != pMsg->szTrID[0])
+               MSG_DEBUG("szTrID = %s \n", pMsg->szTrID);
+
+       MSG_END();
+       return true;
+}
+
+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;
+}
+
+bool MmsDataUpdateLastStatus(MmsMsg *pMsg)
+{
+       MmsMsgMultiStatus*      pStatus = NULL;
+
+       pStatus = pMsg->mmsAttrib.pMultiStatus;
+
+       while (pStatus != NULL) {
+               pStatus->bDeliveyrReportIsLast = false;
+               pStatus->bReadReplyIsLast = false;
+               pStatus = pStatus->pNext;
+       }
+
+       return true;
+}
+
+
+bool MmsAddrUtilCompareAddr(char *pszAddr1, char *pszAddr2)
+{
+       int len1;
+       int len2;
+       char *p;
+
+       MmsAddrUtilRemovePlmnString(pszAddr1);
+       MmsAddrUtilRemovePlmnString(pszAddr2);
+
+       MSG_DEBUG("##### pszAddr1 = %s #####", pszAddr1);
+       MSG_DEBUG("##### pszAddr2 = %s #####", pszAddr2);
+       if (!strcmp(pszAddr1, pszAddr2))
+               return true;
+
+       len1 = strlen(pszAddr1);
+       len2 = strlen(pszAddr2);
+
+       if (len1 > len2) {
+               p = strstr(pszAddr1, pszAddr2);
+       } else {
+               p = strstr(pszAddr2, pszAddr1);
+       }
+
+       if (p)
+               return true;
+
+       return false;
+}
+
+static int __MsgGetLatin2UTFCodeSize(unsigned char *szSrc, int nChar)
+{
+       int nCount = 0;
+
+       MSG_DEBUG("MsgGetLatin2UTFCodeSize: --------------- \n");
+
+       if ((szSrc == NULL) || (nChar <= 0)) {
+               MSG_DEBUG("MsgGetLatin2UTFCodeSize: szSrc is NULL !!!! --------------- \n");
+               return 0;
+       }
+
+       while ((nChar > 0) && (*szSrc != '\0')) {
+               if (0x01 <= *szSrc && *szSrc <= 0x7F) {
+                       nCount += 1;
+                       szSrc++;
+                       nChar--;
+               } else {
+                       nCount += 2;
+                       szSrc++;
+                       nChar--;
+               }
+       }
+
+       return nCount;
+}
+
+static 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;
+
+       org = des;
+       outBufSize--;   //Null Character
+
+       while ((nChar > 0) && (*szSrc != '\0')) {
+
+               if (*szSrc >= 0x01 && *szSrc <= 0x7F) { //basic common
+                       temp = (unsigned short)(*szSrc);
+
+                       outBufSize --;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       *des = (unsigned char) ((*szSrc) & 0x007F);
+
+                       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
+
+                       temp = (unsigned short)(*szSrc);
+
+                       outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 2;
+                       szSrc += 1;
+                       nChar -= 1;
+               } else if (*szSrc == 0xD0) {//empty section OR vendor specific codes.
+
+                       temp = 0x011E;
+
+                       outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 2;
+                       szSrc += 1;
+                       nChar -= 1;
+               } else if (*szSrc == 0xDD) {
+                       temp = 0x0130;
+
+                       outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 2;
+                       szSrc += 1;
+                       nChar -= 1;
+               } else if (*szSrc == 0xDE) {
+                       temp = 0x015E;
+
+                       outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 2;
+                       szSrc += 1;
+                       nChar -= 1;
+               } else if (*szSrc == 0xF0) {
+                       temp = 0x011F;
+                               outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 2;
+                       szSrc += 1;
+                       nChar -= 1;
+               } else if (*szSrc == 0xFD) {
+                       temp = 0x0131;
+
+                       outBufSize -= 2;
+
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 2;
+                       szSrc += 1;
+                       nChar -= 1;
+               } else if (*szSrc == 0xFE) {
+                       temp = 0x015F;
+
+                       outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 2;
+                       szSrc += 1;
+                       nChar -= 1;
+               } else {
+                       return -1;
+               }
+       }
+__RETURN:
+       *des = 0;
+       return(des-org);
+}
+
+static int __MsgGetLatin52UTFCodeSize(unsigned char *szSrc, int nChar)
+{
+       int nCount = 0;
+
+       MSG_DEBUG("MsgGetLatin52UTFCodeSize: --------------- \n");
+
+       if ((szSrc == NULL) || (nChar <= 0))
+               return 0;
+
+       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;
+               }
+       }
+       return nCount;
+}
+
+static int __MsgLatin2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar)
+{
+       unsigned char*  org;
+       unsigned char   t1, t2;
+
+       MSG_DEBUG("MsgLatin2UTF: --------------- \n");
+
+       org = des;
+       outBufSize--;                   // NULL character
+
+       while ((nChar > 0) && (*szSrc != '\0')) {
+               if (0x01 <= *szSrc && *szSrc <= 0x7F) {
+                       /* check outbuffer's room for this UTF8 character */
+
+                       outBufSize --;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       *des = (unsigned char) (*szSrc & 0x007F);
+
+                       des++;
+                       szSrc++;
+                       nChar--;
+               } else {
+                       /* check outbuffer's room for this UTF8 character */
+
+                       outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       t2 = (unsigned char) (*szSrc & 0x003F);                         //      right most 6 bit
+                       t1 = (unsigned char) ((*szSrc & 0xC0) >> 6);            //      right most 2 bit
+
+                       *des = 0xC0 | (t1 & 0x1F);
+                       *(des + 1) = 0x80 | (t2 & 0x3F);
+
+                       des += 2;
+                       szSrc += 1;
+                       nChar -= 1;
+               }
+       }
+
+__RETURN:
+
+       *des = 0;
+       return (des - org);
+}
+
+
+static int __MsgLatin7code2UTF(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar)
+{
+       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--;
+
+               } else if ((*szSrc == 0x00) || (*szSrc >= 0x80 && *szSrc <= 0x9F) ||
+                                       (*szSrc >= 0xA3 && *szSrc <= 0xAD) || (*szSrc == 0xBB)) { // consider 0xA4, 0xA5
+
+                       temp = (unsigned short)(*szSrc);
+
+                       outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       t2 = (unsigned char) (temp & 0x003F);                           //      right most 6 bit
+                       t1 = (unsigned char) ((temp & 0xC0) >> 6);              //      right most 2 bit
+
+                       *des = 0xC0 | (t1 & 0x1F);
+                       *(des + 1) = 0x80 | (t2 & 0x3F);
+
+                       des += 2;
+                       szSrc += 1;
+                       nChar -= 1;
+               } else if (*szSrc == 0xA0) {
+                       temp = 0x0020;
+                       //*des = temp to utf-8
+                       outBufSize--;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       *des = (unsigned char) (temp & 0x007F);
+
+                       des++;
+                       szSrc++;
+                       nChar--;
+
+               } else if (*szSrc == 0xA1) {
+                       temp = 0x2018;
+
+                       outBufSize -= 3;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 3;
+                       szSrc += 1;
+                       nChar -= 1;
+
+               } else if (*szSrc == 0xA2) {
+                       temp = 0x2019;
+
+                       outBufSize -= 3;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 3;
+                       szSrc += 1;
+                       nChar -= 1;
+
+               } else if (*szSrc == 0xAF) {
+                       temp = 0x2015;
+
+                       outBufSize -= 3;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 3;
+                       szSrc += 1;
+                       nChar -= 1;
+
+               } else if (0xB0 <= *szSrc && *szSrc <= 0xB4) { //0x00B0 ~ 0x00B4
+
+                       temp = (unsigned short)(*szSrc);
+
+                       outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 2;
+                       szSrc += 1;
+                       nChar -= 1;
+
+               } else if ((0xB5 <= *szSrc &&  *szSrc <= 0xBA) ||
+                               (0xBC <= *szSrc && *szSrc <= 0xD1) ||
+                               (0xD3 <= *szSrc && *szSrc <= 0xFE)) {
+                       temp= (unsigned short)(*szSrc + 0x02D0);
+
+                       outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       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);
+
+                       des += 2;
+                       szSrc += 1;
+                       nChar -= 1;
+
+               } else {
+                       return -1;
+               }
+
+       }
+
+__RETURN:
+       *des = 0;
+       return(des - org);
+}
+
+static int __MsgGetLatin72UTFCodeSize(unsigned char *szSrc, int nChar)
+{
+       int nCount = 0;
+
+       MSG_DEBUG("MsgGetLatin72UTFCodeSize: --------------- \n");
+
+       if ((szSrc == NULL) || (nChar <= 0))
+               return 0;
+
+       while ((nChar > 0) && (*szSrc != '\0')) {
+
+               if ((*szSrc >= 0x01 && *szSrc <= 0x7F) || (*szSrc == 0xA0)) {
+                       nCount += 1;
+                       szSrc++;
+                       nChar--;
+               } else if (*szSrc == 0x00 || (0x80 <= *szSrc && *szSrc <= 0x9F) || (0xA3 <= *szSrc && *szSrc <= 0xAD) ||
+                                       (0xB0 <= *szSrc && *szSrc <= 0xB4) || (0xB5 <= *szSrc && *szSrc <= 0xFE)) {
+                       nCount += 2;
+                       szSrc++;
+                       nChar--;
+               } else if (*szSrc == 0xA1 ||*szSrc == 0xA2 || *szSrc == 0xAF) {
+                       nCount += 3;
+                       szSrc += 1;
+                       nChar -= 1;
+
+               } else {
+                       return -1;
+               }
+       }
+       return nCount;
+}
+
+static int __MsgUnicode2UTF(unsigned char *des, int outBufSize, unsigned short *szSrc, int nChar)
+{
+       unsigned char *org;
+       unsigned char t1;
+       unsigned char t2;
+       unsigned char t3;
+
+       MSG_DEBUG("MsgUnicode2UTF: --------------- \n");
+
+       org = des;
+       outBufSize--;                   // NULL character
+
+       while ((nChar > 0) && (*szSrc != '\0')) {
+               if (0x0001 <= *szSrc && *szSrc <= 0x007F) {
+                       /* check outbuffer's room for this UTF8 character */
+
+                       outBufSize --;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       *des = (unsigned char) (*szSrc & 0x007F);
+
+                       des++;
+                       szSrc++;
+                       nChar--;
+               } else if  ((*szSrc == 0x0000) || (0x0080 <= *szSrc && *szSrc <= 0x07FF)) {
+                       /* check outbuffer's room for this UTF8 character */
+
+                       outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       t2 = (unsigned char) (*szSrc & 0x003F);                         //      right most 6 bit
+                       t1 = (unsigned char) ((*szSrc & 0x07C0) >> 6);          //      right most 5 bit
+
+                       *des = 0xC0 | (t1 & 0x1F);
+                       *(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;
+               }
+       }
+
+__RETURN:
+
+       *des = 0;
+       return (des - org);
+}
+
+static 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;
+}
+
+static bool __MmsAddrUtilCheckEmailAddress(char *pszAddr)
+{
+       if (!pszAddr || pszAddr[0] == 0)
+               return false;
+
+       if (!strchr (pszAddr, MSG_MMS_CH_EMAIL_AT))
+               return false;
+
+       return true;
+}
+
+bool MmsAddrUtilRemovePlmnString(char *pszAddr)
+{
+       char *pszAddrCopy = NULL;
+       char *pszStrStart = NULL;
+       char *pszStrTemp = NULL;
+       int strLen = 0;
+
+       if ((!pszAddr) || (pszAddr[0] == 0)) {
+               MSG_DEBUG("MmsAddrUtilRemovePlmnString: pszAddr is null or zero\n");
+               return false;
+       }
+
+       strLen = strlen(pszAddr);
+
+       pszAddrCopy = (char*)calloc(1,strLen + 1);
+       if (!pszAddrCopy) {
+               MSG_DEBUG("MmsAddrUtilRemovePlmnString: pszAddrCopy is NULL, mem alloc failed\n");
+               return false;
+       }
+
+       strcpy(pszAddrCopy, pszAddr);
+
+
+       pszAddr[0] = 0;
+       pszStrStart = pszAddrCopy;
+
+       while (true) {
+               char*   pszStrEnd = NULL;
+               int             addressLen = 0;
+
+               if (__MmsAddrUtilCheckEmailAddress(pszAddrCopy))
+                       pszStrEnd = strstr(pszStrStart, "/TYPE=PLMN");
+               else
+                       pszStrEnd = strstr(pszStrStart, "/");
+
+               if (!pszStrEnd) {
+                       // "/TYPE=PLMN" not found
+
+                       int remainedLen = strlen(pszStrStart);
+
+                       if (remainedLen <= 0)
+                               break;
+
+                       strcat(pszAddr, pszStrStart);
+
+                       break;
+               }
+
+               // Get one address length
+               addressLen = pszStrEnd - pszStrStart;
+
+               strncat(pszAddr, pszStrStart, addressLen);
+
+               // Find next address
+               pszStrStart = pszStrEnd;
+
+               pszStrTemp = strstr(pszStrStart, MSG_MMS_STR_ADDR_DELIMETER);
+
+               if (pszStrTemp) {
+                       addressLen = pszStrTemp - pszStrEnd;
+                       pszStrStart += addressLen;
+               } else {
+                       pszStrStart += strlen(pszStrEnd);
+               }
+
+               if (pszStrStart[0] == 0)        // end of string
+                       break;
+
+
+               strcat(pszAddr, MSG_MMS_STR_ADDR_DELIMETER);    // add ';'
+               pszStrStart++;  // remove ';'
+       }
+
+       if (pszAddr[0] == 0)
+               strcpy(pszAddr, pszAddrCopy);
+
+       free(pszAddrCopy);
+
+       return true;
+}
+
+static int __MsgCutUTFString(unsigned char *des, int outBufSize, unsigned char *szSrc, int nChar)
+{
+       unsigned char *org;
+
+       MSG_DEBUG("MsgCutUTFString: --------------- \n");
+
+       org = des;
+       outBufSize--;                   // NULL character
+
+       while ((nChar > 0) && (*szSrc != '\0')) {
+               if (*szSrc < 0x80) {
+                       outBufSize --;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       *des = *szSrc;
+                       des++;
+                       szSrc++;
+               } else if  (((0xC0 <= *szSrc) && (*szSrc < 0xE0)) && (*(szSrc+1) >= 0x80)) {
+                       outBufSize -= 2;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       *des = *szSrc;
+                       *(des + 1) = *(szSrc + 1);
+
+                       des += 2;
+                       szSrc += 2;
+               } else if  ((*szSrc >= 0xE0) && (*(szSrc+1) >= 0x80) && (*(szSrc+2) >= 0x80)) {
+                       outBufSize -= 3;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       *des = *szSrc;
+                       *(des + 1) = *(szSrc + 1);
+                       *(des + 2) = *(szSrc + 2);
+
+                       des += 3;
+                       szSrc += 3;
+               } else {
+                       outBufSize --;
+                       if (outBufSize < 0)
+                               goto __RETURN;
+
+                       *des = *szSrc;
+                       des++;
+                       szSrc++;
+                       MSG_DEBUG("MsgCutUTFString: utf8 incorrect range!\n");
+               }
+
+               nChar--;
+       }
+
+__RETURN:
+
+       *des = 0;
+       return (des - org);
+}
+
+static void __MsgMIMERemoveQuote(char *szSrc)
+{
+       int             length = 0;
+
+       length = MsgStrlen(szSrc);
+       if (szSrc[0] == MSG_CH_QUOT && szSrc[length-1] == MSG_CH_QUOT) {
+               int index = 0;
+
+               for (index = 0; index < length-2; index++)
+                       szSrc[index] = szSrc[index+1];
+               szSrc[index] = '\0';
+       }
+}
+
+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");
+
+               *pBufLen = 0;
+               return false;
+       }
+
+       if (pPtr == NULL || pInBuf1 == NULL || pInBuf2 == NULL) {
+               MSG_DEBUG("Error");
+
+               *pBufLen = 0;
+               return false;
+       }
+
+       if (*pBufLen == 0) {
+               length = maxLen - (*pPtr);
+       } else {
+               length = (*pBufLen) - (*pPtr);
+       }
+
+       if (length < 0)
+               length = 0;
+
+       if ((*ppBuf) == NULL) {
+               memset(pInBuf1, 0, maxLen);
+               (*ppBuf) = pInBuf1;
+       } else if ((*ppBuf) == pInBuf1) {
+               memset(pInBuf2, 0, maxLen);
+               if (length)
+                       memcpy(pInBuf2, pInBuf1 + (*pPtr), length);
+               (*ppBuf) = pInBuf2;
+       } else {
+               memset(pInBuf1, 0, maxLen);
+               if (length)
+                       memcpy(pInBuf1, pInBuf2 + (*pPtr), length);
+               (*ppBuf) = pInBuf1;
+       }
+
+       (*pPtr) = 0;
+
+       if (*pOffset == endOfFile) {
+               *pBufLen = length;
+               return true;
+       }
+
+       if (maxLen == length) {
+               /* (*pPtr) was 0 */
+               if (MsgReadFileForDecode(pFile, (*ppBuf), maxLen, &nRead) == false)
+                       return false;
+
+               *pBufLen = nRead;
+       } else {
+               if (MsgReadFileForDecode(pFile, (*ppBuf) + length, maxLen - length, &nRead) == false)
+                       return false;
+
+               *pBufLen = length + nRead;
+       }
+
+       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);
+
+       return false;
+
+}
+
+
+/*
+ *     This function write media data from raw data to file.
+ *     @param  pMsg
+ *     @param  pPartBody
+ *     @param  pszMailboxPath  : path of mailbox
+ *     @param  pszMsgFilename  : name of msg file
+ *     @param  index                   : used for file naming
+ *     @param  bSave                   : if true, file will be save otherwise just filename will be stored.
+ */
+static bool __MmsMultipartSaveAsTempFile(MsgType *pPartType, MsgBody *pPartBody, char *pszMailboxPath, char *pszMsgFilename, int index, bool bSave)
+{
+       FILE *pFile = 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");
+
+       if (!pPartType) {
+               MSG_DEBUG("pPartType is NULL\n");
+               return true; // why true value is retured ??? ; false;
+       }
+
+       if (pPartType->param.szName[0] == '\0' && pPartType->param.szFileName[0] == '\0')
+               snprintf(pPartType->param.szName, sizeof(pPartType->param.szName), "%s", pPartType->param.szFileName);
+
+       if (pPartType->param.szName[0] != '\0') {
+               snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%s", pPartType->param.szName);
+       } 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
+
+
+       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);
+
+       // save file
+       if (bSave) {
+               if ((pFile = MsgOpenFile(szFullPath, "wb+")) == NULL) {
+                       MSG_DEBUG("MsgOpenFile failed");
+                       goto __CATCH;
+               }
+
+               if (__MmsGetMediaPartData(pPartType, pPartBody, pFile) == false) {
+                       MSG_DEBUG("MmsGetMediaPartData fail [index:%d]\n", index);
+                       goto __CATCH;
+               }
+
+               MsgCloseFile(pFile);
+               pFile = NULL;
+               if (pPartType->drmInfo.drmType != MSG_DRM_TYPE_NONE) {
+                       MsgDrmRegisterFile(MSG_MODE_FILE, szFullPath, strlen(szFullPath));
+
+                       /* change szDrm2FullPath as current content path*/
+                       if (pPartType->drmInfo.szDrm2FullPath) {
+                               free(pPartType->drmInfo.szDrm2FullPath);
+                               pPartType->drmInfo.szDrm2FullPath = MsgStrCopy(szFullPath);
+                       }
+               }
+
+       }
+       MSG_DEBUG("****   MmsGetMediaPartData:  [Multi part]  E  N  D  (Successfully)  ***\n");
+
+       return true;
+
+__CATCH:
+
+       if (pFile != NULL) {
+               MsgCloseFile(pFile);
+               pFile = NULL;
+       }
+
+       return false;
+}
+
+static bool __MmsGetMediaPartData(MsgType *pPartType, MsgBody *pPartBody, FILE* pFile)
+{
+       int nRead = 0;
+       int nRead2 = 0;
+       char *pData = NULL;
+       char *pNewData = NULL;
+       char *pTempData = NULL;
+       int msgEncodingValue = 0;
+       int msgTypeValue = 0;
+       int msgCharsetValue     = 0;
+       int cidLen = 0;
+       char *szCid = NULL;
+       int offset = 0;
+       int size = 0;
+
+       msgEncodingValue = pPartType->encoding;
+       msgTypeValue = pPartType->type;
+       msgCharsetValue = pPartType->param.charset;
+
+       cidLen = MsgStrlen(szCid);
+
+       offset = pPartBody->offset;
+       size = pPartBody->size;
+
+       if (pPartBody->szOrgFilePath[0]) {
+               pTempData = MsgOpenAndReadMmsFile(pPartBody->szOrgFilePath, offset, size, &nRead);
+
+               if (pTempData == NULL) {
+                       MSG_DEBUG("MmsGetMediaPartData : pTempData read fail\n");
+                       goto __CATCH;
+               }
+
+               pData = pTempData;
+       } else if (pPartBody->body.pText) {
+               pData = pPartBody->body.pText;
+               nRead = pPartBody->size;
+       }
+
+       if (pData == NULL) {
+               MSG_DEBUG("MmsGetMediaPartData : there is no data \n");
+               goto __RETURN;
+       }
+
+       pNewData = __MmsGetBinaryUTF8Data(pData, nRead, msgEncodingValue, msgTypeValue, msgCharsetValue, &nRead2);
+       pPartType->encoding = MSG_ENCODING_BINARY;
+
+       if (__MsgIsText(msgTypeValue))
+               pPartType->param.charset = MSG_CHARSET_UTF8;
+
+       if (MsgWriteFile(pNewData, sizeof(char), nRead2,  pFile) != (size_t)nRead2) {
+               MSG_DEBUG("MmsGetMediaPartData: file writing fail \n");
+
+               goto __CATCH;
+       }
+
+__RETURN:
+
+       if (pNewData) {
+               free(pNewData);
+               pNewData = NULL;
+       }
+
+       if (pTempData) {
+               free(pTempData);
+               pTempData = NULL;
+       }
+
+       return true;
+
+__CATCH:
+
+       if (pNewData) {
+               free(pNewData);
+               pNewData = NULL;
+       }
+
+       if (pTempData) {
+               free(pTempData);
+               pTempData = NULL;
+       }
+
+       return false;
+}
+
+static 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;
+
+
+       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);
+
+               pTemp = pConvertedData;
+               nTemp = nByte;
+
+               break;
+
+       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);
+
+               pTemp = pConvertedData;
+               nTemp = nByte;
+
+               break;
+
+       default:
+
+               MSG_DEBUG("MmsGetBinaryUTF8Data: 8bit    OR    Binary   bodyLength = %d \n", nRead);
+
+               pTemp = pData;
+               nTemp = nRead;
+
+               break;
+       }
+
+       if (__MsgIsText(msgTypeValue)) {
+               /* charset converting */
+
+               switch (msgCharsetValue) {
+               case MSG_CHARSET_UTF16:
+               case MSG_CHARSET_USC2:
+
+                       MSG_DEBUG("MmsGetBinaryUTF8Data: MSG_CHARSET_USC2 \n");
+
+                       if (((UINT8)pTemp[0]) == 0xFF && ((UINT8)pTemp[1]) == 0xFE) {
+                               nChar = (nTemp / 2 - 1);
+
+                               mszTempStr = (unsigned short*) malloc(nChar * sizeof(unsigned short));
+                               if (mszTempStr == NULL) {
+                                       MSG_DEBUG("MmsGetBinaryUTF8Data : 1. Memory Full !!! \n");
+                                       goto __CATCH;
+                               }
+
+                               memcpy(mszTempStr, ((unsigned short*)pTemp + 1), nChar * sizeof(unsigned short));
+
+                               nByte = __MsgGetUnicode2UTFCodeSize(((unsigned short*)pTemp + 1), nChar);
+                               if (nByte < 3)
+                                       nByte = 3; //min value
+
+                               pConvertedStr = (char *)malloc(nByte + 1);
+                               if (pConvertedStr != NULL)
+                                       __MsgUnicode2UTF ((unsigned char*)pConvertedStr, nByte + 1, mszTempStr, nChar);
+                       } else {
+                               nChar = (nTemp / 2);
+
+                               mszTempStr = (unsigned short*) malloc(nChar * sizeof(unsigned short));
+                               if (mszTempStr == NULL) {
+                                       MSG_DEBUG("MmsGetBinaryUTF8Data: 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);
+                       }
+
+                       if (pConvertedStr != NULL)
+                               pNewData = pConvertedStr;
+
+                       *npRead = nByte + 1;
+
+                       break;
+
+               case MSG_CHARSET_US_ASCII:
+
+                       MSG_DEBUG("MmsGetBinaryUTF8Data: MSG_CHARSET_US_ASCII \n");
+
+                       /* fall through */
+
+               case MSG_CHARSET_UTF8:
+
+                       MSG_DEBUG("MmsGetBinaryUTF8Data: MSG_CHARSET_UTF8 or Others \n");
+
+                       // 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;
+
+                       break;
+
+               case MSG_CHARSET_ISO_8859_7:
+
+                       /* Greek */
+
+                       MSG_DEBUG("MmsGetBinaryUTF8Data: MSG_CHARSET_ISO_8859_7 \n");
+
+                       nByte = __MsgGetLatin72UTFCodeSize((unsigned char*)pTemp, nTemp);
+                       pConvertedStr = (char *)malloc(nByte + 1);
+                       if (pConvertedStr)
+                               __MsgLatin7code2UTF((unsigned char*)pConvertedStr, nByte + 1, (unsigned char*)pTemp, nTemp);
+
+                       pNewData = pConvertedStr;
+                       *npRead = nByte + 1;
+
+                       break;
+
+               case MSG_CHARSET_ISO_8859_9:
+
+                       /* Turkish */
+                       MSG_DEBUG("MmsGetBinaryUTF8Data: 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);
+
+                       pNewData = pConvertedStr;
+                       *npRead = nByte + 1;
+
+                       break;
+
+               default:
+
+                       MSG_DEBUG("MmsGetBinaryUTF8Data: 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);
+
+                       pNewData = pConvertedStr;
+                       *npRead = nByte + 1;
+
+                       break;
+               }
+       } else {
+               pNewData = pTemp;
+               *npRead = nTemp;
+       }
+
+       pReturnData = (char *)malloc(*npRead);
+       if (pReturnData == NULL) {
+               MSG_DEBUG("MmsGetBinaryUTF8Data : pReturnData alloc fail. \n");
+
+               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;
+       }
+
+       if (mszTempStr) {
+               free(mszTempStr);
+               mszTempStr = NULL;
+       }
+
+       return pReturnData;
+
+__CATCH:
+
+       if (pConvertedData) {
+               free(pConvertedData);
+               pConvertedData = NULL;
+       }
+
+       if (pConvertedStr) {
+               free(pConvertedStr);
+               pConvertedStr = NULL;
+       }
+
+       if (mszTempStr) {
+               free(mszTempStr);
+               mszTempStr = NULL;
+       }
+
+       return NULL;
+}
+
+#ifndef __SUPPORT_DRM__
+static bool __MsgMakeFileName(int iMsgType, char *szFileName, 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 = %d     szFileName = %s \n", iMsgType, szFileName);
+
+       if (szFileName == NULL)
+               return false;
+
+       if (szFileName && (szFileName[0] != '\0')) {
+               MsgGetFileNameWithoutExtension (szTempFileName, szFileName);
+
+               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");
+               }
+       }
+
+       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);
+               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);
+       }
+
+
+       strcpy(szFileName, szTemp);
+
+       MSG_DEBUG("MsgMakeFileName: made szFileName = %s \n", szFileName);
+
+       return true;
+
+__CATCH:
+       {
+               char *p = NULL;
+               p = strrchr(szText, '.');
+               if (p != NULL)
+                       *p = 0;
+               snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%s", szText);
+
+               return false;
+       }
+}
+#else
+static 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);
+
+       if (szFileName == NULL)
+               return false;
+
+       if (szFileName && (szFileName[0] != '\0')) {
+               MsgGetFileNameWithoutExtension (szTempFileName, szFileName);
+
+               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 {
+                       pExt = strrchr(szTempFileName, '.');
+                       if (pExt == NULL) {
+                               memset(szText, 0, MSG_FILENAME_LEN_MAX+1);
+                               strncpy(szText, szTempFileName, MSG_FILENAME_LEN_MAX - 1);
+                               strcat(szText, ".");
+                       } else  {
+                               return true;
+                       }
+               }
+       } 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");
+               }
+       }
+
+       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) {
+
+                               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);
+               }
+       }
+
+       strcpy(szFileName, szTemp);
+
+       MSG_DEBUG("MsgMakeFileName: made szFileName = %s \n", szFileName);
+
+       return true;
+
+__CATCH:
+       {
+               char *p = NULL;
+               p = strrchr(szText, '.');
+               if (p != NULL)
+                       *p = 0;
+               snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%s", szText);
+
+               return false;
+       }
+}
+#endif
+
+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;
+}
+
+int MmsGetMediaPartCount(msg_message_id_t msgId)
+{
+       MmsMsg *pMsg;
+
+       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+
+       if (msgId != pMsg->msgID) {
+               MSG_DEBUG("Invalid Message Id");
+               return -1;
+       }
+
+       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;
+       }
+
+       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+
+       MmsInitMsgType(pHeader);
+
+
+       /* Requires header of non-presentation */
+       if (MsgIsMultipart(pMsg->msgType.type)) {
+               MSG_DEBUG("MmsGetMediaPartHeader: Multipart header [index = %d] \n", index);
+
+               pPart = pMsg->msgBody.body.pMultipart;
+
+               while (pPart && index--)
+                       pPart = pPart->pNext;
+
+               if (pPart == NULL) {
+                       MSG_DEBUG("MmsGetMediaPartHeader: There is no such msg part.\n");
+                       return false;
+               }
+
+               memcpy(pHeader, &pPart->type, sizeof(MsgType));
+       } else {
+               MSG_DEBUG("MmsGetMediaPartHeader: Requires singlepart header \n");
+               memcpy(pHeader, &pMsg->msgType, sizeof(MsgType));
+       }
+
+       return true;
+}
+
+static 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);
+       }
+#endif
+       MSG_DEBUG("------------------------------\n");
+       return true;
+}
diff --git a/plugin/mms_plugin/MmsPluginDrm.cpp b/plugin/mms_plugin/MmsPluginDrm.cpp
new file mode 100755 (executable)
index 0000000..1319b95
--- /dev/null
@@ -0,0 +1,174 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <drm_client_types.h>
+#include <drm_client.h>
+#include "MsgMmsTypes.h"
+#include "MsgDrmWrapper.h"
+#include "MmsPluginDrm.h"
+#include "MmsPluginCodec.h"
+#include "MmsPluginMIME.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginUtil.h"
+
+#ifdef __SUPPORT_DRM__
+
+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)
+{
+       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];
+       MSG_DRM_TYPE drmType = MSG_DRM_NONE;
+
+       MsgDrmGetDrmType(szFilePath, &drmType);
+       MsgDrmGetMimeTypeEx(szFilePath, szMimeType, sizeof(szMimeType));
+       MsgDrmGetContentID(szFilePath, szContentID, sizeof(szContentID));
+       MSG_DEBUG("drmType: %d", drmType);
+
+       switch (drmType) {
+       case MSG_DRM_FORWARD_LOCK:
+               pMsgType->drmInfo.drmType = MSG_DRM_TYPE_FL;
+               pMsgType->drmInfo.contentType = (MimeType)_MsgGetCode(MSG_TYPE, szMimeType);
+               if (MsgCopyDrmInfo(pMsgType) == false) {
+                       MSG_DEBUG("MsgDRM2GetDRMInfo : MsgCopyDrmInfo failed");
+                       return false;
+               }
+               break;
+
+       case MSG_DRM_COMBINED_DELIVERY:
+               pMsgType->drmInfo.drmType = MSG_DRM_TYPE_CD;
+               pMsgType->drmInfo.szContentURI = MsgResolveContentURI(szContentID);
+               break;
+
+       case MSG_DRM_SEPARATE_DELIVERY:
+               pMsgType->drmInfo.drmType = MSG_DRM_TYPE_SD;
+
+               pMsgType->drmInfo.contentType = (MimeType)_MsgGetCode(MSG_TYPE, szMimeType);
+
+               drm_content_info_s dcfHdrInfo;
+               bzero(&dcfHdrInfo, sizeof(drm_content_info_s));
+               drm_get_content_info(szFilePath, &dcfHdrInfo);
+
+               drm_file_info_s fileInfo;
+               bzero(&fileInfo, sizeof(drm_file_info_s));
+               drm_get_file_info(szFilePath,&fileInfo);
+
+               if (fileInfo.oma_info.version == DRM_OMA_DRMV1_RIGHTS) {
+                       pMsgType->drmInfo.szContentName = MsgRemoveQuoteFromFilename(dcfHdrInfo.title);
+                       pMsgType->drmInfo.szContentDescription = MsgStrCopy(dcfHdrInfo.description);
+               }
+               break;
+
+       default:
+               pMsgType->drmInfo.drmType = MSG_DRM_TYPE_NONE;
+               break;
+       }
+
+       pMsgType->drmInfo.szDrm2FullPath = MsgStrCopy(szFilePath);
+       MSG_DEBUG("pMsgType->drmInfo.szDrm2FullPath: %s", pMsgType->drmInfo.szDrm2FullPath);
+
+       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
diff --git a/plugin/mms_plugin/MmsPluginEncode.cpp b/plugin/mms_plugin/MmsPluginEncode.cpp
new file mode 100755 (executable)
index 0000000..4324093
--- /dev/null
@@ -0,0 +1,3182 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilFile.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginEncode.h"
+#include "MmsPluginCodecTypes.h"
+#include "MmsPluginCodecCommon.h"
+#include "MmsPluginMIME.h"
+#include "MmsPluginUtil.h"
+
+
+/**  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;
+
+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 __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 __MmsBinaryEncodeMmsVersion2(FILE *pFile);
+static bool __MmsBinaryEncodeFieldCodeAndValue2(FILE *pFile, UINT8 fieldCode, UINT8 fieldValue);
+
+/** -----------------------------------------------------------------
+ *                                     M   M   S       E   N   C   O   D   E
+ * * -----------------------------------------------------------------*/
+
+static void __MmsCleanEncodeBuff(void)
+{
+       memset(gpMmsEncodeBuf, 0, MSG_MMS_ENCODE_BUFFER_MAX);
+       gCurMmsEncodeBuffPos = 0;
+}
+
+
+void MmsRegisterEncodeBuffer(char *pInBuff, int maxLen)
+{
+       gpMmsEncodeBuf = pInBuff;
+       gCurMmsEncodeBuffPos = 0;
+       gMmsEncodeMaxLen = maxLen;
+       gMmsEncodeCurOffset = 0;
+}
+
+void MmsUnregisterEncodeBuffer(void)
+{
+       gpMmsEncodeBuf = NULL;
+       gCurMmsEncodeBuffPos = 0;
+       gMmsEncodeMaxLen = 0;
+       gMmsEncodeCurOffset = 0;
+}
+
+static int __MmsGetEncodeOffset(void)
+{
+       return (gMmsEncodeCurOffset + gCurMmsEncodeBuffPos);
+}
+
+bool MmsEncodeSendReq(FILE *pFile, MmsMsg *pMsg)
+{
+       return __MmsEncodeSendReq(pFile, pMsg, true);
+}
+
+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);
+
+       if (bIncludeSendReqHeader) {
+               if (__MmsBinaryEncodeSendReqHdr(pFile, pMsg) == false) {
+                       MmsUnregisterEncodeBuffer();
+                       return false;
+               }
+       }
+
+       if (__MmsBinaryEncodeMsgBody(pFile, &pMsg->msgType, &pMsg->msgBody, pMsg->nPartCount, !bIncludeSendReqHeader) == false) {
+               MmsUnregisterEncodeBuffer();
+               return false;
+       }
+
+       MmsUnregisterEncodeBuffer();
+
+       return true;
+}
+
+/* Functions for Acknowledge.ind & NotifyResp.ind ------------------------ */
+
+static void __MmsCleanEncodeBuff2(void)
+{
+       memset(gpMmsEncodeBuf2, 0, MSG_MMS_ENCODE_BUFFER_MAX);
+       gCurMmsEncodeBuffPos2 = 0;
+}
+
+static void __MmsRegisterEncodeBuffer2(char *pInBuff, int maxLen)
+{
+       gpMmsEncodeBuf2 = pInBuff;
+       gCurMmsEncodeBuffPos2 = 0;
+       gMmsEncodeMaxLen2 = maxLen;
+       gMmsEncodeCurOffset2 = 0;
+}
+
+static void __MmsUnregisterEncodeBuffer2(void)
+{
+       gpMmsEncodeBuf2 = NULL;
+       gCurMmsEncodeBuffPos2 = 0;
+       gMmsEncodeMaxLen2 = 0;
+       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)
+{
+       MSG_DEBUG("MmsBinaryEncodeTextString2: \n");
+
+       /**
+        * make text string
+        * Text-string = [Quote] *TEXT End-of-string
+        * If the 1st char in the TEXT is in the range of 128-255, a Quote char must precede it.
+        * Otherwise the Quote char must be omitted.
+        * The Quote is not part of the contents.
+        * Quote = <Octet 127>
+        */
+
+       if (pFile == NULL || source == NULL) {
+               MSG_DEBUG("MmsBinaryEncodeTextString2: source == NULL \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen2 - gCurMmsEncodeBuffPos2) < length) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
+                                                                                       gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeTextString2: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       if (source[0] > 0x7F) {
+               gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = QUOTE;
+               length--;
+       }
+
+       strncpy(gpMmsEncodeBuf2 + gCurMmsEncodeBuffPos2, (char*)source, (length - 1));  /** except NULL */
+       gCurMmsEncodeBuffPos2 += (length - 1);  /** except NULL */
+       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = (UINT8)NULL;
+
+       return true;
+
+__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");
+                       goto __CATCH;
+               }
+       }
+
+       if (fieldCode == 0xff) {
+               MSG_DEBUG("__MmsBinaryEncodeFieldCodeAndValue: invalid fieldCode \n");
+               goto __CATCH;
+       }
+
+       if (fieldValue == 0xff) {
+               MSG_DEBUG("__MmsBinaryEncodeFieldCodeAndValue: invalid fieldValue \n");
+               return true;
+       }
+
+       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = fieldCode;
+       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = fieldValue;
+
+       return true;
+
+__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 ((gMmsEncodeMaxLen2 - gCurMmsEncodeBuffPos2) < 2) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
+                                                                                       gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
+                       MSG_DEBUG("__MmsBinaryEncodeMmsVersion2: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_VERSION) | 0x80;
+       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2] = (majorVer << 4) | (minorVer & 0x0f) | MSB;
+
+       if (gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2] < 0x80) {
+               gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] |= 0x80;
+       } else {
+               gCurMmsEncodeBuffPos2++;
+       }
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+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);
+
+       __MmsCleanEncodeBuff2();
+
+       /* msgType */
+       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");
+               goto __CATCH;
+       }
+
+       /* trID (other type of message) */
+       length = __MmsBinaryEncodeTextStringLen((UINT8*)szTrID);
+       if (length == -1) {
+               MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: MmsBinaryEncodeTextStringLen fail \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen2 - gCurMmsEncodeBuffPos2) < (length + 1)) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
+                                                                                       gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_TRID) | 0x80;
+
+       if (__MmsBinaryEncodeTextString2(pFile, (UINT8*)szTrID, length) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: MmsBinaryEncodeTextString fail\n");
+               goto __CATCH;
+       }
+
+
+       if (__MmsBinaryEncodeMmsVersion2(pFile) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: __MmsBinaryEncodeMmsVersion error\n");
+               goto __CATCH;
+       }
+
+
+       /* Report Allowed */
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPORTALLOWED) | 0x80;
+
+       if (bReportAllowed) {
+               fieldValue = MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_YES) | 0x80;
+       } else {
+               fieldValue = MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_NO) | 0x80;
+       }
+
+       if (__MmsBinaryEncodeFieldCodeAndValue2(pFile, fieldCode, fieldValue) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: Report Allowed error\n");
+               goto __CATCH;
+       }
+
+       /* flush remained data on encoding file */
+       if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
+                                                                               gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeAckIndHdr: remained data MsgWriteDataFromEncodeBuffer fail \n");
+               goto __CATCH;
+       }
+
+       return true;
+
+__CATCH:
+
+       return false;
+}
+
+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);
+
+       __MmsCleanEncodeBuff2();
+
+       /* msgType */
+       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");
+               goto __CATCH;
+       }
+
+
+       /* trID (other type of message) */
+       length = __MmsBinaryEncodeTextStringLen((UINT8*)szTrID);
+       if (length == -1) {
+               MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: MmsBinaryEncodeTextStringLen fail \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen2 - gCurMmsEncodeBuffPos2) < (length + 1)) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
+                                                                                       gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       gpMmsEncodeBuf2[gCurMmsEncodeBuffPos2++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_TRID) | 0x80;
+       if (__MmsBinaryEncodeTextString2(pFile, (UINT8*)szTrID, length) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: MmsBinaryEncodeTextString fail\n");
+               goto __CATCH;
+       }
+
+
+       if (__MmsBinaryEncodeMmsVersion2(pFile) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: __MmsBinaryEncodeMmsVersion error\n");
+               goto __CATCH;
+       }
+
+
+       /* MsgStatus */
+       MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: MsgStatus = %d\n", iStatus);
+
+       if (iStatus != MSG_DELIVERY_REPORT_NONE) {
+               fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGSTATUS) | 0x80;
+               fieldValue = MmsGetBinaryValue(MmsCodeMsgStatus, iStatus) | 0x80;
+               if (__MmsBinaryEncodeFieldCodeAndValue2(pFile, fieldCode, fieldValue) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: MsgStatus error\n");
+                       goto __CATCH;
+               }
+       }
+
+
+       /* Report Allowed */
+       fieldCode  = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPORTALLOWED) | 0x80;
+
+       if (bReportAllowed) {
+               fieldValue = MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_YES) | 0x80;
+       } else {
+               fieldValue = MmsGetBinaryValue(MmsCodeReportAllowed, MMS_REPORTALLOWED_NO) | 0x80;
+       }
+
+       if (__MmsBinaryEncodeFieldCodeAndValue2(pFile, fieldCode, fieldValue) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: Report Allowed error\n");
+               goto __CATCH;
+       }
+
+       /* flush remained data on encoding file */
+       if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf2, &gCurMmsEncodeBuffPos2,
+                                                                               gMmsEncodeMaxLen2, &gMmsEncodeCurOffset2) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeNotiRespIndHdr: remained data MsgWriteDataFromEncodeBuffer fail \n");
+               goto __CATCH;
+       }
+
+       return true;
+
+__CATCH:
+
+       return false;
+}
+
+bool MmsEncodeAckInd(FILE *pFile, char *pTrID, bool bReportAllowed)
+{
+       __MmsRegisterEncodeBuffer2(gszMmsEncodeBuf2, MSG_MMS_ENCODE_BUFFER_MAX);
+
+       MSG_DEBUG("_MmsEncodeAckInd: Start Binary Encoding now ============= \n");
+
+       if (__MmsBinaryEncodeAckIndHdr(pFile, pTrID, bReportAllowed) == false) {
+               MSG_DEBUG("_MmsEncodeAckInd: SendReq Binary encoding fail \n");
+               goto __CATCH;
+       }
+
+       __MmsUnregisterEncodeBuffer2();
+
+       return true;
+
+__CATCH:
+
+       MSG_DEBUG("## _MmsEncodeAckInd: failed");
+       __MmsUnregisterEncodeBuffer2();
+
+       return false;
+}
+
+bool MmsEncodeNotiRespInd(FILE *pFile, char *pTrID, msg_delivery_report_status_t iStatus, bool bReportAllowed)
+{
+       __MmsRegisterEncodeBuffer2(gszMmsEncodeBuf2, MSG_MMS_ENCODE_BUFFER_MAX);
+
+       MSG_DEBUG("_MmsEncodeNotiRespInd: Start Binary Encoding now ============= \n");
+
+       if (__MmsBinaryEncodeNotiRespIndHdr(pFile, pTrID, iStatus, bReportAllowed) == false) {
+               MSG_DEBUG("_MmsEncodeNotiRespInd: SendReq Binary encoding fail \n");
+               goto __CATCH;
+       }
+
+       __MmsUnregisterEncodeBuffer2();
+
+       return true;
+
+__CATCH:
+
+       return false;
+}
+
+/* Functions for Acknowledge.ind & NotifyResp.ind  (END) ------------------------ */
+bool MmsEncodeReadReport10(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
+{
+       char *pText = NULL;
+       MsgMultipart *pPart = NULL;
+       MsgType msgType;
+       MsgBody msgBody;
+
+       char *pszReportMsg = NULL;
+       int     maxLen = 0;
+
+       struct  tm      *dateTime = NULL;
+       time_t  RawTime = 0;
+       time_t  dateSec = 0;
+
+       MmsRegisterEncodeBuffer(gszMmsEncodeBuf, MSG_MMS_ENCODE_BUFFER_MAX);
+
+       MSG_DEBUG("_MmsEncodeMsg: Start Binary Encoding now V1.0============= \n");
+
+       if (__MmsBinaryEncodeReadReport10Hdr(pFile, pMsg, mmsReadStatus) == false) {
+               MSG_DEBUG("_MmsEncodeReadReport10: SendReq Binary encoding fail \n");
+               goto __CATCH;
+       }
+
+       memset(&msgType, 0, sizeof(MsgType));
+       memset(&msgBody, 0, sizeof(MsgBody));
+
+       pText = (char *)malloc(MSG_STDSTR_LONG);
+       if (pText == NULL) {
+               MSG_DEBUG("__MmsSendReadReportV10: text body malloc fail \n");
+               goto __CATCH;
+       }
+
+       memset(pText, 0, MSG_STDSTR_LONG);
+
+       time(&RawTime);
+       dateTime = localtime(&RawTime);
+       dateSec = mktime(dateTime);
+
+       // get report message
+       if (mmsReadStatus == MSG_READ_REPORT_IS_DELETED) {
+               pszReportMsg = (char*)"Your message has been deleted " ;
+       } else {
+               pszReportMsg = (char*)"Your message has been read " ;
+       }
+
+       // make report body ..
+       maxLen = strlen (pszReportMsg) +16 /* date string */ + 8 /* enter chars */ ;
+
+       if (maxLen > MSG_STDSTR_LONG) {
+               snprintf (pText, MSG_STDSTR_LONG, "%s\n", 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);
+       }
+
+       // make header
+       msgType.type = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED;
+       msgType.contentSize = strlen(pText);
+       msgType.param.charset = MSG_CHARSET_UNKNOWN;
+
+       // make body
+       if ((pPart = MmsAllocMultipart()) == NULL) {
+               MSG_DEBUG("__MmsSendReadReportV10: MsgAllocMultipart Fail \n");
+               goto __CATCH;
+       }
+
+
+       pPart->type.type = MIME_TEXT_PLAIN;
+       pPart->type.contentSize = strlen(pText);
+       pPart->type.param.charset = MSG_CHARSET_UTF8;
+
+       if (pPart->pBody == NULL) {
+               MSG_DEBUG("__MmsSendReadReportV10: pPart->pBody is NULL \n");
+               goto __CATCH;
+       }
+
+       pPart->pBody->size = strlen(pText);
+       pPart->pBody->body.pText = pText;
+
+       msgBody.body.pMultipart = pPart;
+
+       if (__MmsBinaryEncodeMsgBody(pFile, &msgType, &msgBody, 1, false) == false) {
+               MSG_DEBUG("__MmsSendReadReportV10: MmsBinaryEncodeMsgBody fail \n");
+               goto __CATCH;
+       }
+
+       MSG_DEBUG("__MmsSendReadReportV10:  Send To RM ReadReport Msg \n");
+
+       if (pText) {
+               free(pText);
+               pText = NULL;
+       }
+
+       if (pPart) {
+               if (pPart->pBody) {
+                       free(pPart->pBody);
+                       pPart->pBody = NULL;
+               }
+               free(pPart);
+               pPart = NULL;
+       }
+
+       MmsUnregisterEncodeBuffer();
+
+       return true;
+
+__CATCH:
+
+       if (pText) {
+               free(pText);
+               pText = NULL;
+       }
+
+       if (pPart) {
+               if (pPart->pBody) {
+                       free(pPart->pBody);
+                       pPart->pBody = NULL;
+               }
+               free(pPart);
+               pPart = NULL;
+       }
+
+       MmsUnregisterEncodeBuffer();
+
+       return false;
+}
+
+bool MmsEncodeReadReport11(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
+{
+       MmsRegisterEncodeBuffer(gszMmsEncodeBuf, MSG_MMS_ENCODE_BUFFER_MAX);
+
+       MSG_DEBUG("_MmsEncodeMsg: Start Binary Encoding now V1.1============= \n");
+
+       if (__MmsBinaryEncodeReadReport11Hdr(pFile, pMsg, mmsReadStatus) == false) {
+               MSG_DEBUG("_MmsEncodeMsg: SendReq Binary encoding fail \n");
+               goto __CATCH;
+       }
+
+       MmsUnregisterEncodeBuffer();
+
+       return true;
+
+__CATCH:
+       MmsUnregisterEncodeBuffer();
+
+       return false;
+}
+
+/* ==========================================================
+
+                                       B  I  N  A  R  Y         E  N  C  O  D  I  N  G
+
+   ==========================================================*/
+
+/*
+ * Binary Encoded Message Format
+ *
+ *             < Single Part Body Message >
+ * -----------------------------------
+ * |           Header Fields                    |
+ * -----------------------------------
+ * | Content Type:start=xxx;type=xxx | ->(ex) Text/Plain, Text/Html, ....
+ * -----------------------------------
+ * |           Single Part Body                 |
+ * -----------------------------------
+ *
+ *             < Multi Part Body Message >
+ * -----------------------------------
+ * |           Header Fields                    |
+ * -----------------------------------
+ * | Content Type:start=xxx;type=xxx | -> (ex) Application/vnd.wap.multipart.mixed(related), multipart/mixed(related)
+ * -----------------------------------
+ * |   # of Entries (body parts)        |
+ * -----------------------------------                         < Each Entry >
+ * |                   Entry 1                          |      ->      -----------------------------
+ * -----------------------------------         |               header Length           |
+ * |                   Entry 2                          |              -----------------------------
+ * -----------------------------------         |               Data Length                     |
+ * |                   ......                           |              -----------------------------  -
+ * -----------------------------------         |               Content-Type            |  |
+ * |                   Entry n                          |              -----------------------------  | Header Length
+ * -----------------------------------         |                       Header                  |  |
+ *                                                                                     -----------------------------  -
+ *                                                                                     |                       Data                    |  | Data Length
+ *                                                                                     -----------------------------  -
+ */
+static bool __MmsBinaryEncodeSendReqHdr(FILE *pFile, MmsMsg *pMsg)
+{
+       UINT8 fieldCode = 0xff;
+       UINT8 fieldValue        = 0xff;
+       int length              = 0;
+
+       __MmsCleanEncodeBuff();
+
+       /* msgType */
+       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");
+               goto __CATCH;
+       }
+
+       /* trID (other type of message) */
+       if (__MmsBinaryEncodeTrID(pFile, pMsg->szTrID, MMS_TR_ID_LEN + 1) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: trID error\n");
+               goto __CATCH;
+       }
+
+       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr:                pMsg->szTrID = %s\n", pMsg->szTrID);
+
+       if (__MmsBinaryEncodeMmsVersion(pFile) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: __MmsBinaryEncodeMmsVersion error\n");
+               goto __CATCH;
+       }
+
+       /* From : Insert Token mode */
+       if (__MmsBinaryEncodeFrom(pFile) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: __MmsBinaryEncodeFrom fail\n");
+               goto __CATCH;
+       }
+
+
+       /* To = Encoded-string-value */
+       if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_TO, pMsg->mmsAttrib.szTo) == false)
+       {
+               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: To __MmsBinaryEncodeAddress fail\n");
+               goto __CATCH;
+       }
+
+
+       /* Cc = Encoded-string-value */
+       if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_CC, pMsg->mmsAttrib.szCc) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: Cc __MmsBinaryEncodeAddress fail\n");
+               goto __CATCH;
+       }
+
+
+       /* Bcc = Encoded-string-value */
+
+       if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_BCC, pMsg->mmsAttrib.szBcc) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: Bcc __MmsBinaryEncodeAddress fail\n");
+               goto __CATCH;
+       }
+
+
+       MSG_DEBUG("_MmsBinaryEnocdeSendReqHdr() pMsg->mmsAttrib.szSubject =%s\n",pMsg->mmsAttrib.szSubject);
+
+       /* Subject = Encoded-string-value */
+       if (pMsg->mmsAttrib.szSubject[0]) {
+               length = __MmsBinaryEncodeEncodedStringLen((UINT8*)pMsg->mmsAttrib.szSubject);
+               if (length == -1) {
+                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: subject MmsBinaryEncodeEncodedStringLen fail \n");
+                       goto __CATCH;
+               }
+
+               if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length + 1) {
+                       if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                               gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: subject MsgWriteDataFromEncodeBuffer fail \n");
+                               goto __CATCH;
+                       }
+               }
+
+               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");
+                       goto __CATCH;
+               }
+       }
+
+       /* MMS-1.3-con-739 */
+       /* Msg class */
+       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");
+               goto __CATCH;
+       }
+       /* MMS-1.3-con-739 */
+       /* MMS-1.3-con-733 */
+       /* Date = Long-integer */
+       if (!__MmsBinaryEncodeDate(pFile)) {
+                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: __MmsBinaryEncodeDate error\n");
+                       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 (__MmsBinaryEncodeTime(pFile, MMS_CODE_EXPIRYTIME, pMsg->mmsAttrib.expiryTime) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: expiryTime __MmsBinaryEncodeTime fail\n");
+                       goto __CATCH;
+               }
+       }
+
+       /* 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 (__MmsBinaryEncodeTime(pFile, MMS_CODE_DELIVERYTIME, pMsg->mmsAttrib.deliveryTime) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: deliveryTime __MmsBinaryEncodeTime fail\n");
+                       goto __CATCH;
+               }
+       }
+
+       /* 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;
+
+               if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: priority error\n");
+                       goto __CATCH;
+               }
+       }
+
+       /* Sender Visible (hide | show) */
+       if (pMsg->mmsAttrib.bHideAddress == true) {
+               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");
+                       goto __CATCH;
+               }
+       }
+
+       /* Delivery Report (yes | no) */
+       fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_DELIVERYREPORT)|0x80;
+
+       if (pMsg->mmsAttrib.bAskDeliveryReport) {
+               fieldValue = MmsGetBinaryValue(MmsCodeDeliveryReport, MMS_REPORT_YES) | 0x80;
+       } else {
+               fieldValue = MmsGetBinaryValue(MmsCodeDeliveryReport, MMS_REPORT_NO) | 0x80;
+       }
+
+       if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: sender visibility error\n");
+               goto __CATCH;
+       }
+
+       /* Read Reply (Yes | no) */
+       fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_READREPLY)|0x80;
+       if (pMsg->mmsAttrib.bAskReadReply) {
+               fieldValue = MmsGetBinaryValue(MmsCodeReadReply, MMS_REPORT_YES)|0x80;
+       } else {
+               fieldValue = MmsGetBinaryValue(MmsCodeReadReply, MMS_REPORT_NO)|0x80;
+       }
+
+       if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: read reply error\n");
+               goto __CATCH;
+       }
+
+       if ((pMsg->mmsAttrib.replyCharge.chargeType == MMS_REPLY_REQUESTED) ||
+               (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;
+
+               if (__MmsBinaryEncodeFieldCodeAndValue(pFile, fieldCode, fieldValue) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: replyCharging error\n");
+                       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");
+                               goto __CATCH;
+                       }
+               }
+
+               /** fixme: Reply-charging-size */
+               if (pMsg->mmsAttrib.replyCharge.chargeSize > 0) {
+                       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");
+                                       goto __CATCH;
+                               }
+                       }
+
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPLYCHARGINGSIZE) | 0x80;
+
+                       if (__MmsBinaryEncodeInteger(pFile, pMsg->mmsAttrib.replyCharge.chargeSize, length) == false)   {
+                               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: replyChargingSize MmsBinaryEncodeInteger error\n");
+                               goto __CATCH;
+                       }
+               }
+
+               /** fixme: Reply-charging-ID  ----> used only when reply message  */
+               if (pMsg->mmsAttrib.replyCharge.szChargeID[0]) {
+                       length = __MmsBinaryEncodeTextStringLen((UINT8*)pMsg->mmsAttrib.replyCharge.szChargeID);
+                       if (length == -1) {
+                               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: szReplyChargingID MmsBinaryEncodeTextStringLen fail\n");
+                               goto __CATCH;
+                       }
+
+                       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < (length + 1)) {
+                               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                               gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: MsgWriteDataFromEncodeBuffer fail \n");
+                                       goto __CATCH;
+                               }
+                       }
+
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_REPLYCHARGINGID) | 0x80;
+
+                       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)pMsg->mmsAttrib.replyCharge.szChargeID, length) == false) {
+                               MSG_DEBUG("szContentLocation MmsBinaryEncodeTextString fail\n");
+                               goto __CATCH;
+                       }
+               }
+       }
+
+       /* flush remained data on encoding file */
+       if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos, gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: remained data MsgWriteDataFromEncodeBuffer fail \n");
+               goto __CATCH;
+       }
+
+       return true;
+
+__CATCH:
+
+       MSG_DEBUG("## _MmsBinaryEncodeSendReqHdr: failed");
+       return false;
+}
+
+static bool __MmsBinaryEncodeReadReport10Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
+{
+       int length      = 0;
+       char *szTo      = NULL;
+       UINT8 fieldCode = 0xff;
+       UINT8 fieldValue = 0xff;
+       char szSubject[MSG_LOCALE_SUBJ_LEN + 8] = {0, };
+
+       if (pMsg == NULL) {
+               MSG_DEBUG("pMsg is NULL");
+               goto __CATCH;
+       }
+
+       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: mmsReadStatus = %d\n", mmsReadStatus);
+
+       __MmsCleanEncodeBuff();
+
+       /* msgType */
+       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");
+               goto __CATCH;
+       }
+
+       /* trID (other type of message) */
+       if (__MmsBinaryEncodeTrID(pFile, NULL, 0) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: __MmsBinaryEncodeTrID error\n");
+               goto __CATCH;
+       }
+
+       if (__MmsBinaryEncodeMmsVersion(pFile) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: __MmsBinaryEncodeMmsVersion error\n");
+               goto __CATCH;
+       }
+
+       /* Date = Long-integer */
+       if (!__MmsBinaryEncodeDate(pFile)) {
+               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: date __MmsBinaryEncodeDate error\n");
+               goto __CATCH;
+       }
+
+       /* From : Insert Token mode */
+       if (__MmsBinaryEncodeFrom(pFile) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: __MmsBinaryEncodeFrom fail\n");
+               goto __CATCH;
+       }
+
+       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To = %s\n", pMsg->mmsAttrib.szFrom);
+
+       /* To = Encoded-string */
+       if (pMsg && (strchr(pMsg->mmsAttrib.szFrom, '/') == NULL)) {
+               length = strlen(pMsg->mmsAttrib.szFrom);
+               szTo = (char *)malloc(length + 11);
+               if (szTo == NULL) {
+                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: szTo alloc fail\n");
+                       goto __CATCH;
+               }
+
+               snprintf(szTo, length + 11, "%s/TYPE=PLMN", pMsg->mmsAttrib.szFrom);
+               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To = %s\n", szTo);
+
+               if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_TO, szTo) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To __MmsBinaryEncodeAddress fail\n");
+                       goto __CATCH;
+               }
+
+               if (szTo) {
+                       free(szTo);
+                       szTo = NULL;
+               }
+       } else {
+               if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_TO, pMsg->mmsAttrib.szFrom) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To __MmsBinaryEncodeAddress fail\n");
+                       goto __CATCH;
+               }
+       }
+
+       /* Subject = Encoded-string-value */
+       if (pMsg && pMsg->mmsAttrib.szSubject[0]) {
+               if (mmsReadStatus == MSG_READ_REPORT_IS_READ) {
+                       snprintf(szSubject, MSG_LOCALE_SUBJ_LEN + 8, "%s%s", MMS_READ_REPORT_STRING_READ, pMsg->mmsAttrib.szSubject);
+               } else {
+                       snprintf(szSubject, MSG_LOCALE_SUBJ_LEN + 8, "%s%s", MMS_READ_REPORT_STRING_DELETED, pMsg->mmsAttrib.szSubject);
+               }
+       } else {
+               if (mmsReadStatus == MSG_READ_REPORT_IS_READ) {
+                       snprintf(szSubject, MSG_LOCALE_SUBJ_LEN + 8, "%s", MMS_READ_REPORT_STRING_READ);
+
+               } else {
+                       snprintf(szSubject, MSG_LOCALE_SUBJ_LEN + 8, "%s", MMS_READ_REPORT_STRING_DELETED );
+               }
+       }
+
+       length = __MmsBinaryEncodeEncodedStringLen((UINT8*)szSubject);
+       if (length == -1) {
+               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: subject MmsBinaryEncodeEncodedStringLen fail \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length + 1) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos, gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: subject MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_SUBJECT) | 0x80;
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = fieldCode;
+       if (__MmsBinaryEncodeEncodedString(pFile, (UINT8*)szSubject, length) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: subject MmsBinaryEncodeEncodedString fail \n");
+               goto __CATCH;
+       }
+
+       /* Msg class */
+       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");
+               goto __CATCH;
+       }
+
+
+       /* Delivery Report (yes | no) */
+       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");
+               goto __CATCH;
+       }
+
+
+       /* Read Reply (Yes | no) */
+       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");
+               goto __CATCH;
+       }
+
+
+       /* Sender Visible (hide | show) */
+       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");
+               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");
+               goto __CATCH;
+       }
+
+       return true;
+
+__CATCH:
+       if (szTo) {
+               free(szTo);
+               szTo = NULL;
+       }
+
+       return false;
+}
+
+static bool __MmsBinaryEncodeReadReport11Hdr(FILE *pFile, MmsMsg *pMsg, msg_read_report_status_t mmsReadStatus)
+{
+       UINT8 fieldCode = 0xff;
+       UINT8 fieldValue = 0xff;
+       char *szTo = NULL;
+
+       __MmsCleanEncodeBuff();
+
+       /* msgType */
+       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");
+               goto __CATCH;
+       }
+
+       /* MMS version */
+       if (__MmsBinaryEncodeMmsVersion(pFile) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: __MmsBinaryEncodeMmsVersion error\n");
+               goto __CATCH;
+       }
+
+       if (__MmsBinaryEncodeMsgID(pFile, pMsg->szMsgID) == false)
+               goto __CATCH;
+
+       /* To = Encoded-string */
+       if (strchr(pMsg->mmsAttrib.szFrom, '/') == NULL) {
+               int length = 0;
+               length = strlen(pMsg->mmsAttrib.szFrom);
+               szTo = (char *)malloc(length + 11);
+
+               if (szTo == NULL) {
+                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: szTo alloc fail\n");
+                       goto __CATCH;
+               }
+
+               snprintf(szTo, length + 11,"%s/TYPE=PLMN", pMsg->mmsAttrib.szFrom);
+               MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To = %s\n", szTo);
+
+               if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_TO, szTo) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeReadReport10Hdr: To __MmsBinaryEncodeAddress fail\n");
+                       goto __CATCH;
+               }
+
+               if (szTo) {
+                       free(szTo);
+                       szTo = NULL;
+               }
+       } else {
+               if (__MmsBinaryEncodeAddress(pFile, MMS_CODE_TO, pMsg->mmsAttrib.szFrom) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: To __MmsBinaryEncodeAddress fail\n");
+                       goto __CATCH;
+               }
+       }
+
+       /* From : Insert Token mode */
+       if (__MmsBinaryEncodeFrom(pFile) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: __MmsBinaryEncodeFrom fail\n");
+               goto __CATCH;
+       }
+
+       /* Date = Long-integer */
+       if (!__MmsBinaryEncodeDate(pFile)) {
+               MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: __MmsBinaryEncodeDate error\n");
+               goto __CATCH;
+       }
+
+       /* Read Status (Yes | no) */
+       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");
+               goto __CATCH;
+       };
+
+       if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                               gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+               MSG_DEBUG("_MmsBinaryEncodeReadReport11Hdr: remained data MsgWriteDataFromEncodeBuffer fail \n");
+               goto __CATCH;
+       }
+
+       return true;
+
+__CATCH:
+       if (szTo) {
+               free(szTo);
+               szTo = NULL;
+       }
+
+       return false;
+}
+
+static bool __MmsBinaryEncodeMsgBody(FILE *pFile, MsgType *pType, MsgBody *pBody, int nPartCount, bool bTemplate)
+{
+       int length = 0;
+       MsgMultipart *pMultipart = NULL;
+
+       MSG_DEBUG("MmsBinaryEncodeMsgBody: nPartCount = %d\n", nPartCount);
+
+       if (pFile == NULL || pType == NULL) {
+               MSG_DEBUG("MmsBinaryEncodeMsgBody: invalid file handle\n");
+               goto __CATCH;
+       }
+
+       if (MmsIsMultipart(pType->type)) {
+
+               int     nEntries   = 0;
+               /* ---------------------------
+                *       Multipart message
+                * ---------------------------*/
+
+               pType->offset = __MmsGetEncodeOffset();
+
+               /* Content type */
+               length = __MmsBinaryEncodeContentTypeLen(pType);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgBody: MmsBinaryEncodeContentTypeLen fail \n");
+                       goto __CATCH;
+               }
+               if (bTemplate == false)
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_CONTENTTYPE) | 0x80;
+
+               if (__MmsBinaryEncodeContentType(pFile, pType, length) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgBody: MmsBinaryEncodeContentType fail \n");
+                       goto __CATCH;
+               }
+
+               pBody->offset = __MmsGetEncodeOffset();
+
+               /* nEntries */
+               if (pBody->pPresentationBody) {
+                       nEntries = nPartCount + 1;
+               } else {
+                       nEntries = nPartCount;
+               }
+
+               if (nEntries >= 0) {
+                       length = __MmsBinaryEncodeUintvarLen(nEntries);
+                       if (length == -1) {
+                               MSG_DEBUG("MmsBinaryEncodeMsgBody: nEntries MmsBinaryEncodeUintvarLen fail \n");
+                               goto __CATCH;
+                       }
+                       if (__MmsBinaryEncodeUintvar(pFile, nEntries, length) == false) {
+                               MSG_DEBUG("MmsBinaryEncodeMsgBody: nEntries MmsBinaryEncodeUintvar fail \n");
+                               goto __CATCH;
+                       }
+
+                       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");
+                                       goto __CATCH;
+                               }
+
+                               nEntries--;
+                       }
+
+                       pMultipart = pBody->body.pMultipart;
+                       while (nEntries && pMultipart) {
+                               if (__MmsBinaryEncodeMsgPart(pFile, pType->type, &pMultipart->type, pMultipart->pBody) == false) {
+                                       MSG_DEBUG("MmsBinaryEncodeMsgBody: __MmsBinaryEncodeMsgPart fail \n");
+                                       goto __CATCH;
+                               }
+                               pMultipart = pMultipart->pNext;
+                               nEntries--;
+                       }
+               } else {
+                       if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                               gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                               MSG_DEBUG("MmsBinaryEncodeMsgBody: Empty message body MsgWriteDataFromEncodeBuffer fail \n");
+                               goto __CATCH;
+                       }
+               }
+
+               pBody->size = __MmsGetEncodeOffset() - pBody->offset;
+       } else {
+               /* ---------------------------
+                *       Singlepart message
+                * ---------------------------*/
+               pType->offset = __MmsGetEncodeOffset();
+
+               if (__MmsBinaryEncodeContentHeader(pFile, (MimeType)pType->type, pType, false) == false)
+                       goto __CATCH;
+
+               length = __MmsBinaryEncodeContentTypeLen(pType);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgBody: Singlepart MmsBinaryEncodeContentTypeLen fail \n");
+                       goto __CATCH;
+               }
+
+               if (__MmsBinaryEncodeContentType(pFile, pType, length) == false)
+                       goto __CATCH;
+
+               pType->size = __MmsGetEncodeOffset() - pType->offset;
+
+               if (__MmsBinaryEncodeContentBody(pFile, pBody) == false)
+                       goto __CATCH;
+       }
+
+       return true;
+
+__CATCH:
+       MSG_DEBUG("## MmsBinaryEncodeMsgBody: failed\n");
+
+       return false;
+}
+
+static int __MmsBinaryEncodeContentTypeLen(MsgType *pType)
+{
+       int length = 0;
+       int     totalLength = 0;
+       UINT16 fieldValue = 0xffff;
+       const char *szTextType = NULL;
+       int     contentType = MIME_UNKNOWN;
+
+       MSG_DEBUG("MSmsBinaryEncodeContentTypeLen:  type\n");
+
+       /*
+        * Content-type-value = Constrained-media | Content-general-form
+        * Constrained-media  = Constrained-encoding
+        *                                              Constrained-encoding = Extension-Media | Short-integer
+        *                                              Extension-media = *TEXT End-of-string
+        * Content-general-form = Value-length Media-type
+        *                                              Media-type = (Well-known-media | Extension-Media) *(Parameter)
+        */
+
+       /* Content-type-value = Content-general-form ------------------------------- */
+       /* Content-Type */
+
+       contentType = pType->type;
+
+       fieldValue = MmsGetBinaryValue(MmsCodeContentType, contentType);
+       if (fieldValue == UNDEFINED_BINARY || fieldValue == 0x0049)     {
+               /* Extension-media type */
+               szTextType = MmsGetTextValue(MmsCodeContentType, contentType);
+               if (szTextType != NULL) {
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
+                       if (length == -1) {
+                               MSG_DEBUG("MSmsBinaryEncodeContentTypeLen: szTextType MmsBinaryEncodeTextStringLen fail \n");
+                               goto __CATCH;
+                       }
+                       totalLength += length;
+               } else {
+                       totalLength++;
+               }
+       } else {
+               totalLength++;
+       }
+
+       /* 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);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: charSet MmsBinaryEncodeIntegerLen fail \n");
+                       goto __CATCH;
+               }
+               totalLength += (length + 1);
+       } else {
+               if (MmsIsText(contentType)) {   // Any-charset
+                       if (!MmsIsVitemContent (contentType, pType->param.szName))
+                               totalLength += 2;
+               }
+       }
+
+
+       /* Name = Text-string ------------------------------------------------------ */
+
+       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);
+               } 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);
+               }
+
+               //change empty space to '_' in the file name
+               if (MsgIsSpace(pszName)) {
+                       char *pszTempName = NULL;
+
+                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: szName has space(' '). \n");
+
+                       MsgReplaceSpecialChar(pszName, &pszTempName, ' ');
+
+                       if (pszTempName) {
+                               free(pszName);
+                               pszName = pszTempName;
+                       }
+                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: pszName : %s\n", pszName);
+               }
+
+               length = __MmsBinaryEncodeTextStringLen((UINT8*)pszName);
+               free(pszName);
+
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: szName MmsBinaryEncodeIntegerLen fail \n");
+                       goto __CATCH;
+               }
+
+               totalLength += (length + 1);
+       }
+
+#ifdef FEATURE_JAVA_MMS
+       if (pType->param.szApplicationID) {
+               length = __MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szApplicationID);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: szApplicationID MmsBinaryEncodeTextStrinLen fail \n");
+                       goto __CATCH;
+               }
+
+               totalLength += (length);
+               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);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: szApplicationID MmsBinaryEncodeTextStrinLen fail \n");
+                       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 */
+               } else {
+                       totalLength++;
+               }
+       }
+#endif
+
+       /* 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);
+               if (fieldValue == UNDEFINED_BINARY || fieldValue == 0x0049) {
+                       /* Extension-media type */
+                       szTextType = MmsGetTextValue(MmsCodeContentType, pType->param.type);
+                       if (szTextType != NULL) {
+                               length  = __MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
+                               if (length == -1) {
+                                       MSG_DEBUG("MmsBinaryEncodeContentTypeLen: type param MmsBinaryEncodeTextStringLen fail \n");
+                                       goto __CATCH;
+                               }
+                               totalLength += (length + 1);
+                       } else {
+                               totalLength += 2;
+                       }
+               } else {
+                       totalLength += 2;
+               }
+
+               /* start = Text-string ----------------------- */
+               if (pType->param.szStart[0]) {
+                       /* start = Text-string */
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStart);
+                       if (length == -1) {
+                               MSG_DEBUG("MmsBinaryEncodeContentType: szStart MmsBinaryEncodeTextStringLen fail \n");
+                               goto __CATCH;
+                       }
+
+                       totalLength += (length + 1);
+               }
+
+
+               /* startInfo = Text-string -------------------- */
+               if (pType->param.szStartInfo[0]) {
+                       /* StartInfo (with multipart/related) = Text-string */
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStartInfo);
+                       if (length == -1) {
+                               MSG_DEBUG("MmsBinaryEncodeContentType: szStartInfo MmsBinaryEncodeTextStringLen fail \n");
+                               goto __CATCH;
+                       }
+
+                       totalLength += (length + 1);
+               }
+       }
+
+       return totalLength;
+
+__CATCH:
+
+       MSG_DEBUG("## MmsBinaryEncodeContentTypeLen: failed");
+       return -1;
+}
+
+static bool __MmsBinaryEncodeContentType(FILE *pFile, MsgType *pType, int typeLength)
+{
+       int length = 0;
+       UINT16 fieldValue = 0xffff;
+       const char *szTextType = NULL;
+       int contentType = MIME_UNKNOWN;
+
+#ifdef FEATURE_JAVA_MMS
+       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
+        *                                              Constrained-encoding = Extension-Media | Short-integer
+        *                                              Extension-media = *TEXT End-of-string
+        * Content-general-form = Value-length Media-type
+        *                                              Media-type = (Well-known-media | Extension-Media) *(Parameter)
+        */
+
+       if (pFile == NULL) {
+               MSG_DEBUG("MmsBinaryEncodeContentType: invalid file handle\n");
+               goto __CATCH;
+       }
+
+
+       /* Content-Type = Content-general-form ------------------------------- */
+
+       length = __MmsBinaryEncodeValueLengthLen(typeLength);
+       if (length == -1) {
+               MSG_DEBUG("MSmsBinaryEncodeContentType : MmsBinaryEncodeValueLengthLen fail.\n");
+               goto __CATCH;
+       }
+
+       if (__MmsBinaryEncodeValueLength(pFile, typeLength, length) == false) {
+               MSG_DEBUG("MSmsBinaryEncodeContentType : MmsBinaryEncodeValueLength fail.\n");
+               goto __CATCH;
+       }
+
+       contentType = pType->type;
+
+       fieldValue = MmsGetBinaryValue(MmsCodeContentType, (int)contentType);
+       if (fieldValue == UNDEFINED_BINARY || fieldValue == 0x0049) {
+               /* Extension-media type */
+               szTextType = MmsGetTextValue(MmsCodeContentType, (int)contentType);
+               if (szTextType == NULL)
+                       fieldValue = 0x00;
+       }
+
+       if (szTextType == NULL) {
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)fieldValue | 0x80;
+       } else {
+               length  = __MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
+               if (length == -1) {
+                       MSG_DEBUG("MSmsBinaryEncodeContentType: szTextType MmsBinaryEncodeTextStringLen fail \n");
+                       goto __CATCH;
+               }
+
+               if (__MmsBinaryEncodeTextString(pFile, (UINT8*)szTextType, length) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeContentType: szTextType MmsBinaryEncodeTextString fail \n");
+                       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);
+               } 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);
+               }
+
+               //change empty space to '_' in the file name
+               if (MsgIsSpace(pszName)) {
+                       char*   pszTempName = NULL;
+
+                       MSG_DEBUG("MmsBinaryEncodeContentType: szName has space(' '). \n");
+
+                       MsgReplaceSpecialChar(pszName, &pszTempName, ' ');
+
+                       if (pszTempName) {
+                               free(pszName);
+                               pszName = pszTempName;
+                       }
+                       MSG_DEBUG("MmsBinaryEncodeContentType: pszName : %s\n", pszName);
+               }
+
+               length = __MmsBinaryEncodeTextStringLen((UINT8*)pszName);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentType: szName MmsBinaryEncodeIntegerLen fail \n");
+                       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");
+                       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);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentType: szApplicationID MmsBinaryEncodeIntegerLen Fail \n");
+                       goto __CATCH;
+               }
+
+               fieldValue = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_APPLICATION_ID);
+
+               if (fieldValue == UNDEFINED_BINARY)
+                       szParameter = MmsGetTextValue(MmsCodeParameterCode, MSG_PARAM_APPLICATION_ID);
+
+               if (szParameter == NULL) {
+                       MSG_DEBUG("MmsBinaryEncodeContentType: szParameter is NULL \n");
+                       goto __CATCH;
+               }
+
+               strncpy(gpMmsEncodeBuf + gCurMmsEncodeBuffPos, (char*)szParameter, strlen(szParameter));
+               gCurMmsEncodeBuffPos += strlen(szParameter);
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] =(UINT8)NULL;
+
+               if (__MmsBinaryEncodeTextString(pFile, (UINT8*) pType->param.szApplicationID, length) == false) {
+                       MSG_DEBUG(" MmsBinaryEncodeContentType: szApplicationID MmsBinaryEncodeTextString fail\n");
+                       goto __CATCH;
+               }
+
+       }
+
+       /* ReplyToApplicationID: Text-string */
+       if (pType->param.szReplyToApplicationID) {
+               length = __MmsBinaryEncodeTextStringLen((UINT8*) pType->param.szReplyToApplicationID);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentType: szReplyToApplicationID MmsBinaryEncodeIntegerLen Fail \n");
+                       goto __CATCH;
+               }
+
+               fieldValue = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_REPLY_TO_APPLICATION_ID);
+
+               if (fieldValue == UNDEFINED_BINARY)
+                       szParameter = MmsGetTextValue(MmsCodeParameterCode, MSG_PARAM_REPLY_TO_APPLICATION_ID);
+
+               if (szParameter == NULL) {
+                       MSG_DEBUG("MmsBinaryEncodeContentType: szParameter is NULL \n");
+                       goto __CATCH;
+               }
+
+               strncpy(gpMmsEncodeBuf + gCurMmsEncodeBuffPos, (char*)szParameter, strlen(szParameter));
+               gCurMmsEncodeBuffPos += strlen(szParameter);
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] =(UINT8)NULL;
+
+               if (__MmsBinaryEncodeTextString(pFile, (UINT8*) pType->param.szReplyToApplicationID, length) == false) {
+                       MSG_DEBUG(" MmsBinaryEncodeContentType: szApplicationID MmsBinaryEncodeTextString fail\n");
+                       goto __CATCH;
+               }
+       }
+#endif
+
+       /* Well-known-charset = Any-charset | Integer-value ----------------------- */
+
+       if (pType->param.charset != MSG_CHARSET_UNKNOWN) {
+               fieldValue = MmsGetBinaryValue(MmsCodeCharSet, pType->param.charset);
+               length = __MmsBinaryEncodeIntegerLen(fieldValue);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentType: charSet MmsBinaryEncodeIntegerLen fail \n");
+                       goto __CATCH;
+               }
+
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_CHARSET) | 0x80;
+               if (__MmsBinaryEncodeInteger(pFile, fieldValue, length) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeContentType: charSet MmsBinaryEncodeInteger fail\n");
+                       goto __CATCH;
+               }
+       } else {
+               /* Any-charset */
+               if (MmsIsText(contentType)) {
+                       if (!MmsIsVitemContent (contentType, pType->param.szName)) {
+                               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeParameterCode, MSG_PARAM_CHARSET) | 0x80;
+                               fieldValue = 0x0000;    //laconic_warning, just to remove warning message
+                               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)fieldValue | 0x80;
+                       }
+               }
+       }
+
+       /* 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);
+               if (fieldValue == UNDEFINED_BINARY || fieldValue == 0x0049) {
+                       /* Extension-media 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;
+               } else {
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)szTextType);
+                       if (length == -1) {
+                               MSG_DEBUG("MmsBinaryEncodeContentType: type param MmsBinaryEncodeTextStringLen fail \n");
+                               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");
+                               goto __CATCH;
+                       }
+               }
+
+               /* start = Text-string ----------------------- */
+               if (pType->param.szStart[0]) {
+                       /* start = Text-string */
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStart);
+                       if (length == -1) {
+                               MSG_DEBUG("MmsBinaryEncodeContentType: szStart MmsBinaryEncodeTextStringLen fail \n");
+                               goto __CATCH;
+                       }
+
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeParameterCode,
+                                                                                                                                                MSG_PARAM_START) | 0x80;
+                       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)pType->param.szStart, length) == false) {
+                               MSG_DEBUG("MmsBinaryEncodeContentType: szStart MmsBinaryEncodeTextString fail \n");
+                               goto __CATCH;
+                       }
+               }
+
+               /* startInfo = Text-string -------------------- */
+               if (pType->param.szStartInfo[0]) {
+                       /* StartInfo (with multipart/related) = Text-string */
+                       length  = __MmsBinaryEncodeTextStringLen((UINT8*)pType->param.szStartInfo);
+                       if (length == -1) {
+                               MSG_DEBUG("MmsBinaryEncodeContentType: szStartInfo MmsBinaryEncodeTextStringLen fail \n");
+                               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");
+                               goto __CATCH;
+                       }
+               }
+       }
+
+       return true;
+
+__CATCH:
+       MSG_DEBUG("## MmsBinaryEncodeContentType: failed");
+       return false;
+}
+
+static bool __MmsBinaryEncodeMsgPart(FILE *pFile, int contentType, MsgType *pType, MsgBody *pBody)
+{
+       FILE *pFile2 = NULL;
+       char *pData = NULL;
+       int     length = 0;
+
+
+       if (pType->offset && pType->size) {
+               /* header length & body length --------------------------- */
+
+               length = __MmsBinaryEncodeUintvarLen(pType->size);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgPart: 1. headerLeng MmsBinaryEncodeUintvarLen fail \n");
+                       goto __CATCH;
+               }
+
+               if (__MmsBinaryEncodeUintvar(pFile, pType->size, length) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgPart: 1. eaderLeng fail \n");
+                       goto __CATCH;
+               }
+
+               length = __MmsBinaryEncodeUintvarLen(pBody->size);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgPart: 1. bodyLeng MmsBinaryEncodeUintvarLen fail \n");
+                       goto __CATCH;
+               }
+
+               if (__MmsBinaryEncodeUintvar(pFile, pBody->size, length) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgPart: 1. bodyLeng fail \n");
+                       goto __CATCH;
+               }
+
+               pFile2 = MsgOpenFile(pType->szOrgFilePath, "rb");
+               if (pFile != NULL) {
+                       pData = (char *)malloc(pType->size);
+                       if (pData == NULL)
+                               goto __CATCH;
+
+                       if (MsgFseek(pFile2, pType->offset, SEEK_SET) < 0) {
+                               MSG_DEBUG("MmsBinaryEncodeMsgPart: MsgFseek fail \n");
+                               goto __CATCH;
+                       }
+
+                       ULONG nRead = 0;
+
+                       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");
+                                       goto __CATCH;
+                               }
+                               pType->offset = __MmsGetEncodeOffset();
+                               if(MsgWriteFile(pData, sizeof(char), nRead, pFile) != (size_t)nRead) {
+                                       MSG_DEBUG("MsgWriteFile failed");
+                                       goto __CATCH;
+                               }
+                               gMmsEncodeCurOffset = MsgFtell(pFile);
+                               if(gMmsEncodeCurOffset < 0) {
+                                       MSG_DEBUG("MsgFtell returns negative value [%ld]", gMmsEncodeCurOffset);
+                                       goto __CATCH;
+                               }
+                       }
+
+                       MsgCloseFile(pFile2);
+                       pFile2 = NULL;
+               }
+       } else {
+               int headerLeng     = 0;
+               int contentTypeLen = 0;
+               int contentHdrLen  = 0;
+
+               /* header length & body length --------------------------- */
+               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");
+                       goto __CATCH;
+               }
+
+               headerLeng = contentTypeLen + contentHdrLen + length;
+               length = __MmsBinaryEncodeUintvarLen(headerLeng);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgPart: headerLeng MmsBinaryEncodeUintvarLen fail \n");
+                       goto __CATCH;
+               }
+
+               if (__MmsBinaryEncodeUintvar(pFile, headerLeng, length) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgPart: headerLeng fail \n");
+                       goto __CATCH;
+               }
+
+               length = __MmsBinaryEncodeUintvarLen(pBody->size);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgPart: bodyLeng MmsBinaryEncodeUintvarLen fail \n");
+                       goto __CATCH;
+               }
+
+               if (__MmsBinaryEncodeUintvar(pFile, pBody->size, length) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgPart: bodyLeng fail \n");
+                       goto __CATCH;
+               }
+
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgPart: 2. header MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+
+               /* content-type & header --------------------------- */
+               pType->offset = __MmsGetEncodeOffset();
+
+               if (__MmsBinaryEncodeContentType(pFile, pType, contentTypeLen) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgPart: MmsBinaryEncodeContentType fail \n");
+                       goto __CATCH;
+               }
+
+               if (__MmsBinaryEncodeContentHeader(pFile, (MimeType)contentType, pType, true) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeMsgPart: MmsBinaryEncodeContentHeader fail \n");
+                       goto __CATCH;
+               }
+
+               pType->size = __MmsGetEncodeOffset() - pType->offset;
+       }
+
+       if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos, gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+               MSG_DEBUG("MmsBinaryEncodeMsgPart: contentBody MsgWriteDataFromEncodeBuffer fail \n");
+               goto __CATCH;
+       }
+
+       /* content-body --------------------------- */
+       if (__MmsBinaryEncodeContentBody(pFile, pBody) == false) {
+               MSG_DEBUG("MmsBinaryEncodeMsgPart: __MmsBinaryEncodeContentBody fail \n");
+               goto __CATCH;
+       }
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       return true;
+
+__CATCH:
+
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       MSG_DEBUG("## MmsBinaryEncodeMsgPart: failed\n");
+       if (pFile2) {
+               MsgCloseFile(pFile2);
+               pFile2 = NULL;
+       }
+
+       return false;
+}
+
+static int __MmsBinaryEncodeContentHeaderLen(MimeType contentType, MsgType *pType, bool bMultipart)
+{
+       int     length = 0;
+       int     totalLength = 0;
+       const char *szTextValue = NULL;
+
+
+       MSG_DEBUG("MmsBinaryEncodeContentHeaderLen: S T A R T \n\n");
+
+       /* content-id ------------------------------------------------- */
+       if (pType->szContentID[0]) {
+               if (bMultipart) { //Binary Encoding
+                       totalLength++;
+               } else {
+                       /* content-id = Quoted-string */
+                       length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-ID");
+                       if (length == -1) {
+                               MSG_DEBUG("MmsBinaryEncodeContentHeaderLen: Content-ID MmsBinaryEncodeTextStringLen fail.\n");
+                               goto __CATCH;
+                       }
+
+                       totalLength += length;
+               }
+
+               length = __MmsBinaryEncodeQuotedStringLen((UINT8*)pType->szContentID);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentID MmsBinaryEncodeQuotedStringLen fail.\n");
+                       goto __CATCH;
+               }
+               totalLength += length;
+       }
+
+
+       if (pType->szContentLocation[0]) {
+               if (bMultipart) { //Binary Encoding
+                       totalLength++;
+               } else {
+                       /* content-location = Quoted-string */
+                       length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-Location");
+                       if (length == -1) {
+                               MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Location MmsBinaryEncodeTextStringLen fail.\n");
+                               goto __CATCH;
+                       }
+
+                       totalLength += length;
+               }
+
+               length = __MmsBinaryEncodeTextStringLen((UINT8*)pType->szContentLocation);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentLocation MmsBinaryEncodeTextStringLen fail.\n");
+                       goto __CATCH;
+               }
+
+               totalLength += length;
+       }
+
+
+       /* MIME_APPLICATION_VND_WAP_MULTIPART_RELATEDrequires always "inline" */
+
+       if (contentType != MIME_APPLICATION_VND_WAP_MULTIPART_RELATED &&
+               contentType != MIME_MULTIPART_RELATED &&
+               pType->disposition != INVALID_VALUE) {
+
+               /*
+                * Content-disposition-value = Value-length Disposition *(Parameter)
+                * Disposition = Form-data | Attachment | Inline | Token-text
+                * Form-data = <Octet 128> : 0x80
+                * Attachment = <Octet 129> : 0x81
+                * Inline = <Octet 130> : 0x82
+                */
+
+               if (bMultipart) { //Binary Encoding
+                       totalLength += 3;
+               } else {
+                       /* content-disposition = Quoted-string */
+                       szTextValue = MmsGetTextValue(MmsCodeMsgDisposition, pType->disposition);
+
+                       if (szTextValue) {
+                               length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-Disposition");
+                               if (length == -1) {
+                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextStringLen fail.\n");
+                                       goto __CATCH;
+                               }
+
+                               totalLength += length;
+
+                               length = __MmsBinaryEncodeTextStringLen((UINT8*)szTextValue);
+                               if (length == -1) {
+                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextStringLen fail.\n");
+                                       goto __CATCH;
+                               }
+                               totalLength += length;
+                       }
+               }
+       }
+
+       return totalLength;
+
+__CATCH:
+       MSG_DEBUG("## MmsBinaryEncodeContentHeadeLen: failed");
+
+       return -1;
+}
+
+static bool __MmsBinaryEncodeContentHeader(FILE *pFile, MimeType contentType, MsgType *pType, bool bMultipart)
+{
+       int     length = 0;
+       const char *szTextValue = NULL;
+
+       MSG_DEBUG("MmsBinaryEncodeContentHeader: S T A R T \n\n");
+
+       /* content-id ------------------------------------------------- */
+       if (pType->szContentID[0]) {
+               if (bMultipart) { //Binary Encoding
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeMsgBodyHeaderCode, MMS_BODYHDR_CONTENTID) | 0x80;
+               } else {
+                       /* content-id = Quoted-string */
+                       length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-ID");
+                       if (length == -1) {
+                               MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-ID MmsBinaryEncodeTextStringLen fail.\n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)"Content-ID", length) == false) {
+                               MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-ID MmsBinaryEncodeTextString fail.\n");
+                               goto __CATCH;
+                       }
+               }
+
+               length = __MmsBinaryEncodeQuotedStringLen((UINT8*)pType->szContentID);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentID MmsBinaryEncodeQuotedStringLen fail.\n");
+                       goto __CATCH;
+               }
+
+               if (__MmsBinaryEncodeQuotedString(pFile, (UINT8*)pType->szContentID, length) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentID MmsBinaryEncodeQuotedString fail.\n");
+                       goto __CATCH;
+               }
+       }
+
+       if (pType->szContentLocation[0]) {
+               if (bMultipart) { //Binary Encoding
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeMsgBodyHeaderCode, MMS_BODYHDR_CONTENTLOCATION) | 0x80;
+               } else {
+                       /* content-location = Quoted-string */
+                       length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-Location");
+                       if (length == -1) {
+                               MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Location MmsBinaryEncodeTextStringLen fail.\n");
+                               goto __CATCH;
+                       }
+
+                       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)"Content-Location", length) == false) {
+                               MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Location MmsBinaryEncodeTextString fail.\n");
+                               goto __CATCH;
+                       }
+               }
+
+               length = __MmsBinaryEncodeTextStringLen((UINT8*)pType->szContentLocation);
+               if (length == -1) {
+                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentLocation MmsBinaryEncodeTextStringLen fail.\n");
+                       goto __CATCH;
+               }
+
+               if (__MmsBinaryEncodeTextString(pFile, (UINT8*)pType->szContentLocation, length) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeContentHeader: pType->szContentLocation MmsBinaryEncodeTextString fail.\n");
+                       goto __CATCH;
+               }
+       }
+
+       /* MIME_APPLICATION_VND_WAP_MULTIPART_RELATEDrequires always "inline" */
+
+       if (contentType != MIME_APPLICATION_VND_WAP_MULTIPART_RELATED &&
+               contentType != MIME_MULTIPART_RELATED &&
+               pType->disposition != INVALID_VALUE) {
+
+               /*
+                * Content-disposition-value = Value-length Disposition *(Parameter)
+                * Disposition = Form-data | Attachment | Inline | Token-text
+                * Form-data = <Octet 128> : 0x80
+                * Attachment = <Octet 129> : 0x81
+                * Inline = <Octet 130> : 0x82
+                */
+
+               if (bMultipart) {//Binary Encoding
+
+                       UINT8 fieldValue  = 0xff;
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeMsgBodyHeaderCode, MMS_BODYHDR_DISPOSITION) | 0x80;
+
+                       fieldValue = MmsGetBinaryValue(MmsCodeMsgDisposition, pType->disposition) | 0x80;
+
+                       if (fieldValue == 0xff)
+                               fieldValue = 0x81;
+
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = 0x01;
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = fieldValue;
+               } else {
+                       /* content-disposition = Disposition (no support parameter) */
+
+                       szTextValue = MmsGetTextValue(MmsCodeMsgDisposition, pType->disposition);
+
+                       if (szTextValue) {
+                               length = __MmsBinaryEncodeTextStringLen((UINT8*)"Content-Disposition");
+                               if (length == -1) {
+                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextStringLen fail.\n");
+                                       goto __CATCH;
+                               }
+
+                               if (__MmsBinaryEncodeTextString(pFile, (UINT8*)"Content-Disposition", length) == false) {
+                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextString fail.\n");
+                                       goto __CATCH;
+                               }
+
+                               length = __MmsBinaryEncodeTextStringLen((UINT8*)szTextValue);
+                               if (length == -1) {
+                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextStringLen fail.\n");
+                                       goto __CATCH;
+                               }
+
+                               if (__MmsBinaryEncodeTextString(pFile, (UINT8*)szTextValue, length) == false) {
+                                       MSG_DEBUG("MmsBinaryEncodeContentHeader: Content-Disposition MmsBinaryEncodeTextString fail.\n");
+                                       goto __CATCH;
+                               }
+                       }
+               }
+       }
+
+       return true;
+
+__CATCH:
+       MSG_DEBUG("## MmsBinaryEncodeContentHeader: failed");
+       return false;
+}
+
+static bool __MmsBinaryEncodeContentBody(FILE *pFile, MsgBody *pBody)
+{
+       int nRead = 0;
+       char *pData = NULL;
+
+
+       if (pFile == NULL)
+               goto __CATCH;
+
+       if (pBody == NULL)
+               return true;
+
+       if (pBody->szOrgFilePath[0]) {
+               pData = MsgOpenAndReadMmsFile(pBody->szOrgFilePath, pBody->offset, pBody->size, &nRead);
+               if (pData == NULL)
+                       goto __CATCH;
+
+               pBody->offset = __MmsGetEncodeOffset();
+               if(MsgWriteFile(pData, sizeof(char), nRead, pFile) != (size_t)nRead) {
+                       MSG_DEBUG("MsgWriteFile failed");
+                       goto __CATCH;
+               }
+               gMmsEncodeCurOffset = MsgFtell(pFile);
+
+               if (gMmsEncodeCurOffset < 0) {
+                       MSG_DEBUG("MsgFtell returns negative value [%ld]", gMmsEncodeCurOffset);
+                       goto __CATCH;
+               }
+
+               if (pData) {
+                       free(pData);
+                       pData = NULL;
+               }
+       } else if (pBody->body.pText && 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;
+               }
+               gMmsEncodeCurOffset = MsgFtell(pFile);
+
+               if(gMmsEncodeCurOffset < 0) {
+                       MSG_DEBUG("MsgFtell returns negative value [%ld]", gMmsEncodeCurOffset);
+                       goto __CATCH;
+               }
+       }
+
+       return true;
+
+__CATCH:
+       MSG_DEBUG("## __MmsBinaryEncodeContentBody: failed\n");
+       if (pData) {
+               free(pData);
+               pData = NULL;
+       }
+
+       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)
+{
+       if (integer < 0x80) {
+               /* short-integer */
+               return 1;
+       } else {
+
+               int     length = 0;
+               /*
+                * Long-integer = Short-length Multi-octet-integer
+                * The Short-length indicates the length of the Multi-octet-integer
+                */
+
+               while (integer) {
+                       length++;
+                       integer = (integer >> 8);
+               }
+
+               length++;       // + Short-length
+
+               return length;
+       }
+}
+
+
+/*
+ * This makes value-length by specified integer value
+ *
+ * @param      length [in] gotten from MmsBinaryEncodeIntegerLen()
+ */
+static bool __MmsBinaryEncodeInteger(FILE *pFile, UINT32 integer, int length)
+{
+       union {
+               UINT32 integer;
+               UINT8 seg[4];
+       } changer;
+
+
+       if (pFile == NULL) {
+               MSG_DEBUG("MmsBinaryEncodeInteger: source == NULL \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeInteger: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       if (integer < 0x80) {
+               /* short-integer */
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)integer | 0x80;
+       } else {
+               /*
+                * Long-integer = Short-length Multi-octet-integer
+                * The Short-length indicates the length of the Multi-octet-integer
+                */
+               changer.integer = integer;
+               length--;                                       // - "Short-length"
+
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)length;
+
+               int i;
+               for(i = 0; i < length; i++)
+                       gpMmsEncodeBuf[gCurMmsEncodeBuffPos + i] = changer.seg[length - (i + 1)];
+
+               gCurMmsEncodeBuffPos += length;
+       }
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+static int __MmsBinaryEncodeLongIntegerLen(UINT32 integer)
+{
+       int length = 0;
+
+       /*
+        * Long-integer = Short-length Multi-octet-integer
+        * The Short-length indicates the length of the Multi-octet-integer
+        */
+
+       if (integer == 0)
+               return 2;
+
+       while (integer) {
+               length++;
+               integer = (integer >> 8);
+       }
+
+       length++;       // + Short-length
+
+       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)
+{
+       int i  = 0;
+       union {
+               UINT32 integer;
+               UINT8 seg[4];
+       }changer;
+
+
+       /*
+        * Long-integer = Short-length Multi-octet-integer
+        * The Short-length indicates the length of the Multi-octet-integer
+        */
+
+       if (pFile == NULL) {
+               MSG_DEBUG("MmsBinaryEncodeLongInteger: source == NULL \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeLongInteger: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       changer.integer = integer;
+       length--;                                       // - "Short-length"
+
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)length;
+
+       for(i = 0; i < length; i++)
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos + i] = changer.seg[length - (i + 1)];
+
+       gCurMmsEncodeBuffPos += length;
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+static int __MmsBinaryEncodeTextStringLen(UINT8 *source)
+{
+       int      length = 0;
+
+       MSG_DEBUG("MmsBinaryEncodeTextStringLen: \n");
+
+       if (source == NULL) {
+               MSG_DEBUG("MmsBinaryEncodeTextStringLen: source == NULL \n");
+               return -1;
+       }
+
+       length = (int)strlen((char*)source);
+       if (source[0] > 0x7F) {
+               length += 2;                    // + NULL
+       } else {
+               length++;                               // + NULL
+       }
+
+       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)
+{
+
+       MSG_DEBUG("MmsBinaryEncodeTextString: \n");
+
+       /*
+        * make text string
+        * Text-string = [Quote] *TEXT End-of-string
+        * If the 1st char in the TEXT is in the range of 128-255, a Quote char must precede it.
+        * Otherwise the Quote char must be omitted.
+        * The Quote is not part of the contents.
+        * Quote = <Octet 127>
+        */
+
+       if (pFile == NULL || source == NULL) {
+               MSG_DEBUG("MmsBinaryEncodeTextString: source == NULL \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeTextString: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       if (source[0] > 0x7F) {
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = QUOTE;
+               length--;
+       }
+
+       strncpy(gpMmsEncodeBuf + gCurMmsEncodeBuffPos, (char*)source, (length - 1));    // except NULL
+       gCurMmsEncodeBuffPos += (length - 1);                   // except NULL
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)NULL;
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+/*
+ * Encode 28bit unsigned integer(Maximum) to uintvar
+ *
+ * @param      interger [in] integer to be encoded
+ * @return     encoded UINTVAR stream
+*/
+const UINT32 UINTVAR_LENGTH_1 =  0x0000007f;           //7bit
+const UINT32 UINTVAR_LENGTH_2 =  0x00003fff;           //14bit
+const UINT32 UINTVAR_LENGTH_3 =  0x001fffff;           //21bit
+
+
+static int __MmsBinaryEncodeUintvarLen(UINT32 integer)
+{
+       UINT32          length  = 0;
+
+       /* Find encoded unitvar length */
+       if (integer  <= UINTVAR_LENGTH_1) {
+               length = 1;
+       } else {
+               if (integer <= UINTVAR_LENGTH_2) {
+                       length = 2;
+               } else {
+                       if (integer <= UINTVAR_LENGTH_3) {
+                               length = 3;
+                       } else {
+                               length = 4;
+                       }
+               }
+       }
+
+       return length;
+}
+
+static bool __MmsBinaryEncodeUintvar(FILE *pFile, UINT32 integer, int length)
+{
+       const char ZERO = 0x00;
+       int i = 2;
+       char szReverse[MSG_STDSTR_LONG] = {0, };
+
+       union {
+               UINT32  integer;
+               char    bytes[4];
+       } source;
+
+       if (pFile == NULL) {
+               MSG_DEBUG("MmsBinaryEncodeUintvar: pFile == INVALID_HBOJ \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeUintvar: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       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++)
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = szReverse[length - i - 1];
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+static int __MmsBinaryEncodeValueLengthLen(UINT32 integer)
+{
+       int length = 0;
+
+       if (integer < 0x1f) {
+               length = 1;
+       } else {
+               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)
+{
+       /*
+        * Value-length = Short-length | (Length-quote Length)
+        * ; Value length is used to indicate the length of the value to follow
+        * Short-length = <Any octet 0-30>
+        * Length-quote = <Octet 31>
+        * Length = Uintvar-integer
+        */
+
+       if (pFile == NULL) {
+               MSG_DEBUG("MmsBinaryEncodeValueLength: pFile == INVALID_HBOJ \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeValueLength: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       if (integer < 0x1F) {
+               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");
+                       goto __CATCH;
+               }
+       }
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+static int __MmsBinaryEncodeQuotedStringLen(UINT8 *pSrc)
+{
+       if (pSrc == NULL) {
+               MSG_DEBUG("MmsBinaryEncodeQuotedStringLen: invalid file\n");
+               goto __CATCH;
+       }
+
+       return (strlen((char*)pSrc) + 2);       // QUOTE + NULL
+
+__CATCH:
+       return -1;
+}
+
+/*
+ * make quoted string
+ * Quoted-string = <Octet 34> *TEXT End-of-string
+ *
+ * @param      source [in] original string
+ * @param      length [in] length (in bytes) of data
+ * @param      dest [out] buffer to store quted string
+ * @return     changed string length
+*/
+static bool __MmsBinaryEncodeQuotedString(FILE *pFile, UINT8 *source, int length)
+{
+       if (source == NULL || pFile == NULL) {
+               MSG_DEBUG("MmsBinaryEncodeQuotedString: invalid file\n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeQuotedString: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = '\"';
+       strncpy(gpMmsEncodeBuf + gCurMmsEncodeBuffPos, (char*)source, length - 2);              // except '\"' & NULL
+       gCurMmsEncodeBuffPos += (length - 2);
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = (UINT8)NULL;
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+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);
+       if (charLeng == -1) {
+               MSG_DEBUG("MmsBinaryEncodeEncodedStringLen : charLeng MmsBinaryEncodeTextStringLen fail.\n");
+               goto __CATCH;;
+       }
+
+       textLeng = __MmsBinaryEncodeTextStringLen((UINT8*)source);
+       if (textLeng == -1)     {
+               MSG_DEBUG("MmsBinaryEncodeEncodedStringLen : textLeng MmsBinaryEncodeTextStringLen fail.\n");
+               goto __CATCH;;
+       }
+
+       valueLengthLen = __MmsBinaryEncodeValueLengthLen(charLeng + textLeng);
+       if (valueLengthLen == -1) {
+               MSG_DEBUG("MmsBinaryEncodeEncodedStringLen : valLengthLen MmsBinaryEncodeTextStringLen fail.\n");
+               goto __CATCH;
+       }
+
+       return (charLeng + textLeng + valueLengthLen);
+
+__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)
+{
+       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");
+               goto __CATCH;
+       }
+
+       /* Estimate charset value length and text string length */
+       charLeng = __MmsBinaryEncodeIntegerLen(charset);
+       if (charLeng == -1) {
+               MSG_DEBUG("MmsBinaryEncodeEncodedString : charLeng MmsBinaryEncodeTextStringLen fail.\n");
+               goto __CATCH;;
+       }
+
+       textLeng = __MmsBinaryEncodeTextStringLen((UINT8*)source);
+       if (textLeng == -1) {
+               MSG_DEBUG("MmsBinaryEncodeEncodedString : textLeng MmsBinaryEncodeTextStringLen fail.\n");
+               goto __CATCH;;
+       }
+
+       valLengthLen = __MmsBinaryEncodeValueLengthLen(charLeng + textLeng);
+       if (valLengthLen == -1) {
+               MSG_DEBUG("MmsBinaryEncodeEncodedString : MmsBinaryEncodeValueLengthLen fail.\n");
+               goto __CATCH;
+       }
+
+       if (length != (charLeng + textLeng + valLengthLen))
+       {
+               MSG_DEBUG("MmsBinaryEncodeEncodedString: invalid length\n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("MmsBinaryEncodeEncodedString: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       /* Value length of charset value and text string */
+       if (__MmsBinaryEncodeValueLength(pFile, charLeng + textLeng, valLengthLen) == false) {
+               MSG_DEBUG("MmsBinaryEncodeEncodedString : MmsBinaryEncodeValueLength fail.\n");
+               goto __CATCH;
+       }
+
+       /* fixme: Write charset on buffer -> integer value not long-integer */
+       if (__MmsBinaryEncodeInteger(pFile, charset, charLeng) == false) {
+               MSG_DEBUG("MmsBinaryEncodeEncodedString : MmsBinaryEncodeInteger fail.\n");
+               goto __CATCH;
+       }
+
+
+       /* Write text string on buffer */
+       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)source, textLeng) == false) {
+               MSG_DEBUG("MmsBinaryEncodeEncodedString : MmsBinaryEncodeTextString fail.\n");
+               goto __CATCH;
+       }
+
+       return true;
+
+__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");
+                       goto __CATCH;
+               }
+       }
+
+       if (fieldCode == 0xff) {
+               MSG_DEBUG("__MmsBinaryEncodeFieldCodeAndValue: invalid fieldCode \n");
+               goto __CATCH;
+       }
+
+       if (fieldValue == 0xff) {
+               MSG_DEBUG("__MmsBinaryEncodeFieldCodeAndValue: invalid fieldValue \n");
+               return true;
+       }
+
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = fieldCode;
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = fieldValue;
+
+       return true;
+
+__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;
+
+       time(&RawTime);
+       dateTime = localtime(&RawTime);
+       dateSec = mktime(dateTime);
+
+
+       fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_TRID) | 0x80;
+       if (fieldCode == 0xff) {
+               MSG_DEBUG("__MmsBinaryEncodeTrID: invalid fieldCode \n");
+               goto __CATCH;
+       }
+
+       snprintf(szBuff, MMS_TR_ID_LEN + 1, "%lu.%lu", dateSec, (unsigned long)random());
+       MSG_DEBUG("__MmsBinaryEncodeTrID: 2. szBuff = %s\n", szBuff);
+
+       length = __MmsBinaryEncodeTextStringLen((UINT8*)szBuff);
+       if (length == -1) {
+               MSG_DEBUG("__MmsBinaryEncodeTrID: MmsBinaryEncodeTextStringLen fail \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < (length + 1)) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("__MmsBinaryEncodeTrID: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = fieldCode;
+       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)szBuff, length) == false) {
+               MSG_DEBUG("__MmsBinaryEncodeTrID: MmsBinaryEncodeTextString fail\n");
+               goto __CATCH;
+       }
+
+       if (szTrID) {
+               memset(szTrID, 0, bufLen);
+               strncpy(szTrID, szBuff, bufLen - 1);
+       }
+
+       return true;
+
+__CATCH:
+
+       return false;
+}
+
+static bool __MmsBinaryEncodeMsgID(FILE *pFile, const char *szMsgID)
+{
+       int     length = 0;
+       UINT8 fieldCode = 0xff;
+
+       fieldCode = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_MSGID) | 0x80;
+       if (fieldCode == 0xff) {
+               MSG_DEBUG("__MmsBinaryEncodeTrID: invalid fieldCode \n");
+               goto __CATCH;
+       }
+
+       MSG_DEBUG("__MmsBinaryEncodeMsgID: 2. szBuff = %s\n", szMsgID);
+
+       length = __MmsBinaryEncodeTextStringLen((UINT8*)szMsgID);
+       if (length == -1) {
+               MSG_DEBUG("__MmsBinaryEncodeMsgID: MmsBinaryEncodeTextStringLen fail \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < (length + 1)) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                               gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("__MmsBinaryEncodeTrID: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = fieldCode;
+       if (__MmsBinaryEncodeTextString(pFile, (UINT8*)szMsgID, length) == false)       {
+               MSG_DEBUG("__MmsBinaryEncodeTrID: MmsBinaryEncodeTextString fail\n");
+               goto __CATCH;
+       }
+
+       return true;
+
+__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 ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < 2) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                               gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("__MmsBinaryEncodeMmsVersion: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_VERSION) | 0x80;
+
+       MSG_DEBUG("__MmsBinaryEncodeMmsVersion: major version (%d)\n", majorVer);
+       MSG_DEBUG("__MmsBinaryEncodeMmsVersion: minor version (%d)\n", minorVer);
+
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos] = (majorVer << 4) | (minorVer & 0x0f) | MSB;
+
+       if (gpMmsEncodeBuf[gCurMmsEncodeBuffPos] < 0x80) {
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] |= 0x80;
+       } else {
+               gCurMmsEncodeBuffPos++;
+       }
+
+       return true;
+
+__CATCH:
+       return false;
+}
+
+static bool __MmsBinaryEncodeDate(FILE *pFile)
+{
+       struct  tm      *dateTime = NULL;
+       time_t  dateSec = 0;
+
+       dateSec = time(NULL);
+       dateTime = localtime(&dateSec);
+
+       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);
+
+       if (dateSec > 0) {
+               int     length  = 0;
+               length = __MmsBinaryEncodeLongIntegerLen(dateSec);
+
+               if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < (length + 1)) { // + fieldCode
+                       if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                               gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                               MSG_DEBUG("__MmsBinaryEncodeDate: MsgWriteDataFromEncodeBuffer fail \n");
+                               goto __CATCH;
+                       }
+               }
+
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, MMS_CODE_DATE) | 0x80;
+
+               if (__MmsBinaryEncodeLongInteger(pFile, dateSec, length) == false) {
+                       MSG_DEBUG("__MmsBinaryEncodeDate: date MmsBinaryEncodeLongInteger error\n");
+                       goto __CATCH;
+               }
+       } else {
+               MSG_DEBUG("__MmsBinaryEncodeDate: date has a negative value (%d) \n", dateSec);
+               goto __CATCH;
+       }
+       return true;
+
+__CATCH:
+       return false;
+}
+
+static bool __MmsBinaryEncodeFrom(FILE *pFile)
+{
+       if (pFile == NULL) {
+               MSG_DEBUG("__MmsBinaryEncodeFrom: invalid input file \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < 3) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("__MmsBinaryEncodeFrom: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       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;
+       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");
+               goto __CATCH;
+       }
+
+       /* EncodedString */
+       length = __MmsBinaryEncodeEncodedStringLen((UINT8*)szAddrStr);
+
+       if (length == -1) {
+               MSG_DEBUG("__MmsBinaryEncodeOneAddress: MmsBinaryEncodeEncodedStringLen fail \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < length + 1) {
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("__MmsBinaryEncodeOneAddress: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, addrType) | 0x80;
+
+
+       if (__MmsBinaryEncodeEncodedString(pFile, (UINT8*)szAddrStr, length) == false) {
+               MSG_DEBUG("__MmsBinaryEncodeOneAddress: MmsBinaryEncodeEncodedString fail \n");
+               goto __CATCH;
+       }
+
+       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");
+               goto __CATCH;
+       }
+
+       while (szAddr && szAddr[0]) {
+               szAddr = _MsgSkipWS3(szAddr);
+               if (szAddr == NULL)
+                       break;
+
+               pSingleAddr = strchr(szAddr, MSG_CH_SEMICOLON);
+               if (pSingleAddr) {
+
+                       *pSingleAddr = MSG_CH_NULL;
+                       if (__MmsBinaryEncodeOneAddress(pFile, addrType, szAddr) == false) {
+                               MSG_DEBUG("__MmsBinaryEncodeAddress: __MmsBinaryEncodeAddress fail\n");
+                               goto __CATCH;
+                       }
+                       *pSingleAddr = MSG_CH_SEMICOLON;
+
+                       szAddr           = pSingleAddr + 1;
+                       pSingleAddr  = NULL;
+               } else {
+                       if (__MmsBinaryEncodeOneAddress(pFile, addrType, szAddr) == false) {
+                               MSG_DEBUG("__MmsBinaryEncodeAddress: __MmsBinaryEncodeAddress fail\n");
+                               goto __CATCH;
+                       }
+
+                       szAddr = NULL;
+               }
+       }
+
+       return true;
+
+__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");
+               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);
+               return true;
+       }
+
+       /*
+        * use temporary buffer to estimate value length
+        * and copy it to pData buffer later.
+        */
+
+       if (time.type == MMS_TIMETYPE_RELATIVE) {
+               timeLen = __MmsBinaryEncodeIntegerLen(time.time);
+       } else {
+               timeLen = __MmsBinaryEncodeLongIntegerLen(time.time);
+       }
+
+       if (timeLen <= 0) {
+               MSG_DEBUG("__MmsBinaryEncodeTime: MmsBinaryEncodeLongIntegerLen fail \n");
+               goto __CATCH;
+       }
+
+       length = __MmsBinaryEncodeValueLengthLen(timeLen + 1);  //time length + time type token
+       if (length == -1) {
+               MSG_DEBUG("__MmsBinaryEncodeTime: MmsBinaryEncodeValueLengthLen fail \n");
+               goto __CATCH;
+       }
+
+       if ((gMmsEncodeMaxLen - gCurMmsEncodeBuffPos) < (length + timeLen + 2)) {       // + fieldCode + timeType
+
+               if (MsgWriteDataFromEncodeBuffer(pFile, gpMmsEncodeBuf, &gCurMmsEncodeBuffPos,
+                                                                                       gMmsEncodeMaxLen, &gMmsEncodeCurOffset) == false) {
+                       MSG_DEBUG("_MmsBinaryEncodeSendReqHdr: MsgWriteDataFromEncodeBuffer fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       /* fieldCode */
+       gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeFieldCode, fieldCode) | 0x80;
+
+       /* value length */
+       if (__MmsBinaryEncodeValueLength(pFile, timeLen + 1, length) == false) {
+               MSG_DEBUG("__MmsBinaryEncodeTime: MmsBinaryEncodeValueLength fail \n");
+               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");
+                       goto __CATCH;
+               }
+       } else {
+               gpMmsEncodeBuf[gCurMmsEncodeBuffPos++] = MmsGetBinaryValue(MmsCodeTimeType, MMS_TIMETYPE_ABSOLUTE) | 0x80;
+               if (__MmsBinaryEncodeLongInteger(pFile, time.time, timeLen) == false) {
+                       MSG_DEBUG("__MmsBinaryEncodeTime: MmsBinaryEncodeLongInteger fail \n");
+                       goto __CATCH;
+               }
+       }
+
+       return true;
+
+__CATCH:
+       return false;
+}
diff --git a/plugin/mms_plugin/MmsPluginEventHandler.cpp b/plugin/mms_plugin/MmsPluginEventHandler.cpp
new file mode 100755 (executable)
index 0000000..d4e3265
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MmsPluginTypes.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginEventHandler.h"
+#include "MmsPluginInternal.h"
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginEventHandler - Member Functions
+==================================================================================================*/
+MmsPluginEventHandler *MmsPluginEventHandler::pInstance = NULL;
+
+
+MmsPluginEventHandler::MmsPluginEventHandler()
+{
+       memset(&listener, 0x00, sizeof(MSG_PLUGIN_LISTENER_S));
+}
+
+
+MmsPluginEventHandler::~MmsPluginEventHandler()
+{
+
+}
+
+
+MmsPluginEventHandler *MmsPluginEventHandler::instance()
+{
+       if (!pInstance)
+               pInstance = new MmsPluginEventHandler();
+
+       return pInstance;
+}
+
+
+void MmsPluginEventHandler::registerListener(MSG_PLUGIN_LISTENER_S *pListener)
+{
+       listener = *pListener;
+}
+
+
+void MmsPluginEventHandler::handleMmsReceivedData(mmsTranQEntity *pRequest, char *pRetrievedFilePath)
+{
+       MSG_MESSAGE_INFO_S msgInfo = {0,};
+
+       switch (pRequest->eMmsPduType) {
+       // received data is send-conf
+       case eMMS_SEND_CONF:
+               MmsPluginInternal::instance()->processSendConf(&msgInfo, pRequest);
+
+               // callback to MSG FW
+               listener.pfMmsConfIncomingCb(&msgInfo, &pRequest->reqID);
+
+               //MsgDeleteFile(pRetrievedFilePath + strlen(MSG_DATA_PATH)); // 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:
+               MmsPluginInternal::instance()->processRetrieveConf(&msgInfo, pRequest, pRetrievedFilePath);
+
+               // callback to MSG FW
+               listener.pfMmsConfIncomingCb(&msgInfo, &pRequest->reqID);
+               break;
+
+       case eMMS_FORWARD_CONF:
+               MmsPluginInternal::instance()->processForwardConf(&msgInfo, pRequest);
+               break;
+
+       case eMMS_READREPORT_CONF:
+               if (remove(pRetrievedFilePath) != 0)
+                       MSG_DEBUG("remove fail");
+               break;
+       default:
+               break;
+       }
+}
+
+
+void MmsPluginEventHandler::handleMmsError(mmsTranQEntity *pRequest)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       MSG_MESSAGE_INFO_S msgInfo = {};
+
+       MSG_DEBUG("pRequest->msgId [%d]", pRequest->msgId);
+
+       switch (pRequest->eMmsPduType) {
+       case eMMS_SEND_REQ:
+       case eMMS_SEND_CONF:
+               msgInfo.msgId = pRequest->msgId;
+               //Set only changed members
+               msgInfo.msgType.mainType = MSG_MMS_TYPE;
+
+               if (pRequest->eMmsPduType == eMMS_SEND_REQ)
+                       msgInfo.msgType.subType = MSG_SENDREQ_MMS;
+               else
+                       msgInfo.msgType.subType = MSG_SENDCONF_MMS;
+
+               msgInfo.networkStatus = MSG_NETWORK_SEND_FAIL;
+
+               msgInfo.folderId = MSG_OUTBOX_ID;
+
+               listener.pfMmsConfIncomingCb(&msgInfo, &pRequest->reqID);
+               break;
+
+       case eMMS_RETRIEVE_AUTO:
+       case eMMS_RETRIEVE_AUTO_CONF:
+               msgInfo.msgId = pRequest->msgId;
+               //Set only changed members
+               msgInfo.msgType.mainType = MSG_MMS_TYPE;
+               msgInfo.msgType.subType = MSG_RETRIEVE_AUTOCONF_MMS;
+
+               msgInfo.networkStatus = MSG_NETWORK_RETRIEVE_FAIL;
+               msgInfo.folderId = MSG_INBOX_ID;
+
+               err = listener.pfMmsConfIncomingCb(&msgInfo, &pRequest->reqID);
+
+               break;
+
+       case eMMS_RETRIEVE_MANUAL:
+       case eMMS_RETRIEVE_MANUAL_CONF:
+               msgInfo.msgId = pRequest->msgId;
+               //Set only changed members
+               msgInfo.msgType.mainType = MSG_MMS_TYPE;
+               msgInfo.msgType.subType = MSG_RETRIEVE_MANUALCONF_MMS;
+
+               msgInfo.networkStatus = MSG_NETWORK_RETRIEVE_FAIL;
+               msgInfo.folderId = MSG_INBOX_ID;
+
+               err = listener.pfMmsConfIncomingCb(&msgInfo, &pRequest->reqID);
+
+               break;
+
+       default:
+               break;
+       }
+
+       MSG_END();
+}
+
diff --git a/plugin/mms_plugin/MmsPluginHttp.cpp b/plugin/mms_plugin/MmsPluginHttp.cpp
new file mode 100755 (executable)
index 0000000..d624617
--- /dev/null
@@ -0,0 +1,677 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MmsPluginConnManWrapper.h"
+
+static bool __httpGetHeaderField(MMS_HTTP_HEADER_FIELD_T httpHeaderItem, char *szHeaderBuffer);
+static void __httpGetHost(char *szUrl, 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);
+
+static void __http_print_profile(CURL *curl);
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+static void __http_print_profile(CURL *curl)
+{
+       double speed_upload, speed_download, total_time;
+       double size_up, size_down;
+       double content_length;
+
+       char *content_type = NULL;
+       char *ip = NULL;
+       char *url = NULL;
+
+       long port;
+       long size;
+
+       MSG_DEBUG("**************************************************************************************************");
+
+       //time
+       curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
+       MSG_DEBUG("profile http Time: total %.3f seconds", total_time);
+
+       //url
+       curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
+       MSG_DEBUG("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);
+
+       curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &size_down);
+       MSG_DEBUG("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);
+
+       curl_easy_getinfo(curl, CURLINFO_REQUEST_SIZE, &size);
+       MSG_DEBUG("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);
+
+       curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD, &speed_download);
+       MSG_DEBUG("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);
+
+       curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &content_length);
+       MSG_DEBUG("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);
+
+       //ip & port
+       curl_easy_getinfo(curl, CURLINFO_PRIMARY_IP, &ip);
+       MSG_DEBUG("profile http primary: ip %s", ip);
+
+       curl_easy_getinfo(curl, CURLINFO_PRIMARY_PORT, &port);
+       MSG_DEBUG("profile http primary: port %ld", port);
+
+       curl_easy_getinfo(curl, CURLINFO_LOCAL_IP, &ip);
+       MSG_DEBUG("profile http local: ip %s", ip);
+
+       curl_easy_getinfo(curl, CURLINFO_LOCAL_PORT, &port);
+       MSG_DEBUG("profile http local: port %ld", port);
+
+       MSG_DEBUG("**************************************************************************************************");
+}
+
+static void __httpAllocHeaderInfo(curl_slist **responseHeaders, char *szUrl, int ulContentLen)
+{
+       char szBuffer[1025] = {0, };
+       char pcheader[HTTP_REQUEST_LEN] = {0, };
+
+       bool nResult = __httpGetHeaderField(MMS_HH_CONTENT_TYPE, szBuffer);
+       if (nResult) {
+               snprintf(pcheader, HTTP_REQUEST_LEN, "Content-Type: %s", 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_DEBUG("%s", pcheader);
+                       *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
+               }
+       }
+
+       memset(szBuffer, 0, 1025);
+       memset(pcheader, 0, HTTP_REQUEST_LEN);
+
+       __httpGetHost(szUrl, szBuffer, 1024);
+       if (strlen(szBuffer)){
+               snprintf(pcheader, HTTP_REQUEST_LEN, "Host: %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_ACCEPT, szBuffer);
+       if (nResult) {
+               snprintf(pcheader, HTTP_REQUEST_LEN, "Accept: %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_ACCEPT_CHARSET, szBuffer);
+       if (nResult) {
+               snprintf(pcheader, HTTP_REQUEST_LEN, "Accept-Charset: %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_ACCEPT_LANGUAGE, szBuffer);
+       if (nResult) {
+               snprintf(pcheader, HTTP_REQUEST_LEN, "Accept-Language: %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_ACCEPT_ENCODING, szBuffer);
+       if (nResult) {
+               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) {
+               snprintf(pcheader, HTTP_REQUEST_LEN, "User-Agent: %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_WAP_PROFILE, szBuffer);
+       if (nResult) {
+               snprintf(pcheader, HTTP_REQUEST_LEN, "X-wap-profile: %s", szBuffer);
+               MSG_DEBUG("%s", pcheader);
+               *responseHeaders = curl_slist_append(*responseHeaders, pcheader);
+       }
+
+       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)
+{
+       bool result;
+
+       result = false;
+       if (szHeaderBuffer != NULL) {
+               switch (httpHeaderItem) {
+               case MMS_HH_CONTENT_TYPE:
+                       snprintf((char *)szHeaderBuffer, 1024, "%s", MSG_MMS_HH_CONTENT_TYPE);
+                       result = true;
+                       break;
+
+               case MMS_HH_ACCEPT:
+                       snprintf((char *)szHeaderBuffer, 1024, "%s", MSG_MMS_HH_ACCEPT);
+                       result = true;
+                       break;
+
+               case MMS_HH_ACCEPT_CHARSET:
+                       snprintf((char *)szHeaderBuffer, 1024, "%s", MSG_MMS_HH_CHARSET);
+                       result = true;
+                       break;
+
+               case MMS_HH_ACCEPT_LANGUAGE:
+                       snprintf((char *)szHeaderBuffer, 1024, "%s", MSG_MMS_HH_LANGUAGE);
+                       result = true;
+                       break;
+
+               case MMS_HH_ACCEPT_ENCODING:
+                       snprintf((char *)szHeaderBuffer, 1024, "%s", MSG_MMS_HH_ENCODING);
+                       result = true;
+                       break;
+
+               case MMS_HH_USER_AGENT:
+                       {
+                               char szUserAgent[1024 + 1];
+
+                               memset(szUserAgent, 0x00, sizeof(szUserAgent));
+                               snprintf(szUserAgent, 1024, "%s", MSG_MMS_HH_USER_AGENT);
+
+                               snprintf((char *)szHeaderBuffer, 1024, "%s", szUserAgent);
+                               result = true;
+                       }
+                       break;
+
+               case MMS_HH_WAP_PROFILE:
+                       {
+                               char szUAProfile[1024 + 1] = {0,};
+
+                               memset(szUAProfile, 0x00, (sizeof(char)*(1024+1) ));
+                               snprintf(szUAProfile, 1024, "%s", MSG_MMS_WAP_PROFILE);
+
+                               snprintf((char *)szHeaderBuffer, 1024, "%s", szUAProfile);
+                               result = true;
+                       }
+                       break;
+
+               default:
+                       MSG_DEBUG("invalid param");
+                       break;
+               }
+       }
+
+       return result;
+}
+
+static void __httpGetHost(char *szUrl, char *szHost, int nBufferLen)
+{
+       if (szUrl == NULL || szHost == NULL)
+               return;
+
+       const char *prefixString = "http://";
+       const char *delim = "/\\=@";
+
+       int prefixLength = strlen(prefixString);
+
+       char *startPtr = szUrl;
+       char *movePtr = NULL;
+
+       MSG_DEBUG("startPtr(%s)", startPtr);
+
+       if (strncasecmp(startPtr, prefixString, prefixLength) == 0) {
+               MSG_DEBUG("(%s) exist", prefixString);
+               startPtr += prefixLength;
+               movePtr = startPtr;
+               movePtr = strpbrk(movePtr, delim);
+               MSG_DEBUG("strpbrk --> movePtr(%s)", movePtr);
+               if (movePtr == NULL) {
+                       strncpy(szHost, startPtr, nBufferLen);
+                       MSG_DEBUG("szHost(%s)", szHost);
+               } else {
+                       int nCopyLen = movePtr - startPtr;
+                       strncpy(szHost, startPtr, nCopyLen);
+                       MSG_DEBUG("szHost(%s)", szHost);
+               }
+       } else {
+               MSG_DEBUG("(%s) not exist", prefixString);
+               movePtr = startPtr;
+               movePtr = strpbrk(movePtr, delim);
+               MSG_DEBUG("strpbrk --> movePtr(%s)", movePtr);
+               if (movePtr == NULL) {
+                       strncpy(szHost, startPtr, nBufferLen);
+                       MSG_DEBUG("szHost(%s)", szHost);
+               } else {
+                       int nCopyLen = movePtr - startPtr;
+                       strncpy(szHost, startPtr, nCopyLen);
+                       MSG_DEBUG("szHost(%s)", szHost);
+               }
+       }
+}
+
+static MMS_NET_ERROR_T __httpReceiveData(void *ptr, size_t size, size_t nmemb, void *userdata)
+{
+       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));
+
+                       if (pMmsPlgCd->final_content_buf == NULL) {
+                               MSG_DEBUG("malloc fail");
+                               return eMMS_HTTP_EVENT_RECV_DATA_ERROR;
+                       }
+
+                       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
+
+                       unsigned char * buf = (unsigned char *)realloc(pMmsPlgCd->final_content_buf,
+                                       (pMmsPlgCd->bufOffset + length_received + 1) * sizeof(unsigned char));
+
+                       if (buf == NULL) {
+                               MSG_DEBUG("realloc fail");
+                               return eMMS_HTTP_EVENT_RECV_DATA_ERROR;
+                       }
+
+                       pMmsPlgCd->final_content_buf = buf;
+                       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");
+
+       char deviceName[1024] = {0,};
+
+       MmsPluginCmAgent::instance()->getDeviceName(deviceName);
+
+       MSG_DEBUG("deviceName: [%s]", deviceName);
+       int curl_status = curl_easy_setopt(httpConfig->session, CURLOPT_INTERFACE, deviceName);
+
+       if (curl_status != CURLM_OK) {
+               MSG_DEBUG("curl_easy_setopt(): CURLOPT_INTERFACE failed");
+
+               return eMMS_EXCEPTIONAL_ERROR;
+       }
+
+       CURLcode rc = curl_easy_perform(httpConfig->session);
+
+       __http_print_profile(httpConfig->session);
+
+       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);
+
+               return eMMS_HTTP_ERROR_NETWORK;
+       }
+
+       MSG_DEBUG("## End Transaction ##");
+
+       srandom((unsigned int) time(NULL));
+       trId = random() % 1000000000 + 1;
+       MSG_DEBUG("############ trID = %d ###########", trId);
+
+       httpConfig->transactionId = trId;
+
+       return eMMS_HTTP_SENT_SUCCESS;
+}
+
+static int __httpCmdGetTransaction(MMS_PLUGIN_HTTP_DATA_S *httpConfig)
+{
+       int trId;
+
+       MSG_DEBUG("HttpCmd Get Transaction");
+       MSG_DEBUG(" === HTTP Agent Thread : Signal ==> eMMS_HTTP_SIGNAL_GET_TRANSACTION");
+
+       char deviceName[1024] = {0,};
+       MmsPluginCmAgent::instance()->getDeviceName(deviceName);
+       MSG_DEBUG("deviceName: [%s]", deviceName);
+
+       int curl_status = curl_easy_setopt(httpConfig->session, CURLOPT_INTERFACE, deviceName);
+       if (curl_status != CURLM_OK) {
+               MSG_DEBUG("curl_easy_setopt(): CURLOPT_INTERFACE failed");
+
+               return eMMS_EXCEPTIONAL_ERROR;
+       }
+
+       CURLcode rc = curl_easy_perform(httpConfig->session);
+
+       __http_print_profile(httpConfig->session);
+
+       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 = %d", rc);
+
+               return eMMS_HTTP_ERROR_NETWORK;
+       }
+
+       MSG_DEBUG("## End Transaction ##");
+
+       srandom((unsigned int) time(NULL));
+       trId = random() % 1000000000 + 1;
+       MSG_DEBUG("############ trID = %d ###########", trId);
+
+       httpConfig->transactionId = trId;
+
+       return eMMS_HTTP_SENT_SUCCESS;
+}
+
+MmsPluginHttpAgent *MmsPluginHttpAgent::pInstance = NULL;
+MmsPluginHttpAgent *MmsPluginHttpAgent::instance()
+{
+       if (!pInstance)
+               pInstance = new MmsPluginHttpAgent();
+
+       return pInstance;
+}
+
+
+MmsPluginHttpAgent::MmsPluginHttpAgent()
+{
+       MSG_DEBUG("MmsPluginHttpAgent()");
+
+       bzero(&httpConfigData, sizeof(httpConfigData));
+       bzero(&mmsPlgCd, sizeof(mmsPlgCd));
+
+       httpCmdHandler.clear();
+
+       httpCmdHandler[eHTTP_CMD_INIT_SESSION] = &__httpCmdInitSession;
+       httpCmdHandler[eHTTP_CMD_POST_TRANSACTION] = &__httpCmdPostTransaction;
+       httpCmdHandler[eHTTP_CMD_GET_TRANSACTION] = &__httpCmdGetTransaction;
+}
+
+MmsPluginHttpAgent::~MmsPluginHttpAgent()
+{
+
+}
+
+void MmsPluginHttpAgent::SetMMSProfile()
+{
+       MSG_BEGIN();
+
+       MMSC_CONFIG_DATA_S *mmscConfig = &(httpConfigData.mmscConfig);
+
+       MmsPluginCmAgent::instance()->getHomeURL(mmscConfig->mmscUrl);
+       if (strlen(mmscConfig->mmscUrl) < 1) {
+               MSG_DEBUG("##### get Home URL Error");
+       }
+
+       MmsPluginCmAgent::instance()->getProxyAddr(mmscConfig->httpProxyIpAddr);
+       mmscConfig->proxyPortNo = MmsPluginCmAgent::instance()->getProxyPort();
+
+       MSG_END();
+}
+
+int MmsPluginHttpAgent::cmdRequest(MMS_HTTP_CMD_TYPE_T cmdType)
+{
+       MSG_DEBUG("cmdRequest:%x", cmdType);
+
+       int ret = 0;
+
+       ret = httpCmdHandler[cmdType](&httpConfigData);
+
+       return ret;
+}
+
+MMS_PLUGIN_HTTP_CONTEXT_S* MmsPluginHttpAgent::getMmsPldCd()
+{
+       return &mmsPlgCd;
+}
+
+MMS_PLUGIN_HTTP_DATA_S *MmsPluginHttpAgent::getHttpConfigData()
+{
+       return &httpConfigData;
+}
+
+int MmsPluginHttpAgent::setSession(mmsTranQEntity *qEntity)
+{
+       MSG_DEBUG("%s %d", qEntity->pPostData, qEntity->postDataLen);
+
+       if (qEntity->eHttpCmdType == eHTTP_CMD_POST_TRANSACTION) {
+               MSG_DEBUG("HttpCmd Post Transaction");
+               MSG_DEBUG(" === HTTP Agent Thread : Signal ==> eMMS_HTTP_SIGNAL_POST_TRANSACTION");
+
+               curl_slist *responseHeaders = NULL;
+
+               __httpAllocHeaderInfo(&responseHeaders, httpConfigData.mmscConfig.mmscUrl, qEntity->postDataLen);
+
+               MSG_DEBUG(" === MMSCURI = %s === ", httpConfigData.mmscConfig.mmscUrl);
+
+               httpConfigData.sessionHeader = (void *)responseHeaders;
+
+               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);
+               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);
+
+               char szUrl[MAX_MMSC_URL_LEN] = {0, };
+
+               memcpy(szUrl, qEntity->pGetData, qEntity->getDataLen);
+
+               MSG_DEBUG("MmsHttpInitTransactionGet  szURL (%s)", szUrl);
+
+               curl_slist *responseHeaders = NULL;
+
+               __httpAllocHeaderInfo(&responseHeaders, szUrl, 0);
+
+               httpConfigData.sessionHeader = (void *)responseHeaders;
+
+               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;
+       }
+
+       return 0;
+}
+
+
+void MmsPluginHttpAgent::clearSession()
+{
+       MSG_BEGIN();
+
+       if (httpConfigData.sessionHeader) {
+               curl_slist_free_all((curl_slist *)httpConfigData.sessionHeader);
+               httpConfigData.sessionHeader = NULL;
+       }
+
+       if (httpConfigData.session == NULL) {
+               MSG_DEBUG("[Error]httpConfigData.session is NULL");
+               return;
+       }
+
+       curl_easy_cleanup(httpConfigData.session);
+
+       httpConfigData.session = NULL;
+
+       MSG_END();
+}
diff --git a/plugin/mms_plugin/MmsPluginInternal.cpp b/plugin/mms_plugin/MmsPluginInternal.cpp
new file mode 100755 (executable)
index 0000000..f248968
--- /dev/null
@@ -0,0 +1,781 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilFile.h"
+#include "MsgException.h"
+#include "MsgSettingTypes.h"
+#include "MsgMmsMessage.h"
+#include "MsgGconfWrapper.h"
+#include "MsgStorageHandler.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginTypes.h"
+#include "MmsPluginCodec.h"
+#include "MmsPluginInternal.h"
+#include "MmsPluginStorage.h"
+#include "MmsPluginSmil.h"
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MmsPluginInternal - Member Functions
+==================================================================================================*/
+MmsPluginInternal *MmsPluginInternal::pInstance = NULL;
+
+
+MmsPluginInternal::MmsPluginInternal()
+{
+
+}
+
+MmsPluginInternal::~MmsPluginInternal()
+{
+
+}
+
+MmsPluginInternal *MmsPluginInternal::instance()
+{
+       if (!pInstance)
+               pInstance = new MmsPluginInternal();
+
+       return pInstance;
+}
+
+void MmsPluginInternal::processReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST_INFO_S *pRequest, bool *bReject)
+{
+       MSG_BEGIN();
+
+       FILE *pFile = NULL;
+       char fileName[MSG_FILENAME_LEN_MAX] = {0,};
+
+       if (pMsgInfo->bTextSms == true) {
+               char fullPath[MAX_FULL_PATH_SIZE+1] = {0,};
+
+               if(MsgCreateFileName(fileName) == false)
+                       THROW(MsgException::FILE_ERROR, "MsgCreateFileName error");
+
+               MSG_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);
+
+               memset(pMsgInfo->msgData, 0x00, sizeof(pMsgInfo->msgData));
+               memcpy(pMsgInfo->msgData, fullPath, strlen(fullPath));
+               pMsgInfo->bTextSms = false;
+       }
+
+       MSG_DEBUG("MMS File Path = %s", pMsgInfo->msgData);
+
+       MmsInitHeader();
+       MmsRegisterDecodeBuffer();
+
+       if ((pFile = MsgOpenFile(pMsgInfo->msgData, "rb+")) == NULL) {
+               MSG_DEBUG("File Open Error: %s", pMsgInfo->msgData);
+       } else {
+               //Decode Header
+               if (!MmsBinaryDecodeMsgHeader(pFile, pMsgInfo->dataSize))
+                       MSG_DEBUG("Decoding Header Failed \r\n");
+
+               MsgDeleteFile(pMsgInfo->msgData + strlen(MSG_IPC_DATA_PATH));
+
+               switch (mmsHeader.type) {
+               case MMS_MSGTYPE_NOTIFICATION_IND:
+                       MSG_DEBUG("process noti.ind\n");
+                       // For Set Value pMsgInfo
+                       if (processNotiInd(pMsgInfo, pRequest) == false)
+                               *bReject = true;
+                       else
+                               *bReject = false;
+                       break;
+
+               case MMS_MSGTYPE_DELIVERY_IND:
+                       MSG_DEBUG("process delivery.ind\n");
+                       // For Set Value pMsgInfo
+                       processDeliveryInd(pMsgInfo);
+                       break;
+
+               case MMS_MSGTYPE_READORG_IND:
+                       MSG_DEBUG("process readorig.ind\n");
+                       processReadOrgInd(pMsgInfo);
+                       break;
+               default:
+                       break;
+               }
+
+               MsgCloseFile(pFile);
+       }
+
+       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;
+
+       MmsInitMsgAttrib(&attrib);
+
+       pMsgInfo->msgType.mainType = MSG_MMS_TYPE;
+       pMsgInfo->msgType.subType = MSG_NOTIFICATIONIND_MMS;
+       pMsgInfo->priority = mmsHeader.priority;
+       strncpy(pMsgInfo->subject, mmsHeader.szSubject, MSG_LOCALE_SUBJ_LEN);
+
+       MSG_DEBUG("pMsgInfo->subject [%s]", pMsgInfo->subject);
+
+       if (strlen(pMsgInfo->subject) < 1)
+               snprintf(pMsgInfo->subject, MAX_SUBJECT_LEN, "MMS Notification Message.");
+
+       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);
+       }
+
+       int roamState = 0;
+
+       roamState = MsgSettingGetInt(VCONFKEY_TELEPHONY_SVC_ROAM);
+       MsgSettingGetBool(MMS_SEND_REPORT_ALLOWED, &bReportAllowed);
+
+       if (checkRejectNotiInd(roamState, bReportAllowed, pMsgInfo->msgData)) {
+               MSG_DEBUG("MMS Message Rejected......");
+
+               pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
+               pMsgInfo->bTextSms = true;
+               memcpy(&pRequest->msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+
+               pRequest->msgInfo.msgType.subType = MSG_NOTIFYRESPIND_MMS;
+
+               return false;
+       }
+
+       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);
+       } else {
+               retrieveType = (MSG_MMS_HOME_RETRIEVE_TYPE_T)MsgSettingGetInt(MMS_RECV_ABROAD_NETWORK);
+               MSG_DEBUG("$$$$$$$$$$ MMS_RECV_ABROAD_NETWORK = %d $$$$$$$$$$$$$", retrieveType);
+
+               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, pMsgInfo->msgData);
+
+                       pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
+                       pMsgInfo->bTextSms = true;
+                       memcpy(&pRequest->msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+
+                       pRequest->msgInfo.msgType.subType = MSG_NOTIFYRESPIND_MMS;
+
+                       return true;
+               }
+       }
+
+       // 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);
+
+               memcpy(pMsgInfo->msgData, mmsHeader.szContentLocation, strlen(mmsHeader.szContentLocation)) ;
+
+               pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
+
+               pMsgInfo->bTextSms = true;
+
+               memcpy(&pRequest->msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+
+               pRequest->msgInfo.msgType.subType = MSG_GET_MMS;
+
+               MSG_DEBUG("MSG SUBTYPE = %d msg data %s bTextsms %d", pRequest->msgInfo.msgType.subType, pRequest->msgInfo.msgData, pRequest->msgInfo.bTextSms);
+       } else {
+       // 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);
+               }
+
+               pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
+               pMsgInfo->bTextSms = true;
+               memcpy(&pRequest->msgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+
+               pRequest->msgInfo.msgType.subType = MSG_NOTIFYRESPIND_MMS;
+       }
+
+       return true;
+}
+
+void MmsPluginInternal::processDeliveryInd(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       MmsMsgMultiStatus status;
+       memset(&status, 0x00, sizeof(MmsMsgMultiStatus));
+
+       status.msgStatus = mmsHeader.msgStatus;
+       status.handledTime = mmsHeader.date;
+       status.bDeliveryReportIsRead = false;
+       status.bDeliveyrReportIsLast= true;
+
+       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->bTextSms = true;
+       pMsgInfo->dataSize = 0;
+       memset(pMsgInfo->msgData, 0x00, MAX_MSG_DATA_LEN + 1);
+
+       strncpy(pMsgInfo->msgData, getMmsDeliveryStatus(status.msgStatus), MAX_MSG_DATA_LEN);
+       pMsgInfo->dataSize  = strlen(pMsgInfo->msgData);
+       MSG_DEBUG("Delivery Status = %s", pMsgInfo->msgData);
+
+       strncpy(pMsgInfo->addressList[0].addressVal, mmsHeader.pTo->szAddr, MAX_ADDRESS_VAL_LEN);
+
+       int tmpId = (msg_message_id_t)MmsSearchMsgId(mmsHeader.pTo->szAddr, mmsHeader.szMsgID);
+       if (tmpId > 0) {
+               MSG_DEBUG("Found MSG_ID = %d", tmpId);
+
+               //Insert to Delievery DB
+               MmsPluginStorage::instance()->insertDeliveryReport(tmpId, mmsHeader.pTo->szAddr, &status);
+
+               pMsgInfo->msgId = (msg_message_id_t)tmpId;
+
+       } else {
+               MSG_DEBUG("Can not find MMS message in DB");
+       }
+
+       MSG_END();
+}
+
+void MmsPluginInternal::processReadOrgInd(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       if (pMsgInfo == NULL) {
+               MSG_DEBUG("parameter err");
+               return;
+       }
+
+       pMsgInfo->msgType.mainType = MSG_MMS_TYPE;
+       pMsgInfo->msgType.subType = MSG_READORGIND_MMS;
+       pMsgInfo->bTextSms = true;
+
+       MmsAddrUtilRemovePlmnString(mmsHeader.pFrom->szAddr);
+       MmsAddrUtilRemovePlmnString(mmsHeader.pTo->szAddr);
+
+       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);
+       strncpy(pMsgInfo->addressList[0].addressVal, mmsHeader.pFrom->szAddr, MAX_ADDRESS_VAL_LEN);
+
+       int tmpId = MmsSearchMsgId(mmsHeader.pFrom->szAddr, mmsHeader.szMsgID);
+       if (tmpId > 0) {
+               pMsgInfo->msgId = (msg_message_id_t)tmpId;
+
+               MmsMsgMultiStatus Status;
+               memset(&Status, 0x00, sizeof(MmsMsgMultiStatus));
+               Status.readTime = mmsHeader.date;
+               Status.readStatus = mmsHeader.readStatus;
+
+               MmsPluginStorage::instance()->insertReadReport(pMsgInfo->msgId, mmsHeader.pFrom->szAddr, &Status);
+
+       } else {
+               MSG_DEBUG("Can't not find Message!");
+       }
+
+       MSG_END();
+}
+
+void MmsPluginInternal::processSendConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTranQEntity *pRequest)
+{
+       MSG_BEGIN();
+
+       MMS_RECV_DATA_S recvData = {{0}, };
+
+       pMsgInfo->msgId = pRequest->msgId;
+
+       //Set only changed members
+       pMsgInfo->msgType.mainType = MSG_MMS_TYPE;
+       pMsgInfo->msgType.subType = MSG_SENDCONF_MMS;
+
+       pMsgInfo->folderId = MSG_OUTBOX_ID;
+
+       strncpy(pMsgInfo->subject, mmsHeader.szSubject, MSG_LOCALE_SUBJ_LEN);
+
+       if (mmsHeader.responseStatus == MMS_RESPSTATUS_OK) {
+               pMsgInfo->networkStatus = MSG_NETWORK_SEND_SUCCESS;
+               pMsgInfo->dataSize = pRequest->postDataLen;
+       } else {
+               pMsgInfo->networkStatus = MSG_NETWORK_SEND_FAIL;
+
+               char responseText[MMS_LOCALE_RESP_TEXT_LEN];
+
+               memset(responseText, 0x00, MMS_LOCALE_RESP_TEXT_LEN);
+               snprintf(responseText, MMS_LOCALE_RESP_TEXT_LEN, " %s [%d]", mmsHeader.szResponseText, mmsHeader.responseStatus);
+
+               memset(pMsgInfo->msgText, 0x00, MAX_MSG_TEXT_LEN + 1);
+               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");
+
+       // set message-id from mmsc
+       strncpy(recvData.szMsgID, mmsHeader.szMsgID, MMS_MSG_ID_LEN);
+       strncpy(recvData.szTrID, mmsHeader.szTrID, MMS_TR_ID_LEN);
+
+       memset(pMsgInfo->msgData, 0x00, MAX_MSG_DATA_LEN + 1);
+       memcpy(pMsgInfo->msgData, &recvData, sizeof(MMS_RECV_DATA_S));
+
+       time_t curTime;
+       curTime = time(NULL);
+
+       pMsgInfo->displayTime = curTime;
+
+       MmsMsg *pMsg = NULL;
+       MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+       MmsInitHeader();
+#ifdef __SUPPORT_DRM__
+       MmsReleaseMsgDRMInfo(&pMsg->msgType.drmInfo);
+#endif
+       MmsReleaseMsgBody(&pMsg->msgBody, pMsg->msgType.type);
+
+
+       MSG_END();
+}
+
+
+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}, };
+
+       MmsAttrib attrib;
+
+       MmsInitMsgAttrib(&attrib);
+
+       attrib.priority = mmsHeader.priority;
+       attrib.bAskDeliveryReport = getMmsReport(mmsHeader.deliveryReport);
+       attrib.bAskReadReply = getMmsReport(mmsHeader.readReply);
+
+       //Set only changed members
+       pMsgInfo->msgId = pRequest->msgId;
+       MSG_DEBUG("@@@@@ msgId = %d @@@@@", pMsgInfo->msgId);
+       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;
+
+       strncpy(pMsgInfo->subject, mmsHeader.szSubject, MSG_LOCALE_SUBJ_LEN);
+
+       strncpy(pRequest->transactionId, mmsHeader.szTrID, MMS_TR_ID_LEN);
+
+       time_t curTime;
+       curTime = time(NULL);
+
+       pMsgInfo->displayTime = curTime;
+
+       if (mmsHeader.retrieveStatus == MMS_RETRSTATUS_OK) {
+               pMsgInfo->networkStatus = MSG_NETWORK_RETRIEVE_SUCCESS;
+               pMsgInfo->folderId = MSG_INBOX_ID;
+       } else {
+               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;
+       }
+
+       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");
+       pMsgInfo->dataSize = pRequest->getDataLen;
+
+       // set message-id & MMS TPDU file path
+       strcpy(recvData.szMsgID, mmsHeader.szMsgID);
+       if (pRetrievedFilePath)
+               strncpy(recvData.retrievedFilePath, pRetrievedFilePath, sizeof(recvData.retrievedFilePath));
+
+#ifdef FEATURE_JAVA_MMS
+       if (mmsHeader.msgType.param.szApplicationID || mmsHeader.msgType.param.szReplyToApplicationID) {
+               recvData.msgAppId.valid = true;
+               if (mmsHeader.msgType.param.szApplicationID)
+                       strncpy(recvData.msgAppId.appId, mmsHeader.msgType.param.szApplicationID, sizeof(recvData.msgAppId.appId));
+               if (mmsHeader.msgType.param.szReplyToApplicationID)
+                       strncpy(recvData.msgAppId.replyToAppId, mmsHeader.msgType.param.szReplyToApplicationID, sizeof(recvData.msgAppId.replyToAppId));
+
+               char fullPath[MAX_FULL_PATH_SIZE+1] = {0, };
+
+               char *filename = NULL;
+               filename = strrchr(pRetrievedFilePath, '/');
+
+               snprintf(fullPath, MAX_FULL_PATH_SIZE+1, "%s%s", MSG_IPC_DATA_PATH, filename + 1);
+
+               int ret  = rename(pRetrievedFilePath, fullPath);
+               if (ret != 0) {
+                       MSG_DEBUG("File rename Error: %s", strerror(errno));
+               }
+
+               if (chmod(fullPath, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) != 0) {
+                       MSG_DEBUG("File Write Error: %s", strerror(errno));
+               }
+
+               if (chown(fullPath, 0, 6502 ) != 0) {
+                       MSG_DEBUG("File Write Error: %s", strerror(errno));
+               }
+       }
+#endif
+       memcpy(pMsgInfo->msgData, &recvData, sizeof(MMS_RECV_DATA_S));
+
+       MSG_DEBUG("@@@@@ MsgData = %s @@@@@", pMsgInfo->msgData);
+       MSG_DEBUG("@@@@@ retrievedFilePath = %s @@@@@", recvData.retrievedFilePath);
+       MSG_DEBUG("@@@@@ szMsgID = %s @@@@@", recvData.szMsgID);
+       //update delivery report, read reply
+
+       MmsPluginStorage *pStorage = MmsPluginStorage::instance();
+
+       MMS_MESSAGE_DATA_S msgData;
+       memset(&msgData, 0, sizeof(MMS_MESSAGE_DATA_S));
+
+       // 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;
+               MmsMsg *pMsg = NULL;
+               char szFileName[MSG_FILENAME_LEN_MAX] = {0, };
+
+               msgData.regionCnt = 0;
+               msgData.pageCnt = 0;
+               msgData.attachCnt = 0;
+               msgData.transitionCnt = 0;
+               msgData.metaCnt = 0;
+               memset(msgData.szSmilFilePath, 0, MSG_FILEPATH_LEN_MAX);
+
+               pSmilDoc = MmsSmilGetPresentationData(pMsgInfo->msgId);
+               MmsSmilParseSmilDoc(&msgData, pSmilDoc);
+               MmsRemovePims(&msgData);
+
+               MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+               strcpy(szFileName, pMsg->szFileName);
+
+               err = pStorage->getMsgText(&msgData, pMsgInfo->msgText);
+               bMultipartRelated = true;
+       } else {
+               MSG_DEBUG("Multipart mixed message doesn't support mms conversation");
+       }
+
+       err = pStorage->updateMmsAttrib(pMsgInfo->msgId, &attrib, pMsgInfo->msgType.subType);
+
+       partCnt = MmsGetMediaPartCount(pMsgInfo->msgId);
+       MSG_DEBUG("MmsUiGetMediaAttachInfo: partCnt=%d\n", partCnt );
+
+       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;
+                       }
+
+                       if (partHeader.contentSize > 0) {
+                               char szBuf[MSG_FILEPATH_LEN_MAX + 1];
+
+                               strcpy((char *)szBuf, partHeader.param.szFileName);
+                               sprintf(partHeader.param.szFileName, MSG_DATA_PATH"%s", szBuf);
+                               if (!bMultipartRelated || MmsCheckAdditionalMedia(&msgData, &partHeader)) {
+                                       MMS_ATTACH_S *attachment = NULL;
+                                       int tempType;
+
+                                       attachment = (MMS_ATTACH_S *)calloc(sizeof(MMS_ATTACH_S), 1);
+
+                                       MsgGetTypeByFileName(&tempType, partHeader.param.szFileName);
+                                       attachment->mediatype = (MimeType)tempType;
+
+                                       strcpy(attachment->szFilePath, partHeader.param.szFileName);
+
+                                       strncpy(attachment->szFileName, partHeader.param.szName, MSG_FILENAME_LEN_MAX - 1);
+
+                                       attachment->fileSize = partHeader.contentSize;
+
+                                       _MsgMmsAddAttachment(&msgData, attachment);
+                                       attachCount++;
+
+                               }
+
+                       }
+               }
+       }
+
+       MmsMakePreviewInfo(pMsgInfo->msgId, &msgData);
+       MSG_DEBUG("attachCount [%d]", attachCount);
+       err = pStorage->updateMmsAttachCount(pMsgInfo->msgId, attachCount);
+
+       if (bMultipartRelated) {
+               _MsgMmsReleasePageList(&msgData);
+               _MsgMmsReleaseRegionList(&msgData);
+               _MsgMmsReleaseAttachList(&msgData);
+               _MsgMmsReleaseTransitionList(&msgData);
+               _MsgMmsReleaseMetaList(&msgData);
+       }
+
+       MmsMsg *pMsg = NULL;
+       pStorage->getMmsMessage(&pMsg);
+       MmsInitHeader();
+#ifdef __SUPPORT_DRM__
+       MmsReleaseMsgDRMInfo(&pMsg->msgType.drmInfo);
+#endif
+       MmsReleaseMsgBody(&pMsg->msgBody, pMsg->msgType.type);
+
+       MSG_END();
+}
+
+void MmsPluginInternal::processForwardConf(MSG_MESSAGE_INFO_S *msgInfo, mmsTranQEntity *pRequest)
+{
+
+}
+
+/* This function Send NotifyRespInd Msg
+ *
+ * @param      pTrID [in] Specifies Transaction ID
+ * @param      iStatus [in] Specifies Msg Status
+ * @param      iReportAllowed [in] Specifies whether to send deliveryReport to sender or not
+ * @return     This function returns true on success, or false on failure.
+ */
+bool MmsPluginInternal::encodeNotifyRespInd(char *szTrID, msg_delivery_report_status_t iStatus, bool bReportAllowed, char *pSendFilePath)
+{
+       MSG_BEGIN();
+
+       FILE *pFile = NULL;
+       char pTempFileName[MSG_FILENAME_LEN_MAX+1] = {0};
+       char pTempFilePath[MAX_FULL_PATH_SIZE] = {0};
+
+       if (MsgCreateFileName(pTempFileName) == false)
+               return false;
+
+       snprintf(pTempFilePath, MAX_FULL_PATH_SIZE, MSG_DATA_PATH"%s.noti.ind", pTempFileName);
+
+       pFile = MsgOpenMMSFile(pTempFilePath);
+
+       if (!pFile) {
+               MSG_DEBUG("[ERROR] MsgOpenMMSFile fail");
+               return false;
+       }
+
+       if (MmsEncodeNotiRespInd(pFile, szTrID, iStatus, bReportAllowed) == false) {
+               MSG_DEBUG("MmsEncodeNotifyRespInd: MmsEncodeNotiRespInd fail");
+               MsgCloseFile(pFile);
+               return false;
+       }
+
+       MsgCloseFile(pFile);
+
+       if (pSendFilePath) {
+               snprintf(pSendFilePath, MAX_MSG_DATA_LEN+1, "%s.mms", pTempFilePath);
+       } else {
+               MSG_DEBUG("[ERROR] pSendFilePath is NULL");
+               return false;
+       }
+
+       MSG_END();
+
+       return true;
+}
+
+/* This function Send AcknowledgeInd Msg
+ *
+ * @param      pTrID [in] Specifies Transaction ID
+ * @param      iReportAllowed [in] Specifies whether to send deliveryReport to sender or not
+ * @return     This function returns true on success, or false on failure.
+ */
+bool MmsPluginInternal::encodeAckInd(char *szTrID, bool bReportAllowed, char *pSendFilePath)
+{
+       MSG_BEGIN();
+       FILE *pFile = NULL;
+       char pTempFileName[MSG_FILENAME_LEN_MAX+1] = {0};
+       char pTempFilePath[MAX_FULL_PATH_SIZE] = {0};
+
+       if (MsgCreateFileName(pTempFileName) == false)
+               return false;
+
+       snprintf(pTempFilePath, MAX_FULL_PATH_SIZE, MSG_DATA_PATH"%s.ack.ind", pTempFileName);
+
+       pFile = MsgOpenMMSFile(pTempFilePath);
+       if (!pFile) {
+               MSG_DEBUG("[ERROR] MsgOpenMMSFile fail \n" );
+               return false;
+       }
+
+       if (MmsEncodeAckInd(pFile, szTrID, bReportAllowed) == false) {
+               MSG_DEBUG("MmsEncodeAckInd: MmsEncodeAckInd fail \n" );
+               MsgCloseFile(pFile);
+               return false;
+       }
+
+       MsgCloseFile(pFile);
+
+       if (pSendFilePath) {
+               snprintf(pSendFilePath, MAX_MSG_DATA_LEN+1, "%s.mms", pTempFilePath);
+       } else {
+               MSG_DEBUG("[ERROR] pSendFilePath is NULL");
+               return false;
+       }
+
+       MSG_END();
+
+       return true;
+}
+
+bool MmsPluginInternal::checkRejectNotiInd(int roamState, bool bReportAllowed, char *pSendFilePath)
+{
+       MSG_BEGIN();
+       MSG_MMS_HOME_RETRIEVE_TYPE_T retrieveType;
+       bool bRejectAnonymous;
+       bool bRejectAdvertisement;
+
+       MsgSettingGetBool(MMS_RECV_REJECT_UNKNOWN, &bRejectAnonymous);
+       MsgSettingGetBool(MMS_RECV_REJECT_ADVERTISE, &bRejectAdvertisement);
+
+       // Anonymous Reject
+       if (bRejectAnonymous &&
+               (mmsHeader.pFrom == NULL || mmsHeader.pFrom->szAddr[0] == '\0')) {
+               MSG_DEBUG("Anonymous Reject... ");
+               encodeNotifyRespInd(mmsHeader.szTrID, MSG_DELIVERY_REPORT_REJECTED, bReportAllowed, pSendFilePath);
+
+               return true;
+       }
+
+       // Advertisement Reject
+       if (bRejectAdvertisement && mmsHeader.msgClass == MMS_MSGCLASS_ADVERTISEMENT) {
+               MSG_DEBUG("Advertisement Reject... ");
+               encodeNotifyRespInd(mmsHeader.szTrID, MSG_DELIVERY_REPORT_REJECTED, bReportAllowed, pSendFilePath);
+
+               return true;
+       }
+
+       // Message Reject - Roaming Case
+       if (roamState == VCONFKEY_TELEPHONY_SVC_ROAM_ON) {
+               retrieveType = (MSG_MMS_HOME_RETRIEVE_TYPE_T)MsgSettingGetInt(MMS_RECV_ABROAD_NETWORK);
+               if (retrieveType == MSG_ABROAD_REJECT) {
+                       MSG_DEBUG("Abroad_Network : Notification Reject... ");
+                       encodeNotifyRespInd(mmsHeader.szTrID, MSG_DELIVERY_REPORT_REJECTED, bReportAllowed, pSendFilePath);
+
+                       return true;
+               }
+       } else {
+               retrieveType = (MSG_MMS_HOME_RETRIEVE_TYPE_T)MsgSettingGetInt(MMS_RECV_HOME_NETWORK);
+               if (retrieveType == MSG_HOME_REJECT) {
+                       MSG_DEBUG("Home_Network : Notification Reject... ");
+                       encodeNotifyRespInd(mmsHeader.szTrID, MSG_DELIVERY_REPORT_REJECTED, bReportAllowed, pSendFilePath);
+
+                       return true;
+               }
+       }
+
+       // Not Rejected
+       MSG_END();
+       return false;
+
+}
+
+bool MmsPluginInternal::getMmsReport(MmsReport mmsReport)
+{
+       bool result = false;
+
+       if (mmsReport == MMS_REPORT_YES)
+               result = true;
+       else if (mmsReport == MMS_REPORT_NO)
+               result = false;
+
+       return result;
+}
+
+const char *MmsPluginInternal::getMmsDeliveryStatus(msg_delivery_report_status_t deliveryStatus)
+{
+       MSG_DEBUG("msgStatus= %d", deliveryStatus);
+
+       switch (deliveryStatus) {
+       case MSG_DELIVERY_REPORT_EXPIRED:
+               return "expired.";
+       case MSG_DELIVERY_REPORT_REJECTED:
+               return "rejected.";
+       case MSG_DELIVERY_REPORT_UNREACHABLE:
+               return "unreachable.";
+       case MSG_DELIVERY_REPORT_UNRECOGNISED:
+               return "unrecognised.";
+       case MSG_DELIVERY_REPORT_SUCCESS:
+               return "delivered.";
+       default:
+               return "delivery failed.";
+       }
+}
+
+const char *MmsPluginInternal::getMmsReadStatus(msg_read_report_status_t readStatus)
+{
+       switch (readStatus) {
+       case MSG_READ_REPORT_IS_READ:
+               return "message is read.";
+       case MSG_READ_REPORT_IS_DELETED:
+               return "message is deleted.";
+       default:
+               return "read status is none.";
+       }
+}
+
diff --git a/plugin/mms_plugin/MmsPluginMIME.cpp b/plugin/mms_plugin/MmsPluginMIME.cpp
new file mode 100755 (executable)
index 0000000..8e737ac
--- /dev/null
@@ -0,0 +1,1325 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MmsPluginDebug.h"
+#include "MmsPluginSmil.h"
+
+#ifndef        NULL
+#define        NULL    0
+#endif
+
+
+/* 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 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
+};
+
+/* Content-Transfer-Encoding header value */
+static const char *szMsgEncoding[MSG_ENCODING_NUM] =
+{
+       "7bit",
+       "8bit",
+       "binary",
+       "base64",
+       "quoted-printable"
+};
+
+/* Content-Disposition header value */
+static const char *szMsgDisposition[MSG_DISPOSITION_NUM] =
+{
+       "form-data",
+       "attachment",
+       "inline"
+};
+
+static const char *szMsgAddrType[MSG_ADDR_TYPE_NUM] =
+{
+       "/TYPE=PLMN",
+       "",
+       "/TYPE=IPV4",
+       "/TYPE=IPV6",
+       ""
+};
+
+/* 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"
+};
+
+
+/**************************************************     MIME definition     ***************************************************/
+static const MimeTable mimeTable[] = {
+       // 0
+       {"*/*",                                                                                                 "",                                     false,          MIME_ASTERISK,                                                                  MIME_ASTERISK,                                                  MIME_APPLICATION_NONE,                  MIME_MAINTYPE_ETC,                              UNDEFINED_BINARY        },
+
+    // 1
+       {"application/xml",                                                                     "",                                     false,          MIME_APPLICATION_XML,                                                   MIME_APPLICATION_XML,                                   MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x27    },
+       {"application/wml+xml",                                                         "",                                     false,          MIME_APPLICATION_WML_XML,                                               MIME_APPLICATION_WML_XML,                               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x3c    },
+       {"application/xhtml+xml",                                                               "xhtml",                        false,          MIME_APPLICATION_XHTML_XML,                                             MIME_APPLICATION_XHTML_XML,                             MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x3b    },
+       {"application/java-vm",                                                         "",                                     false,          MIME_APPLICATION_JAVA_VM,                                               MIME_APPLICATION_JAVA_VM,                               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      0x11    },
+       {"application/smil",                                                                    "smil",                         true,           MIME_APPLICATION_SMIL,                                                  MIME_APPLICATION_SMIL,                                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      UNDEFINED_BINARY        },
+       {"application/java-archive",                                                    "jar",                          true,           MIME_APPLICATION_JAVA_ARCHIVE,                                  MIME_APPLICATION_JAVA_ARCHIVE,                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_ETC,                      UNDEFINED_BINARY        },
+       {"application/java",                                                                    "jar",                          true,           MIME_APPLICATION_JAVA,                                                  MIME_APPLICATION_JAVA,                                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_ETC,                      UNDEFINED_BINARY        },
+       {"application/octet-stream",                                                    "",                                     false,          MIME_APPLICATION_OCTET_STREAM,                                  MIME_APPLICATION_OCTET_STREAM,                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_ETC,                      UNDEFINED_BINARY        },
+       {"application/studiom",                                                         "smp",                          true,           MIME_APPLICATION_STUDIOM,                                               MIME_APPLICATION_STUDIOM,                               MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"application/funMedia",                                                                "smp",                          true,           MIME_APPLICATION_FUNMEDIA,                                              MIME_APPLICATION_FUNMEDIA,                              MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"application/msword",                                                                  "doc",                          true,           MIME_APPLICATION_MSWORD,                                                MIME_APPLICATION_MSWORD,                                MIME_APPLICATION_PICSELVIEWER,                  MIME_MAINTYPE_APPLICATION,      UNDEFINED_BINARY        },
+       {"application/pdf",                                                                     "pdf",                          true,           MIME_APPLICATION_PDF,                                                   MIME_APPLICATION_PDF,                                   MIME_APPLICATION_PICSELVIEWER,                  MIME_MAINTYPE_APPLICATION,      UNDEFINED_BINARY        },
+       {"application/sdp",                                                                     "sdp",                          true,           MIME_APPLICATION_SDP,                                                   MIME_APPLICATION_SDP,                                   MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,    UNDEFINED_BINARY        },
+       {"application/ram",                                                                     "ram",                          true,           MIME_APPLICATION_RAM,                                                   MIME_APPLICATION_RAM,                                   MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"application/*",                                                                               "",                                     false,          MIME_APPLICATION_ASTERIC,                                               MIME_APPLICATION_ASTERIC,                               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      0x10    },
+
+       //16
+       {"application/vnd.wap.xhtml+xml",                                               "",                                     false,          MIME_APPLICATION_VND_WAP_XHTMLXML,                              MIME_APPLICATION_VND_WAP_XHTMLXML,              MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x45    },
+       {"application/vnd.wap.wmlc",                                                    "",                                     false,          MIME_APPLICATION_VND_WAP_WMLC,                                  MIME_APPLICATION_VND_WAP_WMLC,                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x14    },
+       {"application/vnd.wap.wmlscriptc",                                              "",                                     false,          MIME_APPLICATION_VND_WAP_WMLSCRIPTC,                    MIME_APPLICATION_VND_WAP_WMLSCRIPTC,    MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x15    },
+       {"application/vnd.wap.wta-eventc",                                              "",                                     false,          MIME_APPLICATION_VND_WAP_WTA_EVENTC,                    MIME_APPLICATION_VND_WAP_WTA_EVENTC,    MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x16    },
+       {"application/vnd.wap.uaprof",                                                  "",                                     false,          MIME_APPLICATION_VND_WAP_UAPROF,                                MIME_APPLICATION_VND_WAP_UAPROF,                MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x17    },
+       {"application/vnd.wap.sic",                                                     "",                                     false,          MIME_APPLICATION_VND_WAP_SIC,                                   MIME_APPLICATION_VND_WAP_SIC,                   MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x2e    },
+       {"application/vnd.wap.slc",                                                     "",                                     false,          MIME_APPLICATION_VND_WAP_SLC,                                   MIME_APPLICATION_VND_WAP_SLC,                   MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x30    },
+       {"application/vnd.wap.coc",                                                     "",                                     false,          MIME_APPLICATION_VND_WAP_COC,                                   MIME_APPLICATION_VND_WAP_COC,                   MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x32    },
+       {"application/vnd.wap.sia",                                                     "",                                     false,          MIME_APPLICATION_VND_WAP_SIA,                                   MIME_APPLICATION_VND_WAP_SIA,                   MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x34    },
+       {"application/vnd.wap,connectivity-wbxml",                              "",                                     false,          MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML,    MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML,            MIME_APPLICATION_NONE,          MIME_MAINTYPE_TEXT,                     UNDEFINED_BINARY        },
+       {"application/vnd.wap.multipart.form-data",                     "",                                     false,          MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA,   MIME_MULTIPART_FORM_DATA,                               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      0x24    },
+       {"application/vnd.wap.multipart.byteranges",                    "",                                     false,          MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES,  MIME_MULTIPART_BYTERANGE,                               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      0x25    },
+       {"application/vnd.wap.multipart.mixed",                         "",                                     false,          MIME_APPLICATION_VND_WAP_MULTIPART_MIXED,               MIME_MULTIPART_MIXED,                                   MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      0x23    },
+       {"application/vnd.wap.multipart.related",                               "",                                     false,          MIME_APPLICATION_VND_WAP_MULTIPART_RELATED,             MIME_MULTIPART_RELATED,                                 MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      0x33    },
+       {"application/vnd.wap.multipart.alternative",                   "",                                     false,          MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE, MIME_MULTIPART_ALTERNATIVE,                                     MIME_APPLICATION_NONE,                          MIME_MAINTYPE_APPLICATION,      0x26    },
+       {"application/vnd.wap.multipart.*",                                     "",                                     false,          MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC,             MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC,             MIME_APPLICATION_NONE,                  MIME_MAINTYPE_APPLICATION,      0x22    },
+       {"application/vnd.wap.wbxml",                                                   "",                                     false,          MIME_APPLICATION_VND_WAP_WBXML,                                 MIME_APPLICATION_VND_WAP_WBXML,                 MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      0x29    },
+       {"application/vnd.oma.dd+xml",                                                  "dd",                           true,           MIME_APPLICATION_VND_OMA_DD_XML,                                MIME_APPLICATION_VND_OMA_DD_XML,                MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_ETC,                      0x47    },
+       {"application/vnd.oma.drm.message",                                     "dm",                           true,           MIME_APPLICATION_VND_OMA_DRM_MESSAGE,                   MIME_APPLICATION_VND_OMA_DRM_MESSAGE,           MIME_APPLICATION_NONE,                          MIME_MAINTYPE_ETC,                      0x48    },
+       {"application/vnd.oma.drm.content",                                     "dcf",                          true,           MIME_APPLICATION_VND_OMA_DRM_CONTENT,                   MIME_APPLICATION_VND_OMA_DRM_CONTENT,           MIME_APPLICATION_NONE,                          MIME_MAINTYPE_ETC,                      0x49    },
+       {"application/vnd.oma.drm.rights+xml",                                  "ro",                           true,           MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML,                MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML,                MIME_APPLICATION_NONE,                  MIME_MAINTYPE_ETC,                      0x4a    },
+       {"application/vnd.oma.drm.rights+wbxml",                                "ro",                           true,           MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML,              MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML,              MIME_APPLICATION_NONE,                  MIME_MAINTYPE_ETC,                      0x4b    },
+       {"application/vnd.oma.drm.ro+xml",                              "oro",                          true,           MIME_APPLICATION_VND_OMA_DRM_RO_XML,            MIME_APPLICATION_VND_OMA_DRM_RO_XML,            MIME_APPLICATION_NONE,                  MIME_MAINTYPE_ETC,                      0x4b    },
+       {"application/vnd.oma.drm.dcf",                         "odf",                          true,           MIME_APPLICATION_VND_OMA_DRM_DCF,               MIME_APPLICATION_VND_OMA_DRM_DCF,               MIME_APPLICATION_NONE,                  MIME_MAINTYPE_ETC,                      0x4b    },
+       {"application/vnd.oma.drm.roap-pdu+xml",                                "xml",                          true,           MIME_APPLICATION_VND_OMA_ROAPPDU_XML,           MIME_APPLICATION_VND_OMA_ROAPPDU_XML,           MIME_APPLICATION_NONE,                  MIME_MAINTYPE_ETC,                      0x4b    },
+       {"application/vnd.oma.drm.roap-trigger+xml",                            "xml",                          true,           MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML,               MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML,               MIME_APPLICATION_NONE,                  MIME_MAINTYPE_ETC,                      0x4b    },
+       {"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        },
+
+       //49
+       {"application/x-hdmlc",                                                         "",                                     false,          MIME_APPLICATION_X_HDMLC,                                               MIME_APPLICATION_X_HDMLC,                               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x13    },
+       {"application/x-x968-user-cert",                                                "",                                     false,          MIME_APPLICATION_X_X968_USERCERT,                               MIME_APPLICATION_X_X968_USERCERT,               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x2c    },
+       {"application/x-www-form-urlencoded",                                   "",                                     false,          MIME_APPLICATION_X_WWW_FORM_URLENCODED,                 MIME_APPLICATION_X_WWW_FORM_URLENCODED,         MIME_APPLICATION_NONE,                          MIME_MAINTYPE_APPLICATION,      0x12    },
+       {"application/x-smaf",                                                                  "mmf",                          true,           MIME_APPLICATION_X_SMAF,                                                MIME_APPLICATION_X_SMAF,                                MIME_APPLICATION_SOUNDPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"application/x-shockwave-flash",                                               "swf",                          true,           MIME_APPLICATION_X_FLASH,                                               MIME_APPLICATION_X_FLASH,                               MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,            UNDEFINED_BINARY        },
+       {"application/x-msexcel",                                                               "xls",                          true,           MIME_APPLICATION_X_EXCEL,                                               MIME_APPLICATION_X_EXCEL,                               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      UNDEFINED_BINARY        },
+       {"application/x-mspowerpoint",                                                  "ppt",                          true,           MIME_APPLICATION_X_POWERPOINT,                                  MIME_APPLICATION_X_POWERPOINT,                  MIME_APPLICATION_PICSELVIEWER,                  MIME_MAINTYPE_APPLICATION,      UNDEFINED_BINARY        },
+
+
+       //56
+       {"audio/basic",                                                                         "snd"/*,au"*/,          false,          MIME_AUDIO_BASIC,                                                               MIME_AUDIO_BASIC,                                               MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/mpeg",                                                                                  "mp3",                          true,           MIME_AUDIO_MPEG,                                                                MIME_AUDIO_MP3,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/mp3",                                                                                   "mp3",                          true,           MIME_AUDIO_MP3,                                                                 MIME_AUDIO_MP3,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/mpg3",                                                                                  "mp3",                          true,           MIME_AUDIO_MPG3,                                                                MIME_AUDIO_MP3,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/mpeg3",                                                                         "mp3",                          true,           MIME_AUDIO_MPEG3,                                                               MIME_AUDIO_MP3,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/mpg",                                                                                   "mp3",                          true,           MIME_AUDIO_MPG,                                                                 MIME_AUDIO_MP3,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/aac",                                                                                   "aac",                          true,           MIME_AUDIO_AAC,                                                                 MIME_AUDIO_AAC,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/g72",                                                                                   "aac",                          true,           MIME_AUDIO_G72,                                                                 MIME_AUDIO_AAC,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/amr",                                                                                   "amr",                          true,           MIME_AUDIO_AMR,                                                                 MIME_AUDIO_AMR,                                                 MIME_APPLICATION_VOICEMEMO,                             MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"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/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        },
+       {"audio/sp-midi",                                                                               "spm"/*,midi"*/,        true,           MIME_AUDIO_SP_MIDI,                                                             MIME_AUDIO_SP_MIDI,                                             MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/wave",                                                                                  "wav",                          true,           MIME_AUDIO_WAVE,                                                                MIME_AUDIO_WAVE,                                                MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/wav",                                                                                   "wav",                          true,           MIME_AUDIO_WAV,                                                         MIME_AUDIO_WAVE,                                                MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/3gpp",                                                                                  "3gp",                          true,           MIME_AUDIO_3GPP,                                                                MIME_AUDIO_3GPP,                                                MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/mp4",                                                                                   "mp4",                          true,           MIME_AUDIO_MP4,                                                                 MIME_AUDIO_MP4,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/MP4A-LATM",                                                                     "mp4",                          true,           MIME_AUDIO_MP4A_LATM,                                                   MIME_AUDIO_MP4A_LATM,                                   MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/m4a",                                                                                   "m4a",                          true,           MIME_AUDIO_M4A,                                                                 MIME_AUDIO_M4A,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/mpeg4",                                                                         "mp4",                          true,           MIME_AUDIO_MPEG4,                                                               MIME_AUDIO_MPEG4,                                               MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/wma",                                                                                   "wma",                          true,           MIME_AUDIO_WMA,                                                                 MIME_AUDIO_WMA,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/xmf",                                                                                   "xmf",                          true,           MIME_AUDIO_XMF,                                                                 MIME_AUDIO_XMF,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/imy",                                                                                   "imy",                          true,           MIME_AUDIO_IMY,                                                                 MIME_AUDIO_IMY,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/mobile-xmf",                                                                    "mxmf",                         true,           MIME_AUDIO_MOBILE_XMF,                                                  MIME_AUDIO_XMF,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+
+       // 85
+       {"audio/vnd.rn-realaudio",                                                              "rm"/*,ram,ra"*/,       true,           MIME_AUDIO_VND_RN_REALAUDIO,                                    MIME_AUDIO_VND_RN_REALAUDIO,                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+
+       //86
+       {"audio/x-mpeg",                                                                                "mp3",                          true,           MIME_AUDIO_X_MPEG,                                                              MIME_AUDIO_MP3,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-mp3",                                                                         "mp3",                          true,           MIME_AUDIO_X_MP3,                                                               MIME_AUDIO_MP3,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-mpeg3",                                                                               "mp3",                          true,           MIME_AUDIO_X_MPEG3,                                                             MIME_AUDIO_MP3,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-mpg",                                                                         "mp3",                          true,           MIME_AUDIO_X_MPG,                                                               MIME_AUDIO_MP3,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-amr",                                                                         "amr",                          true,           MIME_AUDIO_X_AMR,                                                               MIME_AUDIO_AMR,                                                 MIME_APPLICATION_VOICEMEMO,                             MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-mmf",                                                                         "mmf",                          true,           MIME_AUDIO_X_MMF,                                                               MIME_AUDIO_MMF,                                                 MIME_APPLICATION_VOICEMEMO,                             MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-smaf",                                                                                "mmf",                          true,           MIME_AUDIO_X_SMAF,                                                              MIME_AUDIO_SMAF,                                                MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-iMelody",                                                                     "imy",                          true,           MIME_AUDIO_X_IMELODY,                                                   MIME_AUDIO_IMELODY,                                             MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-midi",                                                                                "mid"/*,midi"*/,        true,           MIME_AUDIO_X_MIDI,                                                              MIME_AUDIO_MID,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-mpegaudio",                                                                   "mp3",                          true,           MIME_AUDIO_X_MPEGAUDIO,                                                 MIME_AUDIO_MP3,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-pn-realaudio",                                                                "ra"/*,ram,ra"*/,       true,           MIME_AUDIO_X_PN_REALAUDIO,                                              MIME_AUDIO_VND_RN_REALAUDIO,                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-pn-multirate-realaudio",                                              "rm"/*,ram,ra"*/,       true,           MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO,                    MIME_AUDIO_VND_RN_REALAUDIO,                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-pn-multirate-realaudio-live",                         "rm"/*,ram,ra"*/,       true,           MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE,               MIME_AUDIO_VND_RN_REALAUDIO,                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-wave",                                                                                "wav",                          true,           MIME_AUDIO_X_WAVE,                                                              MIME_AUDIO_WAVE,                                                MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-wav",                                                                         "wav",                          true,           MIME_AUDIO_X_WAV,                                                               MIME_AUDIO_WAVE,                                                MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-ms-wma",                                                                              "wma",                          true,           MIME_AUDIO_X_MS_WMA,                                                    MIME_AUDIO_WAVE,                                                MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-mid",                                                                         "mid",                          true,           MIME_AUDIO_X_MID,                                                               MIME_AUDIO_MID,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-ms-asf",                                                                              "asf",                          true,           MIME_AUDIO_X_MS_ASF,                                                    MIME_AUDIO_X_MS_ASF,                                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+       {"audio/x-xmf",                                                                         "xmf",                          true,           MIME_AUDIO_X_XMF,                                                               MIME_AUDIO_XMF,                                                 MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_AUDIO,                    UNDEFINED_BINARY        },
+
+       //105
+       {"image/gif",                                                                                   "gif",                          false,          MIME_IMAGE_GIF,                                                                 MIME_IMAGE_GIF,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,                    0x1d    },
+       {"image/jpeg",                                                                                  "jpg"/*,jpeg,jpe,jpz"*/,        false,  MIME_IMAGE_JPEG,                                                        MIME_IMAGE_JPG,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,            0x1e    },
+       {"image/jpg",                                                                                   "jpg",                          false,          MIME_IMAGE_JPG,                                                                 MIME_IMAGE_JPG,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,                    UNDEFINED_BINARY        },
+       {"image/tiff",                                                                                  "tif"/*,tiff"*/,        false,          MIME_IMAGE_TIFF,                                                                MIME_IMAGE_TIF,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,                    0x1f    },
+       {"image/tif",                                                                                   "tif",                          false,          MIME_IMAGE_TIF,                                                                 MIME_IMAGE_TIF,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,                    UNDEFINED_BINARY        },
+       {"image/png",                                                                                   "png"/*,pnz"*/,         false,          MIME_IMAGE_PNG,                                                                 MIME_IMAGE_PNG,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,                    0x20    },
+       {"image/wbmp",                                                                                  "wbmp",                         false,          MIME_IMAGE_WBMP,                                                                MIME_IMAGE_WBMP,                                                MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,                    UNDEFINED_BINARY        },
+       {"image/pjpeg",                                                                         "jpg",                          false,          MIME_IMAGE_PJPEG,                                                               MIME_IMAGE_JPG,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,                    UNDEFINED_BINARY        },
+       {"image/bmp",                                                                                   "bmp",                          false,          MIME_IMAGE_BMP,                                                                 MIME_IMAGE_BMP,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,                    UNDEFINED_BINARY        },
+       {"image/svg+xml",                                                                               "svg",                          false,          MIME_IMAGE_SVG,                                                                 MIME_IMAGE_SVG,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,                    UNDEFINED_BINARY        },
+       {"image/svg-xml",                                                                               "svg",                          false,          MIME_IMAGE_SVG1,                                                                MIME_IMAGE_SVG,                                                 MIME_APPLICATION_IMAGEVIEWER,                   MIME_MAINTYPE_IMAGE,                    UNDEFINED_BINARY        },
+
+       //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    },
+       {"multipart/form-data",                                                         "",                                     false,          MIME_MULTIPART_FORM_DATA,                                               MIME_MULTIPART_FORM_DATA,                               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      0x0d    },
+       {"multipart/byterange",                                                         "",                                     false,          MIME_MULTIPART_BYTERANGE,                                               MIME_MULTIPART_BYTERANGE,                               MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      0x0e    },
+       {"multipart/report",                                                                    "",                                     false,          MIME_MULTIPART_REPORT,                                                  MIME_MULTIPART_REPORT,                                  MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_APPLICATION,      UNDEFINED_BINARY        },
+       {"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/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        },
+
+       //134
+       {"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    },
+       {"text/vnd.wap.connectivity-xml",                                               "",                                     false,          MIME_TEXT_VND_WAP_CONNECTIVITY_XML,                             MIME_TEXT_VND_WAP_CONNECTIVITY_XML,             MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x35    },
+       {"text/vnd.wap.si",                                                                     "",                                     false,          MIME_TEXT_VND_WAP_SI,                                                   MIME_TEXT_VND_WAP_SI,                                   MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x2d    },
+       {"text/vnd.wap.sl",                                                                     "",                                     false,          MIME_TEXT_VND_WAP_SL,                                                   MIME_TEXT_VND_WAP_SL,                                   MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x2f    },
+       {"text/vnd.wap.co",                                                                     "",                                     false,          MIME_TEXT_VND_WAP_CO,                                                   MIME_TEXT_VND_WAP_CO,                                   MIME_APPLICATION_NONE,                                  MIME_MAINTYPE_TEXT,                     0x31    },
+       {"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
+       {"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-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        },
+
+       //148
+       {"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/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        },
+
+       // 157
+       {"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
+       {"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        },
+       {"video/x-pn-multirate-realvideo",                                              "rm",                           true,           MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO,                    MIME_VIDEO_VND_RN_REALVIDEO,                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,                    UNDEFINED_BINARY        },
+       {"video/x-ms-wmv",                                                                              "wmv",                          true,           MIME_VIDEO_X_MS_WMV,                                                    MIME_VIDEO_X_MS_WMV,                                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,                    UNDEFINED_BINARY        },
+       {"video/x-ms-asf",                                                                              "asf",                          true,           MIME_VIDEO_X_MS_ASF,                                                    MIME_VIDEO_X_MS_ASF,                                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,                    UNDEFINED_BINARY        },
+       {"video/x-pv-pvx",                                                                              "pvx",                          true,           MIME_VIDEO_X_PV_PVX,                                                    MIME_VIDEO_X_PV_PVX,                                    MIME_APPLICATION_MEDIAPLAYER,                   MIME_MAINTYPE_VIDEO,                    UNDEFINED_BINARY        }
+
+};
+
+/**********             MIME table information     ***********/
+static const int mimeTableIndex[] = {
+       1,                      16,                     49,
+       56,                     85,                     86,
+       105,            116,            119,
+       120,            120,            120,
+       121,            121,            121,
+       128,            134,            142,
+       148,            157,            159
+};
+
+
+/*****************             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},
+       {"thm",                 MIME_APPLICATION_VND_SAMSUNG_THEME},
+       {"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   ,
+
+       MIME_APPLICATION_XML    ,
+       MIME_APPLICATION_WML_XML        ,
+       MIME_APPLICATION_XHTML_XML      ,
+       MIME_APPLICATION_JAVA_VM        ,
+       MIME_APPLICATION_SMIL   ,
+       MIME_APPLICATION_JAVA_ARCHIVE   ,
+       MIME_APPLICATION_JAVA   ,
+       MIME_APPLICATION_OCTET_STREAM   ,
+       MIME_APPLICATION_STUDIOM        ,
+       MIME_APPLICATION_FUNMEDIA       ,
+       MIME_APPLICATION_MSWORD         ,
+       MIME_APPLICATION_PDF            ,
+       MIME_APPLICATION_SDP            ,
+       MIME_APPLICATION_RAM            ,
+       MIME_APPLICATION_ASTERIC        ,
+
+
+       MIME_APPLICATION_VND_WAP_XHTMLXML       ,
+       MIME_APPLICATION_VND_WAP_WMLC   ,
+       MIME_APPLICATION_VND_WAP_WMLSCRIPTC     ,
+       MIME_APPLICATION_VND_WAP_WTA_EVENTC     ,
+       MIME_APPLICATION_VND_WAP_UAPROF ,
+       MIME_APPLICATION_VND_WAP_SIC    ,
+       MIME_APPLICATION_VND_WAP_SLC    ,
+       MIME_APPLICATION_VND_WAP_COC    ,
+       MIME_APPLICATION_VND_WAP_SIA    ,
+       MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML     ,
+       MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA    ,
+       MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES   ,
+       MIME_APPLICATION_VND_WAP_MULTIPART_MIXED        ,
+       MIME_APPLICATION_VND_WAP_MULTIPART_RELATED      ,
+       MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE  ,
+       MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC      ,
+       MIME_APPLICATION_VND_WAP_WBXML  ,
+       MIME_APPLICATION_VND_OMA_DD_XML ,
+       MIME_APPLICATION_VND_OMA_DRM_MESSAGE    ,
+       MIME_APPLICATION_VND_OMA_DRM_CONTENT    ,
+       MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML ,
+       MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML       ,
+       MIME_APPLICATION_VND_OMA_DRM_RO_XML     ,
+       MIME_APPLICATION_VND_OMA_DRM_DCF        ,
+       MIME_APPLICATION_VND_OMA_ROAPPDU_XML    ,
+       MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML,
+       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,
+
+
+       MIME_APPLICATION_X_HDMLC        ,
+       MIME_APPLICATION_X_X968_USERCERT        ,
+       MIME_APPLICATION_X_WWW_FORM_URLENCODED  ,
+       MIME_APPLICATION_X_SMAF ,
+       MIME_APPLICATION_X_FLASH        ,
+       MIME_APPLICATION_X_EXCEL        ,
+       MIME_APPLICATION_X_POWERPOINT   ,
+
+
+       MIME_AUDIO_BASIC,
+       MIME_AUDIO_MPEG ,
+       MIME_AUDIO_MP3  ,
+       MIME_AUDIO_MPG3 ,
+       MIME_AUDIO_MPEG3        ,
+       MIME_AUDIO_MPG  ,
+       MIME_AUDIO_AAC  ,
+       MIME_AUDIO_G72  ,
+       MIME_AUDIO_AMR  ,
+       MIME_AUDIO_AMR_WB       ,
+       MIME_AUDIO_MMF  ,
+       MIME_AUDIO_SMAF ,
+       MIME_AUDIO_IMELODY      ,
+       MIME_AUDIO_IMELODY2 ,
+       MIME_AUDIO_MELODY       ,
+       MIME_AUDIO_MID  ,
+       MIME_AUDIO_MIDI ,
+       MIME_AUDIO_SP_MIDI      ,
+       MIME_AUDIO_WAVE ,
+       MIME_AUDIO_WAV ,
+       MIME_AUDIO_3GPP ,
+       MIME_AUDIO_MP4  ,
+       MIME_AUDIO_MP4A_LATM    ,
+       MIME_AUDIO_M4A  ,
+       MIME_AUDIO_MPEG4,
+       MIME_AUDIO_WMA,
+       MIME_AUDIO_XMF,
+       MIME_AUDIO_IMY,
+       MIME_AUDIO_MOBILE_XMF,
+
+
+       MIME_AUDIO_VND_RN_REALAUDIO     ,
+
+
+       MIME_AUDIO_X_MPEG       ,
+       MIME_AUDIO_X_MP3        ,
+       MIME_AUDIO_X_MPEG3      ,
+       MIME_AUDIO_X_MPG        ,
+       MIME_AUDIO_X_AMR        ,
+       MIME_AUDIO_X_MMF        ,
+       MIME_AUDIO_X_SMAF       ,
+       MIME_AUDIO_X_IMELODY    ,
+       MIME_AUDIO_X_MIDI       ,
+       MIME_AUDIO_X_MPEGAUDIO  ,
+       MIME_AUDIO_X_PN_REALAUDIO       ,
+       MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO     ,
+       MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE        ,
+       MIME_AUDIO_X_WAVE       ,
+       MIME_AUDIO_X_WAV        ,
+       MIME_AUDIO_X_MS_WMA     ,
+       MIME_AUDIO_X_MID ,
+       MIME_AUDIO_X_MS_ASF ,
+       MIME_AUDIO_X_XMF,
+
+
+       MIME_IMAGE_GIF  ,
+       MIME_IMAGE_JPEG ,
+       MIME_IMAGE_JPG  ,
+       MIME_IMAGE_TIFF ,
+       MIME_IMAGE_TIF  ,
+       MIME_IMAGE_PNG  ,
+       MIME_IMAGE_WBMP ,
+       MIME_IMAGE_PJPEG        ,
+       MIME_IMAGE_BMP  ,
+       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        ,
+
+
+       MIME_MESSAGE_RFC822     ,
+
+
+       MIME_MULTIPART_MIXED    ,
+       MIME_MULTIPART_RELATED  ,
+       MIME_MULTIPART_ALTERNATIVE      ,
+       MIME_MULTIPART_FORM_DATA        ,
+       MIME_MULTIPART_BYTERANGE        ,
+       MIME_MULTIPART_REPORT   ,
+       MIME_MULTIPART_VOICE_MESSAGE    ,
+
+
+       MIME_TEXT_TXT   ,
+       MIME_TEXT_HTML  ,
+       MIME_TEXT_PLAIN ,
+       MIME_TEXT_CSS   ,
+       MIME_TEXT_XML   ,
+       MIME_TEXT_IMELODY       ,
+       MIME_TEXT_VND_WAP_WMLSCRIPT     ,
+       MIME_TEXT_VND_WAP_WML   ,
+       MIME_TEXT_VND_WAP_WTA_EVENT     ,
+       MIME_TEXT_VND_WAP_CONNECTIVITY_XML      ,
+       MIME_TEXT_VND_WAP_SI    ,
+       MIME_TEXT_VND_WAP_SL    ,
+       MIME_TEXT_VND_WAP_CO    ,
+       MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR   ,
+       MIME_TEXT_X_HDML        ,
+       MIME_TEXT_X_VCALENDAR   ,
+       MIME_TEXT_X_VCARD       ,
+       MIME_TEXT_X_IMELODY     ,
+       MIME_TEXT_X_IMELODY2 ,
+       MIME_TEXT_X_VNOTE ,
+
+
+       MIME_VIDEO_MPEG4        ,
+       MIME_VIDEO_MP4  ,
+       MIME_VIDEO_H263 ,
+       MIME_VIDEO_3GPP ,
+       MIME_VIDEO_3GP  ,
+       MIME_VIDEO_AVI  ,
+       MIME_VIDEO_SDP  ,
+       MIME_VIDEO_MP4_ES,
+       MIME_VIDEO_MPEG ,
+       MIME_VIDEO_VND_RN_REALVIDEO     ,
+       MIME_VIDEO_VND_RN_REALMEDIA     ,
+       MIME_VIDEO_X_MP4        ,
+       MIME_VIDEO_X_PV_MP4     ,
+       MIME_VIDEO_X_PN_REALVIDEO       ,
+       MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO     ,
+       MIME_VIDEO_X_MS_WMV ,
+       MIME_VIDEO_X_MS_ASF,
+       MIME_VIDEO_X_PV_PVX ,
+
+       MIME_UNKNOWN    // MIME_MAX
+};
+
+
+#define MIME_MAX_NUM   166
+#define EXT_MAX        67
+#define MIME_SUB_TYPE_VND      1
+#define MIME_SUB_TYPE_X                2
+
+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.
+ *
+ * @param      mime [in] Enumeration number for a MIME type.
+ * @return     This function returns main type of a MIME.
+ */
+MimeMainType MimeGetMainTypeInt(MimeType mime)
+{
+       int index;
+
+       index = __MimeGetTableIndexInt(mime);
+       if (index == MIME_UNKNOWN)
+               return MIME_MAINTYPE_ETC;
+
+       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.
+ *
+ * @param      mime [in] Enumeration number for a MIME type.
+ * @return     This function returns Extension string.
+ */
+char *MimeGetExtFromMimeInt(MimeType mime)
+{
+       int index;
+
+       index = __MimeGetTableIndexInt(mime);
+       if (index == MIME_UNKNOWN)
+               return NULL;
+
+       return (char *)mimeTable[index].szExt;
+}
+
+/*
+ * 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.
+ */
+int __MimeGetTableIndexInt(MimeType mime)
+{
+       int type;
+       int subtype;
+       int index;
+       int tableIndex;
+
+       if (mime == MIME_UNKNOWN)
+               return MIME_UNKNOWN;
+
+       type = (mime & 0xf000) >> 12;
+       subtype = (mime & 0x0f00) >> 8;
+       index = (mime & 0x003f);
+
+       //If 'type' is zero, mimeTableIndex's array value have a minus value
+       //If 'type' is zero, mime type is '*/*'
+       if (type == 0)
+               tableIndex = 0;
+       else
+               tableIndex = mimeTableIndex[(type - 1) * 3 + subtype] + index;
+
+       return tableIndex;
+}
+
+
+#define MIME_MAX_LEN   43
+/*
+ * This function returns index number in MIME definition table with MIME string.
+ * Internal function.
+ */
+int __MimeGetTableIndexString(const char *szMime)
+{
+       int type;
+       int subtype;
+       char szType[50];
+       char szSubType[50];
+       char *szTmpStart = NULL;
+       char c;
+       int i = 0;
+       int j = 0;
+       int start;
+       int end;
+       char *szMIMEType = NULL;
+       int len;
+
+       if (szMime == NULL) {
+               MSG_DEBUG("szMime is NULL");
+               return MIME_UNKNOWN;
+       }
+
+       szMIMEType = (char * )malloc(strlen(szMime) + 1);
+
+       if (szMIMEType == NULL) {
+               MSG_DEBUG("szMime is NULL");
+                return MIME_UNKNOWN;
+       }
+
+       memset(szMIMEType, 0, strlen(szMime) + 1);
+
+       if (!strcmp(szMime, "*/*")) {
+               free(szMIMEType);
+               return 0;
+       }
+       strcpy(szMIMEType, szMime);
+       type = 0;
+       subtype = 0;
+
+       szTmpStart = szMIMEType;
+       len = strlen(szTmpStart);
+
+       while (true) {
+               if (i >= len) {
+                       free(szMIMEType);
+                       return MIME_UNKNOWN;
+               }
+
+               c = szTmpStart[i++];
+
+               if (c == '/') {
+                       szType[j] = '\0';
+                       type = __MimeGetMainTypeName(szType);
+                       szTmpStart = &szTmpStart[i];
+                       break;
+               } else
+                       szType[j++] = c;
+       }
+
+       i = 0;
+       j = 0;
+       len = strlen(szTmpStart);
+
+       while (true) {
+               c = szTmpStart[i++];
+               if (i > len) {
+                       szSubType[j] = '\0';
+                       break;
+               }
+
+               if (c == '.') {
+                       szSubType[j] = '\0';
+                       if (!strcasecmp(szSubType, "vnd"))
+                               subtype = MIME_SUB_TYPE_VND;
+                       break;
+               } else if (c == '-') {
+                       szSubType[j] = '\0';
+                       if (!strcasecmp(szSubType, "x"))
+                               subtype = MIME_SUB_TYPE_X;
+                       break;
+               } else
+                       szSubType[j++] = c;
+       }
+
+
+       start = mimeTableIndex[type * 3 + subtype];
+
+       if (type == MIME_MAINTYPE_VIDEO && subtype == MIME_SUB_TYPE_X)
+               end = MIME_MAX_NUM;
+       else
+               end = mimeTableIndex[type * 3 + subtype + 1];
+
+       if (start == end && type < MIME_MAINTYPE_VIDEO) {
+               end = mimeTableIndex[(type + 1) * 3 + subtype + 1];
+       }
+
+
+       for (i = start; i < end; i++) {
+               if (i >= MIME_MAX_NUM)
+                       break;
+
+               if (!strcasecmp(mimeTable[i].szMIME, szMime)) {
+                       free(szMIMEType);
+                       return i;
+               }
+       }
+
+       free(szMIMEType);
+       return MIME_UNKNOWN;
+}
+
+/*
+ * This function returns main type of MIME : Internal function.
+ */
+MimeMainType __MimeGetMainTypeName(const char *szType)
+{
+       if (szType == NULL )
+               return MIME_MAINTYPE_APPLICATION;
+
+       if (!strcasecmp(szType, "application"))
+               return MIME_MAINTYPE_APPLICATION;
+       else if (!strcasecmp(szType, "audio"))
+               return MIME_MAINTYPE_AUDIO;
+       else if (!strcasecmp(szType, "image"))
+               return MIME_MAINTYPE_IMAGE;
+       else if (!strcasecmp(szType, "message"))
+               return MIME_MAINTYPE_MESSAGE;
+       else if (!strcasecmp(szType, "multipart"))
+               return MIME_MAINTYPE_MULTIPART;
+       else if (!strcasecmp(szType, "text"))
+               return MIME_MAINTYPE_TEXT;
+       else if (!strcasecmp(szType, "video"))
+               return MIME_MAINTYPE_VIDEO;
+
+       return MIME_MAINTYPE_APPLICATION;
+}
+
+
+
+// MimeString -> MimeInt
+MimeType MimeGetMimeIntFromMimeString(char *szMimeStr)
+{
+       int index = __MimeGetTableIndexString(szMimeStr);
+       if (index == MIME_UNKNOWN) {
+               return MIME_UNKNOWN;
+       } else {
+               return (MimeType)mimeTableEnum[index];
+       }
+}
+
+// MimeInt -> MimeString
+char *MimeGetMimeStringFromMimeInt(int mimeType)
+{
+       int idx = __MimeGetTableIndexInt((MimeType)mimeType);
+
+       if (idx == MIME_UNKNOWN)
+               return NULL;
+
+       return (char *)mimeTable[idx].szMIME;
+}
+
+
+// BinaryCode -> MimeInt
+MimeType MimeGetMimeIntFromBi(int binCode)
+{
+       int index;
+
+       if (binCode < 0x00 || binCode > 0x4b)
+               return MIME_UNKNOWN;
+
+       for (index = 0; index < MIME_MAX_NUM; index++) {
+               if (binCode == mimeTable[index].binary)
+                       return (MimeType)mimeTableEnum[index];
+       }
+
+       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)
+{
+       int index;
+
+       index = __MimeGetTableIndexInt(mime);
+       if (index == MIME_UNKNOWN)
+               return UNDEFINED_BINARY;
+
+       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;
+}
+
+
+/*
+ * 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)
+{
+       int index;
+
+       index = __MimeGetTableIndexInt(mime);
+       if (index == MIME_UNKNOWN)
+               return MIME_APPLICATION_NONE;
+
+       return mimeTable[index].appType;
+}
+
+/*
+ * 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;
+
+       index = __MimeGetTableIndexString(szMime);
+       if (index == MIME_UNKNOWN)
+               return MIME_APPLICATION_NONE;
+
+       return mimeTable[index].appType;
+}
+
+
+/*
+ * 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;
+
+       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 MIME_APPLICATION_NONE;
+                       return mimeTable[index].appType;
+               }
+       }
+
+       return MIME_APPLICATION_NONE;
+}
+
+/*
+ * This function gets the representative mime type from MimeType
+ *
+ * @param      mime [in] Enumeration number for a MIME type.
+ * @return     representative mime type Enumeration number
+ */
+
+MimeType MimeGetContentTypeFromInt(MimeType mime)
+{
+       int index;
+
+       for (index = 0; index < MIME_MAX_NUM; index++) {
+               if (mime == mimeTable[index].mime)
+                       return mimeTable[index].contentType;
+       }
+
+       return MIME_UNKNOWN;
+}
+
+/*
+ * 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)
+{
+       int index;
+
+       for (index = 0; index < MIME_MAX_NUM; index++) {
+               if (!strcasecmp(szMime, mimeTable[index].szMIME))
+                       return mimeTable[index].mime;
+       }
+
+       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];
+}
+
+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;
+       }
+}
+
+
+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;
+       }
+
+       for (cCode = 0; cCode < nNum; cCode++) {
+               if (pTable[cCode] != NULL) {
+                       if (!strcasecmp( pStr, pTable[cCode])) {
+                               return cCode;
+                       }
+               }
+       }
+
+       return INVALID_HOBJ;
+}
+
diff --git a/plugin/mms_plugin/MmsPluginMain.cpp b/plugin/mms_plugin/MmsPluginMain.cpp
new file mode 100755 (executable)
index 0000000..38ca717
--- /dev/null
@@ -0,0 +1,320 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgException.h"
+#include "MsgGconfWrapper.h"
+#include "MsgUtilFile.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginTypes.h"
+#include "MmsPluginMain.h"
+#include "MmsPluginTransport.h"
+#include "MmsPluginStorage.h"
+#include "MmsPluginInternal.h"
+#include "MmsPluginEventHandler.h"
+#include "MmsPluginCodec.h"
+
+/*==================================================================================================
+                                                       FUNCTION IMPLEMENTATION
+==================================================================================================*/
+msg_error_t MsgPlgCreateHandle(MSG_PLUGIN_HANDLER_S *pPluginHandle)
+{
+       if (pPluginHandle == NULL) {
+               MSG_DEBUG("MMS plugin: create handler error ");
+               return MSG_ERR_NULL_POINTER;
+       } else {
+               pPluginHandle->pfInitialize = MmsInitialize;
+               pPluginHandle->pfFinalize = MmsFinalize;
+               pPluginHandle->pfRegisterListener = MmsRegisterListener;
+               pPluginHandle->pfSubmitRequest = MmsSubmitRequest;
+               pPluginHandle->pfAddMessage = MmsAddMessage;
+               pPluginHandle->pfProcessReceivedInd = MmsProcessReceivedInd;
+               pPluginHandle->pfUpdateMessage = MmsUpdateMessage;
+               pPluginHandle->pfGetMmsMessage = MmsGetMmsMessage;
+               pPluginHandle->pfUpdateRejectStatus = MmsUpdateRejectStatus;
+               pPluginHandle->pfComposeReadReport = MmsComposeReadReport;
+               pPluginHandle->pfRestoreMsg = MmsRestoreMsg;
+
+               MSG_DEBUG("MMS plugin: create handler OK");
+               MSG_DEBUG ("MMS plugin %p", pPluginHandle);
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MmsPlgDestroyHandle(MSG_PLUGIN_HANDLER_S *pPluginHandle)
+{
+       MSG_BEGIN();
+
+       if (pPluginHandle != NULL) {
+               free(pPluginHandle);
+               pPluginHandle = NULL;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MmsInitialize()
+{
+       MSG_BEGIN();
+
+       // remove temp files
+       MsgMmsInitDir();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MmsFinalize()
+{
+       MSG_BEGIN();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MmsRegisterListener(MSG_PLUGIN_LISTENER_S *pListener)
+{
+       MSG_BEGIN();
+
+       MmsPluginEventHandler::instance()->registerListener(pListener);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MmsSubmitRequest(MSG_REQUEST_INFO_S *pReqInfo)
+{
+       MSG_BEGIN();
+
+       try {
+               MmsPluginTransport::instance()->submitRequest(pReqInfo);
+       } catch (MsgException& e) {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_TRANSPORT;
+       } catch (exception& e) {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_TRANSPORT;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MmsAddMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData)
+{
+       MSG_BEGIN();
+
+       try {
+               MmsPluginStorage::instance()->addMessage(pMsgInfo, pSendOptInfo, pFileData);
+       } catch (MsgException& e) {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_TRANSPORT;
+       } catch (exception& e) {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_TRANSPORT;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MmsProcessReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST_INFO_S *pRequest, bool *bReject)
+{
+       MSG_BEGIN();
+
+       MSG_DEBUG("MMS Plugin ProcessReceivedInd");
+
+       try {
+               MmsPluginInternal::instance()->processReceivedInd(pMsgInfo, pRequest, bReject);
+       } catch (MsgException& e) {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_TRANSPORT;
+       } catch (exception& e) {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_TRANSPORT;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MmsUpdateMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo,  char *pFileData)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       try {
+               if (pMsgInfo->networkStatus == MSG_NETWORK_NOT_SEND || pMsgInfo->networkStatus == MSG_NETWORK_SENDING) {
+                       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) {
+                               err = MmsPluginStorage::instance()->updateConfMessage(pMsgInfo);
+                       } else {
+                               err = MmsPluginStorage::instance()->updateMsgServerID(pMsgInfo, pSendOptInfo);
+                       }
+               }
+       } 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 err;
+}
+
+
+msg_error_t MmsGetMmsMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_MESSAGE_DATA_S *pMmsMsg, char **pDestMsg)
+{
+       MSG_BEGIN();
+
+       msg_error_t     err = MSG_SUCCESS;
+
+       try {
+               err = MmsPluginStorage::instance()->plgGetMmsMessage(pMsg, pSendOptInfo, pMmsMsg, pDestMsg);
+       } 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 err;
+}
+
+
+msg_error_t MmsUpdateRejectStatus(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       try {
+               char szTrID[MMS_TR_ID_LEN + 1] = {0x00};
+               bool bReportAllowed;
+
+               err = MmsPluginStorage::instance()->getTrID(pMsgInfo,szTrID,sizeof(szTrID));
+               if (err != MSG_SUCCESS)
+                       MSG_DEBUG("MmsPlgUpdRejectStatus : Get MMS Transacation id Failed");
+
+               memset(pMsgInfo->msgData, 0, MAX_MSG_DATA_LEN + 1);
+               MsgSettingGetBool(MMS_SEND_REPORT_ALLOWED, &bReportAllowed);
+               if (MmsPluginInternal::instance()->encodeNotifyRespInd(szTrID, MSG_DELIVERY_REPORT_REJECTED, bReportAllowed, pMsgInfo->msgData)) {
+                       MSG_DEBUG("MmsPlgUpdRejectStatus : Encode Notify Response Success");
+                       pMsgInfo->dataSize = strlen(pMsgInfo->msgData);
+                       pMsgInfo->bTextSms = true;
+               } else
+                       MSG_DEBUG("MmsPlgSetRejectStatus : Encode Notify Response Failed");
+       } 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;
+       }
+
+       if (err != MSG_SUCCESS)
+               MSG_DEBUG("MmsPlgSetRejectStatus : Update MMS Message Failed");
+
+       MSG_END();
+
+       return err;
+}
+
+
+msg_error_t MmsComposeReadReport(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       try {
+               MmsPluginStorage::instance()->composeReadReport(pMsgInfo);
+       } 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;
+}
+
+
+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();
+
+               if ((pFile = MsgOpenFile(pMsgInfo->msgData, "rb+")) == NULL) {
+                       MSG_DEBUG("File Open Error: %s", pMsgInfo->msgData);
+               } else {
+                       //Decode Header
+                       if (!MmsBinaryDecodeMsgHeader(pFile, rcvdBodyLen))
+                               MSG_DEBUG("Decoding Header Failed \r\n");
+
+                       MsgCloseFile(pFile);
+               }
+       } else {
+               MSG_DEBUG(":::%d :%s ",rcvdBodyLen, pRcvBody);
+
+               if (filePath) {
+                       snprintf(filePath, MAX_FULL_PATH_SIZE, MSG_DATA_PATH"BODY_%lu.DATA", random() % 1000000000 + 1);
+               } else {
+                       return MSG_ERR_NULL_POINTER;
+               }
+
+               // create temp file
+               if (!MsgOpenCreateAndOverwriteFile(filePath, (char*)pRcvBody,rcvdBodyLen))
+                       return MSG_ERR_PLUGIN_STORAGE;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
diff --git a/plugin/mms_plugin/MmsPluginMessage.cpp b/plugin/mms_plugin/MmsPluginMessage.cpp
new file mode 100755 (executable)
index 0000000..8797fdd
--- /dev/null
@@ -0,0 +1,1036 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "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 "MmsPluginAvCodec.h"
+#include "MmsPluginStorage.h"
+#include "MmsPluginSMILValidate.h"
+#include "MmsPluginUtil.h"
+
+bool MmsSetMsgAddressList(MmsAttrib *pAttrib, const MSG_MESSAGE_INFO_S * pMsgInfo)
+{
+       MSG_DEBUG("MmsSetMsgAddressList");
+       pAttrib->szTo = MmsComposeAddress(pMsgInfo, MSG_RECIPIENTS_TYPE_TO);
+       MSG_DEBUG("To address: %s", pAttrib->szTo);
+       pAttrib->szCc = MmsComposeAddress(pMsgInfo, MSG_RECIPIENTS_TYPE_CC);
+       MSG_DEBUG("Cc address: %s", pAttrib->szCc);
+       pAttrib->szBcc = MmsComposeAddress(pMsgInfo, MSG_RECIPIENTS_TYPE_BCC);
+       MSG_DEBUG("Bcc address: %s", pAttrib->szBcc);
+
+       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");
+       int     addrLen = 0;
+       int     nAddressCnt = 0;
+       int nRecpCnt = 0;
+       char pString[MSG_LOCALE_NAME_LEN + MSG_ADDR_LEN + 3] = {0, };
+       char *szCompose;
+
+       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);
+               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(pMsgInfo->addressList[i].addressVal);
+                       } else if (pMsgInfo->addressList[i].addressType == MSG_ADDRESS_TYPE_EMAIL) {
+                               addrLen += strlen(pMsgInfo->addressList[i].addressVal);
+                       } else
+                               ; // Need to consider IPV4, IPV6, and Alias formatted address
+
+                       nRecpCnt++;
+               }
+       }
+
+       if (nRecpCnt > 1)
+               addrLen = addrLen + nRecpCnt - 1;
+       szCompose = (char *)calloc(addrLen + 1, 1);
+
+       // 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);
+
+                       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));
+                               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);
+               }
+       }
+
+       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)
+{
+       MSG_BEGIN();
+
+       if (MsgReadSmilFile(pMsgBody->szSmilFilePath, pRawdata) < 0)
+               return false;
+
+       MsgDeleteSmilFile(pMsgBody->szSmilFilePath);
+
+       MSG_END();
+
+       return true;
+}
+
+
+bool MmsInsertPresentation(MmsMsg *pMsg, MimeType mimeType, char *pData, int size)
+{
+       MSG_DEBUG("MmsInsertPresentation");
+
+       if (pMsg == NULL) {
+               MSG_DEBUG("pMsg is NULL");
+               return false;
+       }
+
+       if (pMsg->msgBody.pPresentationBody != NULL)
+               goto __CATCH;
+
+       memset(&pMsg->msgBody.presentationType, 0, sizeof(MsgType));
+       pMsg->msgBody.pPresentationBody = (MsgBody *)malloc(sizeof(MsgBody));
+       if (pMsg->msgBody.pPresentationBody == NULL)
+               goto __CATCH;
+
+       MmsInitMsgBody(pMsg->msgBody.pPresentationBody);
+
+       pMsg->msgBody.pPresentationBody->body.pText = (char *)malloc(size + 1);
+       if (pMsg->msgBody.pPresentationBody->body.pText == NULL)
+               goto __CATCH;
+
+       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, "%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);
+
+       return true;
+
+__CATCH:
+
+       if (pMsg->msgBody.pPresentationBody != NULL) {
+               if (pMsg->msgBody.pPresentationBody->body.pText != NULL) {
+                       free(pMsg->msgBody.pPresentationBody->body.pText);
+                       pMsg->msgBody.pPresentationBody->body.pText = NULL;
+               }
+
+               free(pMsg->msgBody.pPresentationBody);
+               pMsg->msgBody.pPresentationBody = NULL;
+       }
+
+       return false;
+}
+
+
+bool MmsInsertPartFromFile(MmsMsg *pMsg, char *szTitleName, char *szOrgFilePath, char *szContentID)
+{
+       MSG_DEBUG("MmsInsertPartFromFile");
+
+       MsgMultipart *pMultipart = NULL;
+       MsgMultipart *pLastPart = NULL;
+       int nFileSize;
+       MimeType 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 (MmsIsMultipart(pMsg->msgType.type) == true) {
+               /* Insert as a multipart */
+               if (MsgGetFileSize(szOrgFilePath, &nFileSize) == false) {
+                       MSG_DEBUG("MsgGetFileSize: failed");
+                       goto __CATCH;
+               }
+
+               pMultipart = MmsMakeMultipart(mimeType, szTitleName, szOrgFilePath, NULL, 0, nFileSize, szContentID);
+               if (pMultipart == NULL)
+                       goto __CATCH;
+
+               if (pMsg->mmsAttrib.contentType == MIME_APPLICATION_VND_WAP_MULTIPART_MIXED ||
+                       pMsg->mmsAttrib.contentType == MIME_MULTIPART_MIXED)
+                       pMultipart->type.disposition = MSG_DISPOSITION_ATTACHMENT;
+
+               if (pMsg->msgBody.body.pMultipart == NULL) {
+                       pMsg->msgBody.body.pMultipart = pMultipart;
+               } else {
+                       pLastPart = pMsg->msgBody.body.pMultipart;
+                       while (pLastPart->pNext) {
+                               pLastPart = pLastPart->pNext;
+                       }
+
+                       pLastPart->pNext = pMultipart;
+               }
+
+               pMsg->msgBody.size += pMultipart->pBody->size;
+               pMsg->msgType.contentSize += pMultipart->pBody->size;
+       } else {
+               /* Single part - Insert as a message body */
+               if (pMsg->mmsAttrib.contentType != mimeType || pMsg->msgType.type != mimeType)
+                       goto __CATCH;
+
+               strncpy(pMsg->msgType.param.szName, szTitleName, MSG_LOCALE_FILENAME_LEN_MAX);
+
+               if (MmsIsText(pMsg->msgType.type) == true) {
+                       pMsg->msgType.param.charset = MSG_CHARSET_UTF8;
+               }
+
+               strncpy(pMsg->msgBody.szOrgFilePath, szOrgFilePath, MSG_FILEPATH_LEN_MAX - 1);
+               if (MsgGetFileSize(szOrgFilePath, &nFileSize) == false) {
+                       MSG_DEBUG("MsgGetFileSize: failed");
+                       goto __CATCH;
+               }
+
+               pMsg->msgBody.offset = 0;
+               pMsg->msgBody.size = nFileSize;
+               pMsg->msgType.contentSize = nFileSize;
+       }
+
+       pMsg->nPartCount++;
+
+       return true;
+
+__CATCH:
+       return false;
+
+}
+
+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;
+       }
+}
+
+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;
+       }
+}
+
+bool MmsIsVitemContent (int type, char *pszName)
+{
+       switch (type) {
+
+/*
+*      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;
+
+       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;
+}
+
+
+
+MsgMultipart *MmsMakeMultipart(MimeType mimeType, char *szTitleName, char *szOrgFilePath, void *pData, int offset, int size, char *szContentID)
+{
+       MsgMultipart *pMultipart = NULL;
+
+       if ((pMultipart = MmsAllocMultipart()) == NULL)
+               goto __CATCH;
+
+       pMultipart->type.type = mimeType;
+
+       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 (szContentID && szContentID[0]) {
+               memset(pMultipart->type.szContentID, 0, MSG_MSG_ID_LEN + 1);
+               snprintf(pMultipart->type.szContentID, MSG_MSG_ID_LEN + 1, "<%s>", szContentID);
+
+               memset(pMultipart->type.szContentLocation, 0, MSG_MSG_ID_LEN + 1);
+               snprintf(pMultipart->type.szContentLocation, MSG_MSG_ID_LEN + 1, "%s", szContentID);
+       }
+
+       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 (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;
+
+                               memset(pMultipart->pBody->body.pText, 0, size + 1);
+                       } else {
+                               pMultipart->pBody->body.pBinary = malloc(size);
+                               if (pMultipart->pBody->body.pBinary == NULL)
+                                       goto __CATCH;
+
+                               memset(pMultipart->pBody->body.pBinary, 0, size);
+                       }
+
+                       memcpy(pMultipart->pBody->body.pBinary, pData, size);
+                       pMultipart->pBody->size = size;
+               }
+       } 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;
+                       }
+                       free(pMultipart->pBody);
+                       pMultipart->pBody = NULL;
+               }
+               free(pMultipart);
+               pMultipart = NULL;
+       }
+
+       return NULL;
+}
+
+
+bool MmsGetTypeByFileName(int *type, char *szFileName)
+{
+       char *pExt   = NULL;
+       AvCodecType AvType = AV_CODEC_NONE;
+
+       /* AVMS unknown or text/image file format identify type from file extention  */
+
+       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) {
+               /* Audio / Video format. If file exists already, AvGetFileCodecType() can identify the format  */
+               if (szFileName[0] != '/')
+                       goto __CATCH;
+
+               AvType = AvGetFileCodecType(szFileName);
+
+               switch (AvType) {
+               case AV_DEC_AUDIO_MPEG4:
+                       *type = MIME_AUDIO_MP4;//*type = MIME_AUDIO_3GPP;
+                       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);
+
+       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)
+{
+       MSG_BEGIN();
+
+       char *pRawData = NULL;
+       AutoPtr<char> buf(&pRawData);
+
+       struct tm *timeInfo = NULL;
+       time_t RawTime = 0;
+       time_t nTimeInSecs = 0;
+
+       msg_error_t     err = MSG_SUCCESS;
+
+       // Initialize mmsMsg structure
+       MmsInitMsgAttrib(&pMmsMsg->mmsAttrib);
+       MmsInitMsgType(&pMmsMsg->msgType);
+       MmsInitMsgBody(&pMmsMsg->msgBody);
+
+       // setting mmsMsg structure
+       pMmsMsg->mailbox = pMsgInfo->folderId;
+       pMmsMsg->msgID = pMsgInfo->msgId;
+
+       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);
+
+       pMmsMsg->mmsAttrib.dataType = MMS_DATATYPE_DRAFT;
+
+       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);
+
+       if (pSendOptInfo->bSetting == false) {
+               unsigned int expiryTime;
+               MSG_MMS_DELIVERY_TIME_T deliveryTime;
+
+               pMmsMsg->mmsAttrib.priority = (MmsPriority)MsgSettingGetInt(MMS_SEND_PRIORITY);
+
+               MsgSettingGetBool(MMS_SEND_DELIVERY_REPORT, &pMmsMsg->mmsAttrib.bAskDeliveryReport);
+               MsgSettingGetBool(MMS_SEND_READ_REPLY, &pMmsMsg->mmsAttrib.bAskReadReply);
+               MsgSettingGetBool(MSG_KEEP_COPY, &pMmsMsg->mmsAttrib.bLeaveCopy);
+
+               expiryTime = (unsigned int)MsgSettingGetInt(MMS_SEND_EXPIRY_TIME);
+
+               if (expiryTime == 0)
+                       pMmsMsg->mmsAttrib.expiryTime.type = MMS_TIMETYPE_NONE;
+               else {
+                       pMmsMsg->mmsAttrib.expiryTime.type = MMS_TIMETYPE_RELATIVE;
+                       pMmsMsg->mmsAttrib.expiryTime.time = expiryTime;
+               }
+
+               deliveryTime = (MSG_MMS_DELIVERY_TIME_T)MsgSettingGetInt(MMS_SEND_DELIVERY_TIME);
+
+               if (deliveryTime == MSG_DELIVERY_TIME_CUSTOM) {
+                       pMmsMsg->mmsAttrib.bUseDeliveryCustomTime = true;
+
+                       pMmsMsg->mmsAttrib.deliveryTime.type = MMS_TIMETYPE_RELATIVE;
+                       pMmsMsg->mmsAttrib.deliveryTime.time = (unsigned int)MsgSettingGetInt(MMS_SEND_CUSTOM_DELIVERY);
+               } else {
+                       pMmsMsg->mmsAttrib.bUseDeliveryCustomTime = false;
+
+                       pMmsMsg->mmsAttrib.deliveryTime.type = MMS_TIMETYPE_RELATIVE;
+                       pMmsMsg->mmsAttrib.deliveryTime.time = (unsigned int)deliveryTime;
+               }
+       } 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
+
+       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);
+
+       // setting date
+       time(&RawTime);
+       timeInfo = localtime(&RawTime);
+       nTimeInSecs = mktime(timeInfo);
+       pMmsMsg->mmsAttrib.date = nTimeInSecs;  // todo: need to subtract timeline value to make GMT+0 time
+
+       //setting subject
+       strcpy(pMmsMsg->mmsAttrib.szSubject, pMsgInfo->subject);
+
+       //setting adddress
+       MmsSetMsgAddressList(&pMmsMsg->mmsAttrib, pMsgInfo);
+       MmsGetMsgBodyfromMsgInfo(pMsgInfo, pMsgData, pFileData);
+
+       int pageCnt = _MsgMmsGetPageCount(pMsgData);
+
+       if (pageCnt == 0) {     // Multipart mixed
+               pMmsMsg->mmsAttrib.contentType = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED;
+               pMmsMsg->msgType.type = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED;
+               MmsMakePreviewInfo(pMsgInfo->msgId, pMsgData);
+       } else {        // Multipart related
+
+               int RawDataSize = 0;
+
+               time_t RawTime = 0;
+               time(&RawTime);
+               snprintf(pMsgData->szSmilFilePath, MSG_FILEPATH_LEN_MAX, "%lu", RawTime);
+
+               MsgMMSCreateSMIL(pMsgData);
+
+               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;
+
+                               default:
+                                       break;
+                               }
+                       }
+               }
+
+               char szFileName[MSG_FILENAME_LEN_MAX+1] = {0, };;
+               snprintf(szFileName, MSG_FILENAME_LEN_MAX+1, "%d.mms", pMsgInfo->msgId);
+
+               MmsPluginStorage *pStorage = MmsPluginStorage::instance();
+               err = pStorage->getMsgText(pMsgData, pMsgInfo->msgText);
+               MmsMakePreviewInfo(pMsgInfo->msgId, pMsgData);
+       }
+
+#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);
+
+                       strcpy(pMmsMsg->msgType.param.szApplicationID, pMsgData->msgAppId.appId);
+               }
+
+               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);
+
+                       strcpy(pMmsMsg->msgType.param.szReplyToApplicationID, pMsgData->msgAppId.replyToAppId);
+               }
+       }
+#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)) {
+                               free(pMedia);
+                               return false;
+                       }
+               }
+       }
+
+       return true;
+}
+
+void MmsComposeNotiMessage(MmsMsg *pMmsMsg, msg_message_id_t msgID)
+{
+       MSG_BEGIN();
+
+       struct tm *timeInfo = NULL;
+       time_t RawTime = 0;
+       time_t nTimeInSecs = 0;
+
+       MmsInitMsgAttrib(&pMmsMsg->mmsAttrib);
+       MmsInitMsgType(&pMmsMsg->msgType);
+       MmsInitMsgBody(&pMmsMsg->msgBody);
+
+       pMmsMsg->msgID = msgID;
+
+       pMmsMsg->mmsAttrib.version = mmsHeader.version;
+
+       // setting date
+       time(&RawTime);
+       timeInfo = localtime(&RawTime);
+       nTimeInSecs = mktime(timeInfo);
+       pMmsMsg->mmsAttrib.date = nTimeInSecs;
+
+       pMmsMsg->mmsAttrib.bReportAllowed = mmsHeader.reportAllowed;
+       pMmsMsg->mmsAttrib.bAskDeliveryReport = mmsHeader.deliveryReport;
+
+       MSG_DEBUG("######## Version = %d ########", pMmsMsg->mmsAttrib.version);
+
+       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);
+       }
+
+       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;
+
+       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;
+
+       strncpy(pMmsMsg->mmsAttrib.replyCharge.szChargeID, mmsHeader.replyCharge.szChargeID, MMS_MSG_ID_LEN);
+
+       MSG_END();
+}
+
+void MmsComposeReadReportMessage(MmsMsg *pMmsMsg, const MSG_MESSAGE_INFO_S *pMsgInfo, msg_message_id_t selectedMsgId)
+{
+       struct tm *timeInfo = NULL;
+       time_t RawTime = 0;
+       time_t nTimeInSecs = 0;
+
+       MmsInitMsgAttrib(&pMmsMsg->mmsAttrib);
+       MmsInitMsgType(&pMmsMsg->msgType);
+       MmsInitMsgBody(&pMmsMsg->msgBody);
+
+       // setting mmsMsg structure
+       pMmsMsg->mailbox = pMsgInfo->folderId;
+       pMmsMsg->msgID = pMsgInfo->msgId;
+
+       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);
+
+       pMmsMsg->mmsAttrib.dataType = MMS_DATATYPE_DRAFT;
+
+       // setting date
+       time(&RawTime);
+       timeInfo = localtime(&RawTime);
+       nTimeInSecs = mktime(timeInfo);
+       pMmsMsg->mmsAttrib.date = nTimeInSecs;
+
+       // setting szMsgId
+       MmsPluginStorage::instance()->getMmsMessageId(selectedMsgId, pMmsMsg);
+
+       //setting subject
+       strcpy(pMmsMsg->mmsAttrib.szSubject, pMsgInfo->subject);
+
+       //setting adddress
+       MmsSetMsgAddressList(&pMmsMsg->mmsAttrib, pMsgInfo);
+
+       if (pMmsMsg->mmsAttrib.szTo)
+               strncpy(pMmsMsg->mmsAttrib.szFrom, pMmsMsg->mmsAttrib.szTo, strlen(pMmsMsg->mmsAttrib.szTo));
+}
+
+int MmsSearchMsgId(char *toNumber, char *szMsgID)
+{
+       MSG_BEGIN();
+
+       int msgId;
+
+       msgId = MmsPluginStorage::instance()->searchMsgId(toNumber, szMsgID);
+
+       if (msgId < 0)
+               return 0;
+
+       MSG_END();
+
+       return msgId;
+}
+
+bool MmsCheckAdditionalMedia(MMS_MESSAGE_DATA_S *pMsgData, MsgType *partHeader)
+{
+       if (_MsgMmsFindMatchedMedia(pMsgData, partHeader->param.szFileName))
+               return false;
+       else
+               return true;
+}
+
+/*PIM objects SHALL be supported as attachments to an MM*/
+bool MmsRemovePims(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       GList *cur_page = NULL;
+       GList *cur_media = NULL;
+
+       if (pMsgData == NULL)
+               return false;
+
+       cur_page = pMsgData->pagelist;
+
+       while(cur_page) {
+               MMS_PAGE_S *page = (MMS_PAGE_S *)cur_page->data;
+               if (page) {
+                       cur_media = page->medialist;
+
+                       while(cur_media) {
+                               MMS_MEDIA_S *pMedia = (MMS_MEDIA_S *)cur_media->data;
+                               if (pMedia) {
+                                       int tempType;
+                                       MsgGetTypeByFileName(&tempType, pMedia->szFilePath);
+                                       if (tempType == MIME_TEXT_X_VCALENDAR || tempType == MIME_TEXT_X_VCARD) {
+                                               page->medialist = g_list_remove_all(page->medialist, pMedia);
+                                               page->mediaCnt = g_list_length(page->medialist);
+                                               cur_media = page->medialist;
+                                               free(pMedia);
+                                       } else {
+                                               cur_media =  g_list_next(cur_media);
+                                       }
+                               } else {
+                                       cur_media =  g_list_next(cur_media);
+                               }
+                       } //cur_media while for remove pims file in list
+
+                       if (page->medialist == NULL) {//remove empty page
+                               pMsgData->pagelist = g_list_remove_all(pMsgData->pagelist, page);
+                               pMsgData->pageCnt = g_list_length(pMsgData->pagelist);
+                               cur_page = pMsgData->pagelist;
+                               free(page);
+                       } else {
+                               cur_page =  g_list_next(cur_page);
+                       }
+               }
+       }//cur_page while
+
+
+       return true;
+}
+
+msg_error_t MmsMakePreviewInfo(int msgId, MMS_MESSAGE_DATA_S *pMmsMsg)
+{
+       MMS_PAGE_S *pPage = NULL;
+       MMS_MEDIA_S *pMedia = NULL;
+
+       if (pMmsMsg == NULL)
+               return MSG_ERR_NULL_POINTER;
+
+       MmsPluginStorage::instance()->removePreviewInfo(msgId); //remove exist previnfo
+
+       if (pMmsMsg->pageCnt > 0) {
+
+               MmsPluginStorage::instance()->insertPreviewInfo(msgId, MSG_MMS_ITEM_TYPE_PAGE, (char *)"pagecount", pMmsMsg->pageCnt);
+
+               pPage = _MsgMmsGetPage(pMmsMsg, 0);
+               for (int j = 0; j < pPage->mediaCnt; j++) {
+
+                       pMedia = _MsgMmsGetMedia(pPage, j);
+                       MSG_DEBUG("pMedia's Name: %s", 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);
+
+                               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, MSG_THUMBNAIL_PATH"/%s.png", szFileName);
+                               } else {
+                                       snprintf(thumbPath, MSG_FILEPATH_LEN_MAX, MSG_THUMBNAIL_PATH"/%s.jpg", szFileName);
+                               }
+
+                               if (pMedia->mediatype == MMS_SMIL_MEDIA_IMG) {
+                                       if (makeImageThumbnail(pMedia->szFilePath, thumbPath) == true) {
+                                               MmsPluginStorage::instance()->insertPreviewInfo(msgId, MSG_MMS_ITEM_TYPE_IMG, thumbPath);
+                                       } else {
+                                               MSG_DEBUG("Fail of generating thumbnail: %s to %s", pMedia->szFilePath, thumbPath);
+                                       }
+                               } else {
+                                       if (makeVideoThumbnail(pMedia->szFilePath, thumbPath) == true) {;
+                                               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);
+                       }
+               }
+       } 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);
+       } else {
+               MSG_DEBUG("There is no attachment");
+       }
+
+       return MSG_SUCCESS;
+}
+
+void MmsPrintFileInfoForVLD(MMS_MESSAGE_DATA_S *pMmsMsg)
+{
+       MMS_PAGE_S *pPage = NULL;
+       MMS_MEDIA_S *pMedia = NULL;
+
+       if (pMmsMsg == NULL)
+               return;
+
+       if (pMmsMsg->pageCnt > 0) {
+               for (int i = 0; i < pMmsMsg->pageCnt; i++) {
+
+                       pPage = _MsgMmsGetPage(pMmsMsg, i);
+
+                       if (pPage == NULL)
+                               continue;
+
+                       for (int j = 0; j < pPage->mediaCnt; j++) {
+
+                               pMedia = _MsgMmsGetMedia(pPage, j);
+                               if (pMedia == NULL)
+                                       continue;
+
+                               MSG_MMS_VLD_FILE("[%s], %d", pMedia->szFilePath, MsgGetFileSize(pMedia->szFilePath));
+                       }
+               }
+       }
+
+       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));
+               }
+       }
+}
diff --git a/plugin/mms_plugin/MmsPluginSMILValidate.cpp b/plugin/mms_plugin/MmsPluginSMILValidate.cpp
new file mode 100755 (executable)
index 0000000..07b8c24
--- /dev/null
@@ -0,0 +1,492 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MmsPluginSmil.h"
+
+
+#define MSG_RETURN_VAL_IF_FAIL(Expr, Val)                                      \
+               if (!(Expr)) {                                                                          \
+                       MSG_DEBUG("%s:[%s] Failed - %d\n", __FUNCTION__, __LINE__, Val); \
+                       return Val;                                                                             \
+               };
+
+MSG_SMIL_ERR_E MsgMMSCreateSMIL(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       MSG_BEGIN();
+
+       MSG_SMIL_ERR_E eRet = MSG_SMIL_ERR_UNKNOWN;
+       bool bRegAdded = false;
+
+       MSG_RETURN_VAL_IF_FAIL((pMsgData!= NULL), MSG_SMIL_ERR_INVALID_PARAM);
+       MSG_RETURN_VAL_IF_FAIL((strlen(pMsgData->szSmilFilePath)> 0), MSG_SMIL_ERR_INVALID_SMIL_FILE_PATH);
+
+       eRet = _MsgMMSValidateSMILRootLayout(pMsgData);
+       if (eRet != MSG_SMIL_SUCCESS) {
+               MSG_DEBUG("MsgMMSCreateSMIL: Root Layout Information Invalid eRet =%d\n", eRet);
+               return eRet;
+       }
+
+       eRet = _MsgMMSValidateSMILRegion(pMsgData, &bRegAdded);
+       if (eRet != MSG_SMIL_SUCCESS) {
+               MSG_DEBUG("MsgMMSCreateSMIL: Region Information Invalid eRet =%d\n", eRet);
+               return eRet;
+       }
+
+       eRet = _MsgMMSValidateSMILPage(pMsgData, bRegAdded);
+       if (eRet != MSG_SMIL_SUCCESS) {
+               MSG_DEBUG("MsgMMSCreateSMIL: Page Information Invalid eRet =%d\n", eRet);
+               return eRet;
+       }
+
+       if (MMSGenerateSmilBuffer(pMsgData)) {
+               MSG_DEBUG("MsgMMSCreateSMIL: Generate SMIL Buffer is success eRet =%d\n", eRet);
+               eRet = MSG_SMIL_SUCCESS;
+       } else {
+               MSG_DEBUG("MsgMMSCreateSMIL: Generate SMIL Buffer failed eRet =%d\n", eRet);
+               eRet = MSG_SMIL_ERR_UNKNOWN;
+       }
+
+       MSG_END();
+       return eRet;
+}
+
+MSG_SMIL_ERR_E _MsgMMSValidateSMILRootLayout(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       MSG_BEGIN();
+
+       MSG_SMIL_ERR_E eRet = MSG_SMIL_ERR_INVALID_ROOTLAYOUT;
+
+       MSG_RETURN_VAL_IF_FAIL((pMsgData!= NULL), MSG_SMIL_ERR_INVALID_PARAM);
+
+       if ((pMsgData->rootlayout.width.value >  0) &&
+               (pMsgData->rootlayout.height.value> 0)) {
+               if (pMsgData->rootlayout.width.bUnitPercent == pMsgData->rootlayout.height.bUnitPercent) {
+                       MSG_DEBUG("_MsgMMSValidateSMILRootLayout: Root Layout Information Valid \n");
+                       eRet = MSG_SMIL_SUCCESS;
+               }
+       } else  {
+               MSG_DEBUG("_MsgMMSValidateSMILRootLayout: Root Layout Information not Present \n");
+               eRet = _MsgMMSAddDefaultSMILRootLayout(pMsgData);
+       }
+
+       MSG_END();
+       return eRet;
+}
+
+MSG_SMIL_ERR_E _MsgMMSAddDefaultSMILRootLayout(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       MSG_BEGIN();
+
+       char *pContent = (char *)MSG_SMIL_ROOT_LAYOUT_BG_COLOR;
+
+       MSG_RETURN_VAL_IF_FAIL((pMsgData!= NULL), MSG_SMIL_ERR_INVALID_PARAM);
+
+       pMsgData->rootlayout.width.value = MSG_SMIL_ROOT_LAYOUT_WIDTH;
+       pMsgData->rootlayout.width.bUnitPercent = MSG_SMIL_ROOT_LAYOUT_IN_PERCENT;
+
+       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]);
+
+       MSG_END();
+       return MSG_SMIL_SUCCESS;
+}
+
+MSG_SMIL_ERR_E _MsgMMSValidateSMILRegion(MMS_MESSAGE_DATA_S *pMsgData, bool *pbRegAdded)
+{
+       MSG_BEGIN();
+
+       MSG_SMIL_ERR_E eRet = MSG_SMIL_ERR_INVALID_REGION_INFO;
+
+       MSG_RETURN_VAL_IF_FAIL((pMsgData!= NULL), MSG_SMIL_ERR_INVALID_PARAM);
+       MSG_RETURN_VAL_IF_FAIL((pbRegAdded!= NULL), MSG_SMIL_ERR_INVALID_PARAM);
+
+       if (pMsgData->regionCnt == 0) {
+               bool bTextReg = MSG_SMIL_TEXT_ON_TOP;
+               bool bfullReg = false;
+               bool btwoReg = false;
+
+               MSG_DEBUG("_MsgMMSValidateSMILRegion: Region Information not Present \n");
+
+               for (int PgIdx = 0; PgIdx < pMsgData->pageCnt; ++PgIdx) {
+                       MMS_PAGE_S *pPage = _MsgMmsGetPage(pMsgData, PgIdx);
+                       int nMediaCnt = 0;
+
+                       MSG_RETURN_VAL_IF_FAIL((NULL != pPage), MSG_SMIL_ERR_INVALID_PAGE_INFO);
+
+                       for (int MediaIdx = 0; MediaIdx < pPage->mediaCnt; ++MediaIdx) {
+                               MMS_MEDIA_S *pMedia = _MsgMmsGetMedia(pPage, MediaIdx);
+
+                               MSG_RETURN_VAL_IF_FAIL((NULL != pMedia), MSG_SMIL_ERR_INVALID_PAGE_INFO);
+
+                               if (pMedia->mediatype != MMS_SMIL_MEDIA_AUDIO)
+                                       nMediaCnt++;
+                       }
+
+                       if (nMediaCnt == 1)
+                               bfullReg = true;
+                       else if (nMediaCnt == 2)
+                               btwoReg = true;
+                       else if (nMediaCnt > 2) {
+                               MSG_DEBUG("_MsgMMSValidateSMILRegion: Invalid Region Information\n");
+                               eRet = MSG_SMIL_ERR_INVALID_PAGE_INFO;
+                               return eRet;
+                       }
+               }
+
+               if (bfullReg) {
+                       eRet = _MsgMMSAddDefaultFullSMILRegion(pMsgData);
+                       if (eRet != MSG_SMIL_SUCCESS) {
+                               MSG_DEBUG("_MsgMMSValidateSMILRegion: Invalid Region Information\n");
+                               return eRet;
+                       }
+               }
+               if (btwoReg) {
+                       eRet = _MsgMMSAddDefaultFirstSMILRegion(pMsgData, bTextReg);
+                       if (eRet != MSG_SMIL_SUCCESS) {
+                               MSG_DEBUG("_MsgMMSValidateSMILRegion: Invalid Region Information\n");
+                               return eRet;
+                       }
+
+                       eRet = _MsgMMSAddDefaultSecondSMILRegion(pMsgData,!bTextReg);
+                       if (eRet != MSG_SMIL_SUCCESS) {
+                               MSG_DEBUG("_MsgMMSValidateSMILRegion: Invalid Region Information\n");
+                               return eRet;
+                       }
+               }
+               *pbRegAdded  = true;
+               eRet = MSG_SMIL_SUCCESS;
+       } else {
+               MSG_DEBUG("_MsgMMSValidateSMILRegion: Region Information Present \n");
+
+               for (int Idx = 0; Idx< pMsgData->regionCnt; ++Idx) {
+                       MMS_SMIL_REGION *pRegion = _MsgMmsGetSmilRegion(pMsgData, Idx);
+
+                       if ((pRegion->width.value == 0) ||
+                                       (pRegion->height.value == 0)) {
+                               MSG_DEBUG("_MsgMMSValidateSMILRegion: Invalid Region information\n");
+
+                               return eRet;
+                       }
+
+                       if (pMsgData->rootlayout.width.bUnitPercent == true) {
+                               if ((pRegion->width.value > 100) ||
+                                       (pRegion->height.value > 100) ||
+                                       (pRegion->nLeft.value > 100) ||
+                                       (pRegion->nTop.value > 100)) {
+                                       MSG_DEBUG("_MsgMMSValidateSMILRegion: Region and root layout information does not map\n");
+
+                                       return eRet;
+                               }
+                       } else {
+                               if (((pRegion->width.bUnitPercent == true) && (pRegion->width.value > 100)) ||
+                                       ((pRegion->height.bUnitPercent == true) && (pRegion->height.value > 100)) ||
+                                       ((pRegion->nLeft.bUnitPercent == true) && (pRegion->nLeft.value > 100)) ||
+                                       ((pRegion->nTop.bUnitPercent == true) && (pRegion->nTop.value > 100))) {
+                                       MSG_DEBUG("_MsgMMSValidateSMILRegion: Invalid Region information\n");
+
+                                       return eRet;
+                               }
+                       }
+               }
+
+               eRet = MSG_SMIL_SUCCESS;
+       }
+
+       MSG_END();
+       return eRet;
+}
+
+MSG_SMIL_ERR_E _MsgMMSAddDefaultFirstSMILRegion(MMS_MESSAGE_DATA_S *pMsgData, bool bTextReg)
+{
+       MSG_BEGIN();
+
+       MSG_SMIL_ERR_E eRet = MSG_SMIL_ERR_INVALID_REGION_INFO;
+       MMS_SMIL_REGION *pRegion = NULL;
+       char *pszfit = (char *)MSG_SMIL_REG_FIT_TYPE;
+       char *pContent = (char *)MSG_SMIL_REG_BG_COLOR;
+
+       MSG_RETURN_VAL_IF_FAIL((pMsgData!= NULL), MSG_SMIL_ERR_INVALID_PARAM);
+       pRegion = (MMS_SMIL_REGION *)calloc(sizeof(MMS_SMIL_REGION), 1);
+
+       if (pRegion == NULL) {
+               MSG_DEBUG("_MsgMMSValidateSMILRegion: Memory Allocation failed\n");
+               return eRet;
+       }
+
+       if (!strcmp(pszfit, "meet"))
+               pRegion->fit = MMSUI_IMAGE_REGION_FIT_MEET;
+       else
+               pRegion->fit = MMSUI_IMAGE_REGION_FIT_HIDDEN;
+       pRegion->bgColor = MmsSmilAtoIHexa((char *)&pContent[1]);
+
+       pRegion->nLeft.value = MSG_SMIL_FIRST_REG_LEFT;
+       pRegion->nLeft.bUnitPercent = true;
+       pRegion->nTop.value = MSG_SMIL_FIRST_REG_TOP;
+       pRegion->nTop.bUnitPercent = true;
+       pRegion->width.value = MSG_SMIL_FIRST_REG_WIDTH;
+       pRegion->width.bUnitPercent = true;
+       pRegion->height.value = MSG_SMIL_FIRST_REG_HEIGHT;
+       pRegion->height.bUnitPercent = true;
+
+       if (bTextReg)
+               snprintf(pRegion->szID, MAX_SMIL_REGION_ID, "%s", MSG_SMIL_DEFAULT_TXT_REG);
+       else
+               snprintf(pRegion->szID, MAX_SMIL_REGION_ID, "%s", MSG_SMIL_DEFAULT_IMG_REG);
+
+       if (_MsgMmsAddRegion(pMsgData,pRegion) != MSG_SUCCESS) {
+               MSG_DEBUG("_MsgMMSValidateSMILRegion: Add Region failed\n");
+               free(pRegion);
+
+               return eRet;
+       }
+
+       eRet = MSG_SMIL_SUCCESS;
+
+       MSG_END();
+       return eRet;
+}
+
+MSG_SMIL_ERR_E _MsgMMSAddDefaultSecondSMILRegion(MMS_MESSAGE_DATA_S *pMsgData, bool bTextReg)
+{
+       MSG_BEGIN();
+
+       MSG_SMIL_ERR_E eRet = MSG_SMIL_ERR_INVALID_REGION_INFO;
+       MMS_SMIL_REGION *pRegion = NULL;
+       char *pszfit = (char *)MSG_SMIL_REG_FIT_TYPE;
+       char *pContent = (char *)MSG_SMIL_REG_BG_COLOR;
+
+       MSG_RETURN_VAL_IF_FAIL((pMsgData!= NULL), MSG_SMIL_ERR_INVALID_PARAM);
+       pRegion = (MMS_SMIL_REGION *)calloc(sizeof(MMS_SMIL_REGION), 1);
+
+       if (pRegion == NULL) {
+               MSG_DEBUG("_MsgMMSValidateSMILRegion: Memory Allocation failed\n");
+               return eRet;
+       }
+
+       if (!strcmp(pszfit, "meet"))
+               pRegion->fit = MMSUI_IMAGE_REGION_FIT_MEET;
+       else
+               pRegion->fit = MMSUI_IMAGE_REGION_FIT_HIDDEN;
+       pRegion->bgColor = MmsSmilAtoIHexa((char *)&pContent[1]);
+
+       pRegion->nLeft.value = MSG_SMIL_SECOND_REG_LEFT;
+       pRegion->nLeft.bUnitPercent = true;
+       pRegion->nTop.value = MSG_SMIL_SECOND_REG_TOP;
+       pRegion->nTop.bUnitPercent = true;
+       pRegion->width.value = MSG_SMIL_SECOND_REG_WIDTH;
+       pRegion->width.bUnitPercent = true;
+       pRegion->height.value = MSG_SMIL_SECOND_REG_HEIGHT;
+       pRegion->height.bUnitPercent = true;
+
+       if (bTextReg)
+               snprintf(pRegion->szID, MAX_SMIL_REGION_ID, "%s", MSG_SMIL_DEFAULT_TXT_REG);
+       else
+               snprintf(pRegion->szID, MAX_SMIL_REGION_ID, "%s", MSG_SMIL_DEFAULT_IMG_REG);
+
+       if (_MsgMmsAddRegion(pMsgData,pRegion) != MSG_SUCCESS) {
+               MSG_DEBUG("_MsgMMSValidateSMILRegion: Add Region failed\n");
+               free(pRegion);
+
+               return eRet;
+       }
+
+       eRet = MSG_SMIL_SUCCESS;
+
+       MSG_END();
+       return eRet;
+}
+
+MSG_SMIL_ERR_E _MsgMMSAddDefaultFullSMILRegion(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       MSG_BEGIN();
+
+       MSG_SMIL_ERR_E eRet = MSG_SMIL_ERR_INVALID_REGION_INFO;
+       MMS_SMIL_REGION *pRegion = NULL;
+       char *pszfit = (char *)MSG_SMIL_REG_FIT_TYPE;
+       char *pContent = (char *)MSG_SMIL_REG_BG_COLOR;
+
+       MSG_RETURN_VAL_IF_FAIL((pMsgData!= NULL), MSG_SMIL_ERR_INVALID_PARAM);
+       pRegion = (MMS_SMIL_REGION *)calloc(sizeof(MMS_SMIL_REGION), 1);
+
+       if (pRegion == NULL) {
+               MSG_DEBUG("_MsgMMSValidateSMILRegion: Memory Allocation failed\n");
+               return eRet;
+       }
+
+       if (!strcmp(pszfit, "meet"))
+               pRegion->fit = MMSUI_IMAGE_REGION_FIT_MEET;
+       else
+               pRegion->fit = MMSUI_IMAGE_REGION_FIT_HIDDEN;
+       pRegion->bgColor = MmsSmilAtoIHexa((char *)&pContent[1]);
+
+       pRegion->nLeft.value = MSG_SMIL_FULL_REG_LEFT;
+       pRegion->nLeft.bUnitPercent = true;
+       pRegion->nTop.value = MSG_SMIL_FULL_REG_TOP;
+       pRegion->nTop.bUnitPercent = true;
+       pRegion->width.value = MSG_SMIL_FULL_REG_WIDTH;
+       pRegion->width.bUnitPercent = true;
+       pRegion->height.value = MSG_SMIL_FULL_REG_HEIGHT;
+       pRegion->height.bUnitPercent = true;
+
+       snprintf(pRegion->szID, MAX_SMIL_REGION_ID, "%s", MSG_SMIL_DEFAULT_FULL_REG);
+
+       if (_MsgMmsAddRegion(pMsgData,pRegion) != MSG_SUCCESS) {
+               MSG_DEBUG("_MsgMMSValidateSMILRegion: Add Region failed\n");
+               free(pRegion);
+
+               return eRet;
+       }
+
+       eRet = MSG_SMIL_SUCCESS;
+
+       MSG_END();
+       return eRet;
+}
+
+MSG_SMIL_ERR_E  _MsgMMSValidateSMILPage(MMS_MESSAGE_DATA_S *pMsgData, bool bRegAdded)
+{
+       MSG_BEGIN();
+
+       MSG_SMIL_ERR_E eRet = MSG_SMIL_ERR_INVALID_PAGE_INFO;
+
+       MSG_RETURN_VAL_IF_FAIL((pMsgData!= NULL), MSG_SMIL_ERR_INVALID_PARAM);
+       MSG_RETURN_VAL_IF_FAIL((pMsgData->pageCnt > 0), eRet);
+
+       for (int PgIdx = 0; PgIdx < pMsgData->pageCnt; ++PgIdx) {
+               MMS_PAGE_S *pPage = _MsgMmsGetPage(pMsgData, PgIdx);
+               int PageRegionCnt = 0;
+               int PageRegionIdx = 0;
+               bool bVidExists = false;
+               bool bImgExists = false;
+               bool bTxtExists = false;
+               bool bAudExists = false;
+               bool bImgOrVidExists = false;
+               bool bResetRegion = false;
+
+               MSG_RETURN_VAL_IF_FAIL((NULL != pPage), MSG_SMIL_ERR_INVALID_PAGE_INFO);
+               MSG_RETURN_VAL_IF_FAIL((pPage->nDur >= 0), MSG_SMIL_ERR_INVALID_PAGE_DUR);
+
+               for (int MediaIdx = 0; MediaIdx < pPage->mediaCnt; ++MediaIdx) {
+                       MMS_MEDIA_S *pMedia = _MsgMmsGetMedia(pPage, MediaIdx);
+
+                       MSG_RETURN_VAL_IF_FAIL((NULL != pMedia), MSG_SMIL_ERR_INVALID_PAGE_INFO);
+
+                       bResetRegion = false;
+                       if ((pMedia->mediatype != MMS_SMIL_MEDIA_AUDIO)) {
+                               if (bRegAdded) {
+                                       bResetRegion = true;
+                               } else if ((strlen(pMedia->regionId) == 0)) {
+                                       MSG_DEBUG("_MsgMMSValidateSMILRegion: Invalid Region Information\n");
+                                       return MSG_SMIL_ERR_INVALID_REGION_INFO;
+                               }
+                               PageRegionCnt++;
+                       }
+               }
+
+               for (int MediaIdx = 0; MediaIdx < pPage->mediaCnt; ++MediaIdx) {
+                       MMS_MEDIA_S *pMedia = _MsgMmsGetMedia(pPage, MediaIdx);
+
+                       MSG_RETURN_VAL_IF_FAIL((NULL != pMedia), MSG_SMIL_ERR_INVALID_PAGE_INFO);
+                       MSG_RETURN_VAL_IF_FAIL((strlen(pMedia->szFilePath) > 0), MSG_SMIL_ERR_INVALID_PAGE_INFO);
+
+                       switch (pMedia->mediatype) {
+                       case MMS_SMIL_MEDIA_IMG:
+                               {
+                                       if ((bImgExists == true) || (bVidExists == true) ||
+                                               (bImgOrVidExists== true)) {
+                                               eRet = MSG_SMIL_ERR_SIMILAR_MEDIA_EXISTS;
+                                       } else
+                                               bImgExists = true;
+                               }
+                               break;
+                       case MMS_SMIL_MEDIA_AUDIO:
+                               {
+                                       if ((bAudExists == true) || (bVidExists == true) ||
+                                               (bImgOrVidExists== true)) {
+                                               eRet = MSG_SMIL_ERR_SIMILAR_MEDIA_EXISTS;
+                                       } else
+                                               bAudExists = true;
+                               }
+                               break;
+                       case MMS_SMIL_MEDIA_VIDEO:
+                               {
+                                       if ((bImgExists == true) || (bVidExists == true) ||
+                                               (bImgOrVidExists== true)) {
+                                               eRet = MSG_SMIL_ERR_SIMILAR_MEDIA_EXISTS;
+                                       } else
+                                               bVidExists = true;
+                               }
+                               break;
+                       case MMS_SMIL_MEDIA_TEXT:
+                               {
+                                       if (bTxtExists == true) {
+                                               eRet = MSG_SMIL_ERR_SIMILAR_MEDIA_EXISTS;
+                                       } else
+                                               bTxtExists = true;
+                               }
+                               break;
+                       case MMS_SMIL_MEDIA_IMG_OR_VIDEO:
+                               {
+                                       if ((bImgExists == true) || (bVidExists == true) ||
+                                               (bImgOrVidExists== true)) {
+                                               eRet = MSG_SMIL_ERR_SIMILAR_MEDIA_EXISTS;
+                                       } else
+                                               bImgOrVidExists = true;
+                               }
+                               break;
+                       default:
+                               {
+                                       MSG_DEBUG("_MsgMMSValidateSMILRegion: Invalid Media Information\n");
+                                       return eRet;
+                               }
+                               break;
+                       }
+
+                       if (eRet == MSG_SMIL_ERR_SIMILAR_MEDIA_EXISTS) {
+                               MSG_DEBUG("_MsgMMSValidateSMILRegion: Similar Media Exists\n");
+                               return eRet;
+                       }
+
+                       if (bResetRegion) {
+                               if (PageRegionCnt > 1) {
+                                       if (pMedia->mediatype == MMS_SMIL_MEDIA_AUDIO) {
+                                               memset(pMedia->regionId,0x00, MAX_SMIL_REGION_ID);
+                                               continue;
+                                       }
+
+                                       if (pMedia->mediatype == MMS_SMIL_MEDIA_TEXT)
+                                               snprintf(pMedia->regionId, MAX_SMIL_REGION_ID, "%s", MSG_SMIL_DEFAULT_TXT_REG);
+                                       else
+                                               snprintf(pMedia->regionId, MAX_SMIL_REGION_ID, "%s", MSG_SMIL_DEFAULT_IMG_REG);
+                               } else
+                                       snprintf(pMedia->regionId, MAX_SMIL_REGION_ID, "%s", MSG_SMIL_DEFAULT_FULL_REG);
+                       }
+                       PageRegionIdx++;
+               }
+       }
+
+       eRet = MSG_SMIL_SUCCESS;
+
+       MSG_END();
+
+       return eRet;
+}
+
diff --git a/plugin/mms_plugin/MmsPluginSmil.cpp b/plugin/mms_plugin/MmsPluginSmil.cpp
new file mode 100755 (executable)
index 0000000..8910c11
--- /dev/null
@@ -0,0 +1,2142 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgMmsMessage.h"
+#include "MsgUtilFile.h"
+#include "MmsPluginTypes.h"
+#include "MmsPluginSmil.h"
+#include "MmsPluginMIME.h"
+#include "MmsPluginStorage.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginCodec.h"
+
+#define MSG_STDSTR_SHORT                       0x7F
+
+/* 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);
+
+#ifdef MMS_SMIL_ANIMATE
+                                       if (cmd[ELEMENT_ANIMATE])
+                                               pMedia->sMedia.sAVI.nDur = MmsSmilGetTime((char *)pAttr->children->content);
+#endif
+                                       break;
+
+                               case ATTRIBUTE_SRC:
+                               {
+                                       char *szSrc;
+                                       char szTmpSrc[MSG_FILEPATH_LEN_MAX] = {0,};
+                                       char szOutBuf[MSG_FILEPATH_LEN_MAX] = {0, };
+                                       int cLen;
+                                       int ret;
+                                       MsgMultipart *pPart = NULL;
+                                       MmsMsg *pMsg;
+
+                                       szSrc = MsgChangeHexString((char *)pAttr->children->content);
+                                       if (szSrc == NULL)
+                                               break;
+
+                                       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__
+                                       ret = MmsSmilGetMediaSrcForNormalMsg(szOutBuf, szTmpSrc, pPart);
+#else
+                                       ret = MmsSmilGetMediaSrcForNormalMsg(szOutBuf, szTmpSrc, pPart, pMedia);
+#endif
+                                       if (ret >= 0 && strlen(szOutBuf) > 0) {
+                                               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;
+#ifdef MMS_SMIL_ANIMATE
+                               case ATTRIBUTE_ATTRIBUTE_NAME:
+                                       strcpy(pMedia->sMedia.sAVI.nAttributeName, (char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_ATTRIBUTE_TYPE:
+                                       strcpy(pMedia->sMedia.sAVI.nAttributeType, (char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_TARGET_ELEMENT:
+                                       strcpy(pMedia->sMedia.sAVI.nTargetElement, (char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_FROM:
+                                       pMedia->sMedia.sAVI.nFrom = atoi((char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_TO:
+                                       pMedia->sMedia.sAVI.nTo = atoi((char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_BY:
+                                       pMedia->sMedia.sAVI.nBy = atoi((char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_VALUES:
+                                       pMedia->sMedia.sAVI.nValues = atoi((char *)pAttr->children->content);
+                                       break;
+
+                               case ATTRIBUTE_CALCMODE:
+                                       strcpy(pMedia->sMedia.sAVI.nCalcMode, (char *)pAttr->children->content);
+                                       break;
+#endif
+                               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 if (strcasecmp(szContentLI, szInBuf) == 0) {
+                       strcpy(szOutbuf, pPart->type.param.szFileName);
+                       MSG_DEBUG("match with szContentLocation");
+                       goto RETURN;
+               } else if (strcasecmp(pPart->type.param.szName, szInBuf) == 0) {
+                       strcpy(szOutbuf, pPart->type.param.szFileName);
+                       MSG_DEBUG("match with Parameter Name");
+                       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;
+#ifdef MMS_SMIL_ANIMATE
+       else if (!strcmp(pString, "attributeName"))
+               return ATTRIBUTE_ATTRIBUTE_NAME;
+       else if (!strcmp(pString, "attributeType"))
+               return ATTRIBUTE_ATTRIBUTE_TYPE;
+       else if (!strcmp(pString, "targetElement"))
+               return ATTRIBUTE_TARGET_ELEMENT;
+       else if (!strcmp(pString, "from"))
+               return ATTRIBUTE_FROM;
+       else if (!strcmp(pString, "to"))
+               return ATTRIBUTE_TO;
+       else if (!strcmp(pString, "by"))
+               return ATTRIBUTE_BY;
+       else if (!strcmp(pString, "values"))
+               return ATTRIBUTE_VALUES;
+       else if (!strcmp(pString, "calcMode"))
+               return ATTRIBUTE_CALCMODE;
+#endif
+       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");
+                       }
+
+                       __MmsSmilInsertNode(pstLayoutList, pstRootLayoutList, pstRegion);
+
+               } 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 (pstMedia) {
+               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;
+}
+
diff --git a/plugin/mms_plugin/MmsPluginStorage.cpp b/plugin/mms_plugin/MmsPluginStorage.cpp
new file mode 100755 (executable)
index 0000000..14eadc9
--- /dev/null
@@ -0,0 +1,1275 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgException.h"
+#include "MsgUtilFile.h"
+#include "MsgMmsMessage.h"
+#include "MsgStorageTypes.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginStorage.h"
+#include "MmsPluginMessage.h"
+#include "MmsPluginSmil.h"
+#include "MmsPluginDrm.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);
+}
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginStorage - Member Functions
+==================================================================================================*/
+MmsPluginStorage *MmsPluginStorage::pInstance = NULL;
+
+
+MmsPluginStorage::MmsPluginStorage()
+{
+       memset(&mmsMsg, 0, sizeof(MmsMsg));
+}
+
+
+MmsPluginStorage::~MmsPluginStorage()
+{
+       if (dbHandle.disconnect() != MSG_SUCCESS) {
+               MSG_DEBUG("DB Disconnect Fail");
+       }
+}
+
+
+MmsPluginStorage *MmsPluginStorage::instance()
+{
+       if (!pInstance)
+               pInstance = new MmsPluginStorage();
+
+       return pInstance;
+}
+
+
+void MmsPluginStorage::getMmsMessage(MmsMsg **pMmsMsg)
+{
+       *pMmsMsg = &mmsMsg;
+}
+
+
+void MmsPluginStorage::addMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData)
+{
+       MSG_BEGIN();
+
+       msg_error_t     err;
+
+       MmsMsg mmsMsg;
+
+       bzero(&mmsMsg, sizeof(mmsMsg));
+
+       mode_t file_mode = (S_IRUSR | S_IWUSR);
+
+       if (pMsgInfo->msgType.subType == MSG_SENDREQ_MMS) {
+
+               char szTemp[MAX_MSG_DATA_LEN + 1];
+
+               MMS_MESSAGE_DATA_S mmsMsgData;
+               bzero(&mmsMsgData,sizeof(MMS_MESSAGE_DATA_S));
+               if (MmsComposeMessage(&mmsMsg, pMsgInfo, pSendOptInfo, &mmsMsgData, pFileData) != true) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       __MmsReleaseMmsLists(&mmsMsgData);
+
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS Message Compose Error");
+               }
+
+               MmsPrintFileInfoForVLD(&mmsMsgData);
+
+               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) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       __MmsReleaseMmsLists(&mmsMsgData);
+
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS Stroage Error");
+               }
+
+               strcpy((char *)pMsgInfo->msgData,szTemp);
+
+               snprintf(fileName, MSG_FILENAME_LEN_MAX+1, MSG_DATA_PATH"%d", mmsMsg.msgID);
+
+               pFile = MsgOpenMMSFile(fileName);
+               if (!pFile) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       __MmsReleaseMmsLists(&mmsMsgData);
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS File open Error");
+               }
+
+               if (fchmod(fileno(pFile), file_mode) < 0) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       __MmsReleaseMmsLists(&mmsMsgData);
+                       MsgCloseFile(pFile);
+
+                       THROW(MsgException::MMS_PLG_ERROR, "chmod() error: %s", strerror(errno));
+               }
+
+               if (MmsEncodeSendReq(pFile, &mmsMsg) != true) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       __MmsReleaseMmsLists(&mmsMsgData);
+                       MsgCloseFile(pFile);
+
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS Message Encode Send Req Error");
+               }
+
+               MsgFsync(pFile);        //file is written to device immediately, it prevents missing file data from unexpected power off
+               MsgCloseFile(pFile);
+
+               char filepath[MSG_FILEPATH_LEN_MAX+1] = {0,};
+               int size = 0;
+
+               snprintf((char *)filepath, MSG_FILEPATH_LEN_MAX+1, MSG_DATA_PATH"%d.mms", pMsgInfo->msgId);
+               if (MsgGetFileSize(filepath, &size) == false) {
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS Message MsgGetFileSize Error");
+               }
+
+               pMsgInfo->dataSize = size;
+
+               MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+               MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+               __MmsReleaseMmsLists(&mmsMsgData);
+
+       } else if (pMsgInfo->msgType.subType == MSG_NOTIFICATIONIND_MMS) {
+               MSG_DEBUG("######## MmsPlgAddMessage -> MSG_NOTIFICATIONIND_MMS ###########");
+
+               MmsComposeNotiMessage(&mmsMsg, pMsgInfo->msgId);
+
+               //Need to store mms specific data (contents location, TrID, ExpiryTime, Delivery Report, message ID)
+               if (addMmsMsgToDB(&mmsMsg, pMsgInfo) != MSG_SUCCESS) {
+                       MmsReleaseMsgBody(&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, };
+
+               if (!MmsReadMsgBody(pMsgInfo->msgId, true, true, pFileData))
+                       THROW(MsgException::MMS_PLG_ERROR, "_MmsReadMsgBody Error");
+
+               MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+
+               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);
+                       MmsMakePreviewInfo(pMsgInfo->msgId, &mmsMsgData);
+                       __MmsReleaseMmsLists(&mmsMsgData);
+               }
+
+               if (addMmsMsgToDB(pMsg, pMsgInfo) != MSG_SUCCESS) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS Stroage Error");
+               }
+               memset(pMsgInfo->msgData, 0, MAX_MSG_DATA_LEN + 1);
+               strcpy((char *)pMsgInfo->msgData,szTemp);
+
+               MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+
+       } else if (pMsgInfo->msgType.subType == MSG_READREPLY_MMS || pMsgInfo->msgType.subType == MSG_READRECIND_MMS) {
+               MSG_DEBUG("######## MmsPlgAddMessage -> MSG_READREPLY_MMS || MSG_READRECIND_MMS ###########");
+
+               char filePath[MAX_FULL_PATH_SIZE+1] = {0, };
+               FILE *pFile = NULL;
+
+               msg_read_report_status_t readStatus;
+               msg_message_id_t selectedMsgId;
+               int     version;
+
+               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));
+
+               version = MmsPluginStorage::instance()->getMmsVersion(selectedMsgId);
+
+               snprintf((char *)pMsgInfo->msgData, MAX_MSG_DATA_LEN+1, MSG_DATA_PATH"%d.mms", pMsgInfo->msgId);
+
+               MmsComposeReadReportMessage(&mmsMsg, pMsgInfo, selectedMsgId);
+
+               if (addMmsMsgToDB(&mmsMsg, pMsgInfo) != MSG_SUCCESS) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS Stroage Error");
+               }
+
+               snprintf(filePath, MAX_FULL_PATH_SIZE+1, MSG_DATA_PATH"%d", mmsMsg.msgID);
+               pFile = MsgOpenMMSFile(filePath);
+               if (!pFile) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       MsgCloseFile(pFile);
+                       pFile = NULL;
+
+                       THROW(MsgException::MMS_PLG_ERROR, "MsgOpenMMSFile error");
+               }
+
+               if (fchmod(fileno(pFile), file_mode) < 0) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       MsgCloseFile(pFile);
+                       pFile = NULL;
+
+                       THROW(MsgException::MMS_PLG_ERROR, "chmod() error: %s", strerror(errno));
+               }
+
+               if (version == 0x90) {
+                       MSG_DEBUG("### version 1.0 ###");
+                       if (MmsEncodeReadReport10(pFile, &mmsMsg, readStatus) != true) {
+                               MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                               MsgCloseFile(pFile);
+                               pFile = 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) {
+                               MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                               MsgCloseFile(pFile);
+                               pFile = NULL;
+
+                               THROW(MsgException::MMS_PLG_ERROR, "MMS Encode Read Report 1.1 Error");
+                       }
+               }
+
+               MsgFsync(pFile);
+               MsgCloseFile(pFile);
+               pFile = NULL;
+
+               MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+
+               MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+
+       } else if (pMsgInfo->msgType.subType == MSG_FORWARD_MMS) {
+               MSG_DEBUG("######## MmsPlgAddMessage -> MSG_FORWARD_MMS ###########");
+
+               char filePath[MAX_FULL_PATH_SIZE + 1] = {0, };
+               char szTemp[MAX_MSG_DATA_LEN + 1] = {0, };
+               FILE *pFile = NULL;
+               MMS_MESSAGE_DATA_S mmsMsgData;
+
+               if (MmsComposeMessage(&mmsMsg, pMsgInfo, pSendOptInfo, &mmsMsgData, pFileData) != true) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       __MmsReleaseMmsLists(&mmsMsgData);
+
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS Message Compose Error");
+               }
+
+               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) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       __MmsReleaseMmsLists(&mmsMsgData);
+
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS Stroage Error");
+               }
+
+               strcpy((char *)pMsgInfo->msgData,szTemp);
+
+               snprintf(filePath, MAX_FULL_PATH_SIZE + 1 , MSG_DATA_PATH"%d", mmsMsg.msgID);
+
+               pFile = MsgOpenMMSFile(filePath);
+               if (!pFile) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       __MmsReleaseMmsLists(&mmsMsgData);
+                       MsgCloseFile(pFile);
+                       pFile = NULL;
+
+                       THROW(MsgException::MMS_PLG_ERROR, "MsgOpenMMSFile error");
+               }
+
+               if (fchmod(fileno(pFile), file_mode) < 0) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       __MmsReleaseMmsLists(&mmsMsgData);
+                       MsgCloseFile(pFile);
+                       pFile = NULL;
+
+                       THROW(MsgException::MMS_PLG_ERROR, "chmod() error: %s", strerror(errno));
+               }
+
+               if (MmsEncodeSendReq(pFile, &mmsMsg) != true) {
+                       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+                       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+                       __MmsReleaseMmsLists(&mmsMsgData);
+                       MsgCloseFile(pFile);
+                       pFile = NULL;
+
+                       THROW(MsgException::MMS_PLG_ERROR, "MMS Message Encode Send Req Error");
+               }
+               MsgFsync(pFile);
+               MsgCloseFile(pFile);
+               pFile = NULL;
+
+               MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+               MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+               __MmsReleaseMmsLists(&mmsMsgData);
+       }
+
+       MSG_END();
+}
+
+
+void MmsPluginStorage::composeReadReport(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       FILE *pFile = NULL;
+
+       msg_read_report_status_t readStatus;
+       int     version;
+
+       memcpy(&readStatus, pMsgInfo->msgData, sizeof(msg_read_report_status_t));
+
+       MSG_DEBUG("pMsgInfo->msgId = %d", pMsgInfo->msgId);
+
+       version = MmsPluginStorage::instance()->getMmsVersion(pMsgInfo->msgId);
+
+       snprintf((char *)pMsgInfo->msgData, MAX_MSG_DATA_LEN+1, MSG_DATA_PATH"%d-Read-Rec.ind", pMsgInfo->msgId);
+
+       if (version == 0x90)
+               pMsgInfo->msgType.subType = MSG_READREPLY_MMS;
+       else
+               pMsgInfo->msgType.subType = MSG_READRECIND_MMS;
+
+       MmsComposeReadReportMessage(&mmsMsg, pMsgInfo, pMsgInfo->msgId);
+
+       pFile = MsgOpenFile(pMsgInfo->msgData, "wb+");
+       if (!pFile)
+               THROW(MsgException::MMS_PLG_ERROR, "MsgOpenMMSFile 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");
+               }
+       } 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");
+               }
+       }
+
+       MsgCloseFile(pFile);
+}
+
+
+msg_error_t MmsPluginStorage::addMmsMsgToDB(MmsMsg *pMmsMsg, const MSG_MESSAGE_INFO_S *pMsgInfo, int attachCnt)
+{
+       MSG_BEGIN();
+
+       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 (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+       if (updateMmsAttachCount(pMmsMsg->msgID, attachCnt) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t    MmsPluginStorage::plgGetMmsMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo, MMS_MESSAGE_DATA_S *pMmsMsg, char **pDestMsg)
+{
+       MSG_BEGIN();
+
+       msg_error_t     err = MSG_SUCCESS;
+
+       int partCnt = 0;
+       unsigned int nSize = 0;
+
+       MsgType partHeader;
+       MmsAttrib pMmsAttrib;
+
+       char szBuf[MSG_FILEPATH_LEN_MAX + 1] = {0, };
+       bool bMultipartRelated = false;
+
+       if (pSendOptInfo != NULL) {
+               char sqlQuery[MAX_QUERY_LEN + 1];
+
+               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);
+
+               MSG_DEBUG("### SQLQuery = %s ###", sqlQuery);
+
+               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+                       MSG_DEBUG("MSG_ERR_DB_PREPARE");
+
+               if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+                       pSendOptInfo->bDeliverReq = dbHandle.columnInt(0);
+                       MSG_DEBUG("## delivery = %d ##", pSendOptInfo->bDeliverReq);
+
+                       pSendOptInfo->bKeepCopy = dbHandle.columnInt(1);
+                       MSG_DEBUG("## bKeepCopy = %d ##", pSendOptInfo->bKeepCopy);
+
+                       pSendOptInfo->option.mmsSendOptInfo.bReadReq = dbHandle.columnInt(2);
+                       MSG_DEBUG("## bReadReq = %d ##", pSendOptInfo->option.mmsSendOptInfo.bReadReq);
+
+                       pSendOptInfo->option.mmsSendOptInfo.priority = dbHandle.columnInt(3);
+                       MSG_DEBUG("## priority = %d ##", pSendOptInfo->option.mmsSendOptInfo.priority);
+
+                       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);
+
+                       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;
+               }
+
+               dbHandle.finalizeQuery();
+       }
+
+       if (MmsReadMsgBody(pMsg->msgId, true, false, NULL) == false) {
+               MSG_DEBUG("The MMS Message might include drm contents!!!");
+
+#ifdef __SUPPORT_DRM__
+               if (MmsDrm2GetConvertState() == MMS_DRM2_CONVERT_REQUIRED) {
+                       bool bRetToConvert = true;
+
+                       bRetToConvert = MmsDrm2ConvertMsgBody(mmsHeader.msgType.szOrgFilePath);
+
+                       MmsDrm2SetConvertState(MMS_DRM2_CONVERT_FINISH);
+
+                       if (bRetToConvert) {
+                               int ret;
+                               ret = remove(mmsHeader.msgType.szOrgFilePath);
+                               if (ret != 0) {
+                                       MSG_DEBUG("remove fail\n");
+                               }
+
+                               ret = rename(MMS_DECODE_DRM_CONVERTED_TEMP_FILE, mmsHeader.msgType.szOrgFilePath);
+                               if (ret != 0) {
+                                       MSG_DEBUG("rename fail\n");
+                               }
+
+                               if (MmsDrm2ReadMsgConvertedBody(pMsg, true, false, NULL) == false) {
+                                       MSG_DEBUG("MmsLoadMsg:MmsDrm2ReadMsgConvertedBody() returns false\n");
+                                       goto L_CATCH;
+                               }
+                       } else {
+                               goto L_CATCH;
+                       }
+               }
+#endif
+       }
+
+       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);
+
+       if (pMmsAttrib.contentType == MIME_MULTIPART_RELATED || pMmsAttrib.contentType == MIME_APPLICATION_VND_WAP_MULTIPART_RELATED) {
+               char *pSmilDoc = NULL;
+
+               pSmilDoc = MmsSmilGetPresentationData(pMsg->msgId);
+               if (!pSmilDoc) {
+                       goto L_CATCH;
+               }
+
+               MmsSmilParseSmilDoc(pMmsMsg, pSmilDoc);
+               MmsRemovePims(pMmsMsg);
+               bMultipartRelated = true;
+       }
+
+       partCnt = MmsGetMediaPartCount(pMsg->msgId);
+       MSG_DEBUG("MmsUiGetMediaAttachInfo: partCnt=%d\n", partCnt);
+
+       if (partCnt < 0) {
+               MSG_DEBUG("MmsUiGetMediaAttachInfo: partCnt=%d\n", partCnt);
+               goto FREE_CATCH;
+       }
+
+       for (int i = 0; i < partCnt; ++i) {
+               if (!MmsGetMediaPartHeader(i, &partHeader)) {
+                       MSG_DEBUG("MmsUiGetMediaAttachInfo: MmsGetMediaPartHeader failed\n");
+                       goto FREE_CATCH;
+               }
+
+               if (partHeader.contentSize > 0) {
+                       if (!strcasecmp(partHeader.param.szFileName, "cid:")) {
+                               strncpy((char *)szBuf, &partHeader.param.szFileName[4], MSG_FILEPATH_LEN_MAX);
+                       } else {
+                               strncpy((char *)szBuf, partHeader.param.szFileName, MSG_FILEPATH_LEN_MAX);
+                       }
+                       sprintf(partHeader.param.szFileName, MSG_DATA_PATH"%s", szBuf);
+
+                       if (!bMultipartRelated || MmsCheckAdditionalMedia(pMmsMsg, &partHeader)) {
+
+                               MMS_ATTACH_S *attachment = NULL;
+                               int tempType;
+
+                               attachment = (MMS_ATTACH_S *)calloc(sizeof(MMS_ATTACH_S), 1);
+
+                               MsgGetTypeByFileName(&tempType, partHeader.param.szFileName);
+                               attachment->mediatype = (MimeType)tempType;
+
+                               strcpy(attachment->szFilePath, partHeader.param.szFileName);
+
+                               strncpy(attachment->szFileName, partHeader.param.szName, MSG_FILENAME_LEN_MAX -1);
+
+                               attachment->fileSize = partHeader.contentSize;
+
+                               _MsgMmsAddAttachment(pMmsMsg, attachment);
+                       }
+               }
+       }
+
+       *pDestMsg = _MsgMmsSerializeMessageData(pMmsMsg, &nSize);
+
+       __MmsReleaseMmsLists(pMmsMsg);
+
+
+       MmsMsg *pStoMmsMsg;
+       MmsPluginStorage::instance()->getMmsMessage(&pStoMmsMsg);
+       MmsInitHeader();
+       MmsUnregisterDecodeBuffer();
+#ifdef __SUPPORT_DRM__
+       MmsReleaseMsgDRMInfo(&pStoMmsMsg->msgType.drmInfo);
+#endif
+       MmsReleaseMsgBody(&pStoMmsMsg->msgBody, pStoMmsMsg->msgType.type);
+
+       pMsg->dataSize = nSize;
+
+       MSG_END();
+
+       return err;
+
+FREE_CATCH:
+       if (bMultipartRelated) {
+               __MmsReleaseMmsLists(pMmsMsg);
+       }
+
+L_CATCH:
+       MSG_DEBUG("MmsPlgUpdateMessage : Update MMS Message Failed");
+       MSG_END();
+       {
+               MmsMsg *pMsg;
+               MmsPluginStorage::instance()->getMmsMessage(&pMsg);
+               MmsInitHeader();
+
+               MmsUnregisterDecodeBuffer();
+#ifdef __SUPPORT_DRM__
+               MmsReleaseMsgDRMInfo(&pMsg->msgType.drmInfo);
+#endif
+               MmsReleaseMsgBody(&pMsg->msgBody, pMsg->msgType.type);
+
+               return MSG_ERR_STORAGE_ERROR;
+       }
+}
+
+
+msg_error_t MmsPluginStorage::updateMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData)
+{
+       MSG_BEGIN();
+
+       msg_error_t     err = MSG_SUCCESS;
+
+       MmsMsg mmsMsg;
+       bzero(&mmsMsg, sizeof(mmsMsg));
+
+       char filePath[MAX_FULL_PATH_SIZE+1] = {0, };
+       char sqlQuery[MAX_QUERY_LEN + 1];
+
+       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;
+
+       MMS_MESSAGE_DATA_S mmsMsgData;
+
+       if (MmsComposeMessage(&mmsMsg, pMsgInfo, pSendOptInfo, &mmsMsgData, pFileData) != true) {
+               MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+               MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+               __MmsReleaseMmsLists(&mmsMsgData);
+
+               THROW(MsgException::MMS_PLG_ERROR, "MMS Message Compose Error");
+       }
+
+       snprintf(filePath, MAX_FULL_PATH_SIZE+1, MSG_DATA_PATH"%d", mmsMsg.msgID);
+
+       pFile = MsgOpenMMSFile(filePath);
+
+       if (MmsEncodeSendReq(pFile, &mmsMsg) != true) {
+               MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+               MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+               __MmsReleaseMmsLists(&mmsMsgData);
+               MsgCloseFile(pFile);
+
+               THROW(MsgException::MMS_PLG_ERROR, "MMS Message Encode Send Req Error");
+       }
+
+       MsgCloseFile(pFile);
+
+       int size = 0;
+       bzero(filePath, sizeof(filePath));
+       snprintf((char *)filePath, MAX_FULL_PATH_SIZE+1, MSG_DATA_PATH"%d.mms", pMsgInfo->msgId);
+       if (MsgGetFileSize(filePath, &size) == false) {
+               THROW(MsgException::MMS_PLG_ERROR, "MMS Message MsgGetFileSize Error");
+       }
+
+       pMsgInfo->dataSize = size;
+
+
+       MmsReleaseMsgBody(&mmsMsg.msgBody, mmsMsg.msgType.type);
+       MmsReleaseMmsAttrib(&mmsMsg.mmsAttrib);
+
+       __MmsReleaseMmsLists(&mmsMsgData);
+
+       MSG_END();
+
+       return err;
+}
+
+
+msg_error_t MmsPluginStorage::updateConfMessage(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       char sqlQuery[MAX_QUERY_LEN + 1];
+
+       MMS_RECV_DATA_S *pMmsRecvData = (MMS_RECV_DATA_S *)pMsgInfo->msgData;
+
+       MSG_DEBUG("###### pMsgInfo->msgData = %s #######", pMmsRecvData->retrievedFilePath);
+
+       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);
+
+       MSG_DEBUG("SQLQuery = %s", sqlQuery);
+
+       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MmsPluginStorage::updateMsgServerID(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo)
+{
+       MSG_BEGIN();
+
+       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_DEBUG("SQLQuery = %s", sqlQuery);
+
+       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);
+
+               MSG_DEBUG("SQLQuery = %s", sqlQuery);
+
+               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
+                       return MSG_ERR_DB_EXEC;
+               }
+       }
+
+       dbHandle.finalizeQuery();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MmsPluginStorage::updateNetStatus(msg_message_id_t msgId, msg_network_status_t netStatus)
+{
+       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, netStatus, msgId);
+
+       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t MmsPluginStorage::insertDeliveryReport(msg_message_id_t msgId, char *address, MmsMsgMultiStatus *pStatus)
+{
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       //( 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("QUERY : [%s]", sqlQuery);
+
+       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t MmsPluginStorage::insertReadReport(msg_message_id_t msgId, char *address, MmsMsgMultiStatus *pStatus)
+{
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       //( 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);
+
+       MSG_DEBUG("QUERY : [%s]", sqlQuery);
+
+       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_BEGIN();
+
+       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, VERSION = %d WHERE MSG_ID = %d;",
+                               MMS_PLUGIN_MESSAGE_TABLE_NAME, attrib->bAskDeliveryReport, attrib->bAskReadReply, attrib->priority, attrib->version, msgId);
+       }
+
+       MSG_DEBUG("QUERY : [%s]", sqlQuery);
+
+       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MmsPluginStorage::updateMmsAttachCount(msg_message_id_t msgId, int count)
+{
+       MSG_BEGIN();
+
+       char sqlQuery[MAX_QUERY_LEN + 1];
+
+       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 (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to execute query [%s]", sqlQuery);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+void MmsPluginStorage::getMmsAttrib(msg_message_id_t msgId, MmsMsg *pMmsMsg)
+{
+       char sqlQuery[MAX_QUERY_LEN + 1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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");
+
+       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);
+       }
+
+       dbHandle.finalizeQuery();
+}
+
+
+msg_error_t MmsPluginStorage::getMmsMessageId(msg_message_id_t selectedMsgId, MmsMsg *pMmsMsg)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int rowCnt = 0;
+
+       char sqlQuery[MAX_QUERY_LEN + 1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MESSAGE_ID FROM %s WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, selectedMsgId);
+
+       err = dbHandle.getTable(sqlQuery, &rowCnt);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               dbHandle.freeTable();
+               MSG_DEBUG("[Error]Failed to Get Table");
+               return MSG_ERR_DB_NORECORD;
+       }
+
+       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.freeTable();
+
+       return MSG_SUCCESS;
+}
+
+
+int MmsPluginStorage::getMmsVersion(msg_message_id_t selectedMsgId)
+{
+       msg_error_t err = MSG_SUCCESS;
+       int rowCnt = 0;
+
+       int     version = 0;
+
+       char sqlQuery[MAX_QUERY_LEN + 1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT VERSION FROM %s WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, selectedMsgId);
+
+       MSG_DEBUG("SqlQuery = %s", sqlQuery);
+
+       err = dbHandle.getTable(sqlQuery, &rowCnt);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               dbHandle.freeTable();
+               MSG_DEBUG("[Error]Failed to Get Table");
+               return version;
+       }
+
+       if (rowCnt != 1) {
+               dbHandle.freeTable();
+               MSG_DEBUG("[Error]MSG_ERR_DB_NORECORD");
+               return version;
+       }
+
+       version = dbHandle.getColumnToInt(1);
+
+       dbHandle.freeTable();
+
+       return version;
+}
+
+
+msg_error_t MmsPluginStorage::getContentLocation(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       char sqlQuery[MAX_QUERY_LEN + 1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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)
+               return MSG_ERR_DB_PREPARE;
+
+       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);
+               }
+       } else {
+               dbHandle.finalizeQuery();
+
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+/* reject_msg_support */
+msg_error_t MmsPluginStorage::getTrID(MSG_MESSAGE_INFO_S *pMsgInfo,char *pszTrID,int nBufferLen)
+{
+       char sqlQuery[MAX_QUERY_LEN + 1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT TRANSACTION_ID FROM %s WHERE MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_TABLE_NAME, pMsgInfo->msgId);
+
+       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       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();
+
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+/* reject_msg_support */
+
+msg_error_t MmsPluginStorage::getAddressInfo(msg_message_id_t msgId, MSG_ADDRESS_INFO_S *pAddrInfo)
+{
+       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);
+
+       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 MmsPluginStorage::getMmsRawFilePath(msg_message_id_t msgId, char *pFilepath)
+{
+       char sqlQuery[MAX_QUERY_LEN + 1];
+
+       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)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+               if (dbHandle.columnText(0) != NULL) {
+                       strcpy(pFilepath, (char *)dbHandle.columnText(0));
+               }
+       } else {
+               dbHandle.finalizeQuery();
+
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+int MmsPluginStorage::searchMsgId(char *toNumber, char *szMsgID)
+{
+       int msgId = -1;
+
+       msg_folder_id_t folderId = MSG_SENTBOX_ID;
+
+       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);
+
+       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::setReadReportSendStatus(msg_message_id_t msgId, int readReportSendStatus)
+{
+       bool bReadReportSent = false;
+
+       if ((MmsRecvReadReportSendStatus)readReportSendStatus == MMS_RECEIVE_READ_REPORT_SENT)
+               bReadReportSent = true;
+       else
+               bReadReportSent = false;
+
+       char sqlQuery[MAX_QUERY_LEN + 1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       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)
+               return MSG_ERR_DB_EXEC;
+
+       return MSG_SUCCESS;
+}
+
+
+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;
+
+       // 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) {
+                               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;
+                                               }
+                                       }
+                               }
+
+                               if (pMmsMsgText) {
+                                       free(pMmsMsgText);
+                                       pMmsMsgText = NULL;
+                               }
+                               bText = true;
+                               break;
+                       }
+               }
+
+               if (bText)
+                       break;
+       }
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t MmsPluginStorage::insertPreviewInfo(int msgId, int type, char *value, int count)
+{
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       //(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("QUERY : [%s]", sqlQuery);
+
+       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t MmsPluginStorage::removePreviewInfo(int msgId)
+{
+       char sqlQuery[MAX_QUERY_LEN + 1];
+       char filePath[MSG_FILEPATH_LEN_MAX] = {0,};
+
+       // 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) {
+               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_DEBUG("Fail to delete file [%s]", filePath);
+               else
+                       MSG_DEBUG("Success to delete file [%s]", filePath);
+       }
+
+       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);
+
+       MSG_DEBUG("QUERY : [%s]", sqlQuery);
+
+       if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+       return MSG_SUCCESS;
+}
diff --git a/plugin/mms_plugin/MmsPluginTextConvert.cpp b/plugin/mms_plugin/MmsPluginTextConvert.cpp
new file mode 100755 (executable)
index 0000000..912be9d
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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)
+{
+       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;
+       }
+
+       pDest = g_convert (pSrc, srcLen,
+                       pToCodeSet, pFromCodeset,
+              &bytes_read, &bytes_written,
+              &error);
+
+       if (error != NULL) {
+               printf("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) {
+               printf("Error in g_convert, pDest = %s, bytes_written = %d, bytes_read = %d\n", pDest, bytes_written, bytes_read);
+               goto __CATCH;
+       }
+
+       *ppDest = pDest;
+       *pDestLen = bytes_written;
+
+       return true;
+
+__CATCH:
+       if (pDest)
+               g_free(pDest);
+
+       return false;
+}
diff --git a/plugin/mms_plugin/MmsPluginTransport.cpp b/plugin/mms_plugin/MmsPluginTransport.cpp
new file mode 100755 (executable)
index 0000000..804f1db
--- /dev/null
@@ -0,0 +1,157 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilFile.h"
+#include "MmsPluginDebug.h"
+#include "MmsPluginTypes.h"
+#include "MmsPluginTransport.h"
+#include "MmsPluginUserAgent.h"
+#include "MsgGconfWrapper.h"
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MmsPluginTransport - Member Functions
+==================================================================================================*/
+MmsPluginTransport *MmsPluginTransport::pInstance = NULL;
+
+
+MmsPluginTransport::MmsPluginTransport()
+{
+
+}
+
+
+MmsPluginTransport::~MmsPluginTransport()
+{
+
+}
+
+
+MmsPluginTransport *MmsPluginTransport::instance()
+{
+       if (!pInstance)
+               pInstance = new MmsPluginTransport();
+
+       return pInstance;
+}
+
+
+void MmsPluginTransport::submitRequest(const MSG_REQUEST_INFO_S *pReqInfo)
+{
+       mmsTranQEntity reqItem = {0};
+
+       reqItem.isCompleted = false;
+       reqItem.reqID = pReqInfo->reqId;
+
+       char *msisdn = NULL;
+       msisdn = MsgSettingGetString(MSG_SIM_MSISDN);
+
+       MSG_DEBUG("pReqInfo->msgInfo.msgType.subType [%d]", pReqInfo->msgInfo.msgType.subType);
+
+       switch (pReqInfo->msgInfo.msgType.subType) {
+       case MSG_SENDREQ_MMS:
+       case MSG_SENDREQ_JAVA_MMS:
+               MSG_DEBUG("######### SEND REQUEST : 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;
+
+       case MSG_GET_MMS:
+               MSG_DEBUG("######### AUTO RETRIEVE : GET TRANSACTION");
+               reqItem.msgId = pReqInfo->msgInfo.msgId;
+               reqItem.eMmsPduType = eMMS_RETRIEVE_AUTO;
+               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);
+               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: //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);
+               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;
+               reqItem.eMmsPduType = eMMS_RETRIEVE_MANUAL;
+               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);
+               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
+               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
+               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();
+}
+
+void MmsPluginTransport::cancelRequest(msg_request_id_t reqId)
+{
+
+
+}
+
diff --git a/plugin/mms_plugin/MmsPluginUserAgent.cpp b/plugin/mms_plugin/MmsPluginUserAgent.cpp
new file mode 100755 (executable)
index 0000000..32fa3c5
--- /dev/null
@@ -0,0 +1,667 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilFile.h"
+#include "MsgGconfWrapper.h"
+
+
+#include "MmsPluginDebug.h"
+#include "MmsPluginUserAgent.h"
+#include "MmsPluginHttp.h"
+#include "MmsPluginConnManWrapper.h"
+#include "MmsPluginEventHandler.h"
+#include "MmsPluginInternal.h"
+#include "MmsPluginCodec.h"
+#include "MmsPluginDrm.h"
+#include "MmsPluginStorage.h"
+
+extern MmsHeader mmsHeader;
+
+void PRINT_PDU_TYPE(MMS_PDU_TYPE_T pduType)
+{
+       switch (pduType) {
+       case eMMS_SEND_REQ:
+               MSG_DEBUG("[SEND_REQ]");
+               break;
+       case eMMS_SEND_CONF:
+               MSG_DEBUG("[MMS_SEND_CONF]");
+               break;
+       case eMMS_RETRIEVE_AUTO:
+               MSG_DEBUG("[MMS_RETRIEVE_AUTO]");
+               break;
+       case eMMS_RETRIEVE_MANUAL:
+               MSG_DEBUG("[MMS_RETRIEVE_MANUAL]");
+               break;
+       case eMMS_RETRIEVE_AUTO_CONF:
+               MSG_DEBUG("[MMS_RETRIEVE_AUTO_CONF]");
+               break;
+       case eMMS_RETRIEVE_MANUAL_CONF:
+               MSG_DEBUG("[MMS_RETRIEVE_MANUAL_CONF]");
+               break;
+       case eMMS_DELIVERY_IND:
+               MSG_DEBUG("[MMS_DELIVERY_IND]");
+               break;
+       case eMMS_NOTIFICATION_IND:
+               MSG_DEBUG("[MMS_NOTIFICATION_IND]");
+               break;
+       case eMMS_NOTIFYRESP_IND:
+               MSG_DEBUG("[MMS_NOTIFYRESP_IND]");
+               break;
+       case eMMS_ACKNOWLEDGE_IND:
+               MSG_DEBUG("[MMS_ACKNOWLEDGE_IND]");
+               break;
+       case eMMS_FORWARD_REQ:
+               MSG_DEBUG("[MMS_FORWARD_REQ]");
+               break;
+       case eMMS_FORWARD_CONF:
+               MSG_DEBUG("[MMS_FORWARD_CONF]");
+               break;
+       case eMMS_CANCEL_REQ:
+               MSG_DEBUG("[MMS_CANCEL_REQ]");
+               break;
+       case eMMS_CANCEL_CONF:
+               MSG_DEBUG("[MMS_CANCEL_CONF]");
+               break;
+       case eMMS_DELETE_REQ:
+               MSG_DEBUG("[MMS_DELETE_REQ]");
+               break;
+       case eMMS_DELETE_CONF:
+               MSG_DEBUG("[MMS_DELETE_CONF]");
+               break;
+       case eMMS_READREC_IND:
+               MSG_DEBUG("[MMS_READREC_IND]");
+               break;
+       case eMMS_READORIG_IND:
+               MSG_DEBUG("[MMS_READORIG_IND]");
+               break;
+       case eMMS_MBOX_STORE_REQ:
+               MSG_DEBUG("[MMS_MBOX_STORE_REQ]");
+               break;
+       case eMMS_MBOX_STORE_CONF:
+               MSG_DEBUG("[MMS_MBOX_STORE_CONF]");
+               break;
+       case eMMS_MBOX_VIEW_REQ:
+               MSG_DEBUG("[MMS_MBOX_VIEW_REQ]");
+               break;
+       case eMMS_MBOX_VIEW_CONF:
+               MSG_DEBUG("[MMS_MBOX_VIEW_CONF]");
+               break;
+       case eMMS_MBOX_UPLOAD_REQ:
+               MSG_DEBUG("[MMS_MBOX_UPLOAD_REQ]");
+               break;
+       case eMMS_MBOX_UPLOAD_CONF:
+               MSG_DEBUG("[MMS_MBOX_UPLOAD_CONF]");
+               break;
+       case eMMS_MBOX_DELETE_REQ:
+               MSG_DEBUG("[MMS_MBOX_DELETE_REQ]");
+               break;
+       case eMMS_MBOX_DELETE_CONF:
+               MSG_DEBUG("[MMS_MBOX_DELETE_CONF]");
+               break;
+       default:
+               MSG_DEBUG("[Unknown PDU Type]");
+               break;
+       }
+}
+
+
+void PRINT_QUEUE_ENTITY(mmsTranQEntity *entity)
+{
+       MSG_DEBUG("Entity: msgId: %d", entity->msgId);
+       MSG_DEBUG("Entity: completed: %d", entity->isCompleted);
+       MSG_DEBUG("Entity: eMmsPduType: %d", entity->eMmsPduType);
+       MSG_DEBUG("Entity: eHttpCmdType: %d", entity->eHttpCmdType);
+       MSG_DEBUG("Entity: GetLen: %d", entity->getDataLen);
+       MSG_DEBUG("Entity: GetData: (%s)", entity->pGetData);
+       MSG_DEBUG("Entity: postLen: %d", entity->postDataLen);
+       MSG_DEBUG("Entity: pPostData: (%s)", entity->pPostData);
+}
+
+void updatePduType(mmsTranQEntity *qEntity)
+{
+       switch(qEntity->eMmsPduType) {
+       case eMMS_SEND_REQ:
+               qEntity->eMmsPduType = eMMS_SEND_CONF;
+               break;
+       case eMMS_RETRIEVE_AUTO:
+               qEntity->eMmsPduType = eMMS_RETRIEVE_AUTO_CONF;
+               break;
+       case eMMS_RETRIEVE_MANUAL:
+               qEntity->eMmsPduType = eMMS_RETRIEVE_MANUAL_CONF;
+               break;
+       case eMMS_RETRIEVE_AUTO_CONF:
+               qEntity->eMmsPduType = eMMS_NOTIFYRESP_IND;
+               break;
+       case eMMS_READREC_IND:
+               qEntity->eMmsPduType = eMMS_SEND_CONF;
+               break;
+       case eMMS_READREPORT_REQ:
+               qEntity->eMmsPduType = eMMS_READREPORT_CONF;
+               break;
+       case eMMS_RETRIEVE_MANUAL_CONF:
+               qEntity->eMmsPduType = eMMS_ACKNOWLEDGE_IND;
+               break;
+       case eMMS_DELETE_REQ:
+               qEntity->eMmsPduType = eMMS_DELETE_CONF;
+               break;
+       case eMMS_FORWARD_REQ:
+               qEntity->eMmsPduType = eMMS_FORWARD_CONF;
+               break;
+       case eMMS_MBOX_STORE_REQ:
+               qEntity->eMmsPduType = eMMS_MBOX_STORE_CONF;
+               break;
+       case eMMS_MBOX_VIEW_REQ:
+               qEntity->eMmsPduType = eMMS_MBOX_VIEW_CONF;
+               break;
+       case eMMS_MBOX_UPLOAD_REQ:
+               qEntity->eMmsPduType = eMMS_MBOX_UPLOAD_CONF;
+               break;
+       case eMMS_MBOX_DELETE_REQ:
+               qEntity->eMmsPduType = eMMS_MBOX_DELETE_CONF;
+               break;
+       default:
+               break;
+       }
+
+       MSG_DEBUG("Update PDU Type:");
+       PRINT_PDU_TYPE(qEntity->eMmsPduType);
+}
+
+MmsPluginUaManager *MmsPluginUaManager::pInstance = NULL;
+
+MmsPluginUaManager::MmsPluginUaManager()
+{
+       running = false;
+       mmsTranQ.clear();
+}
+
+MmsPluginUaManager::~MmsPluginUaManager()
+{
+       if (pInstance) {
+               delete pInstance;
+               pInstance = NULL;
+       }
+}
+
+MmsPluginUaManager *MmsPluginUaManager::instance()
+{
+       if (!pInstance)
+               pInstance = new MmsPluginUaManager();
+
+       return pInstance;
+}
+
+void MmsPluginUaManager::start()
+{
+//     bool bStart = true;
+
+       MutexLocker lock(mx);
+
+       if (!running) {
+
+               running = true;
+               MsgThread::start();
+       }
+}
+
+MMS_NET_ERROR_T MmsPluginUaManager::submitHandler(mmsTranQEntity *qEntity)
+{
+       MMS_NET_ERROR_T ret = eMMS_UNKNOWN;
+       int retryCount = 0;
+
+       MSG_DEBUG("request Submit:");
+       PRINT_PDU_TYPE(qEntity->eMmsPduType);
+       PRINT_QUEUE_ENTITY(qEntity);
+
+       MmsPluginHttpAgent*     httpAgent = MmsPluginHttpAgent::instance();
+
+       while (retryCount < RETRY_MAX) {
+               ret = httpAgent->cmdRequest(qEntity->eHttpCmdType);
+
+               // 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;
+}
+
+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;
+
+       pMmsPldCd = pHttpAgent->getMmsPldCd();
+
+       if (qEntity->pGetData) {
+               free(qEntity->pGetData);
+               qEntity->pGetData = NULL;
+       }
+       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;
+
+       MSG_DEBUG("dataLen:%d  pData:(%s)", qEntity->getDataLen, qEntity->pGetData);
+
+       ret = eMMS_HTTP_CONF_SUCCESS;
+
+       return ret;
+}
+
+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();
+                       wait();
+                       unlock();
+               }
+
+               // Request CM Open
+               if (!(cmAgent->open())) {
+                       MSG_DEBUG("Cm Open Failed");
+
+                       // delete all request from reqQEntities
+                       goto CLEANUP;
+               }
+
+               httpAgent->SetMMSProfile();
+
+               while (!mmsTranQ.empty()) {
+
+                       MSG_DEBUG("###### mmsTranQ.size [%d]", mmsTranQ.size());
+
+                       mmsTranQEntity reqEntity;
+                       memset(&reqEntity, 0, sizeof(mmsTranQEntity));
+
+                       mmsTranQ.front(&reqEntity);
+
+                       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) {
+                                       MSG_DEBUG("Transaction Error: submit failed");
+
+                                       MmsPluginEventHandler::instance()->handleMmsError(&reqEntity);
+                                       mmsTranQ.pop_front();
+                                       //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.isCompleted = true;
+
+                                       mmsTranQ.pop_front();
+
+                                       MSG_DEBUG("Transaction Completed");
+                                       break;
+                               } else {
+                                       // change MmsPduType from XXX.req to XXX.conf for waiting
+                                       MSG_DEBUG("Update Pdutype");
+                                       updatePduType(&reqEntity);
+                                       MSG_DEBUG("Waiting Conf");
+                               }
+
+                               mmsTranQ.pop_front();
+
+                               //////// Waiting Conf //////////////////////
+                               MMS_NET_ERROR_T networkErr;
+
+                               if ((networkErr = waitingConf(&reqEntity)) == eMMS_HTTP_CONF_SUCCESS) {
+                                       bool bReportAllowed;
+                                       char retrievedFilePath[MAX_FULL_PATH_SIZE+1] = {0,};
+
+                                       // process Http data
+                                       try {
+                                               if (processReceivedData(reqEntity.msgId, reqEntity.pGetData, reqEntity.getDataLen, retrievedFilePath) == false) {
+                                                       MmsPluginEventHandler::instance()->handleMmsError(&reqEntity);
+                                                       break;
+                                               }
+                                       } catch (MsgException& e) {
+                                               MSG_FATAL("%s", e.what());
+                                               MmsPluginEventHandler::instance()->handleMmsError(&reqEntity);
+                                               break;
+
+                                       } catch (exception& e) {
+                                               MSG_FATAL("%s", e.what());
+                                               MmsPluginEventHandler::instance()->handleMmsError(&reqEntity);
+                                               break;
+                                       }
+
+                                       if (reqEntity.eMmsPduType != (MMS_PDU_TYPE_T)mmsHeader.type) {
+                                               if (!(reqEntity.eMmsPduType == eMMS_RETRIEVE_MANUAL_CONF && mmsHeader.type == MMS_MSGTYPE_RETRIEVE_CONF)) {
+                                                       MSG_DEBUG("FAIL::type mismatched req:%d received:%d", reqEntity.eMmsPduType, mmsHeader.type);
+
+                                                       MmsPluginEventHandler::instance()->handleMmsError(&reqEntity);
+                                                       break;
+                                               }
+                                       }
+
+                                       MSG_DEBUG("conf received successfully");
+
+                                       try {
+                                               MmsPluginEventHandler::instance()->handleMmsReceivedData(&reqEntity, retrievedFilePath);
+                                       } catch (MsgException& e) {
+                                               MSG_FATAL("%s", e.what());
+                                               break;
+                                       } catch (exception& e) {
+                                               MSG_FATAL("%s", e.what());
+                                               break;
+                                       }
+
+                                       MsgSettingGetBool(MMS_RECV_DELIVERY_RECEIPT, &bReportAllowed);
+
+                                       MSG_DEBUG("conf received successfully -2");
+                                       MSG_DEBUG("reqEntity.eMmsPduType [%d]", reqEntity.eMmsPduType);
+
+                                       // send NotifyResponseInd
+                                       if (reqEntity.eMmsPduType == eMMS_RETRIEVE_AUTO_CONF) {
+                                               char filepath[MAX_FULL_PATH_SIZE] = {0};
+                                               // change MmsPduType for ind or ack
+                                               // make the PDU and then attach to reqEntity also.
+                                               updatePduType(&reqEntity);
+
+                                               MSG_DEBUG("#### eMmsPduType:%d ####", reqEntity.eMmsPduType);
+
+                                               //update http command type & encode m-notify-response-ind
+                                               reqEntity.eHttpCmdType = eHTTP_CMD_POST_TRANSACTION;
+
+                                               try {
+                                                       MmsPluginInternal::instance()->encodeNotifyRespInd(reqEntity.transactionId, MMS_MSGSTATUS_RETRIEVED, bReportAllowed, filepath);
+                                                       //m-notification-resp-ind encoding      if err is not MSG_SUCCESS then should set x-mms-status to deferred
+                                                       if (MsgGetFileSize(filepath, &reqEntity.postDataLen) == false) {
+                                                               MSG_DEBUG("MsgGetFileSize: failed");
+                                                               break;
+                                                       }
+                                               } catch (MsgException& e) {
+                                                       MSG_FATAL("%s", e.what());
+                                                       break;
+                                               } catch (exception& e) {
+                                                       MSG_FATAL("%s", e.what());
+                                                       break;
+                                               }
+
+                                               if (reqEntity.pPostData) {
+                                                       free(reqEntity.pPostData);
+                                                       reqEntity.pPostData = NULL;
+                                               }
+
+                                               reqEntity.pPostData = MsgOpenAndReadMmsFile(filepath, 0, -1, &reqEntity.postDataLen);
+
+                                               mmsTranQ.push_front(reqEntity);
+
+                                               remove(filepath);
+
+                                               MSG_DEBUG("Submit Ind");
+                                       } else if (reqEntity.eMmsPduType == eMMS_RETRIEVE_MANUAL_CONF) {
+                                               /* saved msg trId should be checked  */
+                                               // Send Acknowledge Ind
+                                               char filepath[MAX_FULL_PATH_SIZE] = {0};
+                                               // change MmsPduType for ind or ack
+                                               // make the PDU and then attach to reqEntity also.
+                                               updatePduType(&reqEntity);
+
+                                               MSG_DEBUG("#### eMmsPduType:%d ####", reqEntity.eMmsPduType);
+
+                                               //update http command type & encode m-notify-response-ind
+                                               reqEntity.eHttpCmdType = eHTTP_CMD_POST_TRANSACTION;
+
+                                               try {
+                                                       MmsPluginInternal::instance()->encodeAckInd(reqEntity.transactionId, bReportAllowed, filepath);
+                                                       if (MsgGetFileSize(filepath, &reqEntity.postDataLen) == false) {
+                                                               MSG_DEBUG("MsgGetFileSize: failed");
+                                                               break;
+                                                       }
+                                               } catch (MsgException& e) {
+                                                       MSG_FATAL("%s", e.what());
+                                                       break;
+                                               } catch (exception& e) {
+                                                       MSG_FATAL("%s", e.what());
+                                                       break;
+                                               }
+
+                                               if (reqEntity.pPostData) {
+                                                       free(reqEntity.pPostData);
+                                                       reqEntity.pPostData = NULL;
+                                               }
+
+                                               reqEntity.pPostData = MsgOpenAndReadMmsFile(filepath, 0, -1, &reqEntity.postDataLen);
+
+                                               mmsTranQ.push_front(reqEntity);
+
+                                               remove(filepath); // not ipc
+
+                                               MSG_DEBUG("Submit Ack");
+                                       } else {
+                                               reqEntity.isCompleted = true;
+
+                                               MSG_DEBUG("Transaction complete");
+                                       }
+                               } else {
+                                       MmsPluginEventHandler::instance()->handleMmsError(&reqEntity);
+                                       break;
+                               }
+                       } while (reqEntity.isCompleted == false);
+
+                       MSG_DEBUG("==== MMS Transaction Completed ====\n\n");
+
+                       if (reqEntity.pPostData) {
+                               free(reqEntity.pPostData);
+                               reqEntity.pPostData = NULL;
+                       }
+
+                       if (reqEntity.pGetData) {
+                               free(reqEntity.pGetData);
+                               reqEntity.pGetData = NULL;
+                       }
+
+                       // Http Session Close
+                       httpAgent->clearSession();
+               }
+
+               // Request CM Close
+               cmAgent->close();
+
+       }
+
+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;
+}
+
+void MmsPluginUaManager::getMmsPduData(mmsTranQEntity *qEntity)
+{
+       mmsTranQ.front(qEntity);
+}
+
+void MmsPluginUaManager::addMmsReqEntity(mmsTranQEntity req)
+{
+       MSG_DEBUG("New MMS Tran Added");
+       mmsTranQ.push_back(req);
+       lock();
+       signal();
+       unlock();
+}
+
+bool MmsPluginUaManager::processReceivedData(int msgId, char *pRcvdBody, int rcvdBodyLen, char *retrievedFilePath)
+{
+       MSG_BEGIN();
+
+       char fileName[MSG_FILENAME_LEN_MAX] = {0};
+
+       MSG_DEBUG(":::%d :%s ", rcvdBodyLen, pRcvdBody);
+
+       MmsInitHeader();
+       MmsRegisterDecodeBuffer();
+
+       if (MsgCreateFileName(fileName) == false)
+               return false;
+
+       snprintf(retrievedFilePath, MSG_FILEPATH_LEN_MAX, MSG_DATA_PATH"%s", fileName);
+
+       MSG_DEBUG("retrievedFilePaths [%s]", retrievedFilePath);
+
+       // create temp file
+       if (!MsgOpenCreateAndOverwriteFile(retrievedFilePath, (char *)pRcvdBody, rcvdBodyLen)) {
+               MSG_DEBUG( "_MmsUaInitMsgDecoder: creating temporary file failed(msgID=%d)\n", msgId);
+               return false;
+       }
+
+       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, };
+
+                       pMsg.msgId = msgId;
+
+                       bRetToConvert = MmsDrm2ConvertMsgBody(mmsHeader.msgType.szOrgFilePath);
+
+                       MmsDrm2SetConvertState(MMS_DRM2_CONVERT_FINISH);
+
+                       if (bRetToConvert) {
+                               int ret;
+                               ret = remove(mmsHeader.msgType.szOrgFilePath);
+                               if (ret != 0) {
+                                       MSG_DEBUG("remove fail\n");
+                                       goto ERR_MMS_UA_PROCESS_CONF;
+                               }
+
+                               ret = rename(MMS_DECODE_DRM_CONVERTED_TEMP_FILE, mmsHeader.msgType.szOrgFilePath);
+                               if (ret != 0) {
+                                       MSG_DEBUG("rename fail\n");
+                                       goto ERR_MMS_UA_PROCESS_CONF;
+                               }
+
+                               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();
+
+#ifdef __SUPPORT_DRM__
+               MmsReleaseMsgDRMInfo(&pMsg->msgType.drmInfo);
+#endif
+               MmsReleaseMsgBody(&pMsg->msgBody, pMsg->msgType.type);
+
+               return false;
+       }
+}
+
diff --git a/plugin/mms_plugin/MmsPluginUtil.cpp b/plugin/mms_plugin/MmsPluginUtil.cpp
new file mode 100755 (executable)
index 0000000..42be796
--- /dev/null
@@ -0,0 +1,407 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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"
+
+
+bool makeImageThumbnail(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");
+               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 makeVideoThumbnail(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_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_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);
+               return false;
+       }
+
+       MSG_DEBUG("Make thumbnail: success [%s]", dstPath);
+       mm_file_destroy_content_attrs(content_attrs);
+       return true;
+}
+
+bool MsgIsASCII(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;
+}
+
+bool MsgReplaceNonAscii(char *szInText, char **szOutText, char replaceChar)
+{
+
+       int nCount = 0;
+       int index = 0;
+       int cLen = 0;
+       char *pNew = NULL;
+
+       if (szInText == NULL || szOutText == NULL) {
+               MSG_DEBUG(MMS_DEBUG_STR_INVALID_PARAM" szInText = %p, szOutText = %p", szInText, szOutText);
+               return false;
+       }
+       cLen = strlen(szInText);
+
+       pNew = (char *)malloc(cLen + 1);
+
+       if (pNew == NULL)
+               return false;
+
+       memset(pNew, 0, cLen + 1);
+
+       while (*(szInText+nCount) != '\0') {
+               if (0x0001 <= *(szInText+nCount) && *(szInText+nCount) <= 0x007F) {
+                       MSG_DEBUG("non ascii characters (1bytes). \n");
+                       pNew[index] = szInText[nCount];
+                       nCount += 1;
+                       index += 1;
+               } else {
+                       MSG_DEBUG("UTF-8 characters (2bytes). \n");
+                       pNew[index] = replaceChar;
+                       nCount += 1;
+                       index +=1;
+               }
+       }
+
+       *szOutText = pNew;
+       return true;
+}
+
+bool MsgIsSpace(char *pszText)
+{
+       if (!pszText) {
+               MSG_DEBUG(MMS_DEBUG_STR_INVALID_PARAM);
+               return false;
+       }
+
+       if (strchr(pszText, ' ') == NULL) {
+               MSG_DEBUG("space is Not exist");
+               return false;
+       }
+
+       MSG_DEBUG("space exist");
+       return true;
+}
+
+bool MsgReplaceSpecialChar(char *szInText, char **szOutText, char specialChar)
+{
+       char *pszOutText = NULL;
+       char szBuf[10] = {0, };
+       char temp[5] = {0, };
+       int cLen = 0;
+       int i = 0;
+
+       if (!szInText || !szOutText) {
+               MSG_DEBUG(MMS_DEBUG_STR_INVALID_PARAM" szInText = %p, szOutText = %p", szInText, szOutText);
+               return false;
+       }
+
+       cLen = strlen(szInText);
+
+       if (specialChar == ' ') {
+               if ((pszOutText = (char *)malloc(cLen + 1)) == NULL) {
+                       MSG_DEBUG("%d line. MemAlloc failed.\n", __LINE__);
+                       return false;
+               }
+               memset(pszOutText, 0, cLen + 1);
+
+               *szOutText = pszOutText;
+       }
+
+       for (i = 0; i<cLen; i++) {
+               switch (specialChar) {
+               // changed space to '_'
+               case ' ':
+                       pszOutText[i] = (szInText[i] == specialChar) ? '_' : szInText[i];
+                       break;
+
+               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;
+               }
+       }
+
+       MSG_DEBUG("output text : [%s]\n", pszOutText);
+
+       return true;
+}
+
+char *MsgStrAppend(char *szInputStr1, char *szInputStr2)
+{
+       char *szOutputStr = NULL;
+
+       if (szInputStr1 == NULL) {
+               szOutputStr = MsgStrCopy(szInputStr2);
+       } else {
+               int length1 = 0;
+               int length2 = 0;
+               length1 = MsgStrlen(szInputStr1);
+               length2 = MsgStrlen(szInputStr2);
+
+               szOutputStr = (char *)malloc(length1 + length2 + 1);
+
+               if (szOutputStr == NULL)
+                       goto __CATCH;
+
+               memset(szOutputStr, 0, length1 + length2 + 1);
+
+               strncpy(szOutputStr, szInputStr1, length1);
+
+               if (length2 > 0)
+                       strcat(szOutputStr, szInputStr2);
+
+               free(szInputStr1);
+               szInputStr1 = NULL;
+       }
+
+       return szOutputStr;
+
+__CATCH:
+       return NULL;
+}
+
+char *MsgStrCopy(const char *string)
+{
+       char *pDst = NULL;
+
+       if (string) {
+               pDst = (char *)malloc(1 + strlen(string));
+               if (pDst == NULL) {
+                       MSG_DEBUG("pDst MemAlloc Fail \n");
+                       return NULL;
+               }
+
+               memset(pDst, 0, strlen(string) + 1);
+
+               strcpy(pDst,string);
+
+               return pDst;
+       }
+
+       return NULL;
+}
+
+char *MsgStrNCopy(const char *string, int length)
+{
+       char *pDst = NULL;
+
+       if (string) {
+               pDst = (char *)malloc(1 + length);
+               if (pDst == NULL) {
+                       MSG_DEBUG("pDst MemAlloc Fail \n");
+                       return NULL;
+               }
+
+               memset(pDst, 0, length + 1);
+               strncpy(pDst,string, length);
+
+               return pDst;
+       }
+
+       return NULL;
+}
+
+int MsgStrlen(char * pStr)
+{
+       if (pStr == NULL)
+               return 0;
+
+       return strlen(pStr);
+}
+
+bool MsgConvertCharToHex(char pSrc, char *pDest)
+{
+       static unsigned char saucHex[] = "0123456789ABCDEF";
+
+       pDest[0] = saucHex[pSrc >> 4];
+       pDest[1] = saucHex[pSrc & 0xF];
+       pDest[2] = 0;
+
+       return true;
+}
+
+
+FILE *MmsFileOpen(char *pFileName)
+{
+       int len;
+       mode_t file_mode = (S_IRUSR | S_IWUSR);
+
+       if (!pFileName) {
+               MSG_DEBUG("pFileName NULL: %s", strerror(errno));
+               return NULL;
+       }
+
+       MSG_DEBUG("pFileName = %s", pFileName);
+
+       FILE *pFile = MsgOpenFile(pFileName, "wb+");
+
+       if (pFile == NULL) {
+               MSG_FATAL("File Open Error: %s", strerror(errno));
+               return NULL;
+       }
+
+       if (MsgFseek(pFile, 0L, SEEK_CUR) < 0) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Read Error: %s", strerror(errno));
+               return NULL;
+       }
+
+       if (fchmod(fileno(pFile), file_mode) < 0) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File chmod Error: %s", strerror(errno));
+               return NULL;
+       }
+
+       return pFile;
+}
diff --git a/plugin/mms_plugin/include/MmsPluginAvCodec.h b/plugin/mms_plugin/include/MmsPluginAvCodec.h
new file mode 100755 (executable)
index 0000000..9621c91
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_AVCODEC_H
+#define MMS_PLUGIN_AVCODEC_H
+
+#include "MmsPluginTypes.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);
+
+#endif //MMS_PLUGIN_AVCODEC_H
diff --git a/plugin/mms_plugin/include/MmsPluginCodec.h b/plugin/mms_plugin/include/MmsPluginCodec.h
new file mode 100755 (executable)
index 0000000..1d65432
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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"
+
+#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..0c839cf
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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"
+
+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(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);
+
+#ifdef __SUPPORT_DRM__
+bool MmsInitMsgDRMInfo(MsgDRMInfo *pMsgDrmInfo);
+void MmsReleaseMsgDRMInfo(MsgDRMInfo *pDrmInfo);
+#endif//__SUPPORT_DRM__
+
+bool MmsReleaseMsgBody(MsgBody *pBody, int type);
+bool MmsReleaseMmsAttrib(MmsAttrib *pAttrib);
+void MmsReleaseMmsMsg(MmsMsg *pMmsMsg);
+
+#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..f590a3e
--- /dev/null
@@ -0,0 +1,564 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 _MsgAddress             MsgAddress;
+typedef struct _MsgBody                        MsgBody;
+typedef struct _MsgMultipart   MsgMultipart;
+typedef struct _MsgMessage             MsgMessage;
+
+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_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 {
+       MimeType 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;
+       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;
+#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
+       int 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;
+};
+
+struct _MsgMultipart {
+       MsgType type;
+       MsgBody *pBody;
+       MsgMultipart *pNext;
+};
+
+struct _MsgMessage {
+       MsgHeader header;
+       MsgType type;
+       MsgBody *pBody;
+};
+
+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/MmsPluginConnManWrapper.h b/plugin/mms_plugin/include/MmsPluginConnManWrapper.h
new file mode 100755 (executable)
index 0000000..34fde1d
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_CONNMAN_H
+#define MMS_PLUGIN_CONNMAN_H
+
+#include <network-cm-intf.h>
+#include <network-pm-intf.h>
+#include "MsgMutex.h"
+
+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();
+
+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;
+       Mutex mx;
+       CndVar cv;
+
+       net_profile_info_t mmsProfile;
+};
+
+#endif //MMS_PLUGIN_CONNMAN_H
diff --git a/plugin/mms_plugin/include/MmsPluginDebug.h b/plugin/mms_plugin/include/MmsPluginDebug.h
new file mode 100755 (executable)
index 0000000..578ca3f
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+
+#include "MsgDebug.h"
+
+#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"
+
+
+#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..f0a3519
--- /dev/null
@@ -0,0 +1,130 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 {
+       char *pData;
+       UINT32 length;
+} EncodedPData;
+
+typedef struct {
+       MsgPresentationFactor factor;
+       MsgMultipart *pPrevPart;
+       MsgMultipart *pCurPresentation;
+} MsgPresentaionInfo;
+
+struct _MsgHeaderAddress {
+       char *szAddr;
+       MsgHeaderAddress *pNext;
+};
+
+// 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 MmsHeader mmsHeader;
+
+/* Decoding */
+void MmsInitHeader();
+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 MmsAddrUtilCompareAddr(char *pszAddr1, char *pszAddr2);
+bool MmsDataUpdateLastStatus(MmsMsg *pMsg);
+bool MmsAddrUtilRemovePlmnString(char *pszAddr);
+bool MsgGetTypeByFileName(int *type, char *szFileName);
+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);
+
+#ifdef __SUPPORT_DRM__
+bool MsgCopyDrmInfo(MsgType *pPartType);
+bool MmsDrm2ConvertMsgBody(char *szOriginFilePath);
+bool MmsDrm2ReadMsgConvertedBody(MSG_MESSAGE_INFO_S *pMsg, bool bSavePartsAsTempFiles, bool bRetrieved, char *retrievedPath);
+#endif
+
+#endif //MMS_PLUGIN_DECODE_H
diff --git a/plugin/mms_plugin/include/MmsPluginDrm.h b/plugin/mms_plugin/include/MmsPluginDrm.h
new file mode 100755 (executable)
index 0000000..10f496c
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_DRM_H
+#define MMS_PLUGIN_DRM_H
+
+#include "MsgMmsTypes.h"
+#include "MmsPluginCodecTypes.h"
+
+#ifdef __SUPPORT_DRM__
+
+#define        MMS_DECODE_DRM_CONVERTED_TEMP_FILE MSG_DATA_PATH"Mms_Decode_Drm_Converted"
+#define        MMS_MIMETYPELENGTH 50
+
+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 //__SUPPORT_DRM__
+
+#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..a97e353
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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);
+
+#endif //MMS_PLUGIN_ENCODE_H
diff --git a/plugin/mms_plugin/include/MmsPluginEventHandler.h b/plugin/mms_plugin/include/MmsPluginEventHandler.h
new file mode 100755 (executable)
index 0000000..ed510a1
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgPluginInterface.h"
+#include "MmsPluginTypes.h"
+
+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);
+
+private:
+       MmsPluginEventHandler();
+       virtual ~MmsPluginEventHandler();
+
+       static MmsPluginEventHandler *pInstance;
+
+       MSG_PLUGIN_LISTENER_S listener;
+};
+
+#endif //MMS_PLUGIN_EVENT_HANDLER_H
diff --git a/plugin/mms_plugin/include/MmsPluginHttp.h b/plugin/mms_plugin/include/MmsPluginHttp.h
new file mode 100755 (executable)
index 0000000..d960df0
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_HTTP_H
+#define MMS_PLUGIN_HTTP_H
+
+#include <map>
+#include "MmsPluginTypes.h"
+
+#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; U; Tizen 1.0; en-us) AppleWebKit/534.46 (KHTML, like Gecko) Mobile Tizen Browser/1.0"
+#define MSG_MMS_WAP_PROFILE         ""
+
+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
+};
+
+class MmsPluginHttpAgent
+{
+       public:
+               static MmsPluginHttpAgent *instance();
+
+               int cmdRequest(MMS_HTTP_CMD_TYPE_T cmdType);
+
+               int setSession(mmsTranQEntity *qEntity);
+
+               void clearSession();
+
+               void SetMMSProfile();
+
+               MMS_PLUGIN_HTTP_DATA_S *getHttpConfigData();
+               MMS_PLUGIN_HTTP_CONTEXT_S *getMmsPldCd();
+
+               MMS_PLUGIN_HTTP_DATA_S httpConfigData;
+
+       private:
+               static MmsPluginHttpAgent *pInstance;
+
+               MmsPluginHttpAgent();
+               ~MmsPluginHttpAgent();
+
+               MMS_PLUGIN_HTTP_CONTEXT_S mmsPlgCd;
+
+               std::map<MMS_HTTP_CMD_TYPE_T,int(*)(MMS_PLUGIN_HTTP_DATA_S *)> httpCmdHandler;
+};
+
+#endif //MMS_PLUGIN_HTTP_H
diff --git a/plugin/mms_plugin/include/MmsPluginInternal.h b/plugin/mms_plugin/include/MmsPluginInternal.h
new file mode 100755 (executable)
index 0000000..fbb8090
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MmsPluginTypes.h"
+#include "MmsPluginCodecTypes.h"
+
+class MmsPluginInternal
+{
+       public:
+               static MmsPluginInternal *instance();
+
+               void processReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST_INFO_S *pRequest, bool *bReject);
+               void processSendConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTranQEntity *pRequest);
+               void processRetrieveConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTranQEntity *pRequest, char *pRetrivedFilePath);
+               void processForwardConf(MSG_MESSAGE_INFO_S *pMsgInfo, mmsTranQEntity *pRequest);
+               bool encodeNotifyRespInd(char *szTrID, msg_delivery_report_status_t iStatus, bool bReportAllowed, char *pSendFilePath);
+               bool encodeAckInd(char *szTrID, bool bReportAllowed, char *pSendFilePath);
+
+       private:
+               static MmsPluginInternal *pInstance;
+
+               MmsPluginInternal();
+               ~MmsPluginInternal();
+
+               bool processNotiInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST_INFO_S *pRequest);
+               void processDeliveryInd(MSG_MESSAGE_INFO_S *pMsgInfo);
+               void processReadOrgInd(MSG_MESSAGE_INFO_S *pMsgInfo);
+               bool checkRejectNotiInd(int roamState, bool bReportAllowed, char *pSendFilePath);
+               bool getMmsReport(MmsReport mmsReport);
+               const char *getMmsDeliveryStatus(msg_delivery_report_status_t deliveryStatus);
+               const char *getMmsReadStatus(msg_read_report_status_t readStatus);
+};
+
+#endif //MMS_PLUGIN_INTERNAL_H
diff --git a/plugin/mms_plugin/include/MmsPluginMIME.h b/plugin/mms_plugin/include/MmsPluginMIME.h
new file mode 100755 (executable)
index 0000000..6f5d80c
--- /dev/null
@@ -0,0 +1,273 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_MIME_H
+#define MMS_PLUGIN_MIME_H
+
+#include "MmsPluginTypes.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,                   //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"
+
+typedef enum _MimeMainType {
+       MIME_MAINTYPE_APPLICATION,
+       MIME_MAINTYPE_AUDIO,
+       MIME_MAINTYPE_IMAGE,
+       MIME_MAINTYPE_MESSAGE,
+       MIME_MAINTYPE_MULTIPART,
+       MIME_MAINTYPE_TEXT,
+       MIME_MAINTYPE_VIDEO,
+       MIME_MAINTYPE_THEME,
+       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);
+
+// Append the functions returning index and content type
+
+MimeType MimeGetContentTypeFromInt(MimeType mime);
+MimeType MimeGetContentTypeFromString(const char *szMime);
+MimeType MimeGetMimeTypeFromString(const char *szMime);
+
+MimeType MimeGetMimeIntFromMimeString(char *szMimeStr);
+char *MimeGetMimeStringFromMimeInt(int mimeType);
+
+char *MsgGetString(MsgHeaderField tableId, int code);
+char *_MsgSkipWS3(char *s);
+int    _MsgGetCode(MsgHeaderField tableId, char *pStr);
+
+#endif // MMS_PLUGIN_MIME_H
diff --git a/plugin/mms_plugin/include/MmsPluginMain.h b/plugin/mms_plugin/include/MmsPluginMain.h
new file mode 100755 (executable)
index 0000000..d34e528
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MmsPluginTypes.h"
+#include "MsgPluginInterface.h"
+
+#ifdef __cplusplus
+
+extern "C"
+{
+#endif
+
+msg_error_t MmsInitialize();
+
+msg_error_t MmsFinalize();
+
+msg_error_t MmsRegisterListener(MSG_PLUGIN_LISTENER_S *pListener);
+
+msg_error_t MmsSubmitRequest(MSG_REQUEST_INFO_S *pReqInfo);
+
+msg_error_t MmsAddMessage(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData);
+
+msg_error_t MmsProcessReceivedInd(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_REQUEST_INFO_S *pRequest, bool *bReject);
+
+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 MmsUpdateRejectStatus(MSG_MESSAGE_INFO_S *pMsgInfo);
+
+msg_error_t MmsComposeReadReport(MSG_MESSAGE_INFO_S *pMsgInfo);
+
+msg_error_t MmsRestoreMsg(MSG_MESSAGE_INFO_S *pMsgInfo, char *pRcvBody, int rcvdBodyLen, char *filePath);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //MMS_PLUGIN_MAIN_H
+
diff --git a/plugin/mms_plugin/include/MmsPluginMessage.h b/plugin/mms_plugin/include/MmsPluginMessage.h
new file mode 100755 (executable)
index 0000000..d7fdc12
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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"
+
+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, MimeType mimeType, char *pData, int size);
+bool MmsInsertPartFromFile(MmsMsg *pMsg, char *szTitleName, char *szOrgFilePath, char *szContentID);
+bool MmsGetTypeByFileName(int *type, char *szFileName);
+MsgMultipart *MmsMakeMultipart(MimeType mimeType, char *szTitleName, char *szOrgFilePath, void *pData, int offset, int size, char *szContentID);
+
+bool MmsIsMultipart(int type);
+bool MmsIsText(int type);
+bool MmsIsVitemContent(int type, char *pszName);
+MsgMultipart *MmsAllocMultipart(void);
+
+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);
+void MmsComposeReadReportMessage(MmsMsg *pMmsMsg, const MSG_MESSAGE_INFO_S *pMsgInfo, msg_message_id_t selectedMsgId);
+int MmsSearchMsgId(char *toNumber, char *szMsgID);
+bool MmsCheckAdditionalMedia(MMS_MESSAGE_DATA_S *pMsgData, MsgType *partHeader);
+bool MmsRemovePims(MMS_MESSAGE_DATA_S *pMsgData);
+
+msg_error_t MmsMakePreviewInfo(int msgId, MMS_MESSAGE_DATA_S *pMmsMsg);
+void MmsPrintFileInfoForVLD(MMS_MESSAGE_DATA_S *pMmsMsg);
+#endif //MMS_PLUGIN_MESSAGE_H
diff --git a/plugin/mms_plugin/include/MmsPluginSMILValidate.h b/plugin/mms_plugin/include/MmsPluginSMILValidate.h
new file mode 100755 (executable)
index 0000000..e80ec11
--- /dev/null
@@ -0,0 +1,164 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+
+#include "MsgMmsTypes.h"
+
+/**
+ *     @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,
+};
+
+/**    @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/MmsPluginSmil.h b/plugin/mms_plugin/include/MmsPluginSmil.h
new file mode 100755 (executable)
index 0000000..0222a3c
--- /dev/null
@@ -0,0 +1,261 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_H
+#define MMS_PLUGIN_SMIL_H
+
+#include <libxml/parser.h>
+#include <libxml/tree.h>
+
+#include "MsgMmsTypes.h"
+#include "MmsPluginCodecTypes.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
diff --git a/plugin/mms_plugin/include/MmsPluginStorage.h b/plugin/mms_plugin/include/MmsPluginStorage.h
new file mode 100755 (executable)
index 0000000..b1652fa
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgSqliteWrapper.h"
+#include "MmsPluginCodecTypes.h"
+
+class MmsPluginStorage
+{
+public:
+       static MmsPluginStorage *instance();
+
+       MmsPluginStorage();
+       ~MmsPluginStorage();
+
+       void addMessage(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S *pSendOptInfo, char *pFileData);
+       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);
+
+       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 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 insertDeliveryReport(msg_message_id_t msgId, char *address, MmsMsgMultiStatus *pStatus);
+       msg_error_t insertReadReport(msg_message_id_t msgId, char *address, MmsMsgMultiStatus *pStatus);
+       msg_error_t insertPreviewInfo(int msgId, int type, char *value, int count = 0);
+
+       msg_error_t removePreviewInfo(int msgId);
+
+       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);
+
+       /* reject_msg_support */
+       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);
+
+       msg_error_t getMsgText(MMS_MESSAGE_DATA_S *pMmsMsg, char *pMsgText);
+
+private:
+       msg_error_t addMmsMsgToDB(MmsMsg *pMmsMsg, const MSG_MESSAGE_INFO_S *pMsgInfo, int attachCnt = 0);
+
+       static MmsPluginStorage *pInstance;
+
+       MsgDbHandler dbHandle;
+
+       MmsMsg mmsMsg;
+};
+
+#endif //MMS_PLUGIN_STORAGE_H
+
diff --git a/plugin/mms_plugin/include/MmsPluginTextConvert.h b/plugin/mms_plugin/include/MmsPluginTextConvert.h
new file mode 100755 (executable)
index 0000000..9771488
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
diff --git a/plugin/mms_plugin/include/MmsPluginTransport.h b/plugin/mms_plugin/include/MmsPluginTransport.h
new file mode 100755 (executable)
index 0000000..4ace677
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MmsPluginTypes.h"
+
+class MmsPluginTransport
+{
+       public:
+               static MmsPluginTransport *instance();
+
+               void submitRequest(const MSG_REQUEST_INFO_S *pReqInfo);
+               void cancelRequest(msg_request_id_t reqId);
+
+       private:
+               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
diff --git a/plugin/mms_plugin/include/MmsPluginTypes.h b/plugin/mms_plugin/include/MmsPluginTypes.h
new file mode 100755 (executable)
index 0000000..33e1aea
--- /dev/null
@@ -0,0 +1,162 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_TYPES_H
+#define MMS_PLUGIN_TYPES_H
+
+#include "MsgTypes.h"
+#include "MsgInternalTypes.h"
+
+#define IN        /*! Pfrefix*/
+#define OUT       /*! Pfrefix*/
+#define INOUT     /*! Pfrefix*/
+
+#define RETRY_MAX 1
+#define MAX_MMSC_URL_LEN       100
+#define HTTP_REQUEST_LEN   1024
+#define MAX_URL_LENGTH 1024
+#define MAX_IPV4_LENGTH 30
+
+
+typedef unsigned int MMS_NET_ERROR_T;
+typedef unsigned int MMS_PDU_TYPE_T;
+typedef unsigned char MMS_HTTP_CMD_TYPE_T;
+typedef unsigned int E_MMS_CONNECTION_MODE;
+typedef unsigned int E_MMS_NETWORK_ACCESS_POINT;
+
+enum _MMS_NET_ERROR_E {
+       eMMS_SUCCESS = 0,
+       eMMS_CM_OPEN_SUCCESS,
+       eMMS_CM_OPEN_FAILED,
+       eMMS_CM_CLOSE_IND,
+       eMMS_CM_CLOSE_RSP,
+       eMMS_CM_CLOSE_FAILED,   //5
+       eMMS_CM_KILL_RSP,
+       eMMS_CM_KILL_FAILED,
+
+       eMMS_HTTP_SESSION_INIT,
+       eMMS_HTTP_SESSION_CLOSED,
+       eMMS_HTTP_SESSION_OPEN_FAILED, //10
+       eMMS_HTTP_SENT_SUCCESS,
+       eMMS_HTTP_CONF_SUCCESS,
+       eMMS_HTTP_ERROR_NETWORK,
+       eMMS_HTTP_CONF_RECEIVED_TIMEOUT,
+       eMMS_HTTP_RECV_DATA,    //15
+       eMMS_HTTP_EVENT_RECV_DATA_PROGRESS,
+       eMMS_HTTP_EVENT_RECV_DATA_ERROR,
+       eMMS_HTTP_EVENT_SENT_ACK_COMPLETED,
+       eMMS_HTTP_ERROR_UNKNOWN,
+       eMMS_EXCEPTIONAL_ERROR, //20
+
+       eMMS_UNKNOWN
+};
+
+enum _MMS_PDU_TYPE_E {
+       eMMS_SEND_REQ = 0,
+       eMMS_SEND_CONF,
+       eMMS_NOTIFICATION_IND,
+       eMMS_NOTIFYRESP_IND,
+       eMMS_RETRIEVE_AUTO_CONF,
+       eMMS_ACKNOWLEDGE_IND,
+       eMMS_DELIVERY_IND,
+       eMMS_READREC_IND,
+       eMMS_READORIG_IND,
+       eMMS_READREPORT_REQ,
+       eMMS_READREPORT_CONF,   //10
+       eMMS_FORWARD_REQ,
+       eMMS_FORWARD_CONF,
+       eMMS_RETRIEVE_AUTO,
+       eMMS_RETRIEVE_MANUAL,
+       eMMS_RETRIEVE_MANUAL_CONF,
+       eMMS_CANCEL_REQ,
+       eMMS_CANCEL_CONF,
+       eMMS_DELETE_REQ,
+       eMMS_DELETE_CONF,
+       eMMS_MBOX_STORE_REQ,    // 20
+       eMMS_MBOX_STORE_CONF,
+       eMMS_MBOX_VIEW_REQ,
+       eMMS_MBOX_VIEW_CONF,
+       eMMS_MBOX_UPLOAD_REQ,
+       eMMS_MBOX_UPLOAD_CONF,
+       eMMS_MBOX_DELETE_REQ,
+       eMMS_MBOX_DELETE_CONF,
+};
+
+enum _MMS_HTTP_CMD_TYPE_E {
+       eHTTP_CMD_REGISTER = 0,
+       eHTTP_CMD_DEREGISTER,
+       eHTTP_CMD_INIT_SESSION,
+       eHTTP_CMD_CANCEL_SESSION,
+       eHTTP_CMD_CLOSE_SESSION,
+       eHTTP_CMD_DELETE_SESSION,
+       eHTTP_CMD_POST_TRANSACTION,
+       eHTTP_CMD_GET_TRANSACTION,
+       eHTTP_CMD_DELETE_TRANSACTION
+};
+
+typedef struct _mmsTranQEntity {
+       bool isCompleted;
+       msg_request_id_t reqID;
+       int msgId;
+       unsigned int sessionId;
+       char transactionId[MMS_TR_ID_LEN + 1];
+
+       MMS_PDU_TYPE_T eMmsPduType;
+       MMS_HTTP_CMD_TYPE_T eHttpCmdType;
+
+       MMS_PDU_TYPE_T eMmsTransactionStatus;
+
+       int postDataLen;
+       char *pPostData;
+
+       int getDataLen;
+       char *pGetData;
+} mmsTranQEntity;
+
+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;
+
+
+
+#endif //MMS_PLUGIN_TYPES_H
+
diff --git a/plugin/mms_plugin/include/MmsPluginUserAgent.h b/plugin/mms_plugin/include/MmsPluginUserAgent.h
new file mode 100755 (executable)
index 0000000..ff8f190
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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_USERAGENT_H
+#define MMS_PLUGIN_USERAGENT_H
+
+#include "MsgThread.h"
+#include "MsgMutex.h"
+#include "MsgQueue.h"
+#include "MmsPluginTypes.h"
+
+class MmsPluginUaManager: public MsgThread
+{
+       public:
+               static MmsPluginUaManager *instance();
+               virtual void start();
+
+               void addMmsReqEntity(mmsTranQEntity req);
+               void getMmsPduData(mmsTranQEntity *qEntity);
+               bool processReceivedData(int msgId, char *pRcvdBody, int rcvdBodyLen, char *retrievedFilePath);
+
+               void lock(){ mx.lock(); }
+               void unlock(){ mx.unlock(); }
+               void wait(){ cv.wait(mx.pMutex()); }
+               void signal(){ cv.signal(); }
+
+       private:
+               MmsPluginUaManager();
+               ~MmsPluginUaManager();
+
+               static MmsPluginUaManager *pInstance;
+               virtual void run();
+
+               Mutex mx;
+               CndVar cv;
+
+               MMS_NET_ERROR_T submitHandler(mmsTranQEntity *qEntity);
+               MMS_NET_ERROR_T waitingConf(mmsTranQEntity *qEntity);
+
+               // condition values
+               bool running;           // flag for thread running
+
+               MsgThdSafeQ <mmsTranQEntity> mmsTranQ; // transaction q for mms plugin
+};
+
+#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..7229849
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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>
+
+bool makeImageThumbnail(char *srcPath, char *dstPath);
+bool makeVideoThumbnail(char *srcPath, char *dstPath);
+
+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);
+FILE *MmsFileOpen(char *pFileName);
+#endif //MMS_PLUGIN_UTIL_H
diff --git a/plugin/sms_plugin/CMakeLists.txt b/plugin/sms_plugin/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..e6a8f0d
--- /dev/null
@@ -0,0 +1,59 @@
+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_C_FLAGS} ${EXTRA_CFLAGS} -O0 -g -Wall")
+
+##########################################################
+# Define SMS Plugin
+##########################################################
+
+SET(SMS-PLUGIN-SRCS
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginUDCodec.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginParamCodec.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginTpduCodec.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginSatHandler.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginCbMsgHandler.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginWapPushHandler.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginConcatHandler.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginSetting.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginSimMsg.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginStorage.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginTransport.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginEventHandler.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginUAManager.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginCallback.cpp
+       ${CMAKE_SOURCE_DIR}/plugin/sms_plugin/SmsPluginMain.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(sms_plugin_pkgs REQUIRED glib-2.0 tapi libxml-2.0 libwbxml2 drm-client dlog vconf dbus-glib-1)
+
+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})
+
+INSTALL(TARGETS ${SMS-PLUGIN-LIB} LIBRARY DESTINATION lib)
+
diff --git a/plugin/sms_plugin/SmsPluginCallback.cpp b/plugin/sms_plugin/SmsPluginCallback.cpp
new file mode 100755 (executable)
index 0000000..9deab29
--- /dev/null
@@ -0,0 +1,960 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgException.h"
+#include "SmsPluginEventHandler.h"
+#include "SmsPluginCbMsgHandler.h"
+#include "SmsPluginConcatHandler.h"
+#include "SmsPluginWapPushHandler.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"
+
+extern struct tapi_handle *pTapiHandle;
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+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();
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+
+}
+
+
+void TapiEventSentStatus(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSentStatus is called. : result = [%d]", result);
+
+       msg_network_status_t netStatus;
+
+       // Convert TAPI status -> Messaging status
+       if ((TelSmsResponse_t)result == TAPI_NETTEXT_SENDSMS_SUCCESS)
+               netStatus = MSG_NETWORK_SEND_SUCCESS;
+       else
+               netStatus = MSG_NETWORK_SEND_FAIL;
+
+       try
+       {
+               // Call Event Handler
+               SmsPluginEventHandler::instance()->handleSentStatus(netStatus);
+
+               // Call SAT Handler
+               SmsPluginSatHandler::instance()->ctrlSms(netStatus);
+       }
+       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);
+
+       if (data == NULL) {
+               MSG_DEBUG("Error. evt->pData is NULL.");
+               return;
+       }
+
+       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);
+
+       /// Print tpdu
+       if (tpdu.tpduType == SMS_TPDU_DELIVER)
+       {
+               MSG_DEBUG("############# SMS_TPDU_DELIVER Incoming decoded tpdu values ####################");
+               MSG_DEBUG("tpdu.data.deliver.bMoreMsg : %d", tpdu.data.deliver.bMoreMsg);
+               MSG_DEBUG("tpdu.data.deliver.bStatusReport : %d", tpdu.data.deliver.bStatusReport);
+               MSG_DEBUG("tpdu.data.deliver.bHeaderInd : %d", tpdu.data.deliver.bHeaderInd);
+               MSG_DEBUG("tpdu.data.deliver.bReplyPath : %d", tpdu.data.deliver.bReplyPath);
+               MSG_DEBUG("tpdu.data.deliver.pid : %d", tpdu.data.deliver.pid);
+               MSG_DEBUG("tpdu.data.deliver.dcs.bCompressed : %d", tpdu.data.deliver.dcs.bCompressed);
+               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.dcs.bIndActive : %d", tpdu.data.deliver.dcs.bIndActive);
+               MSG_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);
+               MSG_DEBUG("tpdu.data.deliver.userData.length : %d", tpdu.data.deliver.userData.length);
+               MSG_DEBUG("tpdu.data.deliver.userData.data : %s", tpdu.data.deliver.userData.data);
+               MSG_DEBUG("#####################################################");
+       }
+       else if (tpdu.tpduType == SMS_TPDU_STATUS_REP)
+       {
+               MSG_DEBUG("############# SMS_TPDU_STATUS_REP Incoming decoded tpdu values ####################");
+               MSG_DEBUG("tpdu.data.statusRep.msgRef : %d", tpdu.data.statusRep.msgRef);
+               MSG_DEBUG("tpdu.data.statusRep.bMoreMsg : %d", tpdu.data.statusRep.bMoreMsg);
+               MSG_DEBUG("tpdu.data.statusRep.bStatusReport : %d", tpdu.data.statusRep.bStatusReport);
+               MSG_DEBUG("tpdu.data.statusRep.statusRep : %d", tpdu.data.statusRep.bHeaderInd);
+               MSG_DEBUG("tpdu.data.statusRep.status : %02x", tpdu.data.statusRep.status);
+               MSG_DEBUG("tpdu.data.statusRep.pid : %d", tpdu.data.statusRep.pid);
+               MSG_DEBUG("tpdu.data.statusRep.dcs.bCompressed : %d", tpdu.data.statusRep.dcs.bCompressed);
+               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_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,
+                       tpdu.data.statusRep.dischargeTime.time.absolute.hour, tpdu.data.statusRep.dischargeTime.time.absolute.minute, tpdu.data.statusRep.dischargeTime.time.absolute.second);
+               MSG_DEBUG("tpdu.data.statusRep.userData.headerCnt : %d", tpdu.data.statusRep.userData.headerCnt);
+               MSG_DEBUG("tpdu.data.statusRep.userData.length : %d", tpdu.data.statusRep.userData.length);
+               MSG_DEBUG("tpdu.data.statusRep.userData.data : %s", tpdu.data.statusRep.userData.data);
+               MSG_DEBUG("#####################################################");
+       }
+
+       try
+       {
+               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
+                       }
+                       else
+                       {
+                               SmsPluginEventHandler::instance()->handleMsgIncoming(&tpdu); // Call Event Handler
+                       }
+               }
+               else if (tpdu.tpduType == SMS_TPDU_STATUS_REP)
+               {
+                       SmsPluginEventHandler::instance()->handleMsgIncoming(&tpdu); // Call Event Handler
+               }
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+
+}
+
+
+void TapiEventCbMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventCbMsgIncoming is called. noti_id [%s]", noti_id);
+
+       if (data == NULL) {
+               MSG_DEBUG("Error. evt->pData is NULL.");
+               return;
+       }
+
+       TelSmsCbMsg_t *pCbMsg = (TelSmsCbMsg_t*)data;
+
+       try
+       {
+               SmsPluginCbMsgHandler::instance()->handleCbMsg(pCbMsg);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+
+}
+
+
+void TapiEventEtwsMsgIncoming(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
+{
+       MSG_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(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);
+
+       return;
+}
+
+
+void TapiEventGetSimMsgCnt(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetSimMsgCnt is called.");
+
+       if (result != TAPI_API_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+               MSG_SIM_COUNT_S simCnt;
+               memset(&simCnt, 0x00, sizeof(MSG_SIM_COUNT_S));
+               SmsPluginSimMsg::instance()->setSimMsgCntEvent(&simCnt);
+               return;
+       }
+
+       SmsPluginSimMsg::instance()->setSimMsgCntEvent((MSG_SIM_COUNT_S *)data);
+
+}
+
+
+void TapiEventGetSimMsg(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetSimMsg is called.");
+
+       if (result != TAPI_API_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error!! pEvent->Status [%d]", result);
+
+               SmsPluginSimMsg::instance()->setSimMsgEvent(NULL, false);
+
+               return;
+       }
+
+       TelSmsData_t* pSmsTpdu = (TelSmsData_t*)data;
+
+       // Reading TelSmsData_t
+       MSG_DEBUG ("sim index %d", pSmsTpdu->SimIndex);
+       MSG_DEBUG ("status %d", pSmsTpdu->MsgStatus);
+
+       // Reading TelSmsDatapackageInfo_t
+       if (pSmsTpdu->SmsData.MsgLength > MAX_TPDU_DATA_LEN)
+       {
+               MSG_DEBUG ("WARNING: tpdu_len > MAX_SMS_TPDU_SIZE [%d] bytes. setting to 0.", pSmsTpdu->SmsData.MsgLength);
+
+               SmsPluginSimMsg::instance()->setSimMsgEvent(NULL, false);
+
+               return;
+       }
+
+       SMS_TPDU_S tpdu;
+
+       // decode Tpdu
+       SmsPluginTpduCodec::decodeTpdu(pSmsTpdu->SmsData.szData, pSmsTpdu->SmsData.MsgLength, &tpdu);
+
+       MSG_DEBUG("Sim Message Type [%d]", tpdu.tpduType);
+
+       bool bRead = false;
+
+       // set read status
+       if (pSmsTpdu->MsgStatus == TAPI_NETTEXT_STATUS_READ)
+               bRead = true;
+       else if (pSmsTpdu->MsgStatus == TAPI_NETTEXT_STATUS_UNREAD)
+               bRead = false;
+
+       if (tpdu.tpduType == SMS_TPDU_DELIVER)
+       {
+               if (tpdu.data.deliver.dcs.codingScheme == SMS_CHARSET_8BIT && tpdu.data.deliver.pid == 0x11) {
+                       MSG_DEBUG("Unsupported message!!");
+                       SmsPluginSimMsg::instance()->setSimMsgEvent(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);
+                               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(NULL, false);
+                       return;
+               }
+
+               MSG_DEBUG("headerCnt [%d]", tpdu.data.submit.userData.headerCnt);
+
+               for (int i = 0; i < tpdu.data.submit.userData.headerCnt; i++)
+               {
+                       // Handler Concatenated Message
+                       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);
+                               return;
+                       }
+               }
+       }
+
+       // Make MSG_MESSAGE_INFO_S
+       MSG_MESSAGE_INFO_S msgInfo;
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       SmsPluginEventHandler::instance()->convertTpduToMsginfo(&tpdu, &msgInfo);
+
+       // set Sim Message ID
+       msgInfo.msgId = pSmsTpdu->SimIndex;
+
+       // set read status
+       msgInfo.bRead = bRead;
+
+       // set storage id
+       msgInfo.storageId = MSG_STORAGE_SIM;
+
+       /// 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_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_DEBUG("msgInfo.msgText : %s", msgInfo.msgText);
+       else
+       MSG_DEBUG("msgInfo.msgData : %s", msgInfo.msgData);
+       MSG_DEBUG("###############################################################");
+
+       SmsPluginSimMsg::instance()->setSimMsgEvent(&msgInfo, true); // Call Event Handler
+
+}
+
+
+void TapiEventSaveSimMsg(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSaveSimMsg is called. result [%d]", result);
+
+       int simId = -1;
+
+       if (data != NULL)
+               simId = *((int*)data);
+       else
+               MSG_DEBUG("Data(SIM Msg ID) is NULL");
+
+       SmsPluginSimMsg::instance()->setSaveSimMsgEvent(simId, result);
+}
+
+
+void TapiEventSaveClass2Msg(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSaveSimMsg is called. result [%d]", result);
+
+       int simId = -1;
+
+       if (data != NULL)
+               simId = *((int*)data);
+       else
+               MSG_DEBUG("Data(SIM Msg ID) is NULL");
+
+       SmsPluginSimMsg::instance()->setSaveClass2MsgEvent(simId, result);
+}
+
+
+void TapiEventDeleteSimMsg(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       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);
+               return;
+       }
+
+       int sim_id = *((int*)data);
+
+       SmsPluginSimMsg::instance()->setSimEvent((msg_sim_id_t)sim_id, true);
+
+}
+
+
+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;
+
+       if (*responseType == TAPI_NETTEXT_SETMESSAGESTATUS_RSP)
+               SmsPluginSimMsg::instance()->setSimEvent(0, bRet);
+       else
+               SmsPluginSetting::instance()->setResultFromSim(bRet);
+
+}
+
+
+void TapiEventGetParamCnt(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetParamCnt is called.");
+
+       if (result != TAPI_API_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error. evt->pData is NULL.");
+               SmsPluginSetting::instance()->setParamCntEvent(0);
+               return;
+       }
+
+       int paramCnt = 0;
+       paramCnt = *((int*)data);
+
+       SmsPluginSetting::instance()->setParamCntEvent(paramCnt);
+
+}
+
+
+void TapiEventGetParam(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetConfigData is called.");
+
+       if (result != TAPI_API_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+               SmsPluginSetting::instance()->setParamEvent(NULL, -1, false);
+               return;
+       }
+
+       TelSmsParams_t* smsParam = (TelSmsParams_t*)data;
+
+       int alphaIdLen = 0;
+       int addrLen = 0;
+       MSG_SMSC_DATA_S smscData = {0, };
+
+       /*Check Alpha ID value*/
+       alphaIdLen = smsParam->AlphaIdLen;
+       MSG_DEBUG("alphaId_len[%d]", alphaIdLen);
+
+       if (alphaIdLen < 0 || alphaIdLen > SMSC_NAME_MAX)
+       {
+               MSG_DEBUG("Wrong Alpha ID Length[%d]", alphaIdLen);
+
+               SmsPluginSetting::instance()->setParamEvent(NULL, -1, false);
+
+               return;
+       }
+
+
+       /*Check Address value*/
+       addrLen = smsParam->TpSvcCntrAddr.DialNumLen;
+
+       if(addrLen > SMSC_ADDR_MAX)
+       {
+               MSG_DEBUG("addrLen is too long: %d", addrLen);
+               SmsPluginSetting::instance()->setParamEvent(NULL, -1, false);
+               return;
+       }
+       else if(addrLen < 2)
+       {
+               MSG_DEBUG("addrLen is too short: %d", addrLen);
+               SmsPluginSetting::instance()->setParamEvent(NULL, -1, false);
+               return;
+       }
+
+       MSG_DEBUG("addrLen : %d", addrLen);
+
+
+       /*SMSP Parameter Indicator value*/
+       MSG_DEBUG("ParamIndicator[%02x]", smsParam->ParamIndicator);
+
+       /*Get SMSC Address*/
+       if(0x00 == (0x02 & smsParam->ParamIndicator))
+       {
+               MSG_DEBUG("record index[%d]", (int)smsParam->RecordIndex);
+
+               MSG_DEBUG("TON : %d", smsParam->TpSvcCntrAddr.Ton);
+               MSG_DEBUG("NPI : %d", smsParam->TpSvcCntrAddr.Npi);
+
+               smscData.smscAddr.ton = smsParam->TpSvcCntrAddr.Ton;
+               smscData.smscAddr.npi = smsParam->TpSvcCntrAddr.Npi;
+
+               SmsPluginParamCodec paramCodec;
+
+               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);
+
+               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);
+       }
+       else
+       {
+               MSG_DEBUG("SMSC Address is not present");
+
+//             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(NULL, -1, false);
+
+               return;
+       }
+
+       /*Get the PID value*/
+       if (0x00 == (0x04 & smsParam->ParamIndicator))
+       {
+               SMS_PID_T pid = (SMS_PID_T)smsParam->TpProtocolId;
+
+               MSG_DEBUG("smsParam->TpProtocolId : %d", smsParam->TpProtocolId);
+
+               switch (pid)
+               {
+                       case SMS_PID_NORMAL:
+                               smscData.pid = MSG_PID_TEXT;
+                       break;
+                       case SMS_PID_VOICE:
+                               smscData.pid = MSG_PID_VOICE;
+                       break;
+                       case SMS_PID_TELEX:
+                               smscData.pid = MSG_PID_FAX;
+                       break;
+                       case SMS_PID_x400:
+                               smscData.pid = MSG_PID_X400;
+                       break;
+                       case SMS_PID_ERMES:
+                               smscData.pid = MSG_PID_ERMES;
+                       break;
+                       case SMS_PID_EMAIL:
+                               smscData.pid = MSG_PID_EMAIL;
+                       break;
+                       default:
+                               smscData.pid = MSG_PID_TEXT;
+                       break;
+               }
+
+               MSG_DEBUG("smscData.pid : %d", smscData.pid);
+       }
+       else
+       {
+               MSG_DEBUG("PID is not present");
+               smscData.pid = MSG_PID_TEXT;
+               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))
+       {
+               smscData.valPeriod = smsParam->TpValidityPeriod;
+               MSG_DEBUG("valPeriod : %d", smscData.valPeriod);
+       }
+       else
+       {
+               smscData.valPeriod = 0;
+               MSG_DEBUG("Validity Period is not present");
+       }
+
+       SmsPluginSetting::instance()->setParamEvent(&smscData, (int)smsParam->RecordIndex, 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)
+       {
+               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);
+
+       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;
+       }
+
+       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++)
+       {
+               cbOpt.channelData.channelInfo[i].bActivate = pCBConfig->MsgIDs[i].Net3gpp.Selected;
+               cbOpt.channelData.channelInfo[i].from = pCBConfig->MsgIDs[i].Net3gpp.FromMsgId;
+               cbOpt.channelData.channelInfo[i].to = pCBConfig->MsgIDs[i].Net3gpp.ToMsgId;
+               memset(cbOpt.channelData.channelInfo[i].name, 0x00, CB_CHANNEL_NAME_MAX+1);
+
+               MSG_DEBUG("Channel FROM [%d], Channel TO [%d] ", cbOpt.channelData.channelInfo[i].from, cbOpt.channelData.channelInfo[i].to);
+       }
+
+       SmsPluginSetting::instance()->setCbConfigEvent(&cbOpt, true);
+}
+
+void TapiEventSetMailboxInfo(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSetMailboxInfo is called. result = [%d]", result);
+
+       bool bRet = true;
+
+       if (result != TAPI_SIM_ACCESS_SUCCESS)
+               bRet = false;
+
+       SmsPluginSetting::instance()->setResultFromSim(bRet);
+}
+
+void TapiEventGetMailboxInfo(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetMailboxInfo is called.");
+
+       if (result != TAPI_SIM_ACCESS_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+               SmsPluginSetting::instance()->setMailboxInfoEvent(NULL, false);
+
+               return;
+       }
+
+       TelSimMailboxList_t *list = (TelSimMailboxList_t *)data;
+       SMS_SIM_MAILBOX_LIST_S mbList = {0,};
+
+       if (list->count <= 0) {
+               SmsPluginSetting::instance()->setMailboxInfoEvent(NULL, 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;
+       }
+
+       SmsPluginSetting::instance()->setMailboxInfoEvent(&mbList, 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(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(&simMwiInfo, true);
+}
+
+void TapiEventGetMsisdnInfo(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventGetMsisdnInfo is called.");
+
+       if (result != TAPI_SIM_ACCESS_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+               return;
+       }
+
+       TelSimMsisdnList_t *list = (TelSimMsisdnList_t *)data;
+
+       for (int i = 0; i < list->count; i++) {
+               if (list->list[i].num[0] != '\0') {
+                       if (MsgSettingSetString(MSG_SIM_MSISDN, list->list[i].num) == MSG_SUCCESS)
+                               MSG_DEBUG("Get MSISDN from SIM : [%s]", list->list[i].num);
+                       else
+                               MSG_DEBUG("Getting MSISDN is failed!");
+
+                       break;
+               }
+       }
+}
+
+void TapiEventSatSmsRefresh(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSatSmsRefresh is called.");
+
+       if (result != TAPI_API_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+               return;
+       }
+
+       try
+       {
+               SmsPluginSatHandler::instance()->refreshSms(data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+
+}
+
+
+void TapiEventSatSendSms(TapiHandle *handle, const char *noti_id, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSatSendSms is called.");
+
+       if (data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+               return;
+       }
+
+       try
+       {
+               SmsPluginSatHandler::instance()->sendSms(data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+
+}
+
+
+void TapiEventSatMoSmsCtrl(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("TapiEventSatMoSmsCtrl is called.");
+
+       if (result != TAPI_API_SUCCESS || data == NULL)
+       {
+               MSG_DEBUG("Error. data is NULL.");
+               return;
+       }
+
+       try
+       {
+               SmsPluginSatHandler::instance()->ctrlSms(data);
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return;
+       }
+
+}
+
+void TapiEventMemoryStatus(TapiHandle *handle, int result, void *data, void *user_data)
+{
+       MSG_DEBUG("Tapi result is [%d]", result);
+}
+
+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);
+}
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginCallback - Member Functions
+==================================================================================================*/
+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()
+{
+       tel_register_noti_event(pTapiHandle, TAPI_NOTI_SMS_DEVICE_READY, TapiEventDeviceReady, NULL);
+       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_SMS_ETWS_INCOM_MSG, TapiEventEtwsMsgIncoming, 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);
+}
+
+
+void SmsPluginCallback::deRegisterEvent()
+{
+
+
+}
+
diff --git a/plugin/sms_plugin/SmsPluginCbMsgHandler.cpp b/plugin/sms_plugin/SmsPluginCbMsgHandler.cpp
new file mode 100755 (executable)
index 0000000..e8ddcbd
--- /dev/null
@@ -0,0 +1,967 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgDebug.h"
+#include "MsgCppTypes.h"
+#include "MsgException.h"
+#include "MsgGconfWrapper.h"
+#include "MsgUtilFile.h"
+#include "SmsPluginUDCodec.h"
+#include "SmsPluginStorage.h"
+#include "SmsPluginEventHandler.h"
+#include "SmsPluginCbMsgHandler.h"
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginCbMsgHandler - Member Functions
+==================================================================================================*/
+SmsPluginCbMsgHandler* SmsPluginCbMsgHandler::pInstance = NULL;
+
+
+SmsPluginCbMsgHandler::SmsPluginCbMsgHandler()
+{
+       pageList.clear();
+}
+
+
+SmsPluginCbMsgHandler::~SmsPluginCbMsgHandler()
+{
+
+}
+
+
+SmsPluginCbMsgHandler* SmsPluginCbMsgHandler::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginCbMsgHandler();
+
+       return pInstance;
+}
+
+
+void SmsPluginCbMsgHandler::handleCbMsg(TelSmsCbMsg_t *pCbMsg)
+{
+       MSG_BEGIN();
+
+       SMS_CB_NETWORK_TYPE_T type = pCbMsg->CbMsgType;
+
+       SMS_CBMSG_PAGE_S CbMsgPage = {0};
+
+       switch (type)
+       {
+               case SMS_CB_NETWORK_TYPE_2G_GSM :
+                       Decode2gCbMsg(pCbMsg, &CbMsgPage);
+               break;
+
+               case SMS_CB_NETWORK_TYPE_3G_UMTS :
+                       Decode3gCbMsg(pCbMsg, &CbMsgPage);
+               break;
+       }
+
+       // Check CB Msg Options
+       bool bJavaMsg = false;
+
+       if (!checkCbOpt(CbMsgPage, &bJavaMsg))
+       {
+               MSG_DEBUG("The CB Msg is not supported by option.");
+               return;
+       }
+
+       if (bJavaMsg == true)
+       {
+               MSG_DEBUG("JAVA CB Msg.");
+               CbMsgPage.cbMsgType = SMS_CBMSG_TYPE_JAVACBS;
+       }
+
+       // Check CB Pages
+       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 = {};
+
+               // Make CB Msg Structure
+               MakeCbMsg(CbMsgPage, &cbMsg);
+
+               // Convert to MSG_MESSAGE_INFO_S
+               convertCbMsgToMsginfo(&cbMsg, &msgInfo);
+
+               // Add CB Msg into DB
+               msg_error_t err = MSG_SUCCESS;
+
+               err = SmsPluginStorage::instance()->addMessage(&msgInfo);
+
+               if (err == MSG_SUCCESS)
+               {
+                       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);
+                       if (err != MSG_SUCCESS)
+                       {
+                               MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+                       }
+               }
+               else
+               {
+                       MSG_DEBUG("addMessage() Error !! [%d]", err);
+               }
+
+               // Remove From List
+               removeFromPageList(CbMsgPage);
+       }
+       MSG_END();
+}
+
+
+void SmsPluginCbMsgHandler::handleEtwsMsg(TelSmsEtwsMsg_t *pEtwsMsg)
+{
+       MSG_BEGIN();
+       msg_error_t err = MSG_SUCCESS;
+       SMS_ETWS_NETWORK_TYPE_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 Msg is not supported");
+               return;
+       }
+       DecodeEtwsMsg(pEtwsMsg, &etwsPn);
+       //convertEtwsMsgToMsginfo(CbMsgPage, &msgInfo);
+
+       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);
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginCbMsgHandler::Decode2gCbMsg(TelSmsCbMsg_t *pCbMsg, SMS_CBMSG_PAGE_S *pCbPage)
+{
+       if (pCbMsg->Length > MAX_CBMSG_PAGE_SIZE)
+               THROW(MsgException::SMS_PLG_ERROR, "CB Msg Size is over MAX [%d]", pCbMsg->Length);
+
+       unsigned char cbData[pCbMsg->Length+1];
+
+       memset(cbData, 0x00, sizeof(cbData));
+       memcpy(cbData, pCbMsg->szMsgData, pCbMsg->Length);
+       cbData[pCbMsg->Length] = '\0';
+
+       pCbPage->cbMsgType = SMS_CBMSG_TYPE_CBS;
+
+       // Serial Number
+       pCbPage->pageHeader.serialNum.geoScope = (cbData[0] & 0xC0) >> 6;
+
+       pCbPage->pageHeader.serialNum.msgCode = (cbData[0] & 0x3F) << 4;
+       pCbPage->pageHeader.serialNum.msgCode |= (cbData[1] & 0xF0) >> 4;
+
+       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);
+
+       pCbPage->pageHeader.msgId = (cbData[2] << 8) | cbData[3];
+
+MSG_DEBUG("MSG ID : [%d]", pCbPage->pageHeader.msgId);
+
+       // DCS
+       decodeCbMsgDCS(cbData[4], (unsigned char*)cbData[6], &(pCbPage->pageHeader.dcs));
+
+       // Page Parameter
+       pCbPage->pageHeader.totalPages = cbData[5] & 0x0F;
+       pCbPage->pageHeader.page = (cbData[5] & 0xF0) >> 4;
+
+       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);
+
+       // 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("iso639Lang : [%s]", pCbPage->pageHeader.dcs.iso639Lang);
+       // Get Receive Time
+       pCbPage->pageHeader.recvTime = getRecvTime();
+
+       // Decode CB Data
+       int dataLen = pCbMsg->Length - 6;
+
+       switch (pCbPage->pageHeader.dcs.codingScheme)
+       {
+               case SMS_CHARSET_7BIT :
+               {
+                       MSG_DEBUG("GSM 7 BIT");
+
+                       dataLen = (dataLen*8) / 7;
+
+                       SmsPluginUDCodec udCodec;
+                       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;
+                               memcpy(pCbPage->pageData, &pageData[3], unpackLen);
+                       } else {
+                               memcpy(pCbPage->pageData, &pageData, unpackLen);
+                       }
+
+                       MSG_DEBUG("unpackLen : [%d]", unpackLen);
+
+                       pCbPage->pageLength = unpackLen;
+                       pCbPage->pageData[unpackLen] = '\0';
+               }
+               break;
+
+               case SMS_CHARSET_8BIT :
+               case SMS_CHARSET_UCS2 :
+               {
+                       MSG_DEBUG("UCS2");
+
+                       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);
+}
+
+
+void SmsPluginCbMsgHandler::DecodeEtwsMsg(TelSmsEtwsMsg_t *pEtwsMsg, SMS_ETWS_PRIMARY_S *pEtwsPn)
+{
+       if ( !pEtwsMsg || !pEtwsPn )
+               return;
+
+       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';
+
+       // 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)
+{
+       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);
+
+       char cbData[(MAX_CBMSG_PAGE_SIZE*MAX_CBMSG_PAGE_NUM)+1];
+
+       memset(cbData, 0x00, sizeof(cbData));
+       memcpy(cbData, pCbMsg->szMsgData, sizeof(pCbMsg->szMsgData));
+       cbData[pCbMsg->Length] = '\0';
+
+       pCbPage->cbMsgType = (SMS_CBMSG_TYPE_T)cbData[0];
+
+       pCbPage->pageHeader.msgId = (cbData[1] << 8) | cbData[2];
+
+MSG_DEBUG("MSG ID : [%d]", pCbPage->pageHeader.msgId);
+
+       // Serial Number
+       pCbPage->pageHeader.serialNum.geoScope = (cbData[3] & 0xC0) >> 6;
+
+       pCbPage->pageHeader.serialNum.msgCode = (cbData[3] & 0x3F) << 4;
+       pCbPage->pageHeader.serialNum.msgCode |= (cbData[4] & 0xF0) >> 4;
+
+       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);
+
+       // 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);
+
+       // Get Receive Time
+       pCbPage->pageHeader.recvTime = getRecvTime();
+
+#if 0
+       // Decode CB Data
+       int dataLen = pCbMsg->Length - 6;
+
+       switch (pCbPage->pageHeader.dcs.codingScheme)
+       {
+               case SMS_CHARSET_7BIT :
+               {
+                       dataLen = (dataLen*8) / 7;
+
+                       if (pCbPage->pageLength > MAX_CBMSG_PAGE_SIZE)
+                               THROW(MsgException::SMS_PLG_ERROR, "CB Msg Size is over MAX [%d]", pCbPage->pageLength);
+
+                       SmsPluginUDCodec udCodec;
+                       int unpackLen = udCodec.unpack7bitChar(&cbData[6], dataLen, 0, pCbPage->pageData);
+                       pCbPage->pageData[unpackLen] = '\0';
+
+                       pCbPage->pageLength = unpackLen;
+               }
+               break;
+
+               case SMS_CHARSET_8BIT :
+               case SMS_CHARSET_UCS2 :
+               {
+                       pCbPage->pageLength = dataLen;
+
+                       memcpy(pCbPage->pageData, &cbData[6], pCbPage->pageLength);
+                       pCbPage->pageData[pCbPage->pageLength] = '\0';
+               }
+               break;
+       }
+
+MSG_DEBUG("Page Length : [%d], Page Data : [%s]", pCbPage->pageLength, pCbPage->pageData);
+#endif
+}
+
+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)
+{
+       bool bReceive = false;
+       MsgSettingGetBool(CB_RECEIVE, &bReceive);
+
+       // Receive CB Msg = FALSE
+       if (!bReceive)
+       {
+               MSG_DEBUG("RECEIVE CB = FALSE");
+               return false;
+       }
+
+       char keyName[128];
+
+       // check Language
+       memset(keyName, 0x00, sizeof(keyName));
+       sprintf(keyName, "%s/%d", CB_LANGUAGE, MSG_CBLANG_TYPE_ALL);
+
+       bool bAllLang = false;
+       MsgSettingGetBool(keyName, &bAllLang);
+
+       if (!bAllLang)
+       {
+               MSG_DEBUG("ALL LANGUAGE = FALSE");
+
+               memset(keyName, 0x00, sizeof(keyName));
+               sprintf(keyName, "%s/%d", CB_LANGUAGE, CbPage.pageHeader.langType);
+
+               bool bLang = false;
+
+               MsgSettingGetBool(keyName, &bLang);
+
+               if (!bLang || CbPage.pageHeader.langType == MSG_CBLANG_TYPE_MAX)
+               {
+                       MSG_DEBUG("LANGUAGE [%d] = FALSE", CbPage.pageHeader.langType);
+                       return false;
+               }
+       }
+
+       int MsgIdCnt = MsgSettingGetInt(CB_CHANNEL_COUNT);
+
+       bool bActivate = false;
+       int MsgId_from = 0, MsgId_to = 0;
+
+       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);
+
+               MsgId_to = MsgSettingGetInt(keyName);
+
+               if (bActivate == true && CbPage.pageHeader.msgId >= MsgId_from && CbPage.pageHeader.msgId <= MsgId_to)
+               {
+                       MSG_DEBUG("FIND CHANNEL = [%d]", CbPage.pageHeader.msgId);
+                       return true;
+               }
+       }
+
+       return false;
+}
+
+
+unsigned char SmsPluginCbMsgHandler::checkCbPage(SMS_CBMSG_PAGE_S CbPage)
+{
+       unsigned char currPageCnt = 0;
+
+       bool bFind = false;
+
+       if (CbPage.pageHeader.totalPages > 1)
+       {
+               for (unsigned int i = 0; i < pageList.size(); i++)
+               {
+                       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)
+                               {
+                                       int updateNum = CbPage.pageHeader.serialNum.updateNum - pageList[i].updateNum;
+
+                                       if (updateNum > 0) // New Message Content
+                                       {
+                                               break;
+                                       }
+                                       else if (updateNum == 0) // Same Message Content
+                                       {
+                                               if (pageList[i].data.count(CbPage.pageHeader.page) != 0)
+                                               {
+                                                       MSG_DEBUG("The Page Number already exists [%d]", CbPage.pageHeader.page);
+                                                       return 0;
+                                               }
+
+                                               pair<unsigned char, string> newData(CbPage.pageHeader.page, CbPage.pageData);
+                                               pageList[i].data.insert(newData);
+
+                                               MSG_DEBUG("PAGE DATA : %s", CbPage.pageData);
+                                               MSG_DEBUG("PAIR DATA [%d] : %s", newData.first, newData.second.c_str());
+
+                                               pageList[i].pageCnt++;
+                                               pageList[i].totalSize += CbPage.pageLength;
+
+                                               currPageCnt = pageList[i].pageCnt;
+
+                                               bFind = true;
+
+                                               break;
+                                       }
+                                       else // Old Message Content
+                                       {
+                                               return 0;
+                                       }
+                               }
+                       }
+               }
+       }
+
+       if (bFind == false || CbPage.pageHeader.totalPages == 1)
+       {
+               addToPageLiat(CbPage);
+               return 1;
+       }
+
+       return currPageCnt;
+}
+
+
+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;
+
+       cbPageMap::iterator it;
+       string tmpStr ("");
+
+       for (unsigned int i = 0; i < pageList.size(); i++)
+       {
+               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)
+                       {
+                               for (it = pageList[i].data.begin(); it != pageList[i].data.end(); it++)
+                               {
+                                       tmpStr += it->second;
+                               }
+                       }
+               }
+       }
+
+       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());
+}
+
+
+void SmsPluginCbMsgHandler::convertCbMsgToMsginfo(SMS_CBMSG_S *pCbMsg, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       pMsgInfo->msgId = (msg_message_id_t)pCbMsg->msgId;
+
+       pMsgInfo->folderId = MSG_CBMSGBOX_ID;
+
+       // Convert Type values
+       pMsgInfo->msgType.mainType = MSG_SMS_TYPE;
+
+       if (pCbMsg->cbMsgType == SMS_CBMSG_TYPE_CBS)
+               pMsgInfo->msgType.subType = MSG_CB_SMS;
+       else if (pCbMsg->cbMsgType == SMS_CBMSG_TYPE_JAVACBS)
+               pMsgInfo->msgType.subType = MSG_JAVACB_SMS;
+
+       switch(pCbMsg->classType)
+       {
+               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->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(pCbMsg->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 = pCbMsg->recvTime;
+       MSG_DEBUG("recvTime is %s", ctime(&pMsgInfo->displayTime));
+
+       int bufSize = pCbMsg->msgLength*2;
+
+       char tmpBuf[bufSize];
+       memset(tmpBuf, 0x00, sizeof(tmpBuf));
+
+       MSG_DEBUG("LENGTH %d CB MSG %s", pCbMsg->msgLength, pCbMsg->msgData);
+
+       // Convert Data values
+       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[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);
+               if (MsgWriteIpcFile(fileName, tmpBuf, pMsgInfo->dataSize) == false)
+                       THROW(MsgException::FILE_ERROR, "MsgWriteIpcFile error");
+
+               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 SmsPluginCbMsgHandler::convertEtwsMsgToMsginfo(SMS_CBMSG_PAGE_S EtwsMsg, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       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);
+       MSG_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 %s", ctime(&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,};
+
+       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::addToPageLiat(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.pageCnt = 1;
+       tmpInfo.totalSize = CbPage.pageLength;
+
+       pair<unsigned char, string> newData(CbPage.pageHeader.page, CbPage.pageData);
+       tmpInfo.data.insert(newData);
+
+       MSG_DEBUG("MSG DATA : %s", CbPage.pageData);
+       MSG_DEBUG("PAIR DATA [%d] : %s", newData.first, newData.second.c_str());
+
+       pageList.push_back(tmpInfo);
+}
+
+
+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)
+               {
+                       MSG_DEBUG("geoScope [%d], msgCode [%d]", pageList[index].geoScope, pageList[index].msgCode);
+
+                       if (pageList[index].msgId == CbPage.pageHeader.msgId) break;
+               }
+       }
+
+       MSG_DEBUG("remove index [%d]", index);
+
+       pageList.erase(pageList.begin()+index);
+}
+
+
+void SmsPluginCbMsgHandler::decodeCbMsgDCS(unsigned char dcsData, const unsigned char *pMsgData, SMS_CBMSG_DCS_S* pDcs)
+{
+       pDcs->codingGroup = SMS_CBMSG_CODGRP_GENERAL_DCS;
+       pDcs->classType = SMS_MSG_CLASS_NONE;
+       pDcs->bCompressed = false;
+       pDcs->codingScheme = SMS_CHARSET_7BIT;
+       pDcs->langType = SMS_CBMSG_LANG_UNSPECIFIED;
+       memset(pDcs->iso639Lang, 0x00, sizeof(pDcs->iso639Lang));
+       pDcs->bUDH = false;
+       pDcs->rawData = dcsData;
+
+       unsigned char codingGrp = (dcsData & 0xF0) >> 4;
+
+       switch (codingGrp)
+       {
+               case 0x00 :
+               case 0x02 :
+               case 0x03 :
+               {
+                       pDcs->codingGroup = SMS_CBMSG_CODGRP_GENERAL_DCS;
+                       pDcs->langType = (SMS_CBMSG_LANG_TYPE_T)dcsData;
+               }
+               break;
+
+               case 0x01 :
+               {
+                       if (dcsData == 0x10 || dcsData == 0x11)
+                       {
+                               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)
+                               {
+                                       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 */
+                               }
+                               else
+                               {
+                                       /* Default it to English if pMsgData is NULL */
+                                       pDcs->iso639Lang[0] = 0x45;  /* E */
+                                       pDcs->iso639Lang[1] = 0x4E;  /* N */
+                                       pDcs->iso639Lang[2] = 0x13;  /* CR */
+                               }
+                       }
+               }
+               break;
+
+               case 0x04 :
+               case 0x05 :
+               case 0x06 :
+               case 0x07 :
+               {
+                       pDcs->codingGroup = SMS_CBMSG_CODGRP_GENERAL_DCS;
+
+                       pDcs->bCompressed = (dcsData & 0x20) ? true : false;
+
+                       if (dcsData & 0x10)
+                               pDcs->classType = (SMS_MSG_CLASS_T)(dcsData & 0x03);
+
+                       pDcs->codingScheme = (SMS_CODING_SCHEME_T)(dcsData & 0x0C);
+               }
+               break;
+
+               case 0x09 :
+               {
+                       pDcs->bUDH = true;
+               }
+               break;
+
+               case 0x14 :
+               {
+                       pDcs->codingGroup = SMS_CBMSG_CODGRP_WAP;
+               }
+               break;
+
+               case 0x15 :
+               {
+                       pDcs->codingGroup = SMS_CBMSG_CODGRP_CLASS_CODING;
+                       pDcs->codingScheme = (dcsData & 0x04) ? SMS_CHARSET_UCS2 : SMS_CHARSET_7BIT;
+                       pDcs->classType = (MSG_CLASS_TYPE_T)(dcsData & 0x03);
+               }
+               break;
+       }
+}
+
+
+void SmsPluginCbMsgHandler::convertLangType(SMS_CBMSG_LANG_TYPE_T InType , MSG_CB_LANGUAGE_TYPE_T *pOutType)
+{
+       switch (InType)
+       {
+               case SMS_CBMSG_LANG_GERMAN :
+                       *pOutType = MSG_CBLANG_TYPE_GER;
+               break;
+
+               case SMS_CBMSG_LANG_ENGLISH :
+                       *pOutType = MSG_CBLANG_TYPE_ENG;
+               break;
+
+               case SMS_CBMSG_LANG_ITALIAN :
+                       *pOutType = MSG_CBLANG_TYPE_ITA;
+               break;
+
+               case SMS_CBMSG_LANG_FRENCH :
+                       *pOutType = MSG_CBLANG_TYPE_FRE;
+               break;
+
+               case SMS_CBMSG_LANG_SPANISH :
+                       *pOutType = MSG_CBLANG_TYPE_SPA;
+               break;
+
+               case SMS_CBMSG_LANG_DUTCH :
+                       *pOutType = MSG_CBLANG_TYPE_NED;
+               break;
+
+               case SMS_CBMSG_LANG_SWEDISH :
+                       *pOutType = MSG_CBLANG_TYPE_SWE;
+               break;
+
+               case SMS_CBMSG_LANG_PORTUGUESE :
+                       *pOutType = MSG_CBLANG_TYPE_POR;
+               break;
+
+               case SMS_CBMSG_LANG_TURKISH :
+                       *pOutType = MSG_CBLANG_TYPE_TUR;
+               break;
+
+               default :
+                       *pOutType = MSG_CBLANG_TYPE_MAX;
+               break;
+       }
+}
+
+
+unsigned long SmsPluginCbMsgHandler::getRecvTime()
+{
+       time_t recvTime;
+
+       recvTime = time(NULL);
+
+       return (unsigned long)recvTime;
+}
+
+
+void SmsPluginCbMsgHandler::getDisplayName(unsigned short      MsgId, char *pDisplayName)
+{
+       int MsgIdCnt = MsgSettingGetInt(CB_CHANNEL_COUNT);
+
+       char from[128];
+       char to[128];
+
+       for (int i = 0; i < MsgIdCnt; 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))
+               {
+                       MSG_DEBUG("FIND MSG ID = [%d]", MsgId);
+#if 0
+                       memset(keyName, 0x00, sizeof(keyName));
+                       sprintf(keyName, "%s/%d", CB_CHANNEL_NAME, i);
+
+                       memset(strTmp, 0x00, sizeof(strTmp));
+
+                       channelName = MsgSettingGetString(keyName);
+
+                       strncpy(strTmp, channelName, CB_CHANNEL_NAME_MAX);
+
+                       if (channelName) {
+                               free(channelName);
+                               channelName = NULL;
+                       }
+
+                       if (strlen(strTmp) > 0)
+                               sprintf(pDisplayName, "[%s]", strTmp);
+                       else
+                               sprintf(pDisplayName, "[%d]", MsgId);
+#else
+                       sprintf(pDisplayName, "[%d]", MsgId);
+#endif
+
+                       return;
+               }
+       }
+
+       sprintf(pDisplayName, "[%d]", MsgId);
+}
+
diff --git a/plugin/sms_plugin/SmsPluginConcatHandler.cpp b/plugin/sms_plugin/SmsPluginConcatHandler.cpp
new file mode 100755 (executable)
index 0000000..348418b
--- /dev/null
@@ -0,0 +1,877 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "SmsPluginStorage.h"
+#include "SmsPluginTransport.h"
+#include "SmsPluginEventHandler.h"
+#include "SmsPluginWapPushHandler.h"
+#include "SmsPluginConcatHandler.h"
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginConcatHandler - Member Functions
+==================================================================================================*/
+SmsPluginConcatHandler* SmsPluginConcatHandler::pInstance = NULL;
+
+
+SmsPluginConcatHandler::SmsPluginConcatHandler()
+{
+       concatList.clear();
+}
+
+
+SmsPluginConcatHandler::~SmsPluginConcatHandler()
+{
+       concatList.clear();
+}
+
+
+SmsPluginConcatHandler* SmsPluginConcatHandler::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginConcatHandler();
+
+       return pInstance;
+}
+
+
+bool SmsPluginConcatHandler::IsConcatMsg(SMS_USERDATA_S *pUserData)
+{
+       MSG_BEGIN();
+
+       MSG_DEBUG("headerCnt [%d]", pUserData->headerCnt);
+
+       for (int i = 0; i < pUserData->headerCnt; i++) {
+               /**  Handler Concatenated Message */
+               if (pUserData->header[i].udhType == SMS_UDH_CONCAT_8BIT) {
+                       return true;
+               } else if (pUserData->header[i].udhType == SMS_UDH_CONCAT_16BIT) {
+                       return true;
+               }
+       }
+
+       MSG_END();
+
+       return false;
+}
+
+
+void SmsPluginConcatHandler::handleConcatMsg(SMS_TPDU_S *pTpdu)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+       bool noneConcatTypeHeader = true;
+
+       if (pTpdu->tpduType != SMS_TPDU_DELIVER) {
+               MSG_DEBUG("The TPDU type is not deliver [%d]", pTpdu->tpduType);
+               return;
+       }
+
+       SMS_CONCAT_MSG_S msg = {0};
+
+       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));
+
+#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;
+
+                       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));
+#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;
+
+                       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;
+               AutoPtr<char> dataBuf(&pUserData);
+
+               MSG_MESSAGE_INFO_S msgInfo = {0};
+
+               dataSize = makeConcatUserData(msg.msgRef, &pUserData);
+
+               if (dataSize > 0) {
+                       if (SmsPluginWapPushHandler::instance()->IsWapPushMsg(&(pTpdu->data.deliver.userData)) == true) {
+                               SmsPluginWapPushHandler::instance()->copyDeliverData(&(pTpdu->data.deliver));
+                               SmsPluginWapPushHandler::instance()->handleWapPushMsg(pUserData, dataSize);
+                       } else {
+                               convertConcatToMsginfo(&(pTpdu->data.deliver), pUserData, dataSize, &msgInfo);
+
+                               if (msgInfo.msgPort.valid == false) {
+                                       /** Add Concat Msg into DB */
+                                       err = SmsPluginStorage::instance()->addMessage(&msgInfo);
+                               }
+
+                               if (err == MSG_SUCCESS) {
+                                       /** Callback */
+                                       err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+
+                                       if (err != MSG_SUCCESS) {
+                                               MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+                                       }
+                               } else {
+                                       MSG_DEBUG("addMessage() Error !! [%d]", err);
+                               }
+                       }
+               }
+
+               removeFromConcatList(msg.msgRef);
+       }
+
+       /** Send Deliver Report */
+       SmsPluginTransport::instance()->sendDeliverReport(err);
+
+       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;
+               AutoPtr<char> dataBuf(&pUserData);
+
+               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_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_DEBUG("msgInfo.msgText : %s", msgInfo.msgText);
+                       else
+                               MSG_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;
+               AutoPtr<char> dataBuf(&pUserData);
+
+               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_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_DEBUG("msgInfo.msgText : %s", msgInfo.msgText);
+                       else
+                       MSG_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) {
+               MSG_DEBUG("In Parameter is NULL");
+               return 0;
+       }
+
+       unsigned char currSegCnt = 0;
+
+       bool bFind = false;
+
+       for (unsigned int i = 0; i < concatList.size(); i++) {
+               if (concatList[i].msgRef == pConcatMsg->msgRef) {
+                       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);
+                       concatData.length = pUserData->length;
+
+                       pair<unsigned char, CONCAT_DATA_S> newData(pConcatMsg->seqNum, concatData);
+                       concatList[i].data.insert(newData);
+
+                       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;
+
+                       break;
+               }
+       }
+
+       /** New Concat Msg */
+       if (bFind == false) {
+               SMS_CONCAT_INFO_S tmpInfo;
+
+               tmpInfo.msgRef = pConcatMsg->msgRef;
+               tmpInfo.totalSeg = pConcatMsg->totalSeg;
+               tmpInfo.segCnt = 1;
+
+               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;
+
+               CONCAT_DATA_S concatData = {0};
+
+               memcpy(concatData.data, pUserData->data, pUserData->length);
+               concatData.length = pUserData->length;
+
+               pair<unsigned char, CONCAT_DATA_S> newData(pConcatMsg->seqNum, concatData);
+               tmpInfo.data.insert(newData);
+
+               MSG_DEBUG("MSG DATA : %s", pUserData->data);
+               MSG_DEBUG("PAIR DATA [%d] : %s", newData.first, newData.second.data);
+
+               concatList.push_back(tmpInfo);
+
+               currSegCnt = tmpInfo.segCnt;
+       }
+
+       return currSegCnt;
+}
+
+
+int SmsPluginConcatHandler::makeConcatUserData(unsigned short MsgRef, char **ppTotalData)
+{
+       concatDataMap::iterator it;
+
+       int totalSize = 0, offset = 0;
+
+       for (unsigned int i = 0; i < concatList.size(); i++) {
+               if (concatList[i].msgRef == MsgRef) {
+                       totalSize = concatList[i].totalSize;
+
+                       if (totalSize <= 0) {
+                               MSG_DEBUG("Size Error : totalSize <= 0");
+                               return 0;
+                       }
+
+                       MSG_DEBUG("totalSize [%d]", totalSize);
+
+                       *ppTotalData = new char[totalSize];
+
+                       for (it = concatList[i].data.begin(); it != concatList[i].data.end(); it++) {
+                               memcpy(*ppTotalData+offset, it->second.data, it->second.length);
+                               offset += it->second.length;
+                       }
+               }
+       }
+
+       return totalSize;
+}
+
+
+void SmsPluginConcatHandler::convertConcatToMsginfo(const SMS_DELIVER_S *pTpdu, const char *pUserData, int DataSize, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       /** Convert Type  values */
+       pMsgInfo->msgType.mainType = MSG_SMS_TYPE;
+       pMsgInfo->msgType.subType = MSG_NORMAL_SMS;
+
+       /** 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);
+
+/*** 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, pTpdu->originAddress.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 */
+       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);
+
+#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_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);
+       }
+}
+
+
+#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_DEBUG("Save Message Data into file : size[%d] name[%s]", pMsgInfo->dataSize, fileName);
+}
+#endif
+
+
+void SmsPluginConcatHandler::removeFromConcatList(unsigned short MsgRef)
+{
+       for (int index = concatList.size(); index >= 0 ; index--) {
+               if (concatList[index].msgRef == MsgRef) {
+                       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/SmsPluginEventHandler.cpp b/plugin/sms_plugin/SmsPluginEventHandler.cpp
new file mode 100755 (executable)
index 0000000..2f30d10
--- /dev/null
@@ -0,0 +1,841 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <errno.h>
+
+#include "MsgDebug.h"
+#include "MsgUtilFile.h"
+#include "MsgGconfWrapper.h"
+#include "SmsPluginTransport.h"
+#include "SmsPluginSimMsg.h"
+#include "SmsPluginStorage.h"
+#include "SmsPluginSetting.h"
+#include "SmsPluginConcatHandler.h"
+#include "SmsPluginEventHandler.h"
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginEventHandler - Member Functions
+==================================================================================================*/
+SmsPluginEventHandler* SmsPluginEventHandler::pInstance = NULL;
+
+
+SmsPluginEventHandler::SmsPluginEventHandler()
+{
+       /**  Initialize global parameters */
+       memset(&listener, 0x00, sizeof(MSG_PLUGIN_LISTENER_S));
+
+       pSimCnt = NULL;
+       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::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);
+                       sentInfo.reqInfo.msgInfo.networkStatus = NetStatus;
+                       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) {
+                       SmsPluginStorage::instance()->deleteSmsMessage(sentInfo.reqInfo.msgInfo.msgId);
+                       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_TPDU_S *pTpdu)
+{
+       /** Make MSG_MESSAGE_INFO_S */
+       MSG_MESSAGE_INFO_S msgInfo;
+
+       /** initialize msgInfo */
+       memset(&msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       /** check unsupported message */
+       if (pTpdu->tpduType == SMS_TPDU_DELIVER) {
+               if (pTpdu->data.deliver.dcs.codingScheme == SMS_CHARSET_8BIT && pTpdu->data.deliver.pid == 0x11) {
+                       MSG_DEBUG("Unsupported message!!");
+                       SmsPluginTransport::instance()->sendDeliverReport(MSG_SUCCESS);
+                       return;
+               }
+       }
+
+       /** check discard & indicator inactive message **/
+       if (pTpdu->data.deliver.dcs.bMWI == true &&
+                       pTpdu->data.deliver.dcs.bIndActive == false &&
+                       pTpdu->data.deliver.dcs.codingGroup == SMS_GROUP_DISCARD) {
+               MSG_DEBUG("Discard and no-indication message!!");
+               SmsPluginTransport::instance()->sendDeliverReport(MSG_SUCCESS);
+               return;
+       }
+
+       /** convert to msgInfo */
+       convertTpduToMsginfo(pTpdu, &msgInfo);
+
+       /** Short Message Type 0 - Just Send Deliver Report */
+       if (msgInfo.msgType.subType == MSG_TYPE0_SMS) {
+               SmsPluginTransport::instance()->sendDeliverReport(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);
+       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.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;
+
+       if (msgInfo.msgType.subType == MSG_STATUS_REPORT_SMS) {
+               /** Status Report Message */
+               err = listener.pfMsgIncomingCb(&msgInfo);
+
+               /** Handling of Fail Case ?? */
+               SmsPluginTransport::instance()->sendDeliverReport(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;
+                       }
+               }
+
+               if (msgInfo.msgPort.valid == false) {
+                       err = SmsPluginStorage::instance()->addMessage(&msgInfo);
+               }
+
+               /** Callback to MSG FW */
+               if (msgInfo.msgType.classType != MSG_CLASS_2) {
+                       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 */
+                       if (msgInfo.msgType.classType == MSG_CLASS_0)
+                               SmsPluginTransport::instance()->sendClass0DeliverReport(err);
+                       else
+                               SmsPluginTransport::instance()->sendDeliverReport(err);
+               }
+
+               // Tizen Validation System
+               char *msisdn = NULL;
+               msisdn = MsgSettingGetString(MSG_SIM_MSISDN);
+
+               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);
+       }
+}
+
+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);
+}
+
+
+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);
+}
+
+
+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::callbackCBMsgIncoming(MSG_CB_MSG_S *pCbMsg)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       /** Callback to MSG FW */
+       err = listener.pfCBMsgIncomingCb(pCbMsg);
+
+       MSG_END();
+
+       return err;
+}
+
+
+msg_error_t SmsPluginEventHandler::callbackInitSimBySat()
+{
+       /** Callback to MSG FW */
+       return listener.pfInitSimBySatCb();
+}
+
+
+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::convertTpduToMsginfo(SMS_TPDU_S *pTpdu, MSG_MESSAGE_INFO_S *msgInfo)
+{
+       memset(msgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       switch(pTpdu->tpduType)
+       {
+               case SMS_TPDU_SUBMIT :
+                       convertSubmitTpduToMsginfo(&pTpdu->data.submit, msgInfo);
+                       break;
+               case SMS_TPDU_DELIVER :
+                       convertDeliverTpduToMsginfo(&pTpdu->data.deliver, msgInfo);
+                       break;
+               case SMS_TPDU_STATUS_REP :
+                       convertStatusRepTpduToMsginfo(&pTpdu->data.statusRep, msgInfo);
+                       break;
+       }
+}
+
+
+void SmsPluginEventHandler::convertSubmitTpduToMsginfo(const SMS_SUBMIT_S *pTpdu, MSG_MESSAGE_INFO_S *msgInfo)
+{
+       int addressListCnt = 0;
+
+       /** Convert Type  values */
+       msgInfo->msgType.mainType = MSG_SMS_TYPE;
+       msgInfo->msgType.subType = convertMsgSubType(pTpdu->pid);
+
+       /** set folder id (temporary) */
+       msgInfo->folderId = MSG_OUTBOX_ID;
+
+       switch(pTpdu->dcs.msgClass)
+       {
+               case SMS_MSG_CLASS_0:
+                       msgInfo->msgType.classType = MSG_CLASS_0;
+                       break;
+               case SMS_MSG_CLASS_1:
+                       msgInfo->msgType.classType = MSG_CLASS_1;
+                       break;
+               case SMS_MSG_CLASS_2:
+                       msgInfo->msgType.classType = MSG_CLASS_2;
+                       break;
+               case SMS_MSG_CLASS_3:
+                       msgInfo->msgType.classType = MSG_CLASS_3;
+                       break;
+               default:
+                       msgInfo->msgType.classType = MSG_CLASS_NONE;
+       }
+
+       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->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;
+
+       /** Convert Address values */
+       msgInfo->nAddressCnt = 1;
+       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]");
+               msgInfo->dataSize = strlen(msgInfo->msgText);
+               return;
+       }
+
+       /** Convert Data values */
+       if (pTpdu->dcs.codingScheme == SMS_CHARSET_7BIT) {
+               MSG_LANG_INFO_S langInfo = {0,};
+
+               langInfo.bSingleShift = false;
+               langInfo.bLockingShift = false;
+
+               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 = 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);
+
+       /** set folder id (temporary) */
+       msgInfo->folderId = MSG_INBOX_ID;
+
+       msgInfo->storageId = MSG_STORAGE_PHONE;
+
+       switch(pTpdu->dcs.msgClass)
+       {
+               case SMS_MSG_CLASS_0:
+                       msgInfo->msgType.classType = MSG_CLASS_0;
+                       break;
+               case SMS_MSG_CLASS_1:
+                       msgInfo->msgType.classType = MSG_CLASS_1;
+                       break;
+               case SMS_MSG_CLASS_2:
+                       msgInfo->msgType.classType = MSG_CLASS_2;
+                       msgInfo->storageId = MSG_STORAGE_SIM;
+                       break;
+               case SMS_MSG_CLASS_3:
+                       msgInfo->msgType.classType = MSG_CLASS_3;
+                       break;
+               default:
+                       msgInfo->msgType.classType = MSG_CLASS_NONE;
+                       break;
+       }
+
+       if (pTpdu->dcs.bMWI) {
+               msgInfo->msgType.subType = (pTpdu->dcs.indType + MSG_MWI_VOICE_SMS);
+       }
+
+       msgInfo->networkStatus = MSG_NETWORK_RECEIVED;
+       msgInfo->bRead = false;
+       msgInfo->bProtected = false;
+       msgInfo->priority = MSG_MESSAGE_PRIORITY_NORMAL;
+       msgInfo->direction = MSG_DIRECTION_TYPE_MT;
+       msgInfo->bTextSms = true;
+
+       memset(msgInfo->subject, 0x00, MAX_SUBJECT_LEN+1);
+
+       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[0].addressType = MSG_ADDRESS_TYPE_PLMN;
+       strncpy(msgInfo->addressList[0].addressVal, pTpdu->originAddress.address, MAX_ADDRESS_VAL_LEN);
+
+       msgInfo->msgPort.valid = false;
+       msgInfo->msgPort.dstPort = 0;
+       msgInfo->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) {
+                       msgInfo->msgPort.valid = true;
+                       msgInfo->msgPort.dstPort = pTpdu->userData.header[i].udh.appPort8bit.destPort;
+                       msgInfo->msgPort.srcPort = pTpdu->userData.header[i].udh.appPort8bit.originPort;
+               } else if (pTpdu->userData.header[i].udhType == SMS_UDH_APP_PORT_16BIT) {
+                       msgInfo->msgPort.valid = true;
+                       msgInfo->msgPort.dstPort = pTpdu->userData.header[i].udh.appPort16bit.destPort;
+                       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);
+                       msgInfo->bStore = pTpdu->userData.header[i].udh.specialInd.bStore;
+
+                       if (pTpdu->dcs.codingGroup == SMS_GROUP_DISCARD)
+                               msgInfo->bStore = false;
+
+                       MSG_DEBUG("Message waiting number : [%d]", pTpdu->userData.header[i].udh.specialInd.waitMsgNum);
+                       SmsPluginSetting::instance()->setMwiInfo(msgInfo->msgType.subType, pTpdu->userData.header[i].udh.specialInd.waitMsgNum);
+
+                       if (pTpdu->userData.length == 0) {
+                               switch (msgInfo->msgType.subType) {
+                               case MSG_MWI_VOICE_SMS :
+                                       sprintf(msgInfo->msgText, "%d new voice message", pTpdu->userData.header[i].udh.specialInd.waitMsgNum);
+                                       break;
+                               case MSG_MWI_FAX_SMS :
+                                       sprintf(msgInfo->msgText, "%d new fax message", pTpdu->userData.header[i].udh.specialInd.waitMsgNum);
+                                       break;
+                               case MSG_MWI_EMAIL_SMS :
+                                       sprintf(msgInfo->msgText, "%d new email message", pTpdu->userData.header[i].udh.specialInd.waitMsgNum);
+                                       break;
+                               default :
+                                       sprintf(msgInfo->msgText, "%d new special message", pTpdu->userData.header[i].udh.specialInd.waitMsgNum);
+                                       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);
+               }
+       }
+
+       /**length 0 - no user data - msg should be received */
+       if (pTpdu->userData.length <= 0) {
+               memset(msgInfo->msgText, 0x00, sizeof(msgInfo->msgText));
+               msgInfo->dataSize = 0;
+
+               switch(pTpdu->dcs.codingScheme)
+               {
+                       case SMS_CHARSET_7BIT:
+                               msgInfo->encodeType = MSG_ENCODE_GSM7BIT;
+                               break;
+                       case SMS_CHARSET_8BIT:
+                               msgInfo->encodeType = MSG_ENCODE_8BIT;
+                               break;
+                       case SMS_CHARSET_UCS2:
+                               msgInfo->encodeType = MSG_ENCODE_UCS2;
+                               break;
+                       default:
+                               msgInfo->encodeType = MSG_ENCODE_8BIT;
+                               break;
+               }
+
+               return;
+       } else if (pTpdu->userData.length > MAX_MSG_TEXT_LEN) {
+               sprintf(msgInfo->msgText, "[Broken Message]");
+               msgInfo->dataSize = strlen(msgInfo->msgData);
+               return;
+       }
+
+       /** Convert Data values */
+       if (pTpdu->dcs.codingScheme == SMS_CHARSET_7BIT) {
+               MSG_LANG_INFO_S langInfo = {0,};
+
+               langInfo.bSingleShift = false;
+               langInfo.bLockingShift = false;
+
+               for (int i = 0; i < pTpdu->userData.headerCnt; i++)     {
+                       if (pTpdu->userData.header[i].udhType == SMS_UDH_SINGLE_SHIFT) {
+                               langInfo.bSingleShift = true;
+                               langInfo.singleLang = pTpdu->userData.header[i].udh.singleShift.langId;
+                       } else if (pTpdu->userData.header[i].udhType == SMS_UDH_LOCKING_SHIFT) {
+                               langInfo.bLockingShift = true;
+                               langInfo.lockingLang = pTpdu->userData.header[i].udh.lockingShift.langId;
+                       }
+               }
+
+               msgInfo->encodeType = MSG_ENCODE_GSM7BIT;
+               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, sizeof(pTpdu->userData.data));
+               msgInfo->dataSize = pTpdu->userData.length;
+       } else if (pTpdu->dcs.codingScheme == SMS_CHARSET_UCS2) {
+               msgInfo->encodeType = MSG_ENCODE_UCS2;
+               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 = textCvt.convertEUCKRToUTF8((unsigned char*)msgInfo->msgText, MAX_MSG_TEXT_LEN, (unsigned char*)pTpdu->userData.data, pTpdu->userData.length);
+               return;
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginEventHandler::convertStatusRepTpduToMsginfo(const SMS_STATUS_REPORT_S *pTpdu, MSG_MESSAGE_INFO_S *msgInfo)
+{
+       /** Convert Type  values */
+       msgInfo->msgType.mainType = MSG_SMS_TYPE;
+       msgInfo->msgType.subType = MSG_STATUS_REPORT_SMS;
+
+       /** set folder id */
+       msgInfo->folderId = MSG_INBOX_ID;
+
+       /** set storage id */
+       msgInfo->storageId = MSG_STORAGE_PHONE;
+
+       switch(pTpdu->dcs.msgClass)
+       {
+               case SMS_MSG_CLASS_0:
+                       msgInfo->msgType.classType = MSG_CLASS_0;
+                       break;
+               case SMS_MSG_CLASS_1:
+                       msgInfo->msgType.classType = MSG_CLASS_1;
+                       break;
+               case SMS_MSG_CLASS_2:
+                       msgInfo->msgType.classType = MSG_CLASS_2;
+                       break;
+               case SMS_MSG_CLASS_3:
+                       msgInfo->msgType.classType = MSG_CLASS_3;
+                       break;
+               default:
+                       msgInfo->msgType.classType = MSG_CLASS_NONE;
+                       break;
+       }
+
+       MSG_DEBUG("delivery status : [%d]", pTpdu->status);
+
+       if (pTpdu->status == SMS_STATUS_RECEIVE_SUCCESS) {
+               msgInfo->networkStatus = MSG_NETWORK_DELIVER_SUCCESS;
+       } else {
+               msgInfo->networkStatus = MSG_NETWORK_DELIVER_FAIL;
+       }
+
+       msgInfo->bRead = false;
+       msgInfo->bProtected = false;
+       msgInfo->priority = MSG_MESSAGE_PRIORITY_NORMAL;
+       msgInfo->direction = MSG_DIRECTION_TYPE_MT;
+       msgInfo->bTextSms = true;
+
+       memset(msgInfo->subject, 0x00, MAX_SUBJECT_LEN+1);
+
+       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[0].addressType = MSG_ADDRESS_TYPE_PLMN;
+       strncpy(msgInfo->addressList[0].addressVal, pTpdu->recipAddress.address, MAX_ADDRESS_VAL_LEN);
+
+       msgInfo->msgPort.valid = false;
+       msgInfo->msgPort.dstPort = 0;
+       msgInfo->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) {
+                       msgInfo->msgPort.valid = true;
+                       msgInfo->msgPort.dstPort = pTpdu->userData.header[i].udh.appPort8bit.destPort;
+                       msgInfo->msgPort.srcPort = pTpdu->userData.header[i].udh.appPort8bit.originPort;
+               } else if (pTpdu->userData.header[i].udhType == SMS_UDH_APP_PORT_16BIT) {
+                       msgInfo->msgPort.valid = true;
+                       msgInfo->msgPort.dstPort = pTpdu->userData.header[i].udh.appPort16bit.destPort;
+                       msgInfo->msgPort.srcPort = pTpdu->userData.header[i].udh.appPort16bit.originPort;
+               }
+       }
+
+       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);
+               msgInfo->dataSize = strlen(msgInfo->msgText);
+       } else if (pTpdu->status == SMS_STATUS_TEMP_SERVICE_REJECTED) {
+               strncpy(msgInfo->msgText, "Message delivery rejected.", 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);
+               msgInfo->dataSize = strlen(msgInfo->msgText);
+       } else {
+               strncpy(msgInfo->msgText, "Message delivery failed.", MAX_MSG_TEXT_LEN);
+               msgInfo->dataSize = strlen(msgInfo->msgText);
+       }
+}
+
+
+MSG_SUB_TYPE_T SmsPluginEventHandler::convertMsgSubType(SMS_PID_T pid)
+{
+       switch (pid)
+       {
+               case SMS_PID_TYPE0 :
+                       return MSG_TYPE0_SMS;
+               case SMS_PID_REPLACE_TYPE1 :
+                       return MSG_REPLACE_TYPE1_SMS;
+               case SMS_PID_REPLACE_TYPE2 :
+                       return MSG_REPLACE_TYPE2_SMS;
+               case SMS_PID_REPLACE_TYPE3 :
+                       return MSG_REPLACE_TYPE3_SMS;
+               case SMS_PID_REPLACE_TYPE4 :
+                       return MSG_REPLACE_TYPE4_SMS;
+               case SMS_PID_REPLACE_TYPE5 :
+                       return MSG_REPLACE_TYPE5_SMS;
+               case SMS_PID_REPLACE_TYPE6 :
+                       return MSG_REPLACE_TYPE6_SMS;
+               case SMS_PID_REPLACE_TYPE7 :
+                       return MSG_REPLACE_TYPE7_SMS;
+               case SMS_PID_RETURN_CALL :
+                       return MSG_MWI_OTHER_SMS;
+               default :
+                       return MSG_NORMAL_SMS;
+       }
+
+}
+
+
+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::setDeviceStatus()
+{
+       mx.lock();
+       devStatus = true;
+       cv.signal();
+       mx.unlock();
+}
+
+
+bool SmsPluginEventHandler::getDeviceStatus()
+{
+       int ret = 0;
+
+       mx.lock();
+
+       ret = cv.timedwait(mx.pMutex(), 16);
+
+       if (ret == ETIMEDOUT) {
+               MSG_DEBUG("WARNING: DEVICE STATUS TIME-OUT");
+               devStatus = false;
+       }
+       mx.unlock();
+       return devStatus;
+}
diff --git a/plugin/sms_plugin/SmsPluginMain.cpp b/plugin/sms_plugin/SmsPluginMain.cpp
new file mode 100755 (executable)
index 0000000..4a77e50
--- /dev/null
@@ -0,0 +1,597 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "SmsPluginTransport.h"
+#include "SmsPluginSimMsg.h"
+#include "SmsPluginStorage.h"
+#include "SmsPluginSetting.h"
+#include "SmsPluginCallback.h"
+#include "SmsPluginEventHandler.h"
+#include "SmsPluginUAManager.h"
+#include "SmsPluginMain.h"
+
+extern "C"
+{
+       #include <tapi_common.h>
+       #include <TelSms.h>
+       #include <TapiUtility.h>
+       #include <ITapiSim.h>
+       #include <ITapiNetText.h>
+}
+
+struct tapi_handle *pTapiHandle = NULL;
+
+Mutex mx;
+CndVar cv;
+
+/*==================================================================================================
+                                     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->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;
+
+               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();
+
+       MSG_DEBUG("set MSG_SIM_CHANGED to MSG_SIM_STATUS_NOT_FOUND.");
+       if (MsgSettingSetInt(MSG_SIM_CHANGED, MSG_SIM_STATUS_NOT_FOUND) != MSG_SUCCESS)
+               MSG_DEBUG("MsgSettingSetInt is failed!!");
+
+       bool bReady;
+       MsgSettingGetBool(VCONFKEY_TELEPHONY_READY, &bReady);
+       MSG_DEBUG("Get VCONFKEY_TELEPHONY_READY [%d].", bReady);
+
+       int ret = 0;
+
+       if(!bReady) {
+               MsgSettingRegVconfCBCommon(VCONFKEY_TELEPHONY_READY, MsgTapiInitCB);
+               mx.lock();
+               ret = cv.timedwait(mx.pMutex(), 90);
+               mx.unlock();
+       }
+
+       try
+       {
+               if (ret != ETIMEDOUT) {
+                       pTapiHandle = tel_init(NULL);
+                       SmsPluginCallback::instance()->registerEvent();
+               }
+       }
+       catch (MsgException& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_REGEVENT;
+       }
+       catch (exception& e)
+       {
+               MSG_FATAL("%s", e.what());
+               return MSG_ERR_PLUGIN_REGEVENT;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgFinalize()
+{
+       MSG_BEGIN();
+
+       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 SmsPlgCheckSimStatus(MSG_SIM_STATUS_T *pStatus)
+{
+       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);
+
+                               sleep(3);
+
+                               continue;
+                       }
+
+                       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);
+                       }
+               } 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;
+               memset(&imsiInfo, 0x00, sizeof(TelSimImsiInfo_t));
+
+               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);
+
+                       MsgSettingSetBool(MSG_NATIONAL_SIM, false);
+               }
+       }
+       else
+       {
+               MsgSettingSetBool(MSG_NATIONAL_SIM, false);
+       }
+
+       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;
+               } else {
+                       MSG_DEBUG("Device Is Not Ready.");
+                       return MSG_ERR_PLUGIN_TAPI_FAILED;
+               }
+       }
+
+       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()->addMessage(&(pReqInfo->msgInfo));
+                       if (err != 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);
+
+       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 SmsPlgInitSimMessage()
+{
+       // 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
+       {
+               SmsPluginSimMsg::instance()->initSimMessage();
+       }
+       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;
+       }
+
+       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)
+{
+       // 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
+       {
+               SmsPluginSimMsg::instance()->deleteSimMessage(SimMsgId);
+       }
+       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;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgSetReadStatus(msg_sim_id_t SimMsgId)
+{
+       // 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
+       {
+               SmsPluginSimMsg::instance()->setReadStatus(SimMsgId);
+       }
+       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;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPlgSetMemoryStatus(msg_error_t Error)
+{
+       // 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 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 SmsPlgInitConfigData(MSG_SIM_STATUS_T SimStatus)
+{
+       // 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()->initConfigData(SimStatus);
+       }
+       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 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)
+{
+       // 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);
+       }
+       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;
+}
+
diff --git a/plugin/sms_plugin/SmsPluginParamCodec.cpp b/plugin/sms_plugin/SmsPluginParamCodec.cpp
new file mode 100755 (executable)
index 0000000..30f4a1c
--- /dev/null
@@ -0,0 +1,529 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "SmsPluginParamCodec.h"
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginParamCodec - Member Functions
+==================================================================================================*/
+SmsPluginParamCodec::SmsPluginParamCodec()
+{
+
+
+}
+
+
+SmsPluginParamCodec::~SmsPluginParamCodec()
+{
+
+
+}
+
+
+/*==================================================================================================
+                                     Encode Functions
+==================================================================================================*/
+int SmsPluginParamCodec::encodeAddress(const SMS_ADDRESS_S *pAddress, char **ppParam)
+{
+       int offset = 0, length = 0;
+       char *temp = (char *)pAddress->address;
+
+       SMS_TON_T ton;
+
+       *ppParam = new char[MAX_ADD_PARAM_LEN];
+
+       // Set Address Length
+       if (temp[0] == '+')
+       {
+               (*ppParam)[offset++] = strlen(temp) - 1;
+               temp++;
+
+               ton = SMS_TON_INTERNATIONAL;
+       }
+       else
+       {
+               (*ppParam)[offset++] = strlen(temp);
+
+               ton = pAddress->ton;
+       }
+
+       // Set TON, NPI
+       (*ppParam)[offset++] = 0x80 + (ton << 4) + pAddress->npi;
+
+       MSG_DEBUG("Address length is %d.", (*ppParam)[0]);
+       MSG_DEBUG("pAddress->ton : %d.", ton);
+       MSG_DEBUG("pAddress->npi : %d.", pAddress->npi);
+
+       length = convertDigitToBcd(temp, strlen(temp), (unsigned char *) &((*ppParam)[offset]));
+
+       offset += length;
+
+       return offset ;
+}
+
+
+int SmsPluginParamCodec::encodeTime(const SMS_TIMESTAMP_S *pTimeStamp, char **ppParam)
+{
+       int offset = 0;
+
+       if(pTimeStamp->format == SMS_TIME_ABSOLUTE)
+       {
+               int timeZone = pTimeStamp->time.absolute.timeZone;
+               *ppParam = new char[MAX_ABS_TIME_PARAM_LEN];
+
+               (*ppParam)[offset++] = ((pTimeStamp->time.absolute.year % 10)  << 4) + (pTimeStamp->time.absolute.year / 10);
+               (*ppParam)[offset++] = ((pTimeStamp->time.absolute.month % 10) << 4) + (pTimeStamp->time.absolute.month / 10);
+               (*ppParam)[offset++] = ((pTimeStamp->time.absolute.day % 10) << 4) + (pTimeStamp->time.absolute.day / 10);
+               (*ppParam)[offset++] = ((pTimeStamp->time.absolute.hour % 10) << 4) + (pTimeStamp->time.absolute.hour / 10);
+               (*ppParam)[offset++] = ((pTimeStamp->time.absolute.minute % 10) << 4) + (pTimeStamp->time.absolute.minute / 10);
+               (*ppParam)[offset++] = ((pTimeStamp->time.absolute.second % 10) << 4) + (pTimeStamp->time.absolute.second / 10);
+
+               if(timeZone < 0)
+               {
+                       timeZone *= -1;
+                       (*ppParam)[offset] = 0x08;
+               }
+               (*ppParam)[offset++] += ((pTimeStamp->time.absolute.timeZone % 10) << 4) + (pTimeStamp->time.absolute.timeZone / 10);
+
+
+               return offset;
+       }
+       else if(pTimeStamp->format == SMS_TIME_RELATIVE)
+       {
+               *ppParam = new char[MAX_REL_TIME_PARAM_LEN+1];
+
+               memcpy(*ppParam, &(pTimeStamp->time.relative.time), MAX_REL_TIME_PARAM_LEN);
+
+               return MAX_REL_TIME_PARAM_LEN;
+       }
+
+       return offset;
+}
+
+
+int SmsPluginParamCodec::encodeDCS(const SMS_DCS_S *pDCS, char **ppParam)
+{
+       *ppParam = new char;
+
+       **ppParam = 0x00;
+
+       switch (pDCS->codingGroup)
+       {
+               case SMS_GROUP_GENERAL:
+               {
+                       if (pDCS->msgClass != SMS_MSG_CLASS_NONE)
+                       {
+                               **ppParam = 0x10 + pDCS->msgClass;
+                       }
+
+                       if (pDCS->bCompressed)
+                       {
+                               **ppParam |= 0x20;
+                       }
+               }
+               break;
+
+               case SMS_GROUP_CODING_CLASS:
+               {
+                       **ppParam = 0xF0 + pDCS->msgClass;
+               }
+               break;
+
+               case SMS_GROUP_DELETION:
+                       //not supported
+               break;
+
+               case SMS_GROUP_DISCARD:
+                       //not supported
+               break;
+
+               case SMS_GROUP_STORE:
+                       //not supported
+               break;
+
+               default:
+                       return 0;
+       }
+
+       switch (pDCS->codingScheme)
+       {
+               case SMS_CHARSET_7BIT:
+
+               break;
+
+               case SMS_CHARSET_8BIT:
+                       **ppParam |= 0x04;
+               break;
+
+               case SMS_CHARSET_UCS2:
+                       **ppParam |= 0x08;
+               break;
+
+               default:
+                       return 0;
+       }
+
+       return 1;
+}
+
+
+int SmsPluginParamCodec::encodeSMSC(const char *pAddress, unsigned char *pEncodeAddr)
+{
+       char newAddr[MAX_SMSC_LEN+1];
+       memset(newAddr, 0x00, sizeof(newAddr));
+
+//MSG_DEBUG("SMSC [%s]", pAddress);
+
+       if (pAddress[0] == '+')
+       {
+               strncpy(newAddr, pAddress+1, MAX_SMSC_LEN);
+       }
+       else
+       {
+               strncpy(newAddr, pAddress, MAX_SMSC_LEN);
+       }
+
+       // Set Address
+       int encodeLen = convertDigitToBcd(newAddr, strlen(newAddr), pEncodeAddr);
+
+       pEncodeAddr[encodeLen] = '\0';
+
+       return encodeLen;
+}
+
+
+int SmsPluginParamCodec::encodeSMSC(const SMS_ADDRESS_S *pAddress, unsigned char *pSMSC)
+{
+       char newAddr[MAX_SMSC_LEN+1];
+       memset(newAddr, 0x00, sizeof(newAddr));
+
+       int dataSize = 0, addrLen = 0;
+
+       if (pAddress->address[0] == '+')
+               memcpy(newAddr, pAddress->address+1, strlen(pAddress->address)-1);
+       else
+               memcpy(newAddr, pAddress->address, strlen(pAddress->address));
+
+       addrLen = strlen(newAddr);
+
+       if (addrLen % 2 == 0)
+               dataSize = 2 + (addrLen/2);
+       else
+               dataSize = 2 + (addrLen/2) + 1;
+
+       if (dataSize > MAX_SMSC_LEN)
+       {
+               MSG_DEBUG("addrLen is too long [%d]", addrLen);
+               MSG_DEBUG("dataSize is too long [%d]", dataSize);
+
+               return 0;
+       }
+
+       // Set Address Length
+       // Check IPC 4.0 -> addrLen/2
+       pSMSC[0] = addrLen;
+
+       // Set TON, NPI
+       pSMSC[1] = 0x80 + (pAddress->ton << 4) + pAddress->npi;
+
+       // Set Address
+       convertDigitToBcd(newAddr, addrLen, &(pSMSC[2]));
+
+       pSMSC[dataSize] = '\0';
+
+       return dataSize;
+}
+
+
+/*==================================================================================================
+                                     Decode Functions
+==================================================================================================*/
+int SmsPluginParamCodec::decodeAddress(const unsigned char *pTpdu, SMS_ADDRESS_S *pAddress)
+{
+       int offset = 0, addrLen = 0, bcdLen = 0;
+       MsgTextConvert textCvt;
+       memset(pAddress->address, 0x00, sizeof(pAddress->address));
+
+       addrLen = (int)pTpdu[offset++];
+
+       if (addrLen % 2 == 0)
+               bcdLen = addrLen/2;
+       else
+               bcdLen = addrLen/2 + 1;
+
+       pAddress->ton = (pTpdu[offset] & 0x70) >> 4;
+       pAddress->npi = pTpdu[offset++] & 0x0F;
+
+MSG_DEBUG("ton [%d]", pAddress->ton);
+MSG_DEBUG("npi [%d]", pAddress->npi);
+
+       if (pAddress->ton == SMS_TON_ALPHANUMERIC)
+       {
+               MSG_DEBUG("Alphanumeric address");
+
+               char* tmpAddress = new char[MAX_ADDRESS_LEN];
+               int tmplength = 0;
+
+               tmplength = SmsPluginUDCodec::unpack7bitChar(&(pTpdu[offset]), bcdLen, 0, tmpAddress);
+
+               MSG_LANG_INFO_S langInfo = {0,};
+
+               langInfo.bSingleShift = false;
+               langInfo.bLockingShift = false;
+
+               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]));
+       }
+       else
+       {
+               convertBcdToDigit(&(pTpdu[offset]), bcdLen, &((pAddress->address)[0]));
+       }
+
+       offset +=       bcdLen;
+
+//MSG_DEBUG("address [%s]", pAddress->address);
+
+       return offset;
+}
+
+
+int SmsPluginParamCodec::decodeTime(const unsigned char *pTpdu, SMS_TIMESTAMP_S *pTimeStamp)
+{
+       int offset = 0;
+
+       // decode in ABSOLUTE time type.
+       pTimeStamp->format = SMS_TIME_ABSOLUTE;
+
+       pTimeStamp->time.absolute.year = (pTpdu[offset] & 0x0F)*10 + ((pTpdu[offset] & 0xF0) >> 4);
+       offset++;
+
+       pTimeStamp->time.absolute.month = (pTpdu[offset] & 0x0F)*10 + ((pTpdu[offset] & 0xF0) >> 4);
+       offset++;
+
+       pTimeStamp->time.absolute.day = (pTpdu[offset] & 0x0F)*10 + ((pTpdu[offset] & 0xF0) >> 4);
+       offset++;
+
+       pTimeStamp->time.absolute.hour = (pTpdu[offset] & 0x0F)*10 + ((pTpdu[offset] & 0xF0) >> 4);
+       offset++;
+
+       pTimeStamp->time.absolute.minute = (pTpdu[offset] & 0x0F)*10 + ((pTpdu[offset] & 0xF0) >> 4);
+       offset++;
+
+       pTimeStamp->time.absolute.second = (pTpdu[offset] & 0x0F)*10 + ((pTpdu[offset] & 0xF0) >> 4);
+       offset++;
+
+       pTimeStamp->time.absolute.timeZone = (pTpdu[offset] & 0x07)*10 + ((pTpdu[offset] & 0xF0) >> 4);
+
+       if (pTpdu[offset] & 0x08)
+               pTimeStamp->time.absolute.timeZone *= (-1);
+
+       offset++;
+
+       return offset;
+}
+
+
+int SmsPluginParamCodec::decodeDCS(const unsigned char *pTpdu, SMS_DCS_S *pDCS)
+{
+       int offset = 0;
+       char dcs = pTpdu[offset++];
+
+       pDCS->bMWI = false;
+       pDCS->bIndActive = false;
+       pDCS->indType = SMS_OTHER_INDICATOR;
+
+       if (((dcs & 0xC0) >> 6) == 0)
+       {
+               pDCS->codingGroup = SMS_GROUP_GENERAL;
+               pDCS->bCompressed = (dcs & 0x20) >> 5;
+               pDCS->codingScheme = (dcs & 0x0C) >> 2;
+
+               if (((dcs & 0x10) >> 4) == 0)
+                       pDCS->msgClass = SMS_MSG_CLASS_NONE;
+               else
+                       pDCS->msgClass = dcs & 0x03;
+       }
+       else if (((dcs & 0xF0) >> 4) == 0x0F)
+       {
+               pDCS->codingGroup = SMS_GROUP_CODING_CLASS;
+               pDCS->bCompressed = false;
+               pDCS->codingScheme = (dcs & 0x0C) >> 2;
+
+               pDCS->msgClass = dcs & 0x03;
+       }
+       else if (((dcs & 0xC0) >> 6) == 1)
+       {
+               pDCS->codingGroup = SMS_GROUP_DELETION;
+               pDCS->bCompressed = false;
+               pDCS->msgClass = SMS_MSG_CLASS_NONE;
+
+               // TODO: finish here. ??
+       }
+       else if (((dcs & 0xF0) >> 4) == 0x0C)
+       {
+               pDCS->codingGroup = SMS_GROUP_DISCARD;
+               pDCS->bCompressed = false;
+               pDCS->msgClass = SMS_MSG_CLASS_NONE;
+
+               pDCS->bMWI = true;
+               pDCS->bIndActive = (((dcs & 0x08) >> 3) == 1)? true:false;
+               pDCS->indType = (SMS_INDICATOR_TYPE_T)(dcs & 0x03);
+       }
+       else if (((dcs & 0xF0) >> 4) == 0x0D)
+       {
+               pDCS->codingGroup = SMS_GROUP_STORE;
+               pDCS->codingScheme = SMS_CHARSET_7BIT;
+               pDCS->bCompressed = false;
+               pDCS->msgClass = SMS_MSG_CLASS_NONE;
+
+               pDCS->bMWI = true;
+               pDCS->bIndActive = (((dcs & 0x08) >> 3) == 1)? true:false;
+               pDCS->indType = (SMS_INDICATOR_TYPE_T)(dcs & 0x03);
+       }
+       else if (((dcs & 0xF0) >> 4) == 0x0E)
+       {
+               pDCS->codingGroup = SMS_GROUP_STORE;
+               pDCS->codingScheme = SMS_CHARSET_UCS2;
+               pDCS->bCompressed = false;
+               pDCS->msgClass = SMS_MSG_CLASS_NONE;
+
+               pDCS->bMWI = true;
+               pDCS->bIndActive = (((dcs & 0x08) >> 3) == 1)? false:true;
+               pDCS->indType = (SMS_INDICATOR_TYPE_T)(dcs & 0x03);
+       }
+       else
+       {
+               pDCS->codingGroup = SMS_GROUP_UNKNOWN;
+
+               pDCS->bCompressed = (dcs & 0x20) >> 5;
+               pDCS->codingScheme = (dcs & 0x0C) >> 2;
+
+               pDCS->msgClass = SMS_MSG_CLASS_NONE;
+       }
+
+       return offset;
+}
+
+
+void SmsPluginParamCodec::decodeSMSC(unsigned char* pAddress, int AddrLen, MSG_SMS_TON_T ton, char *pDecodeAddr)
+{
+       if (pAddress == NULL || AddrLen == 0)
+               return;
+
+       if (ton == SMS_TON_INTERNATIONAL)
+       {
+               pDecodeAddr[0] = '+';
+               convertBcdToDigit(pAddress, AddrLen, &(pDecodeAddr[1]));
+       }
+       else
+       {
+               convertBcdToDigit(pAddress, AddrLen, pDecodeAddr);
+       }
+}
+
+
+/*==================================================================================================
+                                     Util Functions
+==================================================================================================*/
+int SmsPluginParamCodec::convertDigitToBcd(char *pDigit, int DigitLen, unsigned char *pBcd)
+{
+       int offset = 0;
+       unsigned char temp;
+
+//MSG_DEBUG("DigitLen [%d]", DigitLen);
+//MSG_DEBUG("pDigit [%s]", pDigit);
+
+       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;
+}
+
diff --git a/plugin/sms_plugin/SmsPluginSatHandler.cpp b/plugin/sms_plugin/SmsPluginSatHandler.cpp
new file mode 100755 (executable)
index 0000000..8a933cf
--- /dev/null
@@ -0,0 +1,625 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgException.h"
+#include "MsgGconfWrapper.h"
+#include "SmsPluginParamCodec.h"
+#include "SmsPluginUDCodec.h"
+#include "SmsPluginSetting.h"
+#include "SmsPluginTransport.h"
+#include "SmsPluginCallback.h"
+#include "SmsPluginEventHandler.h"
+#include "SmsPluginSatHandler.h"
+
+extern "C"
+{
+       #include <tapi_common.h>
+       #include <TelSms.h>
+       #include <TapiUtility.h>
+       #include <ITapiNetText.h>
+       #include <ITapiSat.h>
+}
+
+extern struct tapi_handle *pTapiHandle;
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginCbMsgHandler - Member Functions
+==================================================================================================*/
+SmsPluginSatHandler* SmsPluginSatHandler::pInstance = NULL;
+
+
+SmsPluginSatHandler::SmsPluginSatHandler()
+{
+       commandId = 0;
+
+       bSendSms = false;
+       bInitSim = false;
+       bSMSPChanged = false;
+       bCBMIChanged = false;
+}
+
+
+SmsPluginSatHandler::~SmsPluginSatHandler()
+{
+
+}
+
+
+SmsPluginSatHandler* SmsPluginSatHandler::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginSatHandler();
+
+       return pInstance;
+}
+
+
+void SmsPluginSatHandler::refreshSms(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)
+{
+       TelSatSendSmsIndSmsData_t* pSmsData = (TelSatSendSmsIndSmsData_t*)pData;
+
+       bSendSms = true;
+
+       commandId = pSmsData->commandId;
+
+       MSG_DEBUG("commandId [%d]", commandId);
+
+       // The TPDU Maximum Length at SAT side is 175
+       // This is because Sat can send 160 bytes unpacked and header
+       unsigned char tpdu[MAX_SAT_TPDU_LEN+1];
+       int tpduLen = 0;
+
+       memset(tpdu, 0x00, sizeof(tpdu));
+       memcpy(tpdu, pSmsData->smsTpdu.data, pSmsData->smsTpdu.dataLen);
+
+       // 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);
+               return;
+       }
+
+       // Make Telephony Structure
+       TelSmsDatapackageInfo_t pkgInfo;
+
+       // Set TPDU data
+       memset((void*)pkgInfo.szData, 0x00, sizeof(pkgInfo.szData));
+       memcpy((void*)pkgInfo.szData, tpdu, tpduLen);
+
+       pkgInfo.szData[tpduLen] = '\0';
+       pkgInfo.MsgLength = tpduLen;
+
+       // Set SMSC Address
+       SMS_ADDRESS_S smsc;
+
+       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';
+
+               MSG_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);
+       }
+
+       unsigned char smscAddr[MAX_SMSC_LEN];
+       memset(smscAddr, 0x00, sizeof(smscAddr));
+
+       int smscLen = SmsPluginParamCodec::encodeSMSC(&smsc, smscAddr);
+
+       if (smscLen <= 0) return;
+
+       // Set SMSC Address
+       memset(pkgInfo.Sca, 0x00, sizeof(pkgInfo.Sca));
+       memcpy((void*)pkgInfo.Sca, smscAddr, smscLen);
+       pkgInfo.Sca[smscLen] = '\0';
+
+       int tapiRet = TAPI_API_SUCCESS;
+
+       // Send SMS
+       tapiRet = tel_send_sms(pTapiHandle, &pkgInfo, 0, TapiEventSentStatus, 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);
+       }
+}
+
+
+void SmsPluginSatHandler::ctrlSms(void *pData)
+{
+       TelSatMoSmCtrlIndData_t* pCtrlData = (TelSatMoSmCtrlIndData_t*)pData;
+
+       if (bSendSms == true) // Send SMS By SAT
+       {
+               if (pCtrlData->moSmsCtrlResult == TAPI_SAT_CALL_CTRL_R_NOT_ALLOWED)
+               {
+                       MSG_DEBUG("SIM does not allow to send SMS");
+
+                       sendResult(SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_INTRCTN_WITH_CC_OR_SMS_CTRL_PRMNT_PRBLM);
+               }
+               else if (pCtrlData->moSmsCtrlResult == TAPI_SAT_CALL_CTRL_R_ALLOWED_WITH_MOD)
+               {
+                       MSG_DEBUG("SIM allows to send SMS with modification");
+
+                       sendResult(SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_SUCCESS);
+               }
+       }
+       else // Send SMS By APP
+       {
+               msg_network_status_t netStatus = MSG_NETWORK_NOT_SEND;
+
+               if (pCtrlData->moSmsCtrlResult == TAPI_SAT_CALL_CTRL_R_NOT_ALLOWED)
+               {
+                       MSG_DEBUG("SIM does not allow to send SMS");
+
+                       netStatus = MSG_NETWORK_SEND_FAIL;
+               }
+               else if (pCtrlData->moSmsCtrlResult == TAPI_SAT_CALL_CTRL_R_ALLOWED_WITH_MOD)
+               {
+                       MSG_DEBUG("SIM allows to send SMS with modification");
+
+                       netStatus = MSG_NETWORK_SEND_SUCCESS;
+               }
+
+               // Call Event Handler
+               SmsPluginEventHandler::instance()->handleSentStatus(netStatus);
+       }
+}
+
+
+void SmsPluginSatHandler::ctrlSms(msg_network_status_t netStatus)
+{
+       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");
+
+                       sendResult(SMS_SAT_CMD_SEND_SMS, TAPI_SAT_R_SMS_RP_ERROR);
+               }
+       }
+}
+
+
+void SmsPluginSatHandler::finishSimMsgInit(msg_error_t Err)
+{
+       // SAT Handler is initializing SIM now
+       if (bInitSim == true)
+       {
+               // Init SMSC List and CB ID Info
+               try
+               {
+                       if (bSMSPChanged == true) initSMSCList();
+               }
+               catch (MsgException& e)
+               {
+                       // Send Result to TAPI
+                       sendResult(SMS_SAT_CMD_REFRESH, TAPI_SAT_R_ME_UNABLE_TO_PROCESS_COMMAND);
+
+                       MSG_FATAL("%s", e.what());
+                       return;
+               }
+
+               try
+               {
+                       if (bCBMIChanged == true) initCBConfig();
+               }
+               catch (MsgException& e)
+               {
+                       // Send Result to TAPI
+                       sendResult(SMS_SAT_CMD_REFRESH, TAPI_SAT_R_ME_UNABLE_TO_PROCESS_COMMAND);
+
+                       MSG_FATAL("%s", e.what());
+                       return;
+               }
+
+               // Send Result to TAPI
+               sendResult(SMS_SAT_CMD_REFRESH, TAPI_SAT_R_SUCCESS);
+       }
+}
+
+
+void SmsPluginSatHandler::initSim()
+{
+       bInitSim = true;
+
+       // Init SIM Message
+       if (SmsPluginEventHandler::instance()->callbackInitSimBySat() != MSG_SUCCESS)
+       {
+               MSG_DEBUG("Init Sim Error");
+
+               // Send Result to TAPI
+               sendResult(SMS_SAT_CMD_REFRESH, TAPI_SAT_R_ME_UNABLE_TO_PROCESS_COMMAND);
+       }
+}
+
+
+void   SmsPluginSatHandler::initSMSCList()
+{
+       MSG_SETTING_S settingData;
+
+       settingData.type = MSG_SMSC_LIST;
+
+       // Get Data From SIM
+       SmsPluginSetting::instance()->getConfigData(&settingData);
+
+       MSG_DEBUG("total_count[%d]", settingData.option.smscList.totalCnt);
+       MSG_DEBUG("selected[%d]", settingData.option.smscList.selected);
+
+       for (int i = 0; i < settingData.option.smscList.totalCnt; i++)
+       {
+               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_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);
+       }
+
+       if (MsgSettingSetInt(SMSC_SELECTED, settingData.option.smscList.selected) != MSG_SUCCESS)
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "Error to set config data [%s]", SMSC_SELECTED);
+               return;
+       }
+
+       if (MsgSettingSetInt(SMSC_TOTAL_COUNT, settingData.option.smscList.totalCnt) != MSG_SUCCESS)
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "Error to set config data [%s]", SMSC_TOTAL_COUNT);
+               return;
+       }
+
+       char keyName[128];
+       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);
+
+               if ((err = MsgSettingSetInt(keyName, (int)settingData.option.smscList.smscData[i].pid)) != MSG_SUCCESS)
+                       break;
+
+#if 0
+               memset(keyName, 0x00, sizeof(keyName));
+               sprintf(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);
+
+               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);
+
+               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);
+
+               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);
+
+               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);
+
+               if ((err = MsgSettingSetString(keyName, settingData.option.smscList.smscData[i].smscAddr.address)) != MSG_SUCCESS)
+                       break;
+       }
+
+       if (err != MSG_SUCCESS)
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "Error to set config data [%s]", keyName);
+       }
+}
+
+
+void   SmsPluginSatHandler::initCBConfig()
+{
+       MSG_SETTING_S settingData;
+
+       settingData.type = MSG_CBMSG_OPT;
+
+       // Get Data From SIM
+       SmsPluginSetting::instance()->getConfigData(&settingData);
+
+       if (MsgSettingSetBool(CB_RECEIVE, settingData.option.cbMsgOpt.bReceive) != MSG_SUCCESS)
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "Error to set config data [%s]", CB_RECEIVE);
+               return;
+       }
+
+       if (MsgSettingSetInt(CB_MAX_SIM_COUNT, settingData.option.cbMsgOpt.maxSimCnt) != MSG_SUCCESS)
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "Error to set config data [%s]", CB_MAX_SIM_COUNT);
+               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;
+       }
+
+       if (err != MSG_SUCCESS)
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "Error to set config data [%s]", keyName);
+       }
+}
+
+
+int SmsPluginSatHandler::handleSatTpdu(unsigned char *pTpdu, unsigned char TpduLen, int bIsPackingRequired)
+{
+       if (pTpdu == NULL)
+               THROW(MsgException::SMS_PLG_ERROR, "SAT TPDU is NULL");
+
+       int pos = 0;
+
+       // TP-MTI, TP-RD, TP-VPF,  TP-RP, TP-UDHI, TP-SRR
+       // TP-VPF
+       SMS_VPF_T vpf = (SMS_VPF_T)(pTpdu[pos++] & 0x18) >> 3;
+
+       // TP-MR
+       unsigned char tmpRef = pTpdu[pos];
+
+       MSG_DEBUG("current Msg Ref : %d", tmpRef);
+
+       pTpdu[pos] = tmpRef + 1;
+
+       MSG_DEBUG("new Msg Ref : %d", pTpdu[pos]);
+
+       pos++;
+
+//     pTpdu[pos++] = SmsPluginTransport::instance()->getMsgRef();
+
+
+       // TP-DA
+       SMS_ADDRESS_S destAddr = {0};
+       int addrLen = SmsPluginParamCodec::decodeAddress(&pTpdu[pos], &destAddr);
+
+       pos += addrLen;
+
+       // TP-PID
+       pos++;
+
+       // TP-DCS
+       SMS_DCS_S dcs = {0};
+
+       int dcsLen = SmsPluginParamCodec::decodeDCS(&pTpdu[pos], &dcs);
+
+       if (bIsPackingRequired == true)
+       {
+               dcs.codingScheme = SMS_CHARSET_7BIT;
+
+               char* pDcs = NULL;
+               AutoPtr<char> dcsBuf(&pDcs);
+
+               SmsPluginParamCodec::encodeDCS(&dcs, &pDcs);
+
+               memcpy(&(pTpdu[pos]), pDcs, dcsLen);
+       }
+
+       pos++;
+
+       // TP-VP
+       if (vpf == SMS_VPF_RELATIVE)
+       {
+               pos += MAX_REL_TIME_PARAM_LEN;
+       }
+       else if (vpf == SMS_VPF_ABSOLUTE)
+       {
+               pos += MAX_ABS_TIME_PARAM_LEN;
+       }
+
+       // TP-UDL
+       int udl = pTpdu[pos];
+       int retLen = 0;
+
+       if (bIsPackingRequired == true)
+       {
+               SMS_USERDATA_S userData = {0};
+
+               userData.headerCnt = 0;
+               userData.length = udl;
+               memcpy(userData.data, &pTpdu[pos+1], udl);
+               userData.data[udl] = '\0';
+
+MSG_DEBUG("user data : [%s]", userData.data);
+
+               int encodeSize = SmsPluginUDCodec::encodeUserData(&userData, dcs.codingScheme, (char*)&pTpdu[pos]);
+
+               retLen = pos + encodeSize;
+       }
+       else
+       {
+               retLen = TpduLen;
+       }
+
+       return retLen;
+}
+
+
+void SmsPluginSatHandler::sendResult(SMS_SAT_CMD_TYPE_T CmdType, int ResultType)
+{
+       TelSatAppsRetInfo_t satRetInfo;
+
+       satRetInfo.commandId = commandId;
+
+       MSG_DEBUG("satRetInfo.commandId [%d]", satRetInfo.commandId);
+
+       if (CmdType == SMS_SAT_CMD_REFRESH)
+       {
+               satRetInfo.commandType = TAPI_SAT_CMD_TYPE_REFRESH;
+
+               satRetInfo.appsRet.refresh.appType = TAPI_SAT_REFRESH_MSG;
+               satRetInfo.appsRet.refresh.resp = (TelSatResultType_t)ResultType;
+       }
+       else if (CmdType == SMS_SAT_CMD_SEND_SMS)
+       {
+               satRetInfo.commandType = TAPI_SAT_CMD_TYPE_SEND_SMS;
+
+               satRetInfo.appsRet.sendSms.resp = (TelSatResultType_t)ResultType;
+       }
+
+       int tapiRet = TAPI_API_SUCCESS;
+
+       tapiRet = tel_send_sat_app_exec_result(pTapiHandle, &satRetInfo);
+
+       if (tapiRet == TAPI_API_SUCCESS)
+       {
+               MSG_DEBUG("TelTapiSatSendAppExecutionResult() SUCCESS");
+       }
+       else
+       {
+               MSG_DEBUG("TelTapiSatSendAppExecutionResult() FAIL [%d]", tapiRet);
+       }
+
+       bSendSms = false;
+       bInitSim = false;
+       bSMSPChanged = false;
+       bCBMIChanged = false;
+}
+
diff --git a/plugin/sms_plugin/SmsPluginSetting.cpp b/plugin/sms_plugin/SmsPluginSetting.cpp
new file mode 100755 (executable)
index 0000000..49d6f7f
--- /dev/null
@@ -0,0 +1,1145 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgNotificationWrapper.h"
+#include "MsgSoundPlayer.h"
+
+#include "SmsPluginParamCodec.h"
+#include "SmsPluginCallback.h"
+#include "SmsPluginSetting.h"
+
+
+extern "C"
+{
+       #include <tapi_common.h>
+       #include <TelSms.h>
+       #include <TapiUtility.h>
+       #include <ITapiNetText.h>
+       #include <ITapiSim.h>
+}
+
+extern struct tapi_handle *pTapiHandle;
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginSetting - Member Functions
+==================================================================================================*/
+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));
+       memset(&simMailboxList, 0x00, sizeof(SMS_SIM_MAILBOX_LIST_S));
+
+       bTapiResult = false;
+       paramCnt = 0;
+       selectedParam = 0;
+}
+
+
+SmsPluginSetting::~SmsPluginSetting()
+{
+
+
+}
+
+
+SmsPluginSetting* SmsPluginSetting::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginSetting();
+
+       return pInstance;
+}
+
+
+void SmsPluginSetting::initConfigData(MSG_SIM_STATUS_T SimStatus)
+{
+       MSG_BEGIN();
+
+       msg_error_t     err = MSG_SUCCESS;
+
+       // Init SMS Parameter
+       int paramCnt = 0;
+       int failCnt = 0;
+
+       paramCnt = getParamCount();
+
+       MSG_DEBUG("Parameter Count [%d]", paramCnt);
+
+       MSG_SMSC_DATA_S tmpSmscData = {};
+       MSG_SMSC_LIST_S tmpSmscList = {};
+
+       for (int index = 0; index < paramCnt; index++)
+       {
+               if (getParam(index, &tmpSmscData) == false) {
+                       failCnt++;
+                       continue;
+               }
+
+               memcpy(&(tmpSmscList.smscData[index]), &tmpSmscData, sizeof(MSG_SMSC_DATA_S));
+
+               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_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);
+       }
+
+       tmpSmscList.totalCnt = (paramCnt - failCnt);
+//     below is commented to be the first smsc is selected.
+//     tmpSmscList.selected = selectedParam;
+
+       if (paramCnt > 0) {
+               err = addSMSCList(&tmpSmscList);
+
+               if (err == MSG_SUCCESS) {
+                       MSG_DEBUG("########  Add SMSC List Success !!! #######");
+               } else {
+                       MSG_DEBUG("########  Add SMSC List Fail !!! return : %d #######", err);
+               }
+       }
+
+       // Init CB Config
+       if (SimStatus == MSG_SIM_STATUS_CHANGED) {
+               MSG_DEBUG("simStatus == MSG_SIM_STATUS_CHANGED");
+
+               MSG_CBMSG_OPT_S cbMsgOpt = {};
+
+               if (getCbConfig(&cbMsgOpt) == true) {
+                       err = addCbOpt(&cbMsgOpt);
+
+                       if (err == MSG_SUCCESS) {
+                               MSG_DEBUG("########  Add CB Option Success !!! #######");
+                       } else {
+                               MSG_DEBUG("########  Add CB Option Fail !!! return : %d #######", err);
+                       }
+               }
+       } 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;
+
+               getCbOpt(&cbSetting);
+
+               setCbConfig(&(cbSetting.option.cbMsgOpt));
+       }
+
+       if (SimStatus != MSG_SIM_STATUS_NOT_FOUND)
+       {
+               MSG_VOICEMAIL_OPT_S tmpVoiceMail;
+               memset(&tmpVoiceMail, 0x00, sizeof(MSG_VOICEMAIL_OPT_S));
+
+               if (getVoiceMailInfo(&tmpVoiceMail) == true) {
+                       MSG_DEBUG("########  getVoiceMailInfo Success !!! #######");
+               } else {
+                       MSG_DEBUG("########  getVoiceMailInfo Fail !!! #######");
+               }
+
+               if (getMwiInfo() == true) {
+                       MSG_DEBUG("########  getMwiInfo Success !!! #######");
+               } else {
+                       MSG_DEBUG("########  getMwiInfo Fail !!! #######");
+               }
+
+               if (getMsisdnInfo() == true) {
+                       MSG_DEBUG("########  getMsisdnInfo Success !!! #######");
+               } else {
+                       MSG_DEBUG("########  getMsisdnInfo Fail !!! #######");
+               }
+       }
+
+       MSG_END();
+}
+
+
+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;
+               case MSG_CBMSG_OPT :
+                       setCbConfig(&pSetting->option.cbMsgOpt);
+                       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;
+       }
+}
+
+
+void SmsPluginSetting::getConfigData(MSG_SETTING_S *pSetting)
+{
+       MSG_DEBUG("Setting Type : [%d]", pSetting->type);
+
+       switch (pSetting->type)
+       {
+               case MSG_SMSC_LIST :
+                       getParamList(&pSetting->option.smscList);
+               break;
+
+               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::addSMSCList(MSG_SMSC_LIST_S *pSmscList)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       MSG_DEBUG("total_count[%d]", pSmscList->totalCnt);
+       MSG_DEBUG("selected index[%d]", pSmscList->selected);
+
+       for (int i = 0; i < pSmscList->totalCnt; i++)
+       {
+               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_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;
+       }
+
+       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;
+
+               memset(keyName, 0x00, sizeof(keyName));
+               sprintf(keyName, "%s/%d", SMSC_VAL_PERIOD, i);
+
+               if ((err = MsgSettingSetInt(keyName, (int)pSmscList->smscData[i].valPeriod)) != MSG_SUCCESS)
+                       break;
+
+               memset(keyName, 0x00, sizeof(keyName));
+               sprintf(keyName, "%s/%d", SMSC_NAME, i);
+
+               if ((err = MsgSettingSetString(keyName, pSmscList->smscData[i].name)) != MSG_SUCCESS)
+                       break;
+
+               memset(keyName, 0x00, sizeof(keyName));
+               sprintf(keyName, "%s/%d", SMSC_TON, i);
+
+               if (pSmscList->smscData[i].smscAddr.address[0] == '+')
+                       pSmscList->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;
+
+               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
+
+               if ((err = MsgSettingSetInt(keyName, (int)pSmscList->smscData[i].smscAddr.npi)) != MSG_SUCCESS)
+                       break;
+
+               memset(keyName, 0x00, sizeof(keyName));
+               sprintf(keyName, "%s/%d", SMSC_ADDRESS, i);
+
+               if ((err = MsgSettingSetString(keyName, pSmscList->smscData[i].smscAddr.address)) != MSG_SUCCESS)
+                       break;
+       }
+
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("Error to set config data [%s]", keyName);
+       }
+
+       return err;
+}
+
+
+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("Channel Count [%d]", pCbOpt->channelData.channelCnt);
+
+       for (int i = 0; i < pCbOpt->channelData.channelCnt; i++)
+       {
+               MSG_DEBUG("Channel FROM [%d], Channel TO [%d]", pCbOpt->channelData.channelInfo[i].from, pCbOpt->channelData.channelInfo[i].to);
+       }
+
+       // 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;
+       }
+
+       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;
+       }
+
+       if (MsgSettingSetInt(CB_CHANNEL_COUNT, pCbOpt->channelData.channelCnt) != MSG_SUCCESS) {
+               MSG_DEBUG("Error to set config data [%s]", CB_CHANNEL_COUNT);
+               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;
+       }
+
+       return err;
+}
+
+
+void SmsPluginSetting::getCbOpt(MSG_SETTING_S *pSetting)
+{
+       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);
+
+               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);
+
+               memset(keyName, 0x00, sizeof(keyName));
+               sprintf(keyName, "%s/%d", CB_CHANNEL_ID_TO, i);
+
+               pSetting->option.cbMsgOpt.channelData.channelInfo[i].to = MsgSettingGetInt(keyName);
+
+               memset(keyName, 0x00, sizeof(keyName));
+               sprintf(keyName, "%s/%d", CB_CHANNEL_NAME, i);
+
+               tmpValue = MsgSettingGetString(keyName);
+
+               if (tmpValue != NULL)
+               {
+                       strncpy(pSetting->option.cbMsgOpt.channelData.channelInfo[i].name, tmpValue, CB_CHANNEL_NAME_MAX);
+                       free(tmpValue);
+                       tmpValue = NULL;
+               }
+       }
+
+       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);
+
+               MsgSettingGetBool(keyName, &pSetting->option.cbMsgOpt.bLanguage[i]);
+       }
+
+}
+
+
+void SmsPluginSetting::setParamList(const MSG_SMSC_LIST_S *pSMSCList)
+{
+       MSG_BEGIN();
+
+       TelSmsParams_t smsParam = {0};
+
+       int ret = TAPI_API_SUCCESS;
+
+       for (int index = 0; index < pSMSCList->totalCnt; index++) {
+               /*Setting the SMSP Record index value*/
+               smsParam.RecordIndex = (unsigned char)index;
+
+               /*Setting the SMSP Record Length value = 28 + alphaId_len*/
+               smsParam.RecordLen = 28 + strlen(pSMSCList->smscData[index].name);
+
+               /*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;
+
+               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;
+
+                       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("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");
+               }
+
+               /*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);
+
+               /*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.ParamIndicator = ~(smsParam.ParamIndicator);
+               MSG_DEBUG("ParamIndicator = [%02x]", smsParam.ParamIndicator);
+
+               ret = tel_set_sms_parameters(pTapiHandle, (const TelSmsParams_t*)&smsParam, TapiEventSetConfigData, NULL);
+
+               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();
+}
+
+
+void SmsPluginSetting::getParamList(MSG_SMSC_LIST_S *pSMSCList)
+{
+       MSG_BEGIN();
+
+       int paramCnt = 0;
+
+       paramCnt = getParamCount();
+
+       MSG_DEBUG("Parameter Count [%d]", paramCnt);
+
+       int ret = TAPI_API_SUCCESS;
+
+       MSG_SMSC_DATA_S tmpSmscData = {};
+
+       for (int index = 0; index < paramCnt; index++) {
+               ret = tel_get_sms_parameters(pTapiHandle, index, TapiEventGetParam, NULL);
+
+               if (ret == TAPI_API_SUCCESS) {
+                       MSG_DEBUG("######## tel_get_sms_parameters() Success !!! #######");
+               } else {
+                       THROW(MsgException::SMS_PLG_ERROR, "######## tel_get_sms_parameters() Fail !!! return : %d #######", ret);
+               }
+
+               if (getParamEvent(&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));
+
+               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("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);
+       }
+
+       pSMSCList->totalCnt = paramCnt;
+       pSMSCList->selected = selectedParam;
+
+       MSG_DEBUG("total_count[%d]", pSMSCList->totalCnt);
+
+       MSG_END();
+}
+
+
+int SmsPluginSetting::getParamCount()
+{
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_get_sms_parameter_count(pTapiHandle, TapiEventGetParamCnt, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_get_sms_parameter_count() Success !!! #######");
+       } else {
+               THROW(MsgException::SMS_PLG_ERROR, "tel_get_sms_parameter_count() Error. [%d]", ret);
+       }
+
+       return getParamCntEvent();
+}
+
+
+bool SmsPluginSetting::getParam(int Index, MSG_SMSC_DATA_S *pSmscData)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_get_sms_parameters(pTapiHandle, Index, TapiEventGetParam, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_get_sms_parameters() Success !!! #######");
+       } else {
+               MSG_DEBUG("######## tel_get_sms_parameters() Fail !!! return : %d #######", ret);
+               return false;
+       }
+
+       if (getParamEvent(pSmscData) == true) {
+               MSG_DEBUG("######## Get Parameter was Successful !!! #######");
+       } else {
+               MSG_DEBUG("######## Get Parameter was Failed !!! #######");
+               return false;
+       }
+
+       return true;
+}
+
+
+bool SmsPluginSetting::setCbConfig(const MSG_CBMSG_OPT_S *pCbOpt)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       TelSmsCbConfig_t cbConfig = {};
+
+       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(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 (getResultFromSim() == true) {
+               MSG_DEBUG("######## Set Cb Config was Successful !!! #######");
+       } else {
+               MSG_DEBUG("######## Set Cb Config was Failed !!! #######");
+               return false;
+       }
+
+       return true;
+}
+
+
+bool SmsPluginSetting::getCbConfig(MSG_CBMSG_OPT_S *pCbOpt)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       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;
+       }
+
+       return true;
+}
+
+void SmsPluginSetting::setVoiceMailInfo(const MSG_VOICEMAIL_OPT_S *pVoiceOpt)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       TelSimMailBoxNumber_t mailboxInfo = {0,};
+
+       for (int i = 0; i < simMailboxList.count; i++) {
+               if (simMailboxList.list[i].mb_type == TAPI_SIM_MAILBOX_VOICE) {
+                       memset(&simMailboxList.list[i].num, 0x00, sizeof(simMailboxList.list[i].num));
+                       snprintf(simMailboxList.list[i].num, sizeof(simMailboxList.list[i].num), "%s", pVoiceOpt->mailNumber);
+                       MSG_DEBUG("Mailbox number config [%s]", simMailboxList.list[i].num);
+
+                       mailboxInfo.b_cphs = simMailboxList.list[i].b_cphs;
+                       mailboxInfo.alpha_id_max_len = simMailboxList.list[i].alpha_id_max_len;
+                       mailboxInfo.mb_type = (TelSimMailboxType_t)simMailboxList.list[i].mb_type;
+                       mailboxInfo.profile_num = simMailboxList.list[i].profile_num;
+                       mailboxInfo.rec_index = simMailboxList.list[i].rec_index;
+                       mailboxInfo.ton = (TelSimTypeOfNum_t)simMailboxList.list[i].ton;
+                       mailboxInfo.npi = (TelSimNumberingPlanIdentity_t)simMailboxList.list[i].npi;
+                       snprintf(mailboxInfo.alpha_id, sizeof(mailboxInfo.alpha_id), "%s", simMailboxList.list[i].alpha_id);
+                       snprintf(mailboxInfo.num, sizeof(mailboxInfo.num), "%s", simMailboxList.list[i].num);
+                       mailboxInfo.cc_id = simMailboxList.list[i].cc_id;
+                       mailboxInfo.ext1_id = simMailboxList.list[i].ext1_id;
+
+                       break;
+               }
+       }
+
+       ret = tel_set_sim_mailbox_info(pTapiHandle, &mailboxInfo, TapiEventSetMailboxInfo, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_set_sim_mailbox_info() Success !!! #######");
+       } else {
+               MSG_DEBUG("######## tel_set_sim_mailbox_info() Fail !!! return : %d #######", ret);
+       }
+
+       if (getResultFromSim() == true) {
+               MSG_DEBUG("######## Set mailbox info Success !!! #######");
+       } else {
+               THROW(MsgException::SMS_PLG_ERROR, "########  Set mailbox info Failed !!!#######");
+       }
+
+       return;
+}
+
+bool SmsPluginSetting::getVoiceMailInfo(MSG_VOICEMAIL_OPT_S *pVoiceOpt)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_get_sim_mailbox_info(pTapiHandle, TapiEventGetMailboxInfo, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               MSG_DEBUG("######## tel_get_sim_mailbox_info() Success !!! #######");
+       } else {
+               MSG_DEBUG("######## tel_get_sim_mailbox_info() Fail !!! return : %d #######", ret);
+               return false;
+       }
+
+       if (getMailboxInfoEvent(pVoiceOpt) == true) {
+               MSG_DEBUG("######## Get MWI info was Successful !!! #######");
+       } else {
+               MSG_DEBUG("######## Get MWI info was Failed !!! #######");
+               return false;
+       }
+
+       return true;
+}
+
+void SmsPluginSetting::setMwiInfo(MSG_SUB_TYPE_T type, int count)
+{
+       if (type < MSG_MWI_VOICE_SMS || type > MSG_MWI_OTHER_SMS) {
+               MSG_DEBUG("Invalid parameter");
+               return;
+       }
+
+       int ret = TAPI_API_SUCCESS;
+
+       TelSimMessageWaitingReq_t mwReq = {0,};
+
+       if (simMwiInfo.b_cphs) {
+               if (type == MSG_MWI_VOICE_SMS)
+                       simMwiInfo.cphs_mwi.b_voice1 = true;
+               else if (type == MSG_MWI_FAX_SMS)
+                       simMwiInfo.cphs_mwi.b_fax = true;
+               else
+                       MSG_DEBUG("There is no type [%d] in CPHS.", type);
+
+               mwReq.mw_data_u.cphs_mw.b_voice1 = simMwiInfo.cphs_mwi.b_voice1;
+               mwReq.mw_data_u.cphs_mw.b_voice2 = simMwiInfo.cphs_mwi.b_voice2;
+               mwReq.mw_data_u.cphs_mw.b_fax = simMwiInfo.cphs_mwi.b_fax;
+               mwReq.mw_data_u.cphs_mw.b_data = simMwiInfo.cphs_mwi.b_data;
+       } else {
+               if (type == MSG_MWI_VOICE_SMS)
+                       simMwiInfo.mwi_list.mw_info[0].voice_count = count;
+               else if (type == MSG_MWI_FAX_SMS)
+                       simMwiInfo.mwi_list.mw_info[0].fax_count = count;
+               else if (type == MSG_MWI_EMAIL_SMS)
+                       simMwiInfo.mwi_list.mw_info[0].email_count = count;
+               else // MSG_MWI_OTHER_SMS
+                       simMwiInfo.mwi_list.mw_info[0].other_count = count;
+
+               mwReq.mw_data_u.mw.rec_index = simMwiInfo.mwi_list.mw_info[0].rec_index;
+               mwReq.mw_data_u.mw.indicator_status = simMwiInfo.mwi_list.mw_info[0].indicator_status;
+               mwReq.mw_data_u.mw.voice_count = simMwiInfo.mwi_list.mw_info[0].voice_count;
+               mwReq.mw_data_u.mw.fax_count = simMwiInfo.mwi_list.mw_info[0].fax_count;
+               mwReq.mw_data_u.mw.email_count = simMwiInfo.mwi_list.mw_info[0].email_count;
+               mwReq.mw_data_u.mw.other_count = simMwiInfo.mwi_list.mw_info[0].other_count;
+               mwReq.mw_data_u.mw.video_count = simMwiInfo.mwi_list.mw_info[0].video_count;
+       }
+
+       mwReq.b_cphs = simMwiInfo.b_cphs;
+
+       ret = tel_set_sim_messagewaiting_info(pTapiHandle, &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(void)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_get_sim_messagewaiting_info(pTapiHandle, 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(void)
+{
+       int ret = TAPI_API_SUCCESS;
+       bool result = true;
+
+       ret = tel_get_sim_msisdn(pTapiHandle, TapiEventGetMsisdnInfo, NULL);
+
+       if (ret == TAPI_API_SUCCESS) {
+               result = true;
+               MSG_DEBUG("######## tel_get_sim_msisdn() Success !!! #######");
+       } else {
+               result = false;
+               MSG_DEBUG("######## tel_get_sim_msisdn() Fail !!! return : %d #######", ret);
+       }
+
+       return result;
+}
+
+
+void SmsPluginSetting::setParamCntEvent(int ParamCnt)
+{
+       mx.lock();
+
+       paramCnt = ParamCnt;
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+
+int SmsPluginSetting::getParamCntEvent()
+{
+       int ret = 0;
+
+       mx.lock();
+
+       ret = cv.timedwait(mx.pMutex(), 10);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT) {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return 0;
+       }
+
+       return paramCnt;
+}
+
+
+void SmsPluginSetting::setParamEvent(const MSG_SMSC_DATA_S *pSmscData, int RecordIdx, bool bSuccess)
+{
+       mx.lock();
+
+       bTapiResult = bSuccess;
+
+       memset(&smscData, 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));
+       }
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+
+bool SmsPluginSetting::getParamEvent(MSG_SMSC_DATA_S *pSmscData)
+{
+       int ret = 0;
+
+       mx.lock();
+
+       bTapiResult = false;
+       ret = cv.timedwait(mx.pMutex(), 10);
+
+       mx.unlock();
+
+       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));
+       }
+
+       return bTapiResult;
+}
+
+
+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(), 10);
+
+       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::setMailboxInfoEvent(SMS_SIM_MAILBOX_LIST_S *pMailboxList, bool bSuccess)
+{
+       mx.lock();
+
+       bTapiResult = bSuccess;
+
+       memset(&simMailboxList, 0x00, sizeof(SMS_SIM_MAILBOX_LIST_S));
+
+       if (bTapiResult == true) {
+               int i = 0;
+
+               if (pMailboxList && pMailboxList->count > 0) {
+                       memcpy(&simMailboxList, pMailboxList, sizeof(SMS_SIM_MAILBOX_LIST_S));
+
+                       /* Temp :: Save voicemail number with VOICE1 line number */
+                       for (i = 0; i < pMailboxList->count ; i++) {
+                               MSG_DEBUG("Mailbox list[%d] type=[%d] address = [%s]", i, pMailboxList->list[i].mb_type, pMailboxList->list[i].num);
+                               if (pMailboxList->list[i].mb_type == TAPI_SIM_MAILBOX_VOICE) {
+                                       char mailNumber[MAX_PHONE_NUMBER_LEN+1];
+                                       memset(mailNumber, 0x00 , sizeof(mailNumber));
+                                       if (simMailboxList.list[i].ton == MSG_TON_INTERNATIONAL && simMailboxList.list[i].num[0] != '+') {
+                                               snprintf(mailNumber, MAX_PHONE_NUMBER_LEN, "+%s", simMailboxList.list[i].num);
+                                               MSG_DEBUG("MSG_TON_INTERNATIONAL [%s]", mailNumber);
+                                       } else {
+                                               snprintf(mailNumber, MAX_PHONE_NUMBER_LEN, "%s", simMailboxList.list[i].num);
+                                               MSG_DEBUG("[%s]", mailNumber);
+                                       }
+
+                                       if (mailNumber[0] != '\0') {
+                                               if (MsgSettingSetString(VOICEMAIL_NUMBER, mailNumber) != MSG_SUCCESS)
+                                                       MSG_DEBUG("MsgSettingSetString is failed!!");
+                                       }
+                                       break;
+                               }
+                       }
+               }
+       }
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+bool SmsPluginSetting::getMailboxInfoEvent(MSG_VOICEMAIL_OPT_S *pVoiceOpt)
+{
+       int ret = 0;
+
+       mx.lock();
+
+       bTapiResult = false;
+       ret = cv.timedwait(mx.pMutex(), 10);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT) {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return false;
+       }
+
+       memset(pVoiceOpt, 0x00, sizeof(MSG_VOICEMAIL_OPT_S));
+
+       if (bTapiResult == true) {
+               for(int i = 0; i < simMailboxList.count; i++) {
+                       if (simMailboxList.list[i].mb_type == MSG_SIM_MAILBOX_VOICE) {
+                               if (simMailboxList.list[i].ton == MSG_TON_INTERNATIONAL && simMailboxList.list[i].num[0] != '+') {
+                                       snprintf(pVoiceOpt->mailNumber, sizeof(pVoiceOpt->mailNumber), "+%s", simMailboxList.list[i].num);
+                               } else {
+                                       snprintf(pVoiceOpt->mailNumber, sizeof(pVoiceOpt->mailNumber), "%s", simMailboxList.list[i].num);
+                               }
+
+                               break;
+                       }
+               }
+       }
+
+       return bTapiResult;
+}
+
+void SmsPluginSetting::setMwiInfoEvent(SMS_SIM_MWI_INFO_S *pMwiInfo, bool bSuccess)
+{
+       mx.lock();
+
+       bTapiResult = bSuccess;
+
+       memset(&simMwiInfo, 0x00, sizeof(SMS_SIM_MWI_INFO_S));
+
+       if (bTapiResult == true) {
+               int mwi_cnt = 0;
+               int index = 0;
+
+               memcpy(&simMwiInfo, pMwiInfo, sizeof(SMS_SIM_MWI_INFO_S));
+
+               /* Save MW count with VOICE line number */
+               for(int i = 0; i < simMailboxList.count; i++) {
+
+                       if (simMailboxList.list[i].mb_type == MSG_SIM_MAILBOX_VOICE) {
+
+                               index = simMailboxList.list[i].profile_num - 1;
+                               if (index < 0) {
+                                       MSG_DEBUG("SIM profile number is invalid.");
+                                       break;
+                               }
+
+                               MSG_DEBUG("SIM MWI profile number=[%d], index=[%d]", simMailboxList.list[i].profile_num, index);
+
+                               if (simMwiInfo.b_cphs == false) { // Normal case
+                                       mwi_cnt = simMwiInfo.mwi_list.mw_info[index].voice_count;
+                               } else { // CPHS case
+                                       /* For CPHS case, mwi_cnt value is boolean */
+                                       mwi_cnt = simMwiInfo.cphs_mwi.b_voice1;
+                               }
+
+                               if (MsgSettingSetInt(VOICEMAIL_COUNT, mwi_cnt) != MSG_SUCCESS)
+                                       MSG_DEBUG("MsgSettingSetInt is failed!!");
+
+                               if (mwi_cnt > 0) {
+                                       MSG_MESSAGE_INFO_S msgInfo = {0,};
+
+                                       msgInfo.displayTime = time(NULL);
+                                       snprintf(msgInfo.addressList[0].addressVal, sizeof(msgInfo.addressList[0].addressVal), \
+                                                       "%s", simMailboxList.list[i].num);
+                                       memset(msgInfo.addressList[0].displayName, 0x00, sizeof(msgInfo.addressList[0].displayName));
+                                       msgInfo.msgType.mainType = MSG_SMS_TYPE;
+                                       msgInfo.msgType.subType = MSG_MWI_VOICE_SMS;
+
+                                       snprintf(msgInfo.msgText, sizeof(msgInfo.msgText), "%d new voice message", mwi_cnt);
+
+                                       MsgSoundPlayStart(false);
+                                       MsgInsertNoti(&msgInfo);
+                               }
+                               break;
+                       }
+               }
+       }
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+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(), 10);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT) {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return false;
+       }
+
+       return bTapiResult;
+}
+
+
+SMS_PID_T SmsPluginSetting::convertPid(MSG_SMS_PID_T pid)
+{
+       SMS_PID_T retPid;
+
+       switch (pid)
+       {
+               case MSG_PID_TEXT :
+                       retPid = SMS_PID_NORMAL;
+               break;
+               case MSG_PID_VOICE :
+                       retPid = SMS_PID_VOICE;
+               break;
+               case MSG_PID_FAX :
+                       retPid = SMS_PID_TELEX;
+               break;
+               case MSG_PID_X400 :
+                       retPid = SMS_PID_x400;
+               break;
+               case MSG_PID_ERMES :
+                       retPid = SMS_PID_ERMES;
+               break;
+               case MSG_PID_EMAIL :
+                       retPid = SMS_PID_EMAIL;
+               break;
+               default :
+                       retPid = SMS_PID_NORMAL;
+               break;
+       }
+
+       return retPid;
+}
+
diff --git a/plugin/sms_plugin/SmsPluginSimMsg.cpp b/plugin/sms_plugin/SmsPluginSimMsg.cpp
new file mode 100755 (executable)
index 0000000..a9f9be0
--- /dev/null
@@ -0,0 +1,730 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "SmsPluginParamCodec.h"
+#include "SmsPluginTpduCodec.h"
+#include "SmsPluginTransport.h"
+#include "SmsPluginStorage.h"
+#include "SmsPluginEventHandler.h"
+#include "SmsPluginCallback.h"
+#include "SmsPluginSimMsg.h"
+
+extern struct tapi_handle *pTapiHandle;
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginSimMsg - Member Functions
+==================================================================================================*/
+SmsPluginSimMsg* SmsPluginSimMsg::pInstance = NULL;
+
+
+SmsPluginSimMsg::SmsPluginSimMsg()
+{
+       // Initialize member variables
+       simMsgId = 0;
+       usedCnt = 0;
+       totalCnt = 0;
+       bTapiResult = false;
+       memset(&simMsgDataInfo, 0x00, sizeof(simMsgDataInfo));
+}
+
+
+SmsPluginSimMsg::~SmsPluginSimMsg()
+{
+
+
+}
+
+
+SmsPluginSimMsg* SmsPluginSimMsg::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginSimMsg();
+
+       return pInstance;
+}
+
+
+void SmsPluginSimMsg::initSimMessage()
+{
+       MSG_BEGIN();
+
+       MSG_SIM_COUNT_S tmpMsgCnt;
+       memset(&tmpMsgCnt, 0x00, sizeof(MSG_SIM_COUNT_S));
+
+       getSimMsgCount(&tmpMsgCnt);
+
+       MSG_MESSAGE_INFO_S tmpMsgInfo;
+       memset(&tmpMsgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       for (int i = 0; i < tmpMsgCnt.usedCount; i++)
+       {
+               // Get SIM Msg
+               if (getSimMsg(tmpMsgCnt.indexList[i], &tmpMsgInfo) == false)
+                       continue;
+
+               if (SmsPluginStorage::instance()->addSimMessage(&tmpMsgInfo) != MSG_SUCCESS)
+               {
+                       MSG_DEBUG("Fail to addSimMessage()");
+               }
+       }
+
+       MSG_END();
+}
+
+
+msg_error_t SmsPluginSimMsg::saveSimMessage(const MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SIM_ID_LIST_S *pSimIdList)
+{
+       // 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)
+       {
+               MSG_DEBUG("SIM storage is full.");
+
+               return MSG_ERR_SIM_STORAGE_FULL;
+       }
+
+       tpdu.data.deliver.userData.headerCnt = 0;
+
+       if (submitData.segCount > 1)
+               tpdu.data.deliver.bHeaderInd = true;
+
+       int bufLen = 0;
+
+       char buf[MAX_TPDU_DATA_LEN];
+
+       int addLen = strlen(submitData.destAddress.address);
+
+       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, addLen);
+       tpdu.data.deliver.originAddress.address[addLen] = '\0';
+
+       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);
+
+               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;
+
+#ifdef MSG_FOR_DEBUG
+               MSG_DEBUG("Sim Message.");
+               for (int j = 0; j < simSmsData.SmsData.MsgLength; j++)
+               {
+                       MSG_DEBUG("[%02x]", simSmsData.SmsData.szData[j]);
+               }
+#endif
+
+               MSG_DEBUG("Read Status [%d]", pMsgInfo->bRead);
+
+               if (pMsgInfo->bRead == true)
+                       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_READ;
+               else
+                       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_UNREAD;
+
+               // Save SMS in SIM
+               int ret = 0;
+
+               ret = tel_write_sms_in_sim(pTapiHandle, &simSmsData, TapiEventSaveSimMsg, NULL);
+
+               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;
+               }
+
+               msg_sim_id_t SimId = 0;
+
+               bool bResult = false;
+
+               bResult = getSimEvent(&SimId);
+
+               int usedCnt = 0;
+
+               if (bResult == true)
+               {
+                       MSG_DEBUG("########  Saving Msg was Successful !!! SIM ID : [%d] #######", SimId);
+
+                       usedCnt = MsgSettingGetInt(SIM_USED_COUNT);
+
+                       usedCnt++;
+
+                       if (MsgSettingSetInt(SIM_USED_COUNT, 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 !!! SIM ID : [%d] #######", SimId);
+
+                       return MSG_ERR_PLUGIN_STORAGE;
+               }
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPluginSimMsg::saveClass2Message(const MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       // Reset Flag
+       SMS_TPDU_S tpdu;
+
+       tpdu.tpduType = SMS_TPDU_DELIVER;
+
+       // Set SMS TPDU Options
+       setSmsOptions(&(tpdu.data.deliver));
+
+       // Make SMS_SUBMIT_DATA_S from MSG_REQUEST_INFO_S to get segment count
+       SMS_SUBMIT_DATA_S submitData;
+       SmsPluginTransport::instance()->msgInfoToSubmitData(pMsgInfo, &submitData, &(tpdu.data.deliver.dcs.codingScheme), 0);
+
+       // Check sim message full.
+       if (checkSimMsgFull(submitData.segCount) == true)
+       {
+               MSG_DEBUG("SIM storage is full.");
+
+               SmsPluginTransport::instance()->sendDeliverReport(MSG_ERR_SIM_STORAGE_FULL);
+
+               return MSG_ERR_SIM_STORAGE_FULL;
+       }
+
+       // Create TelSmsData_t data
+       TelSmsData_t simSmsData = {0,};
+
+       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;
+
+       // Set message status
+       simSmsData.MsgStatus = TAPI_NETTEXT_STATUS_UNREAD;
+
+       // Save Class 2 Msg in SIM
+       int tapiRet = TAPI_API_SUCCESS;
+
+       tapiRet = tel_write_sms_in_sim(pTapiHandle, &simSmsData, TapiEventSaveClass2Msg, NULL);
+
+       if (tapiRet == TAPI_API_SUCCESS)
+       {
+               memset(&simMsgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+               memcpy(&simMsgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+
+               MSG_DEBUG("########  tel_write_sms_in_sim Success !!! #######");
+       }
+       else
+       {
+               MSG_DEBUG("########  tel_write_sms_in_sim Fail !!! return : [%d] #######", tapiRet);
+
+               SmsPluginTransport::instance()->sendDeliverReport(MSG_ERR_STORAGE_ERROR);
+
+               return MSG_ERR_PLUGIN_STORAGE;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+void SmsPluginSimMsg::deleteSimMessage(msg_sim_id_t SimMsgId)
+{
+       int tapiRet = TAPI_API_SUCCESS;
+
+       tapiRet = tel_delete_sms_in_sim(pTapiHandle, (int)SimMsgId, TapiEventDeleteSimMsg, NULL);
+
+       if (tapiRet == TAPI_API_SUCCESS)
+       {
+               MSG_DEBUG("########  tel_delete_sms_in_sim Success !!! #######");
+       }
+       else
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "########  tel_delete_sms_in_sim Fail !!! return : [%d] #######", tapiRet);
+       }
+
+       msg_sim_id_t SimId = 0;
+       bool bResult = false;
+
+       bResult = getSimEvent(&SimId);
+
+       int usedCnt = 0, totalCnt = 0;
+
+       if (bResult == true)
+       {
+               MSG_DEBUG("########  Deleting Msg was Successful !!! SIM ID : [%d] #######", SimId);
+
+               usedCnt = MsgSettingGetInt(SIM_USED_COUNT);
+               totalCnt = MsgSettingGetInt(SIM_TOTAL_COUNT);
+
+               if (usedCnt == totalCnt)
+               {
+                       tapiRet = tel_set_sms_memory_status(pTapiHandle, TAPI_NETTEXT_PDA_MEMORY_STATUS_AVAILABLE, NULL, 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);
+                       }
+               }
+
+               usedCnt--;
+
+               if (MsgSettingSetInt(SIM_USED_COUNT, usedCnt) != MSG_SUCCESS)
+               {
+                       MSG_DEBUG("Error to set config data [%s]", SIM_USED_COUNT);
+               }
+       }
+       else
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "########  Deleting Msg was Failed !!! SIM ID : [%d] #######", SimId);
+       }
+}
+
+
+bool SmsPluginSimMsg::checkSimMsgFull(unsigned int SegCnt)
+{
+       int usedCnt = 0, totalCnt = 0;
+
+       usedCnt = MsgSettingGetInt(SIM_USED_COUNT);
+       totalCnt = MsgSettingGetInt(SIM_TOTAL_COUNT);
+
+       MSG_DEBUG("Segment Count [%d]", SegCnt);
+       MSG_DEBUG("usedCnt [%d], totalCnt [%d]", usedCnt, totalCnt);
+
+       if ((usedCnt + (int)SegCnt) <= totalCnt)
+               return false;
+       else
+               return true;
+}
+
+
+void SmsPluginSimMsg::setReadStatus(msg_sim_id_t SimMsgId)
+{
+       MSG_DEBUG("Sim Message ID [%d]", SimMsgId);
+
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_set_sms_message_status(pTapiHandle, (int)SimMsgId, TAPI_NETTEXT_STATUS_READ, TapiEventSetMsgStatus, (void *)&SimMsgId);
+
+       if (ret == TAPI_API_SUCCESS)
+       {
+               MSG_DEBUG("########  tel_set_sms_message_status Success !!! return : %d #######", ret);
+       }
+       else
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "########  tel_set_sms_message_status Fail !!! return : %d #######", ret);
+       }
+
+       msg_sim_id_t SimId = 0;
+       bool bResult = false;
+
+       bResult = getSimEvent(&SimId);
+
+       if (bResult == true)
+       {
+               MSG_DEBUG("######## Setting Read Status was Successful !!!, sim id=[%d] #######", SimId);
+       }
+       else
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "######## Setting Read Status was Failed !!! #######");
+       }
+}
+
+
+void SmsPluginSimMsg::getSimMsgCount(MSG_SIM_COUNT_S *pSimMsgCnt)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_get_sms_count(pTapiHandle, TapiEventGetSimMsgCnt, NULL);
+
+       if (ret == TAPI_API_SUCCESS)
+       {
+               MSG_DEBUG("######## tel_get_sms_count() Success !!! #######");
+       }
+       else
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "########  tel_get_sms_count() Fail !!! return : %d #######", ret);
+       }
+
+       if (getSimMsgCntEvent(pSimMsgCnt) == true)
+       {
+               MSG_DEBUG("######## Get Sim Msg Count was Successful !!! #######");
+       }
+       else
+       {
+               THROW(MsgException::SMS_PLG_ERROR, "######## Get Sim Msg Count was Failed !!! #######");
+       }
+}
+
+
+bool SmsPluginSimMsg::getSimMsg(msg_sim_id_t SimMsgId, MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       int ret = TAPI_API_SUCCESS;
+
+       ret = tel_read_sms_in_sim(pTapiHandle, SimMsgId, TapiEventGetSimMsg, NULL);
+
+       if (ret == TAPI_API_SUCCESS)
+       {
+               MSG_DEBUG("######## tel_read_sms_in_sim() Success !!! Sim ID : [%d] #######", SimMsgId);
+       }
+       else
+       {
+               MSG_DEBUG("########  tel_read_sms_in_sim() Fail !!! return : %d #######", ret);
+               return false;
+       }
+
+       if (getSimMsgEvent(pMsgInfo) == true)
+       {
+               MSG_DEBUG("######## Get Sim Msg was Successful !!! #######");
+       }
+       else
+       {
+               MSG_DEBUG("######## Get Sim Msg was Failed !!! #######");
+               return false;
+       }
+
+       return true;
+}
+
+
+void SmsPluginSimMsg::setSmsOptions(SMS_DELIVER_S *pDeliver)
+{
+       pDeliver->bMoreMsg = false;
+       pDeliver->bStatusReport = false;
+       pDeliver->bHeaderInd = false;
+       pDeliver->bReplyPath = false;
+
+       pDeliver->dcs.bCompressed = false;
+       pDeliver->dcs.msgClass = SMS_MSG_CLASS_NONE;
+       pDeliver->dcs.codingGroup = SMS_GROUP_GENERAL;
+
+       pDeliver->dcs.codingScheme = (SMS_CODING_SCHEME_T)MsgSettingGetInt(SMS_SEND_DCS);
+
+       MSG_DEBUG("DCS : %d", pDeliver->dcs.codingScheme);
+
+       pDeliver->pid = SMS_PID_NORMAL;
+
+       MSG_DEBUG("PID : %d", pDeliver->pid);
+}
+
+
+void SmsPluginSimMsg::convertTimeStamp(const MSG_MESSAGE_INFO_S* pMsgInfo, SMS_DELIVER_S *pDeliver)
+{
+       MSG_BEGIN();
+
+       // encode time stamp
+       pDeliver->timeStamp.format = SMS_TIME_ABSOLUTE;
+
+       // encode absolute time
+       struct tm timeinfo = {0,};
+       gmtime_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);
+
+       pDeliver->timeStamp.time.absolute.month = timeinfo.tm_mon + 1;
+       MSG_DEBUG("pDeliver->timeStamp.time.absolute.month is %d",pDeliver->timeStamp.time.absolute.month);
+
+       pDeliver->timeStamp.time.absolute.day = timeinfo.tm_mday;
+       MSG_DEBUG("pDeliver->timeStamp.time.absolute.day is %d",pDeliver->timeStamp.time.absolute.day);
+
+       pDeliver->timeStamp.time.absolute.hour = timeinfo.tm_hour;
+       MSG_DEBUG("pDeliver->timeStamp.time.absolute.hour is %d",pDeliver->timeStamp.time.absolute.hour);
+
+       pDeliver->timeStamp.time.absolute.minute = timeinfo.tm_min;
+       MSG_DEBUG("pDeliver->timeStamp.time.absolute.minute is %d",pDeliver->timeStamp.time.absolute.minute);
+
+       pDeliver->timeStamp.time.absolute.second = timeinfo.tm_sec;
+       MSG_DEBUG("pDeliver->timeStamp.time.absolute.second is %d",pDeliver->timeStamp.time.absolute.second);
+
+       pDeliver->timeStamp.time.absolute.timeZone = 0;
+       MSG_DEBUG("pDeliver->timeStamp.time.absolute.timeZone is %d",pDeliver->timeStamp.time.absolute.timeZone);
+
+       MSG_END();
+}
+
+
+void SmsPluginSimMsg::setSimMsgCntEvent(const MSG_SIM_COUNT_S *pSimMsgCnt)
+{
+       mx.lock();
+
+       MSG_DEBUG("Sim Message Count is %d.", pSimMsgCnt->usedCount);
+
+       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)
+       {
+               MSG_DEBUG("Error to set config data [%s]", SIM_USED_COUNT);
+       }
+
+       if (MsgSettingSetInt(SIM_TOTAL_COUNT, (int)pSimMsgCnt->totalCount) != MSG_SUCCESS)
+       {
+               MSG_DEBUG("Error to set config data [%s]", SIM_TOTAL_COUNT);
+       }
+
+       memset(&simMsgCnt, 0x00, sizeof(MSG_SIM_COUNT_S));
+       memcpy(&simMsgCnt, pSimMsgCnt, sizeof(MSG_SIM_COUNT_S));
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+
+bool SmsPluginSimMsg::getSimMsgCntEvent(MSG_SIM_COUNT_S *pSimMsgCnt)
+{
+       int ret = 0;
+
+       mx.lock();
+
+       ret = cv.timedwait(mx.pMutex(), 10);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT)
+       {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return false;
+       }
+
+       memcpy(pSimMsgCnt, &simMsgCnt, sizeof(MSG_SIM_COUNT_S));
+
+       return true;
+}
+
+void SmsPluginSimMsg::setSimMsgEvent(const MSG_MESSAGE_INFO_S *pMsgInfo, bool bSuccess)
+{
+       mx.lock();
+
+       bTapiResult = bSuccess;
+
+       memset(&simMsgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       if (bTapiResult  == true)
+       {
+               MSG_DEBUG("Success to get sim msg - Id : [%d]", pMsgInfo->msgId);
+
+               memcpy(&simMsgInfo, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+       }
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+
+bool SmsPluginSimMsg::getSimMsgEvent(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       int ret = 0;
+
+       mx.lock();
+
+       bTapiResult = false;
+       ret = cv.timedwait(mx.pMutex(), 10);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT)
+       {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return false;
+       }
+
+       memset(pMsgInfo, 0x00, sizeof(MSG_MESSAGE_INFO_S));
+
+       if (bTapiResult == true)
+       {
+               memcpy(pMsgInfo, &simMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+       }
+
+       return bTapiResult;
+}
+
+
+void SmsPluginSimMsg::setSaveSimMsgEvent(int simMsgId, int result)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       mx.lock();
+
+       if (result != TAPI_NETTEXT_SENDSMS_SUCCESS) {
+               if (result == TAPI_NETTEXT_ROUTING_NOT_AVAILABLE)
+                       err = MSG_ERR_SIM_STORAGE_FULL;
+               else
+                       err = MSG_ERR_UNKNOWN;
+       }
+
+       if (err == MSG_SUCCESS)
+               bTapiResult = true;
+       else
+               bTapiResult = false;
+
+       cv.signal();
+
+       mx.unlock();
+
+       // Send Deliver Report
+       SmsPluginTransport::instance()->sendDeliverReport(err);
+
+}
+
+
+void SmsPluginSimMsg::setSaveClass2MsgEvent(int simMsgId, int result)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if (result == TAPI_NETTEXT_SENDSMS_SUCCESS && simMsgId >= 0) {
+
+               simMsgInfo.msgId = simMsgId;
+
+               err = SmsPluginStorage::instance()->addSimMessage(&simMsgInfo);
+
+               if (err == MSG_SUCCESS)
+               {
+                       MSG_DEBUG("addSimMessage() Success !!");
+
+                       // Callback
+                       err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&simMsgInfo);
+
+                       if (err != MSG_SUCCESS)
+                       {
+                               MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+                       }
+
+                       usedCnt = MsgSettingGetInt(SIM_USED_COUNT);
+
+                       usedCnt++;
+
+                       if (MsgSettingSetInt(SIM_USED_COUNT, usedCnt) != MSG_SUCCESS)
+                       {
+                               MSG_DEBUG("Error to set config data [%s]", SIM_USED_COUNT);
+                       }
+               } else  {
+                       MSG_DEBUG("addMessage() Error !! [%d]", err);
+               }
+       } else {
+                       if (result == TAPI_NETTEXT_ROUTING_NOT_AVAILABLE)
+                               err = MSG_ERR_SIM_STORAGE_FULL;
+                       else
+                               err = MSG_ERR_UNKNOWN;
+       }
+
+       // Send Deliver Report
+       SmsPluginTransport::instance()->sendDeliverReport(err);
+}
+
+
+void SmsPluginSimMsg::setSimEvent(msg_sim_id_t SimId, bool bResult)
+{
+       mx.lock();
+
+       simMsgId = SimId;
+       bTapiResult = bResult;
+
+       cv.signal();
+
+       mx.unlock();
+}
+
+
+bool SmsPluginSimMsg::getSimEvent(msg_sim_id_t *pSimId)
+{
+       int ret = 0;
+
+       mx.lock();
+
+       bTapiResult = false;
+       ret = cv.timedwait(mx.pMutex(), 10);
+
+       mx.unlock();
+
+       if (ret == ETIMEDOUT)
+       {
+               MSG_DEBUG("WARNING: TAPI callback TIME-OUT");
+               return false;
+       }
+
+       *pSimId = simMsgId;
+
+       MSG_DEBUG("Returned SimMsgId is %d.", simMsgId);
+
+       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;
+}
diff --git a/plugin/sms_plugin/SmsPluginStorage.cpp b/plugin/sms_plugin/SmsPluginStorage.cpp
new file mode 100755 (executable)
index 0000000..6b89d7d
--- /dev/null
@@ -0,0 +1,1295 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgGconfWrapper.h"
+#include "MsgNotificationWrapper.h"
+#include "SmsPluginMain.h"
+#include "SmsPluginSimMsg.h"
+#include "SmsPluginStorage.h"
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginStorage - Member Functions
+==================================================================================================*/
+SmsPluginStorage* SmsPluginStorage::pInstance = NULL;
+
+
+SmsPluginStorage::SmsPluginStorage()
+{
+/*** No need to connect DB anymore.
+       if (dbHandle.connect() != MSG_SUCCESS) {
+               MSG_DEBUG("DB Connect Fail");
+       }
+***/
+}
+
+
+SmsPluginStorage::~SmsPluginStorage()
+{
+       if (dbHandle.disconnect() != MSG_SUCCESS) {
+               MSG_DEBUG("DB Disconnect Fail");
+       }
+}
+
+
+SmsPluginStorage* SmsPluginStorage::instance()
+{
+       if (!pInstance) {
+               MSG_DEBUG("pInstance is NULL. Now creating instance.");
+               pInstance = new SmsPluginStorage();
+       }
+
+       return pInstance;
+}
+
+
+msg_error_t SmsPluginStorage::updateSentMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_network_status_t status)
+{
+       MSG_BEGIN();
+
+/***  Comment below line to not save the time value after sent status (it could be used later.)
+       time_t curTime = time(NULL);
+***/
+       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 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;
+}
+
+#ifdef SMS_REPORT_OPERATION
+msg_error_t SmsPluginStorage::updateMsgRef(msg_message_id_t MsgId, unsigned char MsgRef)
+{
+       MSG_BEGIN();
+
+       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::updateStatusReport(unsigned char MsgRef, msg_delivery_report_status_t Status, time_t DeliveryTime)
+{
+       MSG_BEGIN();
+
+       MSG_DEBUG("tmpMsgRef : %d", tmpMsgRef);
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       /** Get Msg Id for Quickpanel Noti */
+       msg_message_id_t msgId = 0;
+
+       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 (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;
+       }
+
+       /** Insert Quickpanel Noti */
+       msg_error_t ret = MSG_SUCCESS;
+
+       ret = MsgInsertSmsNotiToQuickpanel(&dbHandle, msgId, Status);
+
+       if (ret != MSG_SUCCESS) {
+               MSG_DEBUG("MsgInsertSmsNotiToQuickpanel() Failed : [%d]", ret);
+               return ret;
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+#endif
+
+msg_error_t SmsPluginStorage::addSimMessage(MSG_MESSAGE_INFO_S *pSimMsgInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       msg_message_id_t msgId = 0;
+       msg_thread_id_t convId = 0;
+       unsigned int simId = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       dbHandle.beginTrans();
+
+       err = MsgStoAddAddress(&dbHandle, pSimMsgInfo, &convId);
+
+       if (err != MSG_SUCCESS) {
+               dbHandle.endTrans(false);
+               return err;
+       }
+
+       pSimMsgInfo->threadId = convId;
+
+       err = dbHandle.getRowId(MSGFW_MESSAGE_TABLE_NAME, &msgId);
+
+       if (err != MSG_SUCCESS) {
+               dbHandle.endTrans(false);
+               return err;
+       }
+
+       simId = pSimMsgInfo->msgId;
+       pSimMsgInfo->msgId = msgId;
+
+       SMS_CONCAT_SIM_MSG_S concatSimMsg = {0};
+
+       /** Get Data from Concat SIM Msg */
+       if (pSimMsgInfo->msgType.subType == MSG_CONCAT_SIM_SMS && pSimMsgInfo->bTextSms == false) {
+
+               int fileSize = 0;
+
+               char* pFileData = NULL;
+               AutoPtr<char> buf(&pFileData);
+
+               if (MsgOpenAndReadFile(pSimMsgInfo->msgData, &pFileData, &fileSize) == false) {
+                       dbHandle.endTrans(false);
+                       return MSG_ERR_STORAGE_ERROR;
+               }
+
+
+               memcpy(&concatSimMsg, (SMS_CONCAT_SIM_MSG_S*)pFileData, fileSize);
+
+               /** Delete temporary file */
+               MsgDeleteFile(pSimMsgInfo->msgData); /** ipc */
+
+               MSG_DEBUG("SIM ID [%d], MSG DATA [%s]", concatSimMsg.simIdCnt, concatSimMsg.msgData);
+       }
+
+       /**  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, ?, '', '', ?, 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_DEBUG("QUERY : %s", sqlQuery);
+
+       if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               dbHandle.endTrans(false);
+               return MSG_ERR_DB_PREPARE;
+       }
+
+       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);
+
+       if (dbHandle.stepQuery() != MSG_ERR_DB_DONE) {
+               dbHandle.endTrans(false);
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbHandle.finalizeQuery();
+
+       /** Insert to Sim table */
+       if (pSimMsgInfo->msgType.subType == MSG_CONCAT_SIM_SMS && pSimMsgInfo->bTextSms == false) {
+
+               MSG_DEBUG("sim count : %d", concatSimMsg.simIdCnt);
+
+               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_DEBUG("QUERY : %s", sqlQuery);
+
+               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 err;
+}
+
+
+msg_error_t SmsPluginStorage::addMessage(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;
+                       if (addSmsMessage(pMsgInfo) != MSG_SUCCESS) {
+                               MSG_DEBUG("addSmsMessage is failed!");
+                       }
+               }
+               return err;
+       }
+
+       if (pMsgInfo->msgType.subType == MSG_NORMAL_SMS || pMsgInfo->msgType.subType == MSG_REJECT_SMS) {
+
+               MSG_DEBUG("Add 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 {
+                       /** 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);
+               }
+
+       } else if ((pMsgInfo->msgType.subType == MSG_CB_SMS) || (pMsgInfo->msgType.subType == MSG_JAVACB_SMS)) {
+               /** check add message option */
+               bool bSave = false;
+               MsgSettingGetBool(CB_SAVE, &bSave);
+               if(bSave) {
+                       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);
+       } else if ((pMsgInfo->msgType.subType >= MSG_MWI_VOICE_SMS) && (pMsgInfo->msgType.subType <= MSG_MWI_OTHER_SMS)) {
+               if (pMsgInfo->bStore == true) {
+                       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;
+
+                       case MSG_WAP_CO_SMS:
+                       {
+                               err = handleCOWAPMessage(pMsgInfo);
+                       }
+                       break;
+               }
+       }
+
+       if (err == MSG_SUCCESS) {
+               MSG_DEBUG("Success to add message !!");
+       } else {
+               MSG_DEBUG("fail to add 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;
+
+       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;
+       }
+
+       dbHandle.endTrans(true);
+
+       pMsgInfo->msgId = (msg_message_id_t)rowId;
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t SmsPluginStorage::addSmsSendOption(MSG_MESSAGE_INFO_S *pMsg, MSG_SENDINGOPT_INFO_S *pSendOptInfo)
+{
+       MSG_BEGIN();
+
+       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];
+
+               dbHandle.beginTrans();
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "INSERT INTO %s VALUES (%d, %d, %d, %d);",
+                               MSGFW_SMS_SENDOPT_TABLE_NAME, pMsg->msgId, pSendOptInfo->bDeliverReq,
+                               pSendOptInfo->bKeepCopy, pSendOptInfo->option.smsSendOptInfo.bReplyPath);
+
+               MSG_DEBUG("Query = [%s]", sqlQuery);
+
+               if (dbHandle.execQuery(sqlQuery) != MSG_SUCCESS) {
+                       dbHandle.endTrans(false);
+                       err = MSG_ERR_DB_EXEC;
+               } else {
+                       dbHandle.endTrans(true);
+               }
+       }
+
+       MSG_END();
+
+       return err;
+}
+
+
+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 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 = ? 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);
+
+       if (err != MSG_SUCCESS) {
+               dbHandle.endTrans(false);
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       err = MsgStoClearConversationTable(&dbHandle);
+
+       if (err != MSG_SUCCESS) {
+               dbHandle.endTrans(false);
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       dbHandle.endTrans(true);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPluginStorage::deleteSmsMessage(msg_message_id_t msgId)
+{
+       MSG_BEGIN();
+
+       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 \
+                       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;
+
+       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);
+
+               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();
+               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;
+               }
+       }
+
+       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.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);
+               }
+       }
+
+       int smsCnt = 0, mmsCnt = 0;
+
+       smsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_SMS_TYPE);
+       mmsCnt = MsgStoGetUnreadCnt(&dbHandle, MSG_MMS_TYPE);
+
+       MsgSettingHandleNewMsg(smsCnt, mmsCnt);
+       MsgRefreshNoti(false);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPluginStorage::addCbMessage(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();
+
+       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));
+
+       sprintf(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 SmsPluginStorage::addReplaceTypeMsg(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       unsigned int retCnt = 0;
+       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 */
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(*), MSG_ID FROM %s WHERE SUB_TYPE = %d AND CONV_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsgInfo->msgType.subType, convId);
+
+               if (dbHandle.prepareQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_PREPARE;
+
+               if (dbHandle.stepQuery() == MSG_ERR_DB_ROW) {
+                       retCnt = dbHandle.columnInt(0);
+                       pMsgInfo->msgId = dbHandle.columnInt(1);
+               } else {
+                       dbHandle.finalizeQuery();
+                       return MSG_ERR_DB_STEP;
+               }
+
+               dbHandle.finalizeQuery();
+       }
+
+       /** Update New Replace Type Msg */
+       if (retCnt == 0) { /** Insert New Replace Type Msg */
+               MSG_DEBUG("Insert Replace Type Msg");
+               err = addSmsMessage(pMsgInfo);
+       } else {
+               MSG_DEBUG("Update Replace Type Msg");
+               err = updateSmsMessage(pMsgInfo);
+       }
+
+       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);
+
+       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 validation check value is false */
+       /** return and drop message. */
+       if (bProceed == false)
+               return MSG_ERR_INVALID_MESSAGE;
+
+#if 0
+       /**  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';
+       } else {
+               strncpy(pMsgInfo->subject, pushMsg.contents, MAX_SUBJECT_LEN);
+       }
+#endif
+
+       /**  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;
+       }
+
+       /**  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.endTrans(false);
+               return err;
+       }
+
+       /** Update conversation table. */
+       if (MsgStoUpdateConversation(&dbHandle, convId) != MSG_SUCCESS) {
+               dbHandle.endTrans(false);
+               return MSG_ERR_STORAGE_ERROR;
+       }
+
+       dbHandle.endTrans(true);
+
+       pMsgInfo->msgId = (msg_message_id_t)rowId;
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t SmsPluginStorage::handleCOWAPMessage(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;
+
+       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);
+
+               dbHandle.beginTrans();
+
+               err = dbHandle.prepareQuery(sqlQuery);
+
+               if ((dbHandle.stepQuery() == MSG_ERR_DB_ROW) && err == MSG_SUCCESS) {
+
+                       msgid = dbHandle.getColumnToInt(1);
+
+                       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 (updateAllAddress() != 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.getColumnToInt(1);
+
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+                       sprintf(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 (updateAllAddress() != 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 SmsPluginStorage::checkPushMsgValidation(MSG_PUSH_MESSAGE_S *pPushMsg, bool *pbProceed)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       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);
+
+       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 SmsPluginStorage::checkStorageStatus(MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       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::updateAllAddress()
+{
+       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;
+       }
+
+
+       for (int i = 0; i < rowCnt; i++) {
+
+               err = MsgStoUpdateConversation(&dbHandle, index++);
+
+               if (err != MSG_SUCCESS)
+                       break;
+       }
+
+       dbHandle.freeTable();
+
+       return err;
+}
+
+
+msg_error_t SmsPluginStorage::getRegisteredPushEvent(char* pPushHeader, int *count, char *application_id, char *contentType)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       int rowCnt = 0, index = 3;
+
+       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);
+       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 content_type[MAX_WAPPUSH_CONTENT_TYPE_LEN + 1];
+       char app_id[MAX_WAPPUSH_ID_LEN + 1];
+       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(content_type, 0, MAX_WAPPUSH_CONTENT_TYPE_LEN);
+               memset(app_id, 0, MAX_WAPPUSH_ID_LEN);
+
+               dbHandle.getColumnToString(index++, MAX_WAPPUSH_CONTENT_TYPE_LEN + 1, content_type);
+               dbHandle.getColumnToString(index++, MAX_WAPPUSH_ID_LEN + 1, app_id);
+               appcode = dbHandle.getColumnToInt(index++);
+
+               //MSG_DEBUG("content_type: %s, app_id: %s", content_type, app_id);
+               _content_type = strcasestr(pPushHeader, content_type);
+               if(_content_type) {
+                       _app_id = strcasestr(pPushHeader, app_id);
+                       if(appcode)
+                               default_appcode = appcode;
+
+                       if(_app_id) {
+                               PUSH_APPLICATION_INFO_S pInfo = {0, };
+                               pInfo.appcode = appcode;
+                               MSG_DEBUG("appcode: %d, app_id: %s", pInfo.appcode, app_id);
+                               strcpy(application_id, app_id);
+                               strcpy(contentType, content_type);
+                               pushAppInfoList.push_back(pInfo);
+                               (*count)++;
+                               found = true;
+                       }
+               }
+       }
+
+       if(!found)
+       {
+               // perform default action.
+               PUSH_APPLICATION_INFO_S pInfo = {0, };
+               pInfo.appcode = default_appcode;
+               strcpy(application_id, app_id);
+               strcpy(contentType, content_type);
+               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_plugin/SmsPluginTpduCodec.cpp b/plugin/sms_plugin/SmsPluginTpduCodec.cpp
new file mode 100755 (executable)
index 0000000..1e6c76f
--- /dev/null
@@ -0,0 +1,629 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgCppTypes.h"
+#include "MsgException.h"
+#include "MsgGconfWrapper.h"
+
+#include "SmsPluginTpduCodec.h"
+#include "SmsPluginParamCodec.h"
+#include "SmsPluginUDCodec.h"
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginTpduCodec - Member Functions
+==================================================================================================*/
+SmsPluginTpduCodec::SmsPluginTpduCodec()
+{
+
+
+}
+
+
+SmsPluginTpduCodec::~SmsPluginTpduCodec()
+{
+
+
+}
+
+
+int SmsPluginTpduCodec::encodeTpdu(const SMS_TPDU_S *pSmsTpdu, char *pTpdu)
+{
+       int tpduLen = 0;
+
+       switch (pSmsTpdu->tpduType)
+       {
+               case SMS_TPDU_SUBMIT:
+                       tpduLen = encodeSubmit(&(pSmsTpdu->data.submit), pTpdu);
+               break;
+
+               case SMS_TPDU_DELIVER:
+                       tpduLen = encodeDeliver(&(pSmsTpdu->data.deliver), pTpdu);
+               break;
+
+               case SMS_TPDU_DELIVER_REP:
+                       tpduLen = encodeDeliverReport(&(pSmsTpdu->data.deliverRep), pTpdu);
+               break;
+
+               case SMS_TPDU_STATUS_REP:
+                       tpduLen = encodeStatusReport(&(pSmsTpdu->data.statusRep), pTpdu);
+               break;
+       }
+
+       return tpduLen;
+}
+
+
+int SmsPluginTpduCodec::decodeTpdu(const unsigned char *pTpdu, int TpduLen, SMS_TPDU_S *pSmsTpdu)
+{
+       int decodeLen = 0;
+
+       char mti = pTpdu[0] & 0x03;
+
+       switch (mti)
+       {
+               case 0x00:
+                       pSmsTpdu->tpduType = SMS_TPDU_DELIVER;
+                       decodeLen = decodeDeliver(pTpdu, TpduLen, &(pSmsTpdu->data.deliver));
+               break;
+
+               case 0x01:
+                       pSmsTpdu->tpduType = SMS_TPDU_SUBMIT;
+                       decodeLen = decodeSubmit(pTpdu, TpduLen, &(pSmsTpdu->data.submit));
+               break;
+
+               case 0x02:
+                       pSmsTpdu->tpduType = SMS_TPDU_STATUS_REP;
+                       decodeLen = decodeStatusReport(pTpdu, TpduLen, &(pSmsTpdu->data.statusRep));
+               break;
+       }
+
+       return decodeLen;
+}
+
+
+int SmsPluginTpduCodec::encodeSubmit(const SMS_SUBMIT_S *pSubmit, char *pTpdu)
+{
+       int offset = 0, length = 0, encodeSize = 0;
+
+       char* address = NULL;
+       AutoPtr<char> addressBuf(&address);
+
+       char* dcs = NULL;
+       AutoPtr<char> dcsBuf(&dcs);
+
+       char* vpTime = NULL;
+       AutoPtr<char> vpBuf(&vpTime);
+
+       //TP-MTI
+       pTpdu[offset] = 0x01;
+
+       //TP-RD
+       if(pSubmit->bRejectDup == false)
+               pTpdu[offset] |= 0x04;
+
+       //TP-VPF
+       switch (pSubmit->vpf)
+       {
+               case SMS_VPF_NOT_PRESENT:
+                       break;
+               case SMS_VPF_ENHANCED:
+                       pTpdu[offset] |= 0x08;
+                       break;
+               case SMS_VPF_RELATIVE:
+                       pTpdu[offset] |= 0x10;
+                       break;
+               case SMS_VPF_ABSOLUTE:
+                       pTpdu[offset] |= 0x18;
+                       break;
+               default:
+                       break;
+       }
+
+       //TP-SRR
+       if (pSubmit->bStatusReport == true)
+               pTpdu[offset] |= 0x20;
+
+       MSG_DEBUG("TP-SRR pSubmit->bStatusReport : %d.", pSubmit->bStatusReport);
+
+       //TP-UDHI
+       if (pSubmit->bHeaderInd == true)
+               pTpdu[offset] |= 0x40;
+
+       //TP-RP
+       if (pSubmit->bReplyPath == true)
+               pTpdu[offset] |= 0x80;
+
+       offset++;
+
+       //TP-MR
+       pTpdu[offset++] = pSubmit->msgRef;
+
+       MSG_DEBUG("TP-MR pSubmit->msgRef : %d.", pSubmit->msgRef);
+
+       //TP-DA
+       length = SmsPluginParamCodec::encodeAddress(&pSubmit->destAddress, &address);
+       memcpy(&(pTpdu[offset]), address, length);
+       offset += length;
+
+       MSG_DEBUG("TP-DA length : %d.", length);
+
+       //TP-PID
+       pTpdu[offset++] = pSubmit->pid;
+
+       MSG_DEBUG("TP-PID pSubmit->pid : %d.", pSubmit->pid);
+
+       //TP-DCS
+       length = SmsPluginParamCodec::encodeDCS(&pSubmit->dcs, &dcs);
+       memcpy(&(pTpdu[offset]), dcs, length);
+       offset += length;
+
+       MSG_DEBUG("TP-DCS length : %d.", length);
+
+       //TP-VP
+       if (pSubmit->vpf != SMS_VPF_NOT_PRESENT)
+       {
+               length = SmsPluginParamCodec::encodeTime(&pSubmit->validityPeriod, &vpTime);
+
+               if (length > 0)
+               {
+                       memcpy(&(pTpdu[offset]), vpTime, length);
+                       offset += length;
+               }
+       }
+
+       encodeSize = SmsPluginUDCodec::encodeUserData(&(pSubmit->userData), pSubmit->dcs.codingScheme, &(pTpdu[offset]));
+
+MSG_DEBUG("encodeSize : %d", encodeSize);
+
+       offset += encodeSize;
+
+       return offset;
+}
+
+
+int SmsPluginTpduCodec::encodeDeliver(const SMS_DELIVER_S *pDeliver, char *pTpdu)
+{
+       int offset = 0, length = 0, encodeSize = 0;
+
+       char* address = NULL;
+       AutoPtr<char> addressBuf(&address);
+
+       char* dcs = NULL;
+       AutoPtr<char> dcsBuf(&dcs);
+
+       char* scts = NULL;
+       AutoPtr<char> timeBuf(&scts);
+
+       // TP-MTI : 00
+       pTpdu[offset] = 0x00;
+
+       // TP-MMS
+       if (pDeliver->bMoreMsg == false)
+               pTpdu[offset] |= 0x04;
+
+       // TP-SRI
+       if (pDeliver->bStatusReport == true)
+               pTpdu[offset] |= 0x20;
+
+       // TP-UDHI
+       if (pDeliver->bHeaderInd == true)
+               pTpdu[offset] |= 0x40;
+
+       // TP-RP
+       if (pDeliver->bReplyPath == true)
+               pTpdu[offset] |= 0x80;
+
+       offset++;
+
+       // TP-OA
+       length = SmsPluginParamCodec::encodeAddress(&pDeliver->originAddress, &address);
+       memcpy(&(pTpdu[offset]), address, length);
+       offset += length;
+
+       // TP-PID
+       pTpdu[offset++] = pDeliver->pid;
+
+       // TP-DCS
+       length = SmsPluginParamCodec::encodeDCS(&pDeliver->dcs, &dcs);
+       memcpy(&(pTpdu[offset]), dcs, length);
+       offset += length;
+
+       // TP-SCTS
+       length = SmsPluginParamCodec::encodeTime(&pDeliver->timeStamp, &scts);
+       memcpy(&(pTpdu[offset]), scts, length);
+       offset += length;
+
+       // TP-UDL & TP-UD
+       encodeSize = SmsPluginUDCodec::encodeUserData(&(pDeliver->userData), pDeliver->dcs.codingScheme, &(pTpdu[offset]));
+
+       MSG_DEBUG("encodeSize : %d", encodeSize);
+
+       offset += encodeSize;
+
+       return offset;
+}
+
+
+int SmsPluginTpduCodec::encodeDeliverReport(const SMS_DELIVER_REPORT_S *pDeliverRep, char *pTpdu)
+{
+       int offset = 0;
+
+       // TP-MTI : 00
+       pTpdu[offset] = 0x00;
+
+       // TP-UDHI
+       if (pDeliverRep->bHeaderInd == true)
+               pTpdu[offset] |= 0x40;
+
+       offset++;
+
+       // TP-FCS
+       if (pDeliverRep->reportType == SMS_REPORT_NEGATIVE)
+               pTpdu[offset++] = pDeliverRep->failCause;
+
+       // TP-PI
+       pTpdu[offset++] = pDeliverRep->paramInd;
+
+       // TP-PID
+       if (pDeliverRep->paramInd & 0x01)
+               pTpdu[offset++] = pDeliverRep->pid;
+
+       // TP-DCS
+       if (pDeliverRep->paramInd & 0x02)
+       {
+               int length = 0;
+
+               char* dcs = NULL;
+               AutoPtr<char> dcsBuf(&dcs);
+
+               length = SmsPluginParamCodec::encodeDCS(&pDeliverRep->dcs, &dcs);
+               memcpy(&(pTpdu[offset]), dcs, length);
+
+               offset += length;
+       }
+
+       // TP-UDL & TP-UD
+       if (pDeliverRep->paramInd & 0x04)
+       {
+               int encodeSize = 0;
+
+               encodeSize = SmsPluginUDCodec::encodeUserData(&(pDeliverRep->userData), pDeliverRep->dcs.codingScheme, &(pTpdu[offset]));
+
+               MSG_DEBUG("encodeSize : %d", encodeSize);
+
+               offset += encodeSize;
+       }
+
+       pTpdu[offset] = '\0';
+
+       return offset;
+}
+
+
+int SmsPluginTpduCodec::encodeStatusReport(const SMS_STATUS_REPORT_S *pStatusRep, char *pTpdu)
+{
+       int offset = 0, length = 0;
+
+       char* address = NULL;
+       AutoPtr<char> addressBuf(&address);
+
+       char* scts = NULL;
+       AutoPtr<char> sctsBuf(&scts);
+
+       char* dt = NULL;
+       AutoPtr<char> dtBuf(&dt);
+
+       // TP-MTI : 10
+       pTpdu[offset] = 0x02;
+
+       // TP-MMS
+       if (pStatusRep->bMoreMsg == true)
+               pTpdu[offset] |= 0x04;
+
+       // TP-SRQ
+       if (pStatusRep->bStatusReport == true)
+               pTpdu[offset] |= 0x20;
+
+       // TP-UDHI
+       if (pStatusRep->bHeaderInd == true)
+               pTpdu[offset] |= 0x40;
+
+       offset++;
+
+       // TP-MR
+       pTpdu[offset++] = pStatusRep->msgRef;
+
+       // TP-RA
+       length = SmsPluginParamCodec::encodeAddress(&pStatusRep->recipAddress, &address);
+       memcpy(&(pTpdu[offset]), address, length);
+       offset += length;
+
+       // TP-SCTS
+       length = SmsPluginParamCodec::encodeTime(&pStatusRep->timeStamp, &scts);
+       memcpy(&(pTpdu[offset]), scts, length);
+       offset += length;
+
+       // TP-DT
+       length = SmsPluginParamCodec::encodeTime(&pStatusRep->dischargeTime, &dt);
+       memcpy(&(pTpdu[offset]), dt, length);
+       offset += length;
+
+       // TP-Status
+       pTpdu[offset++] = pStatusRep->status;
+
+       // TP-PI
+       pTpdu[offset++] = pStatusRep->paramInd;
+
+       // TP-PID
+       if (pStatusRep->paramInd & 0x01)
+               pTpdu[offset++] = pStatusRep->pid;
+
+       // TP-DCS
+       if (pStatusRep->paramInd & 0x02)
+       {
+               int length = 0;
+
+               char* dcs = NULL;
+               AutoPtr<char> dcsBuf(&dcs);
+
+               length = SmsPluginParamCodec::encodeDCS(&pStatusRep->dcs, &dcs);
+               memcpy(&(pTpdu[offset]), dcs, length);
+
+               offset += length;
+       }
+
+       // TP-UDL & TP-UD
+       if (pStatusRep->paramInd & 0x04)
+       {
+               int encodeSize = 0;
+
+               encodeSize = SmsPluginUDCodec::encodeUserData(&(pStatusRep->userData), pStatusRep->dcs.codingScheme, &(pTpdu[offset]));
+
+               MSG_DEBUG("encodeSize : %d", encodeSize);
+
+               offset += encodeSize;
+       }
+
+       pTpdu[offset] = '\0';
+
+       return offset;
+}
+
+
+int SmsPluginTpduCodec::decodeSubmit(const unsigned char *pTpdu, int TpduLen, SMS_SUBMIT_S *pSubmit)
+{
+       int offset = 0, udLen = 0;
+
+       // TP-RD
+       if (pTpdu[offset] & 0x04)
+               pSubmit->bRejectDup = false;
+       else
+               pSubmit->bRejectDup = true;
+
+       // TP-VPF
+       pSubmit->vpf = (SMS_VPF_T)(pTpdu[offset] & 0x18);
+
+       // TP-SRR
+       if (pTpdu[offset] & 0x20)
+               pSubmit->bStatusReport = true;
+       else
+               pSubmit->bStatusReport = false;
+
+       // TP-UDHI
+       if (pTpdu[offset] & 0x40)
+               pSubmit->bHeaderInd = true;
+       else
+               pSubmit->bHeaderInd = false;
+
+       // TP-RP
+       if (pTpdu[offset] & 0x80)
+               pSubmit->bReplyPath = true;
+       else
+               pSubmit->bReplyPath = false;
+
+       offset++;
+
+       // TP-MR
+       pSubmit->msgRef = pTpdu[offset++];
+
+       // TP-DA
+       offset += SmsPluginParamCodec::decodeAddress(pTpdu+offset, &(pSubmit->destAddress));
+
+       // TP-PID
+       pSubmit->pid = pTpdu[offset++];
+
+       // TP-DCS
+       offset += SmsPluginParamCodec::decodeDCS(pTpdu+offset, &(pSubmit->dcs));
+
+       // TP-VP
+       if (pSubmit->vpf != SMS_VPF_NOT_PRESENT)
+       {
+               // Decode VP
+       }
+
+       // TP-UDL & TP-UD
+       udLen = SmsPluginUDCodec::decodeUserData(pTpdu+offset, TpduLen, pSubmit->bHeaderInd, pSubmit->dcs.codingScheme, &(pSubmit->userData));
+
+       return udLen;
+}
+
+
+int SmsPluginTpduCodec::decodeDeliver(const unsigned char *pTpdu, int TpduLen, SMS_DELIVER_S *pDeliver)
+{
+       int offset = 0, udLen = 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_DEBUG("[%s]", tpduTmp);
+
+
+       // TP-MMS
+       if (pTpdu[offset] & 0x04)
+               pDeliver->bMoreMsg = false;
+       else
+               pDeliver->bMoreMsg = true;
+
+       // TP-SRI
+       if (pTpdu[offset] & 0x20)
+               pDeliver->bStatusReport = true;
+       else
+               pDeliver->bStatusReport = false;
+
+       // TP-UDHI
+       if (pTpdu[offset] & 0x40)
+               pDeliver->bHeaderInd = true;
+       else
+               pDeliver->bHeaderInd = false;
+
+       // TP-RP
+       if (pTpdu[offset] & 0x80)
+               pDeliver->bReplyPath = true;
+       else
+               pDeliver->bReplyPath = false;
+
+       offset++;
+
+       // TP-OA
+       offset += SmsPluginParamCodec::decodeAddress(&pTpdu[offset], &(pDeliver->originAddress));
+
+       // TP-PID
+       pDeliver->pid = pTpdu[offset++];
+
+       // TP-DCS
+       offset += SmsPluginParamCodec::decodeDCS(&pTpdu[offset], &(pDeliver->dcs));
+
+       // TP-SCTS
+       offset += SmsPluginParamCodec::decodeTime(&pTpdu[offset], &(pDeliver->timeStamp));
+
+       // TP-UD
+       udLen = SmsPluginUDCodec::decodeUserData(&pTpdu[offset], TpduLen, pDeliver->bHeaderInd, pDeliver->dcs.codingScheme, &(pDeliver->userData), &(pDeliver->udData));
+
+       return udLen;
+}
+
+
+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);
+
+       char* scts = NULL;
+       AutoPtr<char> sctsBuf(&scts);
+
+       char* dt = NULL;
+       AutoPtr<char> dtBuf(&dt);
+
+       // TP-MMS
+       if (pTpdu[offset] & 0x04)
+               pStatusRep->bMoreMsg = false;
+       else
+               pStatusRep->bMoreMsg = true;
+
+       // TP-SRQ
+       if (pTpdu[offset] & 0x20)
+               pStatusRep->bStatusReport = true;
+       else
+               pStatusRep->bStatusReport = false;
+
+       // TP-UDHI
+       if (pTpdu[offset] & 0x40)
+               pStatusRep->bHeaderInd = true;
+       else
+               pStatusRep->bHeaderInd = false;
+
+       offset++;
+
+       // TP-MR
+       pStatusRep->msgRef = pTpdu[offset++];
+
+       // TP-RA
+       offset += SmsPluginParamCodec::decodeAddress(&pTpdu[offset], &(pStatusRep->recipAddress));
+
+       // TP-SCTS
+       // Decode timestamp
+       offset += SmsPluginParamCodec::decodeTime(&pTpdu[offset], &(pStatusRep->timeStamp));
+
+       // TP-DT
+       // Decode timestamp
+       offset += SmsPluginParamCodec::decodeTime(&pTpdu[offset], &(pStatusRep->dischargeTime));
+
+       // TP-Status
+       pStatusRep->status = pTpdu[offset++];
+
+       // TP-PI
+       pStatusRep->paramInd = pTpdu[offset++];
+
+       // No Parameters
+       if (pStatusRep->paramInd == 0)
+       {
+               pStatusRep->pid = SMS_PID_NORMAL;
+
+               pStatusRep->dcs.bCompressed = false;
+               pStatusRep->dcs.bMWI = false;
+               pStatusRep->dcs.bIndActive = false;
+
+               pStatusRep->dcs.msgClass = MSG_CLASS_NONE;
+               pStatusRep->dcs.codingScheme = SMS_CHARSET_7BIT;
+               pStatusRep->dcs.codingGroup = SMS_GROUP_GENERAL;
+               pStatusRep->dcs.indType = SMS_OTHER_INDICATOR;
+
+               pStatusRep->userData.headerCnt = 0;
+               pStatusRep->userData.length = 0;
+               memset(pStatusRep->userData.data, 0x00, MAX_USER_DATA_LEN+1);
+       }
+
+       // TP-PID
+       if (pStatusRep->paramInd & 0x01)
+               pStatusRep->pid = pTpdu[offset++];
+
+       // TP-DCS
+       if (pStatusRep->paramInd & 0x02)
+       {
+               offset += SmsPluginParamCodec::decodeDCS(&pTpdu[offset], &(pStatusRep->dcs));
+       }
+
+       // TP-UDL & TP-UD
+       if (pStatusRep->paramInd & 0x04)
+       {
+               // Decode User Data
+               udLen = SmsPluginUDCodec::decodeUserData(&pTpdu[offset], TpduLen, pStatusRep->bHeaderInd, pStatusRep->dcs.codingScheme, &(pStatusRep->userData));
+       }
+
+       return udLen;
+}
+
diff --git a/plugin/sms_plugin/SmsPluginTransport.cpp b/plugin/sms_plugin/SmsPluginTransport.cpp
new file mode 100755 (executable)
index 0000000..c31f16c
--- /dev/null
@@ -0,0 +1,1004 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <math.h>
+
+#include "MsgDebug.h"
+#include "MsgCppTypes.h"
+#include "MsgException.h"
+#include "MsgGconfWrapper.h"
+#include "MsgUtilFile.h"
+#include "MsgNotificationWrapper.h"
+#include "SmsPluginParamCodec.h"
+#include "SmsPluginTpduCodec.h"
+#include "SmsPluginEventHandler.h"
+#include "SmsPluginStorage.h"
+#include "SmsPluginCallback.h"
+#include "SmsPluginTransport.h"
+
+extern "C"
+{
+       #include <ITapiNetText.h>
+}
+
+
+extern struct tapi_handle *pTapiHandle;
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginTransport - Member Functions
+==================================================================================================*/
+SmsPluginTransport* SmsPluginTransport::pInstance = NULL;
+
+
+SmsPluginTransport::SmsPluginTransport()
+{
+       msgRef          = 0x00;
+       msgRef8bit      = 0x00;
+       msgRef16bit     = 0x0000;
+}
+
+
+SmsPluginTransport::~SmsPluginTransport()
+{
+
+}
+
+
+SmsPluginTransport* SmsPluginTransport::instance()
+{
+       if (!pInstance)
+               pInstance = new SmsPluginTransport();
+
+       return pInstance;
+}
+
+
+void SmsPluginTransport::submitRequest(SMS_REQUEST_INFO_S *pReqInfo)
+{
+       MSG_BEGIN();
+
+       SMS_TPDU_S tpdu = {0,};
+
+       tpdu.tpduType = SMS_TPDU_SUBMIT;
+
+       // Set SMS Send Options - Setting
+       setSmsSendOptions(&(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;
+       }
+
+       // 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;
+
+               MSG_DEBUG("DCS is changed by application : [%d]", tpdu.data.submit.dcs.codingScheme);
+       }
+
+#ifdef MSG_SMS_REPORT
+       // Update Msg Ref into Report Table
+       if (tpdu.data.submit.bStatusReport == true)
+       {
+               MSG_DEBUG("Update Msg Ref [%d] in Report Table", tpdu.data.submit.msgRef);
+
+               SmsPluginStorage::instance()->updateMsgRef(pReqInfo->msgInfo.msgId, tpdu.data.submit.msgRef);
+       }
+#endif
+
+       // Set SMSC Options
+       SMS_ADDRESS_S smsc;
+       setSmscOptions(&smsc);
+       int i = 0;
+       int j = 0;
+
+       MSG_DEBUG("pReqInfo->msgInfo.nAddressCnt [%d]", pReqInfo->msgInfo.nAddressCnt);
+
+       for (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);
+
+               // Encode SMSC Address
+               unsigned char smscAddr[MAX_SMSC_LEN];
+               memset(smscAddr, 0x00, sizeof(smscAddr));
+
+               int smscLen = SmsPluginParamCodec::encodeSMSC(&smsc, smscAddr);
+
+               if (smscLen <= 0) {
+                       MSG_DEBUG("smscLen <= 0");
+                       return;
+               }
+
+               char smscAddrTmp[(smscLen*2)+1];
+               memset(smscAddrTmp, 0x00, sizeof(smscAddrTmp));
+               for (j = 0; j < smscLen; j++) {
+                       snprintf(smscAddrTmp+(j*2), sizeof(smscAddrTmp)-(j*2), "%02X", smscAddr[j]);
+               }
+               MSG_DEBUG("pSCAInfo [%s]", smscAddrTmp);
+
+               int bufLen = 0;
+
+               char buf[MAX_TPDU_DATA_LEN];
+
+               int addLen = strlen(submitData.destAddress.address);
+
+               tpdu.data.submit.destAddress.ton = submitData.destAddress.ton;
+               tpdu.data.submit.destAddress.npi = submitData.destAddress.npi;
+
+               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';
+               }
+
+MSG_DEBUG("ton [%d]", tpdu.data.submit.destAddress.ton);
+MSG_DEBUG("npi [%d]", tpdu.data.submit.destAddress.npi);
+MSG_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) {
+                               tpdu.data.submit.bHeaderInd = true;
+                       } 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);
+
+                       // 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;
+
+                       // Set SMSC data
+                       memset(pkgInfo.Sca, 0x00, sizeof(pkgInfo.Sca));
+                       memcpy((void*)pkgInfo.Sca, smscAddr, smscLen);
+                       pkgInfo.Sca[smscLen] = '\0';
+
+
+                       char pkgInfoTmp[(pkgInfo.MsgLength*2)+1];
+                       memset(pkgInfoTmp, 0x00, sizeof(pkgInfoTmp));
+                       for (j = 0; j < pkgInfo.MsgLength; j++) {
+                               snprintf(pkgInfoTmp+(j*2), sizeof(pkgInfoTmp)-(j*2), "%02X", pkgInfo.szData[j]);
+                       }
+                       MSG_DEBUG("Submit Request TPDU.");
+                       MSG_DEBUG("[%s]", pkgInfoTmp);
+
+                       SMS_SENT_INFO_S sentInfo;
+                       memset(&sentInfo, 0x00, sizeof(SMS_SENT_INFO_S));
+
+                       bool bMoreMsg = FALSE;
+
+                       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 = MSG_NETWORK_SENDING;
+
+                       // Send SMS
+                       int tapiRet = TAPI_API_SUCCESS;
+
+                       tapiRet = tel_send_sms(pTapiHandle, &pkgInfo, bMoreMsg, 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
+                       char *msisdn = NULL;
+                       msisdn = MsgSettingGetString(MSG_SIM_MSISDN);
+
+                       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);
+
+                       msg_network_status_t retStatus = getNetStatus();
+
+       #ifdef MSG_SMS_REPORT
+                       if (err == MSG_SUCCESS && tmpInfo.msgInfo.msgPort.valid == false)
+                       {
+                               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_SMS_VLD_INFO("%d, SMS Send End, %s->%s, %s",  pReqInfo->msgInfo.msgId, \
+                                                                                                                                       (msisdn == NULL)?"ME":msisdn, \
+                                                                                                                                       pReqInfo->msgInfo.addressList[0].addressVal, \
+                                                                                                                                       (retStatus == MSG_NETWORK_SEND_SUCCESS)?"Success":"Fail");
+
+
+                       if (retStatus == MSG_NETWORK_SEND_SUCCESS)
+                       {
+                               if (bMoreMsg == false) {
+                                       MsgInsertTicker("SMS is sent", SMS_MESSAGE_SENT);
+                               }
+                               MSG_DEBUG("########  Msg Sent was Successful !!! return : [%d] #######", retStatus);
+                       }
+                       else
+                       {
+                               MsgInsertTicker("Sending SMS is failed", NULL);
+                               MsgInsertTicker("Sending SMS is failed", SMS_MESSAGE_SENDING_FAIL);
+
+                               SmsPluginEventHandler::instance()->handleSentStatus(MSG_NETWORK_SEND_FAIL);
+
+                               THROW(MsgException::SMS_PLG_ERROR, "########  Msg Sent was Failed !!! return : [%d] #######", retStatus);
+                       }
+
+                       if (tpdu.data.submit.userData.headerCnt > 0) tpdu.data.submit.userData.headerCnt--;
+               }
+       }
+
+       MSG_END();
+}
+
+
+void SmsPluginTransport::sendDeliverReport(msg_error_t err)
+{
+       MSG_BEGIN();
+
+       SMS_TPDU_S tpdu;
+
+       tpdu.tpduType = SMS_TPDU_DELIVER_REP;
+
+       TelSmsResponse_t response;
+
+       int tapiRet = TAPI_API_SUCCESS;
+
+       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, 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_MSG_CAPA_EXCEEDED;
+               response = TAPI_NETTEXT_SIM_FULL;
+
+               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_MESSAGE_COUNT_FULL)
+       {
+               tpdu.data.deliverRep.reportType = SMS_REPORT_NEGATIVE;
+               tpdu.data.deliverRep.failCause = SMS_FC_MSG_CAPA_EXCEEDED;
+               response = TAPI_NETTEXT_ME_FULL;
+
+               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
+       {
+               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;
+
+       }
+
+       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;
+
+       // Set SMSC Address
+       SMS_ADDRESS_S smsc;
+
+       // Set SMSC Options
+       setSmscOptions(&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(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::sendClass0DeliverReport(msg_error_t err)
+{
+       MSG_BEGIN();
+
+       SMS_TPDU_S tpdu;
+
+       tpdu.tpduType = SMS_TPDU_DELIVER_REP;
+
+       TelSmsResponse_t response;
+
+       int tapiRet = TAPI_API_SUCCESS;
+
+       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, 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(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_MESSAGE_COUNT_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, 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;
+
+       }
+
+       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);
+
+       // 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;
+
+       // Set SMSC Address
+       SMS_ADDRESS_S smsc;
+
+       // Set SMSC Options
+       setSmscOptions(&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(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::setSmsSendOptions(SMS_SUBMIT_S *pSubmit)
+{
+       // Set SMS Send Options
+       pSubmit->bRejectDup = false;
+       pSubmit->bHeaderInd = false;
+
+       MsgSettingGetBool(SMS_SEND_DELIVERY_REPORT, &pSubmit->bStatusReport);
+       MsgSettingGetBool(SMS_SEND_REPLY_PATH, &pSubmit->bReplyPath);
+
+       pSubmit->msgRef = msgRef++;
+
+       pSubmit->dcs.bCompressed = false;
+       pSubmit->dcs.msgClass = SMS_MSG_CLASS_NONE;
+       pSubmit->dcs.codingGroup = SMS_GROUP_GENERAL;
+
+       pSubmit->dcs.codingScheme = (SMS_CODING_SCHEME_T)MsgSettingGetInt(SMS_SEND_DCS);
+
+       MSG_DEBUG("DCS : %d", pSubmit->dcs.codingScheme);
+
+       int selectIdx = MsgSettingGetInt(SMSC_SELECTED);
+
+       char keyName[128];
+
+       memset(keyName, 0x00, sizeof(keyName));
+       sprintf(keyName, "%s/%d", SMSC_PID, selectIdx);
+       MSG_SMS_PID_T pid = (MSG_SMS_PID_T)MsgSettingGetInt(keyName);
+
+       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);
+
+       MSG_DEBUG("valPeriod : %d", valPeriod);
+
+       if (valPeriod == 0)
+       {
+               pSubmit->vpf = SMS_VPF_NOT_PRESENT;
+       }
+       else
+       {
+               pSubmit->vpf = SMS_VPF_RELATIVE;
+               pSubmit->validityPeriod.format = SMS_TIME_RELATIVE;
+               pSubmit->validityPeriod.time.relative.time = valPeriod;
+       }
+}
+
+
+void SmsPluginTransport::setSmscOptions(SMS_ADDRESS_S *pSmsc)
+{
+       // Set SMSC Options
+       int selectIdx = MsgSettingGetInt(SMSC_SELECTED);
+
+       char keyName[128];
+
+       memset(keyName, 0x00, sizeof(keyName));
+       sprintf(keyName, "%s/%d", SMSC_ADDRESS, selectIdx);
+
+       char* tmpValue = NULL;
+
+       tmpValue = MsgSettingGetString(keyName);
+
+       if (tmpValue != NULL)
+       {
+               memset(pSmsc->address, 0x00, sizeof(pSmsc->address));
+               strncpy(pSmsc->address, tmpValue, MAX_ADDRESS_LEN);
+
+               MSG_DEBUG("address : %s", pSmsc->address);
+       }
+       else
+       {
+               strncpy(pSmsc->address, "+8210911111", MAX_ADDRESS_LEN);
+       }
+
+       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);
+
+       memset(keyName, 0x00, sizeof(keyName));
+       sprintf(keyName, "%s/%d", SMSC_NPI, selectIdx);
+       pSmsc->npi = (SMS_NPI_T)MsgSettingGetInt(keyName);
+
+       MSG_DEBUG("npi : %d", pSmsc->npi);
+
+       if (tmpValue != NULL)
+       {
+               free(tmpValue);
+               tmpValue = NULL;
+       }
+}
+
+
+void SmsPluginTransport::msgInfoToSubmitData(const MSG_MESSAGE_INFO_S *pMsgInfo, SMS_SUBMIT_DATA_S *pData, SMS_CODING_SCHEME_T *pCharType, int addrIndex)
+{
+       // Destination Address
+       pData->destAddress.ton = SMS_TON_UNKNOWN;
+       pData->destAddress.npi = SMS_NPI_ISDN;
+
+       memset(pData->destAddress.address, 0x00, MAX_ADDRESS_LEN+1);
+       memcpy(pData->destAddress.address, pMsgInfo->addressList[addrIndex].addressVal, MAX_ADDRESS_LEN);
+
+       MSG_DEBUG("ton [%d]", pData->destAddress.ton);
+       MSG_DEBUG("npi [%d]", pData->destAddress.npi);
+       MSG_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));
+
+       msg_encode_type_t encodeType = MSG_ENCODE_GSM7BIT;
+
+       MSG_LANGUAGE_ID_T langId = MSG_LANG_ID_RESERVED;
+
+       bool bAbnormal = false;
+
+       // User Data
+       if (pMsgInfo->bTextSms == true)
+       {
+               if (*pCharType == SMS_CHARSET_7BIT)
+               {
+                       decodeLen = textCvt.convertUTF8ToGSM7bit(decodeData, bufSize, (unsigned char*)pMsgInfo->msgText, (int)pMsgInfo->dataSize, &langId, &bAbnormal);
+               }
+               else if (*pCharType == SMS_CHARSET_8BIT)
+               {
+                       memcpy(decodeData, pMsgInfo->msgText, pMsgInfo->dataSize);
+                       decodeLen = pMsgInfo->dataSize;
+               }
+               else if (*pCharType == SMS_CHARSET_UCS2)
+               {
+                       decodeLen = textCvt.convertUTF8ToUCS2(decodeData, bufSize, (unsigned char*)pMsgInfo->msgText, (int)pMsgInfo->dataSize);
+               }
+               else if (*pCharType == SMS_CHARSET_AUTO)
+               {
+                       decodeLen = textCvt.convertUTF8ToAuto(decodeData, bufSize, (unsigned char*)pMsgInfo->msgText, (int)pMsgInfo->dataSize, &encodeType);
+                       *pCharType = encodeType;
+               }
+       }
+       else
+       {
+               int fileSize = 0;
+
+               char* pFileData = NULL;
+               AutoPtr<char> FileBuf(&pFileData);
+
+               // Read Message Data from File
+               if (MsgOpenAndReadFile(pMsgInfo->msgData, &pFileData, &fileSize) == false)
+                       THROW(MsgException::FILE_ERROR, "MsgOpenAndReadFile error");
+
+               MSG_DEBUG("file size : [%d] file data : [%s]", fileSize, pFileData);
+
+               if (*pCharType == SMS_CHARSET_7BIT)
+               {
+                       decodeLen = textCvt.convertUTF8ToGSM7bit(decodeData, bufSize, (unsigned char*)pFileData, fileSize, &langId, &bAbnormal);
+               }
+               else if (*pCharType == SMS_CHARSET_8BIT)
+               {
+                       memcpy(decodeData, pFileData, fileSize);
+                       decodeLen = fileSize;
+               }
+               else if (*pCharType == SMS_CHARSET_UCS2)
+               {
+                       decodeLen = textCvt.convertUTF8ToUCS2(decodeData, bufSize, (unsigned char*)pFileData, fileSize);
+               }
+               else if (*pCharType == SMS_CHARSET_AUTO)
+               {
+                       decodeLen = textCvt.convertUTF8ToAuto(decodeData, bufSize, (unsigned char*)pFileData, fileSize, &encodeType);
+                       *pCharType = encodeType;
+               }
+
+               // Delete File
+               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);
+
+       int addrLen = 0;
+
+       char* encodedAddr = NULL;
+       AutoPtr<char> addressBuf(&encodedAddr);
+
+       if (strlen(pMsgInfo->replyAddress) > 0)
+       {
+               SMS_ADDRESS_S replyAddr = {};
+
+               replyAddr.ton = SMS_TON_NATIONAL;
+               replyAddr.npi = SMS_NPI_ISDN;
+
+               memset(replyAddr.address, 0x00, MAX_ADDRESS_LEN+1);
+               memcpy(replyAddr.address, pMsgInfo->replyAddress, MAX_ADDRESS_LEN);
+
+               addrLen = SmsPluginParamCodec::encodeAddress(&replyAddr, &encodedAddr);
+
+               MSG_DEBUG("reply addr length : [%d]", addrLen);
+       }
+
+       int segSize = 0, index = 0;
+
+       segSize = getSegmentSize(*pCharType, decodeLen, pMsgInfo->msgPort.valid, langId, addrLen);
+
+       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);
+
+       int headerCnt = 0;
+
+       for (unsigned int i = 0; i < pData->segCount; i++)
+       {
+               headerCnt = 0;
+
+               if ((i + 1) == pData->segCount)
+                       pData->userData[i].length = decodeLen - (i*segSize);
+               else
+                       pData->userData[i].length = segSize;
+
+               memset(pData->userData[i].data, 0x00, MAX_USER_DATA_LEN+1);
+               memcpy(pData->userData[i].data, &(decodeData[index]), pData->userData[i].length);
+               pData->userData[i].data[pData->userData[i].length] = 0;
+
+MSG_DEBUG("user data len [%d]", pData->userData[i].length);
+MSG_DEBUG("user data [%s]", pData->userData[i].data);
+
+               index += segSize;
+
+               // Set User Data Header for Concatenated Message
+               if (pData->segCount > 1)
+               {
+                       pData->userData[i].header[headerCnt].udhType = SMS_UDH_CONCAT_8BIT;
+                       pData->userData[i].header[headerCnt].udh.concat8bit.msgRef = msgRef8bit;
+                       pData->userData[i].header[headerCnt].udh.concat8bit.totalSeg = pData->segCount;
+                       pData->userData[i].header[headerCnt].udh.concat8bit.seqNum = i + 1;
+
+                       headerCnt++;
+               }
+
+               // Set User Data Header Port Information
+               if (pMsgInfo->msgPort.valid == true)
+               {
+                       pData->userData[i].header[headerCnt].udhType = SMS_UDH_APP_PORT_16BIT;
+                       pData->userData[i].header[headerCnt].udh.appPort16bit.destPort = pMsgInfo->msgPort.dstPort;
+                       pData->userData[i].header[headerCnt].udh.appPort16bit.originPort = pMsgInfo->msgPort.srcPort;
+
+                       headerCnt++;
+               }
+
+               // Set User Data Header for Alternate Reply Address
+               if (strlen(pMsgInfo->replyAddress) > 0)
+               {
+                       pData->userData[i].header[headerCnt].udhType = SMS_UDH_ALTERNATE_REPLY_ADDRESS;
+
+                       pData->userData[i].header[headerCnt].udh.alternateAddress.ton = SMS_TON_NATIONAL;
+                       pData->userData[i].header[headerCnt].udh.alternateAddress.npi = SMS_NPI_ISDN;
+
+                       memset(pData->userData[i].header[headerCnt].udh.alternateAddress.address, 0x00, MAX_ADDRESS_LEN+1);
+                       memcpy(pData->userData[i].header[headerCnt].udh.alternateAddress.address, pMsgInfo->replyAddress, MAX_ADDRESS_LEN);
+
+                       headerCnt++;
+               }
+
+               // Set User Data Header for National Language Single Shift
+               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;
+
+                       headerCnt++;
+               }
+
+               pData->userData[i].headerCnt = headerCnt;
+       }
+
+       msgRef8bit++;
+}
+
+
+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;
+
+       if (CodingScheme == SMS_CHARSET_7BIT)
+       {
+               MSG_DEBUG("SMS_CHARSET_7BIT");
+               maxSize = MAX_GSM_7BIT_DATA_LEN;
+       }
+       else if (CodingScheme == SMS_CHARSET_8BIT || CodingScheme == SMS_CHARSET_UCS2)
+       {
+               MSG_DEBUG("SMS_CHARSET_8BIT or SMS_CHARSET_UCS2 [%d]", CodingScheme);
+               maxSize = MAX_UCS2_DATA_LEN;
+       }
+
+       if (bPortNum == true)
+       {
+               MSG_DEBUG("Port Number Exists");
+               headerSize += port;
+       }
+
+       if (LangId != MSG_LANG_ID_RESERVED)
+       {
+               MSG_DEBUG("National Language Exists");
+               headerSize += lang;
+       }
+
+       if (ReplyAddrLen > 0)
+       {
+               MSG_DEBUG("Reply Address Exists");
+               headerSize += reply;
+               headerSize += ReplyAddrLen;
+       }
+
+       if (CodingScheme == SMS_CHARSET_7BIT)
+       {
+               if (((DataLen+headerSize)/maxSize) >= 1)
+                       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)
+                       segSize = 140 - (headerLen + concat + headerSize);
+               else
+                       segSize = DataLen;
+       }
+
+       return segSize;
+}
+
+
+void SmsPluginTransport::setConcatHeader(SMS_UDH_S *pSrcHeader, SMS_UDH_S *pDstHeader)
+{
+       pDstHeader->udhType = pSrcHeader->udhType;
+
+       switch (pDstHeader->udhType)
+       {
+               case SMS_UDH_CONCAT_8BIT :
+               {
+                       pDstHeader->udh.concat8bit.msgRef = pSrcHeader->udh.concat8bit.msgRef;
+                       pDstHeader->udh.concat8bit.totalSeg = pSrcHeader->udh.concat8bit.totalSeg;
+                       pDstHeader->udh.concat8bit.seqNum = pSrcHeader->udh.concat8bit.seqNum;
+               }
+               break;
+
+               case SMS_UDH_CONCAT_16BIT :
+               {
+                       pDstHeader->udh.concat16bit.msgRef = pSrcHeader->udh.concat16bit.msgRef;
+                       pDstHeader->udh.concat16bit.totalSeg = pSrcHeader->udh.concat16bit.totalSeg;
+                       pDstHeader->udh.concat16bit.seqNum = pSrcHeader->udh.concat16bit.seqNum;
+               }
+               break;
+       }
+}
+
+
+void SmsPluginTransport::setNetStatus(msg_network_status_t netStatus)
+{
+       mx.lock();
+       curStatus = netStatus;
+       cv.signal();
+       mx.unlock();
+}
+
+
+msg_network_status_t SmsPluginTransport::getNetStatus()
+{
+       mx.lock();
+
+       int ret = 0;
+
+       if (curStatus == MSG_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;
+       }
+
+       return curStatus;
+}
+
+
+unsigned char SmsPluginTransport::getMsgRef()
+{
+       return msgRef++;
+}
+
+
+SMS_PID_T SmsPluginTransport::convertPid(MSG_SMS_PID_T pid)
+{
+       SMS_PID_T retPid;
+
+       switch (pid)
+       {
+               case MSG_PID_TEXT :
+                       retPid = SMS_PID_NORMAL;
+               break;
+               case MSG_PID_VOICE :
+                       retPid = SMS_PID_VOICE;
+               break;
+               case MSG_PID_FAX :
+                       retPid = SMS_PID_TELEX;
+               break;
+               case MSG_PID_X400 :
+                       retPid = SMS_PID_x400;
+               break;
+               case MSG_PID_ERMES :
+                       retPid = SMS_PID_ERMES;
+               break;
+               case MSG_PID_EMAIL :
+                       retPid = SMS_PID_EMAIL;
+               break;
+               default :
+                       retPid = SMS_PID_NORMAL;
+               break;
+       }
+
+       return retPid;
+}
diff --git a/plugin/sms_plugin/SmsPluginUAManager.cpp b/plugin/sms_plugin/SmsPluginUAManager.cpp
new file mode 100755 (executable)
index 0000000..80c6e27
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgException.h"
+#include "SmsPluginEventHandler.h"
+#include "SmsPluginWapPushHandler.h"
+#include "SmsPluginConcatHandler.h"
+#include "SmsPluginTransport.h"
+#include "SmsPluginUAManager.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)
+       {
+               if (smsTranQ.empty())
+                       cv.wait(mx.pMutex());
+
+               SMS_REQUEST_INFO_S request;
+               smsTranQ.front(&request);
+
+               try
+               {
+                       SmsPluginTransport::instance()->submitRequest(&request);
+               }
+               catch (MsgException& e)
+               {
+                       MSG_FATAL("%s", e.what());
+
+                       smsTranQ.pop_front();
+                       continue;
+               }
+               catch (exception& e)
+               {
+                       MSG_FATAL("%s", e.what());
+
+                       smsTranQ.pop_front();
+                       continue;
+               }
+
+               smsTranQ.pop_front();
+       }
+}
+
+
+void SmsPluginUAManager::addReqEntity(SMS_REQUEST_INFO_S *request)
+{
+       SMS_REQUEST_INFO_S reqTmp = {0,};
+
+       memcpy(&reqTmp, request, sizeof(SMS_REQUEST_INFO_S));
+       smsTranQ.push_back(reqTmp);
+       cv.signal();
+}
+
diff --git a/plugin/sms_plugin/SmsPluginUDCodec.cpp b/plugin/sms_plugin/SmsPluginUDCodec.cpp
new file mode 100755 (executable)
index 0000000..c9e1760
--- /dev/null
@@ -0,0 +1,861 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "SmsPluginParamCodec.h"
+#include "SmsPluginUDCodec.h"
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF SmsPluginUDCodec - Member Functions
+==================================================================================================*/
+SmsPluginUDCodec::SmsPluginUDCodec()
+{
+
+}
+
+
+SmsPluginUDCodec::~SmsPluginUDCodec()
+{
+
+}
+
+
+int SmsPluginUDCodec::encodeUserData(const SMS_USERDATA_S *pUserData, SMS_CODING_SCHEME_T CodingScheme, char *pEncodeData)
+{
+       int encodeSize = 0;
+
+       switch (CodingScheme)
+       {
+               case SMS_CHARSET_7BIT:
+                       encodeSize = encodeGSMData(pUserData, pEncodeData);
+                       break;
+               case SMS_CHARSET_8BIT:
+                       encodeSize = encode8bitData(pUserData, pEncodeData);
+                       break;
+               case SMS_CHARSET_UCS2:
+                       encodeSize = encodeUCS2Data(pUserData, pEncodeData);
+                       break;
+       }
+
+       return encodeSize;
+}
+
+
+int SmsPluginUDCodec::decodeUserData(const unsigned char *pTpdu, const int tpduLen, bool bHeaderInd, SMS_CODING_SCHEME_T CodingScheme, SMS_USERDATA_S *pUserData)
+{
+       int decodeSize = 0;
+
+       memset(pUserData, 0x00, sizeof(SMS_USERDATA_S));
+
+       switch (CodingScheme)
+       {
+               case SMS_CHARSET_7BIT:
+                       decodeSize = decodeGSMData(pTpdu, tpduLen, bHeaderInd, pUserData, NULL);
+                       break;
+               case SMS_CHARSET_8BIT:
+                       decodeSize = decode8bitData(pTpdu, bHeaderInd, pUserData, NULL);
+                       break;
+               case SMS_CHARSET_UCS2:
+                       decodeSize = decodeUCS2Data(pTpdu, tpduLen, bHeaderInd, pUserData, NULL);
+                       break;
+       }
+
+       return decodeSize;
+}
+
+
+int SmsPluginUDCodec::decodeUserData(const unsigned char *pTpdu, const int tpduLen, bool bHeaderInd, SMS_CODING_SCHEME_T CodingScheme, SMS_USERDATA_S *pUserData, SMS_TPUD_S *pTPUD)
+{
+       int decodeSize = 0;
+
+       memset(pUserData, 0x00, sizeof(SMS_USERDATA_S));
+
+       switch (CodingScheme)
+       {
+               case SMS_CHARSET_7BIT:
+                       decodeSize = decodeGSMData(pTpdu, tpduLen, bHeaderInd, pUserData, pTPUD);
+                       break;
+               case SMS_CHARSET_8BIT:
+                       decodeSize = decode8bitData(pTpdu, bHeaderInd, pUserData, pTPUD);
+                       break;
+               case SMS_CHARSET_UCS2:
+                       decodeSize = decodeUCS2Data(pTpdu, tpduLen, bHeaderInd, pUserData, pTPUD);
+                       break;
+               case SMS_CHARSET_EUCKR:
+                       decodeSize = decodeUCS2Data(pTpdu, tpduLen, bHeaderInd, pUserData, pTPUD);
+                       break;
+       }
+
+       return decodeSize;
+}
+
+
+int SmsPluginUDCodec::encodeGSMData(const SMS_USERDATA_S *pUserData, char *pEncodeData)
+{
+       int headerLen = 0, offset = 0, fillBits = 0, packSize = 0, encodeLen = 0;
+       unsigned char udhl = 0x00;
+
+       if (pUserData->headerCnt > 0)
+               offset = 2;
+       else
+               offset = 1;
+
+MSG_DEBUG("pUserData->headerCnt [%d]", pUserData->headerCnt);
+
+       // Encode User Data Header
+       for (int i = 0; i < pUserData->headerCnt; i++)
+       {
+               headerLen = encodeHeader(pUserData->header[i], &(pEncodeData[offset]));
+
+MSG_DEBUG("headerLen [%d]", headerLen);
+
+               udhl += headerLen;
+               offset += headerLen;
+       }
+
+MSG_DEBUG("udhl [%d]", udhl);
+
+       if (udhl > 0)
+               fillBits = ((udhl+1)*8)%7; // + UDHL
+
+       if (fillBits > 0)
+               fillBits = 7 - fillBits;
+
+MSG_DEBUG("fillBits [%d]", fillBits);
+MSG_DEBUG("dataLen [%d]", pUserData->length);
+
+       // Set UDL, UDHL
+       if (udhl > 0)
+       {
+               pEncodeData[0] = (((udhl+1)*8) + fillBits + (pUserData->length*7)) / 7;
+               pEncodeData[1] =  udhl;
+       }
+       else
+       {
+               pEncodeData[0] = (char)pUserData->length;
+       }
+
+       packSize = pack7bitChar((unsigned char*)pUserData->data, pUserData->length, fillBits, &(pEncodeData[offset]));
+
+       encodeLen = offset + packSize;
+
+MSG_DEBUG("packSize [%d]", packSize);
+MSG_DEBUG("encodeLen [%d]", encodeLen);
+
+       return encodeLen;
+}
+
+
+int SmsPluginUDCodec::encode8bitData(const SMS_USERDATA_S *pUserData, char *pEncodeData)
+{
+       int headerLen = 0, offset = 2, fillBits = 0, encodeLen = 0;
+       unsigned char udhl = 0x00;
+
+       if (pUserData->headerCnt > 0)
+               offset = 2;
+       else
+               offset = 1;
+
+       // Encode User Data Header
+       for (int i = 0; i < pUserData->headerCnt; i++)
+       {
+               headerLen = encodeHeader(pUserData->header[i], &(pEncodeData[offset]));
+
+               udhl += headerLen;
+               offset += headerLen;
+       }
+
+MSG_DEBUG("fillBits [%d]", fillBits);
+MSG_DEBUG("dataLen [%d]", pUserData->length);
+
+       // Set UDL, UDHL
+       if (udhl > 0)
+       {
+               pEncodeData[0] = (udhl+1) + fillBits + pUserData->length;
+               pEncodeData[1] =  udhl;
+       }
+       else
+       {
+               pEncodeData[0] = (char)pUserData->length;
+       }
+
+       memcpy(&(pEncodeData[offset]), pUserData->data, pUserData->length);
+
+       encodeLen = offset + pUserData->length;
+
+       return encodeLen;
+}
+
+
+int SmsPluginUDCodec::encodeUCS2Data(const SMS_USERDATA_S *pUserData, char *pEncodeData)
+{
+       int headerLen = 0, offset = 2, fillBits = 0, encodeLen = 0;
+       unsigned char udhl = 0x00;
+
+       if (pUserData->headerCnt > 0)
+               offset = 2;
+       else
+               offset = 1;
+
+       // Encode User Data Header
+       for (int i = 0; i < pUserData->headerCnt; i++)
+       {
+               headerLen = encodeHeader(pUserData->header[i], &(pEncodeData[offset]));
+
+               udhl += headerLen;
+               offset += headerLen;
+       }
+
+MSG_DEBUG("fillBits [%d]", fillBits);
+MSG_DEBUG("dataLen [%d]", pUserData->length);
+
+       // Set UDL, UDHL
+       if (udhl > 0)
+       {
+               pEncodeData[0] = (udhl+1) + fillBits + pUserData->length;
+               pEncodeData[1] =  udhl;
+       }
+       else
+       {
+               pEncodeData[0] = (char)pUserData->length;
+       }
+
+       memcpy(&(pEncodeData[offset]), pUserData->data, pUserData->length);
+
+       encodeLen = offset + pUserData->length;
+
+       return encodeLen;
+}
+
+
+int SmsPluginUDCodec::decodeGSMData(const unsigned char *pTpdu, const int tpduLen, bool bHeaderInd, SMS_USERDATA_S *pUserData, SMS_TPUD_S *pTPUD)
+{
+       int offset = 0, udl = 0, udhl = 0, headerLen = 0, fillBits = 0, octetUdl = 0;
+
+       // UDL
+       udl = pTpdu[offset++];
+       octetUdl = (udl*7)/8;
+
+MSG_DEBUG("udl = %d, tpdulen = %d, octetUdl = %d.", udl, tpduLen, octetUdl);
+MSG_DEBUG("bHeaderInd = %d", bHeaderInd);
+
+       if (udl > MAX_GSM_7BIT_DATA_LEN || octetUdl > tpduLen)
+       {
+               pUserData->length = 0;
+               pUserData->headerCnt = 0;
+               return 0;
+       }
+
+       // Setting for Wap Push
+       if (pTPUD != NULL)
+       {
+               pTPUD->udl = udl;
+
+               memcpy(pTPUD->ud, &(pTpdu[offset]), udl);
+               pTPUD->ud[udl] = '\0';
+       }
+
+       // Decode User Data Header
+       if (bHeaderInd == true)
+       {
+               // UDHL
+               udhl = pTpdu[offset++];
+
+               MSG_DEBUG("udhl = %d", udhl);
+
+               pUserData->headerCnt = 0;
+
+               for (int i = 0; offset < udhl; i++)
+               {
+                       headerLen = decodeHeader(&(pTpdu[offset]), &(pUserData->header[i]));
+
+                       if (headerLen <= 0) {
+                               MSG_DEBUG("Error to decode User Data Header. headerLen [%d]", headerLen);
+
+                               pUserData->length = 0;
+                               memset(pUserData->data, 0x00, sizeof(pUserData->data));
+
+                               return 0;
+                       }
+
+                       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++;
+               }
+       }
+       else
+               pUserData->headerCnt = 0;
+
+       MSG_DEBUG("headerCnt = %d", pUserData->headerCnt);
+
+       if (udhl > 0)
+       {
+               fillBits = ((udl*7) - ((udhl+1)*8)) % 7;
+               udl = ((udl*7) - ((udhl+1)*8)) / 7;
+       }
+
+MSG_DEBUG("fillBits = %d", fillBits);
+MSG_DEBUG("udhl = %d", udhl);
+MSG_DEBUG("udl = %d", udl);
+
+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;
+}
+
+
+int SmsPluginUDCodec::decode8bitData(const unsigned char *pTpdu, bool bHeaderInd, SMS_USERDATA_S *pUserData, SMS_TPUD_S *pTPUD)
+{
+       int offset = 0, udl = 0, udhl = 0, headerLen = 0;
+
+       // UDL
+       udl = pTpdu[offset++];
+
+       if (udl > MAX_UCS2_DATA_LEN)
+       {
+               pUserData->length = 0;
+               return 0;
+       }
+
+       // Setting for Wap Push
+       if (pTPUD != NULL)
+       {
+               pTPUD->udl = udl;
+
+               memcpy(pTPUD->ud, &(pTpdu[offset]), udl);
+               pTPUD->ud[udl] = '\0';
+       }
+
+MSG_DEBUG("udl = %d", udl);
+MSG_DEBUG("bHeaderInd = %d", bHeaderInd);
+
+       // Decode User Data Header
+       if (bHeaderInd == true)
+       {
+               // UDHL
+               udhl = pTpdu[offset++];
+
+               MSG_DEBUG("udhl = %d", udhl);
+
+               pUserData->headerCnt = 0;
+
+               for (int i = 0; offset < udhl; i++)
+               {
+                       headerLen = decodeHeader(&(pTpdu[offset]), &(pUserData->header[i]));
+
+                       if (headerLen <= 0) {
+                               MSG_DEBUG("Error to decode User Data Header. headerLen [%d]", headerLen);
+
+                               pUserData->length = 0;
+                               memset(pUserData->data, 0x00, sizeof(pUserData->data));
+
+                               return 0;
+                       }
+
+                       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++;
+               }
+       }
+       else
+               pUserData->headerCnt = 0;
+
+MSG_DEBUG("headerCnt = %d", pUserData->headerCnt);
+
+       if (udhl > 0)
+               pUserData->length = (udl) - (udhl+1);
+       else
+               pUserData->length = udl;
+
+MSG_DEBUG("pUserData->length = %d", pUserData->length);
+MSG_DEBUG("offset = %d", offset);
+
+       memcpy(pUserData->data, &(pTpdu[offset]), pUserData->length);
+
+       return pUserData->length;
+}
+
+
+int SmsPluginUDCodec::decodeUCS2Data(const unsigned char *pTpdu, const int tpduLen, bool bHeaderInd, SMS_USERDATA_S *pUserData, SMS_TPUD_S *pTPUD)
+{
+       int offset = 0, udl = 0, udhl = 0, headerLen = 0;
+
+       // UDL
+       udl = pTpdu[offset++];
+
+MSG_DEBUG("udl = %d, tpdulen = %d.", udl, tpduLen);
+MSG_DEBUG("bHeaderInd = %d", bHeaderInd);
+
+       if (udl > MAX_UCS2_DATA_LEN || udl > tpduLen)
+       {
+               pUserData->length = 0;
+               pUserData->headerCnt = 0;
+               return 0;
+       }
+
+       // Setting for Wap Push
+       if (pTPUD != NULL)
+       {
+               pTPUD->udl = udl;
+
+               memcpy(pTPUD->ud, &(pTpdu[offset]), udl);
+               pTPUD->ud[udl] = '\0';
+       }
+
+       // Decode User Data Header
+       if (bHeaderInd == true)
+       {
+               // UDHL
+               udhl = pTpdu[offset++];
+
+               MSG_DEBUG("udhl = %d", udhl);
+
+               pUserData->headerCnt = 0;
+
+               for (int i = 0; offset < udhl; i++)
+               {
+                       headerLen = decodeHeader(&(pTpdu[offset]), &(pUserData->header[i]));
+
+                       if (headerLen <= 0) {
+                               MSG_DEBUG("Error to decode User Data Header. headerLen [%d]", headerLen);
+
+                               pUserData->length = 0;
+                               memset(pUserData->data, 0x00, sizeof(pUserData->data));
+
+                               return 0;
+                       }
+
+                       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++;
+               }
+       }
+       else
+               pUserData->headerCnt = 0;
+
+       if (udhl > 0)
+               pUserData->length = (udl) - (udhl+1);
+       else
+               pUserData->length = udl;
+
+MSG_DEBUG("pUserData->length = %d", pUserData->length);
+MSG_DEBUG("offset = %d", offset);
+
+       memcpy(pUserData->data, &(pTpdu[offset]), pUserData->length);
+       pUserData->data[pUserData->length] = 0;
+
+       return pUserData->length;
+}
+
+
+int SmsPluginUDCodec::encodeHeader(const SMS_UDH_S header, char *pEncodeHeader)
+{
+       int offset = 0, addrLen = 0;
+
+       char* encodedAddr = NULL;
+       AutoPtr<char> addressBuf(&encodedAddr);
+
+       switch (header.udhType)
+       {
+               case SMS_UDH_CONCAT_8BIT :
+                       // IEI
+                       pEncodeHeader[offset++] = SMS_UDH_CONCAT_8BIT;
+
+                       // IEDL
+                       pEncodeHeader[offset++] = 0x03;
+
+                       // Reference Number
+                       pEncodeHeader[offset++] = header.udh.concat8bit.msgRef;
+
+                       // Number of Segments
+                       pEncodeHeader[offset++] = header.udh.concat8bit.totalSeg;
+
+                       // Sequence Number
+                       pEncodeHeader[offset++] = header.udh.concat8bit.seqNum;
+               break;
+
+               case SMS_UDH_CONCAT_16BIT :
+                       // IEI
+                       pEncodeHeader[offset++] = SMS_UDH_CONCAT_16BIT;
+
+                       // IEDL
+                       pEncodeHeader[offset++] = 0x04;
+
+                       // Reference Number
+                       pEncodeHeader[offset++] = (char)(header.udh.concat16bit.msgRef >> 8);
+                       pEncodeHeader[offset++] = header.udh.concat16bit.msgRef & 0x00FF;
+
+                       // Number of Segments
+                       pEncodeHeader[offset++] = header.udh.concat16bit.totalSeg;
+
+                       // Sequence Number
+                       pEncodeHeader[offset++] = header.udh.concat16bit.seqNum;
+               break;
+
+               case SMS_UDH_APP_PORT_8BIT :
+                       // IEI
+                       pEncodeHeader[offset++] = SMS_UDH_APP_PORT_8BIT;
+
+                       // IEDL
+                       pEncodeHeader[offset++] = 0x02;
+
+                       // Dest Port
+                       pEncodeHeader[offset++] = header.udh.appPort8bit.destPort;
+
+                       // Origin Port
+                       pEncodeHeader[offset++] = header.udh.appPort8bit.originPort;
+               break;
+
+               case SMS_UDH_APP_PORT_16BIT :
+                       // IEI
+                       pEncodeHeader[offset++] = SMS_UDH_APP_PORT_16BIT;
+
+                       // IEDL
+                       pEncodeHeader[offset++] = 0x04;
+
+                       // Dest Port
+                       pEncodeHeader[offset++] = (char)(header.udh.appPort16bit.destPort >> 8);
+                       pEncodeHeader[offset++] = header.udh.appPort16bit.destPort & 0x00FF;
+
+                       // Origin Port
+                       pEncodeHeader[offset++] = (char)(header.udh.appPort16bit.originPort >> 8);
+                       pEncodeHeader[offset++] = header.udh.appPort16bit.originPort & 0x00FF;
+               break;
+
+               case SMS_UDH_ALTERNATE_REPLY_ADDRESS :
+                       // IEI
+                       pEncodeHeader[offset++] = SMS_UDH_ALTERNATE_REPLY_ADDRESS;
+
+                       addrLen = SmsPluginParamCodec::encodeAddress(&(header.udh.alternateAddress), &encodedAddr);
+
+                       // IEDL
+                       pEncodeHeader[offset++] = addrLen;
+
+                       // Alternate Reply Address
+                       memcpy(&pEncodeHeader[offset], encodedAddr, addrLen);
+
+                       offset += addrLen;
+               break;
+
+               case SMS_UDH_SINGLE_SHIFT :
+                       // IEI
+                       pEncodeHeader[offset++] = SMS_UDH_SINGLE_SHIFT;
+
+                       // IEDL
+                       pEncodeHeader[offset++] = 0x01;
+
+                       // National Language Identifier
+                       pEncodeHeader[offset++] = header.udh.singleShift.langId;
+               break;
+
+               case SMS_UDH_LOCKING_SHIFT :
+                       // IEI
+                       pEncodeHeader[offset++] = SMS_UDH_LOCKING_SHIFT;
+
+                       // IEDL
+                       pEncodeHeader[offset++] = 0x01;
+
+                       // National Language Identifier
+                       pEncodeHeader[offset++] = header.udh.lockingShift.langId;
+               break;
+
+               case SMS_UDH_NONE :
+               default :
+               break;
+       }
+
+       return offset;
+}
+
+
+int SmsPluginUDCodec::decodeHeader(const unsigned char *pTpdu, SMS_UDH_S *pHeader)
+{
+       int offset = 0;
+       unsigned char IEDL = 0;
+
+       pHeader->udhType = pTpdu[offset++];
+
+       switch (pHeader->udhType)
+       {
+               case SMS_UDH_CONCAT_8BIT :
+               {
+                       IEDL = pTpdu[offset++];
+
+                       if (IEDL == 0) return 0;
+
+                       pHeader->udh.concat8bit.msgRef = pTpdu[offset++];
+                       pHeader->udh.concat8bit.totalSeg = pTpdu[offset++];
+                       pHeader->udh.concat8bit.seqNum = pTpdu[offset++];
+
+MSG_DEBUG("concat8bit.msgRef [%02x]", pHeader->udh.concat8bit.msgRef);
+MSG_DEBUG("concat8bit.totalSeg [%02x]", pHeader->udh.concat8bit.totalSeg);
+MSG_DEBUG("concat8bit.seqNum [%02x]", pHeader->udh.concat8bit.seqNum);
+               }
+               break;
+
+               case SMS_UDH_CONCAT_16BIT :
+               {
+                       IEDL = pTpdu[offset++];
+
+                       if (IEDL == 0) return 0;
+
+                       pHeader->udh.concat16bit.msgRef = pTpdu[offset++];
+                       pHeader->udh.concat16bit.msgRef = (unsigned short)((pHeader->udh.concat16bit.msgRef << 8) | pTpdu[offset++]);
+                       pHeader->udh.concat16bit.totalSeg = pTpdu[offset++];
+                       pHeader->udh.concat16bit.seqNum = pTpdu[offset++];
+
+MSG_DEBUG("concat16bit.msgRef [%04x]", pHeader->udh.concat16bit.msgRef);
+MSG_DEBUG("concat16bit.totalSeg [%02x]", pHeader->udh.concat16bit.totalSeg);
+MSG_DEBUG("concat16bit.seqNum [%02x]", pHeader->udh.concat16bit.seqNum);
+               }
+               break;
+
+               case SMS_UDH_APP_PORT_8BIT :
+               {
+                       IEDL = pTpdu[offset++];
+
+                       if (IEDL == 0) return 0;
+
+                       pHeader->udh.appPort8bit.destPort = pTpdu[offset++];
+                       pHeader->udh.appPort8bit.originPort = pTpdu[offset++];
+
+MSG_DEBUG("appPort8bit.destPort [%02x]", pHeader->udh.appPort8bit.destPort);
+MSG_DEBUG("appPort8bit.originPort [%02x]", pHeader->udh.appPort8bit.originPort);
+               }
+               break;
+
+               case SMS_UDH_APP_PORT_16BIT :
+               {
+                       IEDL = pTpdu[offset++];
+
+                       if (IEDL == 0) return 0;
+
+                       pHeader->udh.appPort16bit.destPort = pTpdu[offset++];
+                       pHeader->udh.appPort16bit.destPort = (unsigned short)((pHeader->udh.appPort16bit.destPort << 8) | pTpdu[offset++]);
+                       pHeader->udh.appPort16bit.originPort = pTpdu[offset++];
+                       pHeader->udh.appPort16bit.originPort = (unsigned short)((pHeader->udh.appPort16bit.originPort << 8) | pTpdu[offset++]);
+
+MSG_DEBUG("appPort16bit.destPort [%04x]", pHeader->udh.appPort16bit.destPort);
+MSG_DEBUG("appPort16bit.originPort [%04x]", pHeader->udh.appPort16bit.originPort);
+               }
+               break;
+
+               case SMS_UDH_SPECIAL_SMS :
+               {
+                       IEDL = pTpdu[offset++];
+
+                       if (IEDL != 2) return 0;
+MSG_DEBUG("Decoding special sms udh.");
+
+                       pHeader->udh.specialInd.bStore = (bool) (pTpdu[offset] & 0x80);
+                       pHeader->udh.specialInd.msgInd = (unsigned short) (pTpdu[offset++] & 0x7F);
+                       pHeader->udh.specialInd.waitMsgNum = (unsigned short) pTpdu[offset];
+               }
+               break;
+
+               case SMS_UDH_ALTERNATE_REPLY_ADDRESS :
+               {
+                       IEDL = pTpdu[offset++];
+
+                       if (IEDL == 0) return 0;
+
+                       offset += SmsPluginParamCodec::decodeAddress(&pTpdu[offset], &(pHeader->udh.alternateAddress));
+
+MSG_DEBUG("alternate reply address [%s]", pHeader->udh.alternateAddress.address);
+               }
+               break;
+
+               case SMS_UDH_SINGLE_SHIFT :
+               {
+                       IEDL = pTpdu[offset++];
+
+                       if (IEDL == 0) return 0;
+
+                       pHeader->udh.singleShift.langId = pTpdu[offset++];
+
+MSG_DEBUG("singleShift.langId [%02x]", pHeader->udh.singleShift.langId);
+               }
+               break;
+
+               case SMS_UDH_LOCKING_SHIFT :
+               {
+                       IEDL = pTpdu[offset++];
+
+                       if (IEDL == 0) return 0;
+
+                       pHeader->udh.lockingShift.langId = pTpdu[offset++];
+
+MSG_DEBUG("lockingShift.langId [%02x]", pHeader->udh.lockingShift.langId);
+               }
+               break;
+
+               default :
+               {
+                       MSG_DEBUG("Not Supported Header Type [%02x]", pHeader->udhType);
+
+                       IEDL = pTpdu[offset++];
+
+                       MSG_DEBUG("IEDL [%d]", IEDL);
+                       return (offset + IEDL);
+               }
+               break;
+       }
+
+       return offset;
+}
+
+
+int SmsPluginUDCodec::pack7bitChar(const unsigned char *pUserData, int dataLen, int fillBits, char *pPackData)
+{
+       int srcIdx = 0, dstIdx = 0, shift = fillBits;
+
+//MSG_DEBUG("dataLen = %d", dataLen);
+
+       if (shift > 0)
+               dstIdx = 1;
+
+       while (srcIdx < dataLen)
+       {
+               if (shift == 0)
+               {
+//                     if (srcIdx > 0) srcIdx++;
+
+//MSG_DEBUG("pUserData [%02x]", pUserData[srcIdx]);
+//MSG_DEBUG("shift = %d", shift);
+
+                       pPackData[dstIdx] = pUserData[srcIdx];
+
+//MSG_DEBUG("pPackData [%02x]", pPackData[dstIdx]);
+                       if (srcIdx >= dataLen) break;
+
+                       shift = 7;
+                       srcIdx++;
+                       dstIdx++;
+               }
+
+               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;
+}
+
+
+int SmsPluginUDCodec::unpack7bitChar(const unsigned char *pTpdu, unsigned char dataLen, int fillBits, char *pUnpackData)
+{
+       int srcIdx = 0, dstIdx = 0, shift = fillBits;
+
+MSG_DEBUG("dataLen = %d", dataLen);
+
+       if (shift > 0)
+               srcIdx = 1;
+
+       for (; dstIdx < dataLen; dstIdx++)
+       {
+               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++;
+
+                       if (dstIdx >= dataLen) break;
+               }
+
+               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++;
+               }
+       }
+
+       return dstIdx;
+}
+
diff --git a/plugin/sms_plugin/SmsPluginWapPushHandler.cpp b/plugin/sms_plugin/SmsPluginWapPushHandler.cpp
new file mode 100755 (executable)
index 0000000..6f9a5ca
--- /dev/null
@@ -0,0 +1,3375 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "SmsPluginStorage.h"
+#include "SmsPluginTransport.h"
+#include "SmsPluginEventHandler.h"
+#include "SmsPluginWapPushHandler.h"
+
+
+#include <drm_client.h>
+#include <dbus/dbus-glib.h>
+
+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},
+       {(char*)"application/vnd.wap.sic", (char*)"X-Wap-Application-Id: x-wap-application:wml.ua\r\n", SMS_WAP_APPLICATION_PUSH_SIC},
+       {(char*)"text/vnd.wap.sl", (char*)"X-Wap-Application-Id: x-wap-application:wml.ua\r\n", SMS_WAP_APPLICATION_PUSH_SL},
+       {(char*)"application/vnd.wap.slc", (char*)"X-Wap-Application-Id: x-wap-application:wml.ua\r\n", SMS_WAP_APPLICATION_PUSH_SLC},
+       {(char*)"text/vnd.wap.co", (char*)"X-Wap-Application-Id: x-wap-application:wml.ua\r\n", SMS_WAP_APPLICATION_PUSH_CO},
+       {(char*)"application/vnd.wap.coc", (char*)"X-Wap-Application-Id: x-wap-application:wml.ua\r\n", SMS_WAP_APPLICATION_PUSH_COC},
+
+       {(char*)"application/vnd.wap.mms-message", (char*)"X-Wap-Application-Id: x-wap-application:mms.ua\r\n", SMS_WAP_APPLICATION_MMS_UA},
+
+       {(char*)"application/vnd.wap.sia", (char*)"X-Wap-Application-Id: x-wap-application:push.sia\r\n", SMS_WAP_APPLICATION_PUSH_SIA},
+
+       {(char*)"application/vnd.syncml.dm+wbxml", (char*)"X-Wap-Application-Id: x-wap-application:push.syncml.dm\r\n", SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP},
+       {(char*)"application/vnd.syncml.dm+xml", (char*)"X-Wap-Application-Id: x-wap-application:push.syncml.dm\r\n", SMS_WAP_APPLICATION_SYNCML_DM_BOOTSTRAP_XML},
+       {(char*)"application/vnd.syncml.notification", (char*)"X-Wap-Application-Id: x-wap-application:push.syncml.dm\r\n", SMS_WAP_APPLICATION_SYNCML_DM_NOTIFICATION},
+       {(char*)"application/vnd.syncml.ds.notification", (char*)"X-Wap-Application-Id: x-wap-application:push.syncml.ds\r\n", SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION},
+       {(char*)"application/vnd.syncml+wbxml", (char*)"X-Wap-Application-Id:x-wap-application:push.syncml", SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION_WBXML},
+
+       {(char*)"application/vnd.wap.locc+wbxml", (char*)"X-Wap-Application-Id: x-wap-application:loc.ua\r\n", SMS_WAP_APPLICATION_LOC_UA_WBXML},
+       {(char*)"application/vnd.wap.loc+xml", (char*)"X-Wap-Application-Id: x-wap-application:loc.ua\r\n", SMS_WAP_APPLICATION_LOC_UA_XML},
+
+       {(char*)"application/vnd.oma.dd+xml", (char*)"X-Wap-Application-Id: x-wap-application:drm.ua\r\n", SMS_WAP_APPLICATION_DRM_UA_XML},
+       {(char*)"application/vnd.oma.drm.message", (char*)"X-Wap-Application-Id: x-wap-application:drm.ua\r\n", SMS_WAP_APPLICATION_DRM_UA_MESSAGE},
+       {(char*)"application/vnd.oma.drm.content", (char*)"X-Wap-Application-Id: x-wap-application:drm.ua\r\n", SMS_WAP_APPLICATION_DRM_UA_CONETENT},
+       {(char*)"application/vnd.oma.drm.rights+xml", (char*)"X-Wap-Application-Id: x-wap-application:drm.ua\r\n", SMS_WAP_APPLICATION_DRM_UA_RIGHTS_XML},
+       {(char*)"application/vnd.oma.drm.rights+wbxml", (char*)"X-Wap-Application-Id: x-wap-application:drm.ua\r\n", SMS_WAP_APPLICATION_DRM_UA_RIGHTS_WBXML},
+       {(char*)"application/vnd.oma.drm.ro+xml", (char*)"X-Wap-Application-Id: x-wap-application:drm.ua\r\n", SMS_WAP_APPLICATION_DRM_V2_RO_XML},
+       {(char*)"application/vnd.oma.drm.roap-pdu+xml", (char*)"X-Wap-Application-Id: x-wap-application:drm.ua\r\n", SMS_WAP_APPLICATION_DRM_V2_ROAP_PDU_XML},
+       {(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];
+
+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-docomo:xmd.mail.ua", 0x905C },
+};
+
+
+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(SMS_USERDATA_S *pUserData)
+{
+       MSG_BEGIN();
+
+       if (pUserData == NULL) {
+               MSG_DEBUG("pUserData is NULL");
+               return false;
+       }
+
+       int PortCount = sizeof(wapPushPortList)/sizeof(wapPushPortList[0]);
+
+       MSG_DEBUG("Port Count [%d]", PortCount);
+
+       for (int i = 0; i < pUserData->headerCnt; i++) {
+               if (pUserData->header[i].udhType == SMS_UDH_APP_PORT_8BIT) {
+                       /** Have to check something??? */
+               } else if (pUserData->header[i].udhType == SMS_UDH_APP_PORT_16BIT) {
+
+                       for (int j = 0; j < PortCount; j++) {
+                               if (pUserData->header[i].udh.appPort16bit.destPort == wapPushPortList[j]) {
+                                       MSG_DEBUG("Wap Push Msg : [%04x]", wapPushPortList[j]);
+                                       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_DELIVER_S *pDeliver)
+{
+       tmpAddress.ton = pDeliver->originAddress.ton;
+       tmpAddress.npi = pDeliver->originAddress.npi;
+
+       strncpy(tmpAddress.address, pDeliver->originAddress.address, MAX_ADDRESS_LEN);
+
+       MSG_DEBUG("Address [%s]", tmpAddress.address);
+
+       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;
+       AutoPtr<char> pushHeaderBuf(&pPushHeader);
+       unsigned long pushHeaderLen = 0;
+
+       char* pPushBody = NULL;
+       AutoPtr<char> PushBodyBuf(&pPushBody);
+       unsigned long pushBodyLen = 0;
+
+       unsigned long iPDU = 1;
+
+       char* pWspHeader = NULL;
+       AutoPtr<char> WspHeaderBuf(&pWspHeader);
+       unsigned long   wspHeaderLen = 0;
+
+       char* pWspBody = NULL;
+       AutoPtr<char> WspBodyBuf(&pWspBody);
+       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;
+       DBusGConnection *connection = NULL;
+       DBusGProxy *dbus_proxy;
+
+       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 = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
+                               if (error != NULL) {
+                                       MSG_DEBUG("Connecting to system bus failed: %s\n", error->message);
+                                       g_error_free(error);
+                                       MSG_END();
+                               }
+                               dbus_proxy = dbus_g_proxy_new_for_name(connection, "com.samsung.omadmagent",
+                                                                      "/com/samsung/omadmagent", "com.samsung.omadmagent");
+                               MSG_DEBUG("dbus_proxy %x", dbus_proxy);
+                               dbus_g_proxy_call(dbus_proxy, "Hello_Agent", &error, G_TYPE_INVALID, G_TYPE_INVALID);
+                               g_object_unref(dbus_proxy);
+                               dbus_g_connection_unref(connection);
+                               MSG_END();
+                       }
+                       break;
+               case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION:
+               case SMS_WAP_APPLICATION_SYNCML_DS_NOTIFICATION_WBXML:
+                       {
+                               connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
+                               if (error != NULL) {
+                                       MSG_DEBUG("Connecting to system bus failed: %s\n", error->message);
+                                       g_error_free(error);
+                                       MSG_END();
+                               }
+                               dbus_proxy = dbus_g_proxy_new_for_name(connection, "com.samsung.omadsagent",
+                                                                                "/com/samsung/omadsagent", "com.samsung.omadsagent");
+                               MSG_DEBUG("dbus_proxy %x", dbus_proxy);
+                               dbus_g_proxy_call(dbus_proxy, "Hello_Agent", &error, G_TYPE_INVALID, G_TYPE_INVALID);
+                               g_object_unref(dbus_proxy);
+                               dbus_g_connection_unref(connection);
+                               MSG_END();
+                       }
+                       break;
+               default:
+                       break;
+       }
+       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, 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;
+               }
+
+               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;
+#if 0
+               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;
+#endif
+
+               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));
+
+       createMsgInfo(&msgInfo);
+
+       /** Convert Type values */
+       msgInfo.msgType.mainType = MSG_MMS_TYPE;
+       msgInfo.msgType.subType = MSG_NOTIFICATIONIND_MMS;
+       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()->addMessage(&msgInfo);
+
+       if (err == MSG_SUCCESS) {
+               /**  Callback */
+               err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+               }
+       } else {
+               MSG_DEBUG("addMessage() 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_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;
+
+       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()->addMessage(&msgInfo);
+
+       if (err == MSG_SUCCESS) {
+               /** Callback */
+               err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+
+               if (err != MSG_SUCCESS){
+                       MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+               }
+       } else {
+               MSG_DEBUG("addMessage() 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_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);
+                       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_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;
+
+       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);
+
+       /** Callback to MSG FW */
+       err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+
+       if (err != MSG_SUCCESS)
+               MSG_DEBUG("callbackMsgIncoming is failed, err=[%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_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_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;
+
+       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()->addMessage(&msgInfo);
+
+       if (err == MSG_SUCCESS) {
+               /** Callback */
+               err = SmsPluginEventHandler::instance()->callbackMsgIncoming(&msgInfo);
+
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("callbackMsgIncoming() Error !! [%d]", err);
+               }
+       } else {
+               MSG_DEBUG("addMessage() Error !! [%d]", err);
+       }
+
+       xmlFree(xmlDoc);
+
+       return;
+}
+
+
+void SmsPluginWapPushHandler::handleDrmVer1(char* pPushBody, int PushBodyLen)
+{
+       int drmRt = DRM_RETURN_SUCCESS;
+       char* cid = NULL;
+       AutoPtr<char> buf(&cid);
+
+       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.");
+       }
+
+       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[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)
+{
+       if (pPushBody == NULL) {
+               MSG_DEBUG("pPushBody is NULL");
+               return;
+       }
+
+
+       if (isText) {
+               *pXmlDoc = xmlParseMemory(pPushBody, strlen(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, strlen((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 (strlen(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 = strcmp( "signal-none", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SI_ACTION_SIGNAL_NONE;
+
+       /** compare  with signal-low. */
+       comp = strcmp( "signal-low", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SI_ACTION_SIGNAL_LOW;
+
+       /**  compare  with signal-medium. */
+       comp = strcmp( "signal-medium", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SI_ACTION_SIGNAL_MEDIUM;
+
+       /**  compare  with signal-high. */
+       comp = strcmp( "signal-high", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SI_ACTION_SIGNAL_HIGH;
+
+       /**  compare  with delete. */
+       comp = strcmp( "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 = strcmp( "execute-low", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SL_ACTION_EXECUTE_LOW;
+
+       /**  compare pSrcStr with execute-high. */
+       comp = strcmp( "execute-high", pAction );
+       if (comp == 0)
+               return MSG_PUSH_SL_ACTION_EXECUTE_HIGH;
+
+       /** compare pSrcStr with cache. */
+       comp = strcmp( "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;
+       AutoPtr<char> encodedHeaderbuf(&encodedHeader);
+
+       char* outTemper = NULL;
+
+       char* temper = NULL;
+       AutoPtr<char> temperbuf(&temper);
+
+       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 */
+               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));
+
+               /* 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;
+                                                                               AutoPtr<char> parambuf(&param);
+                                                                               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;
+
+                                                               /* 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 ((wspUnregisterContentsType[i].contentsTypeCode != contentsTypeCode) && (i < wspUnregisteredContentsTypeCount)) 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;
+                                                                       AutoPtr<char> parambuf(&param);
+                                                                       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;
+                                                                       AutoPtr<char> parambuf(&param);
+                                                                       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)-strlen(temper)-1);
+                                                                               break;
+                                                                       }
+                                                               }
+                                                       }
+                                                       break;
+                                               /* Accept-Application */
+                                               case 0x32 :
+                                                       if (0x80 == fieldValue[0]) {
+                                                               strncat( (char*)temper, "*", (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(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)-strlen(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;
+                                                               AutoPtr<char> decodedStringbuf(&decodedString);
+                                                               wspHeaderDecodeDateValue( fieldValueLen, fieldValue, &decodedString);
+                                                               strncat( (char*)temper, (char*)decodedString, (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(temper)-1 );
+                                                       }
+                                                       break;
+
+                                               /* connection */
+                                               case 0x09 :
+                                                       if (fieldValue[0] == 0x80 )
+                                                               strncat( (char*)temper, "Close", (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(temper)-1 );
+                                                       break;
+                                               /* accept-ranges */
+                                               case 0x04 :
+                                                       if (fieldValue[0] == 0x80 )
+                                                               strncat( (char*)temper, "None", (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(temper)-1 );
+                                                       if (fieldValue[0] == 0x81 )
+                                                               strncat( (char*)temper, "Bytes", (WSP_STANDARD_STR_LEN_MAX * 5)-strlen(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;
+                                                               AutoPtr<char> addStringbuf(&addString);
+                                                               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;
+                                                                       AutoPtr<char> parambuf(&param);
+                                                                       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;
+                                                               AutoPtr<char> addStringbuf(&addString);
+                                                               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;
+                                                               sprintf( (char*)addedString, "%s %s", authScheme, realmValue );
+                                                               wspHeaderCopyDecodedString( addedString, &currentLength, &temper );
+
+                                                               if (iField < fieldValueLen) {
+                                                                       char* param = NULL;
+                                                                       AutoPtr<char> parambuf(&param);
+                                                                       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;
+                                                               AutoPtr<char> cacheStringbuf(&cacheString);
+
+                                                               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;
+                                                                       AutoPtr<char> parambuf(&param);
+                                                                       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;
+                                                               AutoPtr<char> tempbuf(&temp);
+
+                                                               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;
+                                                               sprintf( (char*)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);
+
+                                                                       sprintf( (char*)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;
+                                                               AutoPtr<char> parambuf(&param);
+                                                               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];
+
+                                                               sprintf( (char*)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;
+                                                                               AutoPtr<char> decodedStringbuf(&decodedString);
+                                                                               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 > 12 ) || (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 :
+                       sprintf( (char*)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 :
+                       sprintf( (char*)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.                     */
+                       sprintf( (char*)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 );
+
+       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;
+
+       *pDecodedString = new char[WSP_STANDARD_STR_LEN_MAX * 2];
+
+       if (*pDecodedString == NULL) {
+               MSG_DEBUG("WspLHeaderDecodeAuth:MemAlloc failed\n" );
+               return;
+       }
+
+       /* skip 'basic' code */
+       iField++;
+       sscanf((char*)(fieldValue + iField), "%s", userId );
+       iField = iField + AcStrlen( (char*)userId ) + 1;
+       sscanf( (char*)(fieldValue + iField), "%s", passWd );
+       iField = iField + AcStrlen( (char*)userId ) + 1;
+       sprintf( (char*)*pDecodedString, "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;
+
+       *pDecodedString = new char[WSP_STANDARD_STR_LEN_MAX];
+
+       if (*pDecodedString == NULL) {
+               MSG_DEBUG( "WspLHeaderDecodeChallenge:MemAlloc failed\n");
+               return;
+       }
+
+       /* skip 'basic' code */
+       iField++;
+       sscanf( (char*)(fieldValue + iField), "%s", userId );
+       iField = iField + AcStrlen( (char*)userId ) + 1;
+
+       sprintf( (char*)*pDecodedString, "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 :
+                               sprintf( (char*)paramString, "%u", (unsigned int)wspHeaderDecodeInteger( fieldValue + 1));
+                               break;
+
+                       default :
+                               break;
+
+               }
+               sprintf((char*)*pCacheString, "%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 ));
+
+                               sprintf( 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_plugin/include/SmsPluginCallback.h b/plugin/sms_plugin/include/SmsPluginCallback.h
new file mode 100755 (executable)
index 0000000..9b710d4
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_CALLBACK_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <map>
+#include <vector>
+
+extern "C"
+{
+       #include <tapi_common.h>
+       #include <TelSms.h>
+       #include <TapiUtility.h>
+       #include <ITapiNetText.h>
+}
+
+/*==================================================================================================
+                                     FUNCTION PROTOTYPES
+==================================================================================================*/
+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 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 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 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, 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);
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginCallback
+{
+public:
+       static SmsPluginCallback* instance();
+
+       void registerEvent();
+       void deRegisterEvent();
+
+private:
+       SmsPluginCallback();
+       ~SmsPluginCallback();
+
+       static SmsPluginCallback* pInstance;
+};
+
+#endif //SMS_PLUGIN_CALLBACK_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginCbMsgHandler.h b/plugin/sms_plugin/include/SmsPluginCbMsgHandler.h
new file mode 100755 (executable)
index 0000000..17e400f
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_CBMSG_HANDLER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <map>
+#include <vector>
+
+using namespace std;
+
+#include "MsgTextConvert.h"
+#include "SmsPluginTypes.h"
+
+extern "C"
+{
+       #include <tapi_common.h>
+       #include <TelSms.h>
+       #include <ITapiNetText.h>
+}
+
+
+/*==================================================================================================
+                                         VARIABLES
+==================================================================================================*/
+typedef map<unsigned char, string> cbPageMap;
+
+
+typedef struct _CB_PAGE_INFO_S
+{
+       unsigned char           geoScope;
+       unsigned char           updateNum;
+       unsigned short          msgCode;
+       unsigned short          msgId;
+       unsigned char           totalPages;
+
+       unsigned char           pageCnt;
+       unsigned int            totalSize;
+       cbPageMap               data;
+} CB_PAGE_INFO_S;
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginCbMsgHandler
+{
+public:
+       static SmsPluginCbMsgHandler* instance();
+
+       void handleCbMsg(TelSmsCbMsg_t *pCbMsg);
+       void handleEtwsMsg(TelSmsEtwsMsg_t *pEtwsMsg);
+
+private:
+       SmsPluginCbMsgHandler();
+       virtual ~SmsPluginCbMsgHandler();
+
+       static SmsPluginCbMsgHandler* pInstance;
+
+       void Decode2gCbMsg(TelSmsCbMsg_t *pCbMsg, SMS_CBMSG_PAGE_S *pCbPage);
+       void Decode3gCbMsg(TelSmsCbMsg_t *pCbMsg, SMS_CBMSG_PAGE_S *pCbPage);
+       void DecodeEtwsMsg(TelSmsEtwsMsg_t *pEtwsMsg, SMS_ETWS_PRIMARY_S *pEtwsPn);
+       unsigned short encodeCbSerialNum ( SMS_CBMSG_SERIAL_NUM_S snFields );
+
+       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 *pCbMsg, MSG_MESSAGE_INFO_S *pMsgInfo);
+       void convertEtwsMsgToMsginfo(SMS_CBMSG_PAGE_S EtwsMsg, MSG_MESSAGE_INFO_S *pMsgInfo);
+       int convertTextToUtf8 (unsigned char* outBuf, int outBufSize, SMS_CBMSG_S* pCbMsg);
+       void addToPageLiat(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);
+
+       vector<CB_PAGE_INFO_S> pageList;
+
+       MsgTextConvert textCvt;
+};
+
+#endif //SMS_PLUGIN_CBMSG_HANDLER_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginConcatHandler.h b/plugin/sms_plugin/include/SmsPluginConcatHandler.h
new file mode 100755 (executable)
index 0000000..a04d704
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_CONCAT_HANDLER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <string>
+#include <map>
+#include <vector>
+
+using namespace std;
+
+#include "MsgTextConvert.h"
+#include "SmsPluginTypes.h"
+
+
+/*==================================================================================================
+                                         VARIABLES AND DEFINES
+==================================================================================================*/
+#define MAX_CONCAT_LIST        10
+
+struct CONCAT_DATA_S
+{
+       int     length;
+       char data[MAX_USER_DATA_LEN+1];
+};
+
+typedef map<unsigned char, CONCAT_DATA_S> concatDataMap;
+
+typedef struct _SMS_CONCAT_MSG_S
+{
+       unsigned short          msgRef;
+       unsigned char           totalSeg;
+       unsigned char           seqNum;
+
+       SMS_TIMESTAMP_S timeStamp;
+       SMS_ADDRESS_S   originAddress;
+       SMS_DCS_S               dcs;
+       bool                            bRead;
+} SMS_CONCAT_MSG_S;
+
+typedef struct _SMS_CONCAT_INFO_S
+{
+       unsigned short          msgRef;
+       unsigned char           totalSeg;
+       unsigned char           segCnt;
+
+       SMS_TIMESTAMP_S timeStamp;
+       SMS_ADDRESS_S   originAddress;
+       SMS_DCS_S               dcs;
+       bool                            bRead;
+
+       unsigned int            totalSize;
+       concatDataMap   data;
+} SMS_CONCAT_INFO_S;
+
+typedef struct _SMS_SIM_ID_S
+{
+       unsigned short          msgRef;
+       msg_sim_id_t            simId;
+} SMS_SIM_ID_S;
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginConcatHandler
+{
+public:
+       static SmsPluginConcatHandler* instance();
+
+       bool IsConcatMsg(SMS_USERDATA_S *pUserData);
+       void handleConcatMsg(SMS_TPDU_S *pTpdu);
+//     void handleConcatMsg(SMS_TPDU_S *pTpdu, msg_sim_id_t SimMsgId, bool bRead);
+
+//     void handleBrokenMsg();
+
+private:
+       SmsPluginConcatHandler();
+       virtual ~SmsPluginConcatHandler();
+
+       static SmsPluginConcatHandler* pInstance;
+
+       unsigned char checkConcatMsg(SMS_CONCAT_MSG_S *pConcatMsg, SMS_USERDATA_S *pUserData);
+       int makeConcatUserData(unsigned short MsgRef, char **ppTotalData);
+
+       void convertConcatToMsginfo(const SMS_DELIVER_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 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;
+
+       MsgTextConvert textCvt;
+};
+
+#endif //SMS_PLUGIN_CONCAT_HANDLER_H
diff --git a/plugin/sms_plugin/include/SmsPluginEventHandler.h b/plugin/sms_plugin/include/SmsPluginEventHandler.h
new file mode 100755 (executable)
index 0000000..534330f
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_EVENT_HANDLER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgMutex.h"
+#include "MsgTextConvert.h"
+#include "MsgPluginInterface.h"
+#include "SmsPluginTypes.h"
+
+
+/*==================================================================================================
+                                     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_TPDU_S *pTpdu);
+       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);
+
+       msg_error_t callbackMsgIncoming(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t callbackCBMsgIncoming(MSG_CB_MSG_S *pCbMsg);
+       msg_error_t callbackInitSimBySat();
+       msg_error_t callbackStorageChange(msg_storage_change_type_t storageChangeType, MSG_MESSAGE_INFO_S *pMsgInfo);
+
+       void SetSentInfo(SMS_SENT_INFO_S *pSentInfo);
+
+       void setDeviceStatus();
+       bool getDeviceStatus();
+
+       void convertTpduToMsginfo(SMS_TPDU_S *pTpdu, MSG_MESSAGE_INFO_S *msgInfo); // temp
+
+private:
+       SmsPluginEventHandler();
+       virtual ~SmsPluginEventHandler();
+
+       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;
+
+       MSG_PLUGIN_LISTENER_S listener;
+       MSG_SIM_COUNT_S* pSimCnt;
+       SMS_SENT_INFO_S sentInfo;
+
+       bool devStatus;
+
+       Mutex mx;
+       CndVar cv;
+
+       MsgTextConvert textCvt;
+};
+
+#endif //SMS_PLUGIN_EVENT_HANDLER_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginMain.h b/plugin/sms_plugin/include/SmsPluginMain.h
new file mode 100755 (executable)
index 0000000..9eb0168
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_MAIN_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "SmsPluginTypes.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 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 SmsPlgGetSimMessage(msg_sim_id_t SimMsgId);
+
+msg_error_t SmsPlgGetSimMessageCount();
+
+msg_error_t SmsPlgSetReadStatus(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 SmsPlgSetConfigData(const MSG_SETTING_S *pSetting);
+
+msg_error_t SmsPlgGetConfigData(MSG_SETTING_S *pSetting);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //SMS_PLUGIN_MAIN_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginParamCodec.h b/plugin/sms_plugin/include/SmsPluginParamCodec.h
new file mode 100755 (executable)
index 0000000..fcfd73a
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_PARAMCODEC_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "SmsPluginTypes.h"
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginParamCodec
+{
+public:
+       SmsPluginParamCodec();
+       virtual ~SmsPluginParamCodec();
+
+       static int encodeAddress(const SMS_ADDRESS_S *pAddress, char **ppParam);
+       static int encodeTime(const SMS_TIMESTAMP_S *pTimeStamp, char **ppParam);
+       static int encodeDCS(const SMS_DCS_S *pDCS, char **ppParam);
+       static int encodeSMSC(const char *pAddress, unsigned char *pEncodeAddr);
+       static int encodeSMSC(const SMS_ADDRESS_S *pAddress, unsigned char *pSMSC);
+
+       static int decodeAddress(const unsigned char *pTpdu, SMS_ADDRESS_S *pAddress);
+       static int decodeTime(const unsigned char *pTpdu, SMS_TIMESTAMP_S *pTimeStamp);
+       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);
+
+private:
+       static int convertDigitToBcd(char *pDigit, int DigitLen, unsigned char *pBcd);
+       static int convertBcdToDigit(const unsigned char *pBcd, int BcdLen, char *pDigit);
+};
+
+#endif //SMS_PLUGIN_PARAMCODEC_H
diff --git a/plugin/sms_plugin/include/SmsPluginSatHandler.h b/plugin/sms_plugin/include/SmsPluginSatHandler.h
new file mode 100755 (executable)
index 0000000..9d3b4b8
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_SAT_HANDLER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "SmsPluginTypes.h"
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+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 finishSimMsgInit(msg_error_t Err);
+
+private:
+       SmsPluginSatHandler();
+       virtual ~SmsPluginSatHandler();
+
+       void initSim();
+
+       void    initSMSCList();
+       void    initCBConfig();
+
+       int handleSatTpdu(unsigned char *pTpdu, unsigned char TpduLen, int bIsPackingRequired);
+
+       void sendResult(SMS_SAT_CMD_TYPE_T CmdType, int ResultType);
+
+       static SmsPluginSatHandler* pInstance;
+
+       int commandId;
+
+       bool bSendSms;
+       bool bInitSim;
+       bool bSMSPChanged;
+       bool bCBMIChanged;
+};
+
+#endif //SMS_PLUGIN_SAT_HANDLER_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginSetting.h b/plugin/sms_plugin/include/SmsPluginSetting.h
new file mode 100755 (executable)
index 0000000..a8beeaa
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_SETTING_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgMutex.h"
+#include "MsgSettingTypes.h"
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+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 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 setMailboxInfoEvent(SMS_SIM_MAILBOX_LIST_S *pVoiceOpt, bool bSuccess);
+       void setMwiInfo(MSG_SUB_TYPE_T type, int count);
+       void setMwiInfoEvent(SMS_SIM_MWI_INFO_S *pMwiInfo, bool bSuccess);
+       void setResultFromSim(bool bResult);
+
+private:
+       SmsPluginSetting();
+       ~SmsPluginSetting();
+
+       msg_error_t addSMSCList(MSG_SMSC_LIST_S *pSmscList);
+
+       msg_error_t addCbOpt(MSG_CBMSG_OPT_S *pCbOpt);
+       void getCbOpt(MSG_SETTING_S *pSetting);
+
+       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);
+
+       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(MSG_VOICEMAIL_OPT_S *pVoiceOpt);
+       bool getMwiInfo(void);
+       bool getMsisdnInfo(void);
+
+       int getParamCntEvent();
+       bool getParamEvent(MSG_SMSC_DATA_S *pSmscData);
+       bool getCbConfigEvent(MSG_CBMSG_OPT_S *pCbOpt);
+
+       bool getMailboxInfoEvent(MSG_VOICEMAIL_OPT_S *pVoiceOpt);
+
+       bool getResultFromSim();
+
+       SMS_PID_T convertPid(MSG_SMS_PID_T pid);
+
+       static SmsPluginSetting* pInstance;
+
+       MSG_SMSC_DATA_S         smscData;
+       MSG_CBMSG_OPT_S         cbOpt;
+
+       /* Message Waiting Indicator */
+       SMS_SIM_MAILBOX_LIST_S  simMailboxList;
+       SMS_SIM_MWI_INFO_S      simMwiInfo;
+
+       bool            bTapiResult;
+       int             paramCnt;
+       int             selectedParam;
+
+       Mutex mx;
+       CndVar cv;
+};
+
+#endif //SMS_PLUGIN_SETTING_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginSimMsg.h b/plugin/sms_plugin/include/SmsPluginSimMsg.h
new file mode 100755 (executable)
index 0000000..f9f9a5f
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_SIMMSG_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgMutex.h"
+
+#include "MsgStorageTypes.h"
+#include "SmsPluginTypes.h"
+#include "MsgInternalTypes.h"
+
+extern "C"
+{
+       #include <tapi_common.h>
+       #include <TelSms.h>
+       #include <TapiUtility.h>
+       #include <ITapiNetText.h>
+}
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginSimMsg
+{
+public:
+       static SmsPluginSimMsg* instance();
+
+       void initSimMessage();
+       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 getSimMessageList(MSG_SIM_MSG_INFO_LIST_S **ppSimMsgList);
+       void setReadStatus(msg_sim_id_t SimMsgId);
+       bool checkSimMsgFull(unsigned int SegCnt);
+
+       void setSimMsgCntEvent(const MSG_SIM_COUNT_S *pSimMsgCnt);
+       void setSimMsgEvent(const MSG_MESSAGE_INFO_S *pMsgInfo, bool bSuccess);
+       void setSaveSimMsgEvent(int simMsgId, int result);
+       void setSaveClass2MsgEvent(int simMsgId, int result);
+       void setSimEvent(msg_sim_id_t SimId, bool bResult);
+
+       void setSmsData(const char *sca, const char *szData, int msgLength);
+
+private:
+       SmsPluginSimMsg();
+       ~SmsPluginSimMsg();
+
+       void getSimMsgCount(MSG_SIM_COUNT_S *pSimMsgCnt);
+       bool getSimMsg(msg_sim_id_t SimMsgId, MSG_MESSAGE_INFO_S* pMsgInfo);
+
+       void setSmsOptions(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 getSimEvent(msg_sim_id_t *pSimId);
+
+       static SmsPluginSimMsg* pInstance;
+
+       msg_sim_id_t                            simMsgId;
+
+       MSG_SIM_COUNT_S                 simMsgCnt;
+
+       MSG_MESSAGE_INFO_S              simMsgInfo;
+
+       unsigned int                            usedCnt;
+       unsigned int                            totalCnt;
+
+       bool                                            bTapiResult;
+
+       SMS_DATA_INFO_S                 simMsgDataInfo;
+
+       Mutex mx;
+       CndVar cv;
+};
+
+#endif //SMS_PLUGIN_SIMMSG_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginStorage.h b/plugin/sms_plugin/include/SmsPluginStorage.h
new file mode 100755 (executable)
index 0000000..c20a341
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_STORAGE_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgMutex.h"
+
+#include "MsgStorageTypes.h"
+#include "SmsPluginTypes.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 updateSentMsg(MSG_MESSAGE_INFO_S *pMsgInfo, msg_network_status_t Status);
+
+       msg_error_t addSimMessage(MSG_MESSAGE_INFO_S *pSimMsgInfo);
+
+       msg_error_t addMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
+       msg_error_t addSmsMessage(MSG_MESSAGE_INFO_S *pMsgInfo);
+
+       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 getRegisteredPushEvent(char* pPushHeader, int *count, char *app_id, char *content_type);
+       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();
+
+       static SmsPluginStorage* pInstance;
+
+       MsgDbHandler dbHandle;
+       std::list<PUSH_APPLICATION_INFO_S> pushAppInfoList;
+//     unsigned char tmpMsgRef;
+};
+
+#endif //SMS_PLUGIN_STORAGE_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginTpduCodec.h b/plugin/sms_plugin/include/SmsPluginTpduCodec.h
new file mode 100755 (executable)
index 0000000..30bc0af
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_TPDU_CODEC_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "SmsPluginTypes.h"
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginTpduCodec
+{
+public:
+       SmsPluginTpduCodec();
+       virtual ~SmsPluginTpduCodec();
+
+       static int encodeTpdu(const SMS_TPDU_S *pSmsTpdu, char *pTpdu);
+       static int decodeTpdu(const unsigned char *pTpdu, int TpduLen, SMS_TPDU_S *pSmsTpdu);
+
+private:
+       static int encodeSubmit(const SMS_SUBMIT_S *pSubmit, char *pTpdu);
+       static int encodeDeliver(const SMS_DELIVER_S *pDeliver, char *pTpdu);
+       static int encodeDeliverReport(const SMS_DELIVER_REPORT_S *pDeliverRep, char *pTpdu);
+       static int encodeStatusReport(const SMS_STATUS_REPORT_S *pStatusRep, char *pTpdu);
+
+       static int decodeSubmit(const unsigned char *pTpdu, int TpduLen, SMS_SUBMIT_S *pSubmit);
+       static int decodeDeliver(const unsigned char *pTpdu, int TpduLen, SMS_DELIVER_S *pDeliver);
+       static int decodeStatusReport(const unsigned char *pTpdu, int TpduLen, SMS_STATUS_REPORT_S *pStatusRep);
+};
+
+#endif //SMS_PLUGIN_TPDU_CODEC_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginTransport.h b/plugin/sms_plugin/include/SmsPluginTransport.h
new file mode 100755 (executable)
index 0000000..8de007e
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_TRANSPORT_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgMutex.h"
+#include "MsgTextConvert.h"
+#include "MsgTransportTypes.h"
+#include "MsgSettingTypes.h"
+#include "SmsPluginTypes.h"
+#include "MsgInternalTypes.h"
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginTransport
+{
+public:
+       static SmsPluginTransport* instance();
+
+       void submitRequest(SMS_REQUEST_INFO_S *pReqInfo);
+       void sendDeliverReport(msg_error_t err);
+       void sendClass0DeliverReport(msg_error_t err);
+
+       void setSmsSendOptions(SMS_SUBMIT_S *pSubmit);
+       void setSmscOptions(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();
+
+       unsigned char getMsgRef();
+
+private:
+       SmsPluginTransport();
+       ~SmsPluginTransport();
+
+       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;
+
+       unsigned char           msgRef;
+
+       unsigned char           msgRef8bit;
+       unsigned short  msgRef16bit;
+
+       msg_network_status_t curStatus;
+
+       Mutex mx;
+       CndVar cv;
+
+       MsgTextConvert textCvt;
+};
+
+#endif //SMS_PLUGIN_TRANSPORT_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginTypes.h b/plugin/sms_plugin/include/SmsPluginTypes.h
new file mode 100755 (executable)
index 0000000..6fa65bb
--- /dev/null
@@ -0,0 +1,1004 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_TYPES_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgTextConvert.h"
+#include "MsgInternalTypes.h"
+#include "MsgStorageTypes.h"
+#include "MsgSettingTypes.h"
+
+
+/*==================================================================================================
+                                    DEFINES
+==================================================================================================*/
+#define MAX_ADDRESS_LEN                        21 // including '+'
+#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_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_ETWS_SIZE                  56
+#define MAX_CBMSG_PAGE_NUM             15
+#define MAX_SIM_SMS_NUM                        255
+#define MAX_SIM_XDN_ALPHA_ID_LEN       30
+#define MAX_SIM_MSP_CNT                        2
+
+#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"
+
+
+/*==================================================================================================
+                                         TYPES
+==================================================================================================*/
+
+/**
+\brief Represents TPDU Type.
+*/
+typedef unsigned char SMS_TPDU_TYPE_T;
+
+/**
+\brief Represents TPDU Type.
+*/
+typedef unsigned char SMS_VPF_T;
+
+/**
+\brief Represents TPDU Type.
+*/
+typedef unsigned char SMS_TON_T;
+
+/**
+\brief Represents TPDU Type.
+*/
+typedef unsigned char SMS_NPI_T;
+
+/**
+\brief Represents TPDU Type.
+*/
+typedef unsigned char SMS_PID_T;
+
+
+/**
+\brief Represents TPDU Type.
+*/
+typedef unsigned char SMS_MSG_CLASS_T;
+
+
+/**
+\brief Represents TPDU Type.
+*/
+typedef unsigned char SMS_CODING_SCHEME_T;
+
+
+/**
+\brief Represents TPDU Type.
+*/
+typedef unsigned char SMS_CODING_GROUP_T;
+
+
+/**
+\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_CB_NETWORK_TYPE_T;
+
+
+typedef unsigned char SMS_CBMSG_TYPE_T;
+
+
+typedef unsigned char SMS_CBMSG_LANG_TYPE_T;
+
+
+typedef unsigned char SMS_CBMSG_CODING_GROUP_T;
+
+
+typedef unsigned char SMS_SAT_CMD_TYPE_T;
+
+
+typedef unsigned short SMS_SIM_EFILE_NAME_T;
+
+
+typedef unsigned char SMS_ETWS_NETWORK_TYPE_T;
+
+/**
+\brief Represents SIM mailbox type. See enum _SMS_SIM_MAILBOX_TYPE_E
+*/
+typedef unsigned char SMS_SIM_MAILBOX_TYPE_T;
+
+/*==================================================================================================
+                                    ENUMS
+==================================================================================================*/
+enum _SMS_TPDU_TYPE_E
+{
+       SMS_TPDU_SUBMIT,
+       SMS_TPDU_DELIVER,
+       SMS_TPDU_DELIVER_REP,
+       SMS_TPDU_STATUS_REP,
+};
+
+
+enum _SMS_VPF_E
+{
+       SMS_VPF_NOT_PRESENT = 0,
+       SMS_VPF_ENHANCED,
+       SMS_VPF_RELATIVE,
+       SMS_VPF_ABSOLUTE,
+};
+
+
+enum _SMS_TON_E
+{
+       SMS_TON_UNKNOWN = 0,            /* unknown */
+       SMS_TON_INTERNATIONAL,  /* international */
+       SMS_TON_NATIONAL,                       /* national */
+       SMS_TON_NETWORK,                        /* network */
+       SMS_TON_SUBSCRIBER,             /* subscriber */
+       SMS_TON_ALPHANUMERIC,           /* alpha numberic */
+       SMS_TON_ABBREVIATED,            /* abbreviated */
+       SMS_TON_RESERVE,                        /* reserve */
+};
+
+
+enum _SMS_NPI_E
+{
+       SMS_NPI_UNKNOWN = 0,            /* unknown */
+       SMS_NPI_ISDN = 1,                       /* idsn */
+       SMS_NPI_DATA = 3,                       /* data */
+       SMS_NPI_TELEX = 4,                      /* telex */
+       SMS_NPI_SMSC = 5,                       /* smsc */
+       SMS_NPI_NATIONAL = 8,           /* national */
+       SMS_NPI_PRIVATE = 9,                    /* private */
+       SMS_NPI_ERMES = 10,                     /* ermes */
+};
+
+
+enum _SMS_PID_E
+{
+       SMS_PID_NORMAL = 0x00,
+
+       SMS_PID_TELEX = 0x21,
+       SMS_PID_GROUP3_TELEX = 0x22,
+       SMS_PID_GROUP4_TELEX = 0x23,
+       SMS_PID_VOICE = 0x24,
+       SMS_PID_ERMES = 0x25,
+       SMS_PID_NPS = 0x26,
+       SMS_PID_VIDEO = 0x27,
+       SMS_PID_TELETEX_UNSPEC = 0x28,
+       SMS_PID_TELETEX_PSPDN = 0x29,
+       SMS_PID_TELETEX_CSPDN = 0x2A,
+       SMS_PID_TELETEX_PSTN = 0x2B,
+       SMS_PID_TELETEX_ISDN = 0x2C,
+       SMS_PID_UCI = 0x2D,
+       SMS_PID_x400 = 0x31,
+       SMS_PID_EMAIL = 0x32,
+
+       SMS_PID_TYPE0 = 0x40,
+       SMS_PID_REPLACE_TYPE1 = 0x41,
+       SMS_PID_REPLACE_TYPE2 = 0x42,
+       SMS_PID_REPLACE_TYPE3 = 0x43,
+       SMS_PID_REPLACE_TYPE4 = 0x44,
+       SMS_PID_REPLACE_TYPE5 = 0x45,
+       SMS_PID_REPLACE_TYPE6 = 0x46,
+       SMS_PID_REPLACE_TYPE7 = 0x47,
+
+       SMS_PID_RETURN_CALL = 0x5F,
+};
+
+
+enum _SMS_MSG_CLASS_E
+{
+       SMS_MSG_CLASS_0 = 0,
+       SMS_MSG_CLASS_1,
+       SMS_MSG_CLASS_2,
+       SMS_MSG_CLASS_3,
+       SMS_MSG_CLASS_NONE,
+};
+
+
+enum _SMS_CODING_SCHEME_E
+{
+       SMS_CHARSET_7BIT = 0,
+       SMS_CHARSET_8BIT,
+       SMS_CHARSET_UCS2,
+       SMS_CHARSET_AUTO,
+       SMS_CHARSET_EUCKR,
+};
+
+
+enum _SMS_CODING_GROUP_E
+{
+       SMS_GROUP_GENERAL = 0,
+       SMS_GROUP_CODING_CLASS,
+       SMS_GROUP_DELETION,
+       SMS_GROUP_DISCARD,
+       SMS_GROUP_STORE,
+       SMS_GROUP_UNKNOWN,
+};
+
+
+enum _SMS_INDICATOR_TYPE_E
+{
+       SMS_VOICE_INDICATOR = 0,
+       SMS_FAX_INDICATOR,
+       SMS_EMAIL_INDICATOR,
+       SMS_OTHER_INDICATOR,
+};
+
+
+enum _SMS_TIME_FORMAT_E
+{
+       SMS_TIME_RELATIVE = 0,
+       SMS_TIME_ABSOLUTE
+};
+
+
+enum _SMS_FAIL_CAUSE_E
+{
+       SMS_FC_MSG_TYPE0_NOT_SUPPORTED = 0x81,
+       SMS_FC_SM_CANNOT_BE_REPLACED = 0x82,
+       SMS_FC_UNSPEC_PID_ERROR = 0x8F,
+       SMS_FC_MSG_CLASS_NOT_SUPPORTED = 0x91,
+       SMS_FC_UNSPEC_DCS_ERROR = 0x9F,
+       SMS_FC_TPDU_NOT_SUPPORTED = 0xB0,
+       SMS_FC_SIM_STORAGE_FULL = 0xD0,
+       SMS_FC_NO_STORAGE_IN_SIM = 0xD1,
+       SMS_FC_ERROR_IN_MS = 0xD2,
+       SMS_FC_MSG_CAPA_EXCEEDED = 0xD3,
+       SMS_FC_SAT_BUSY = 0xD4,
+       SMS_FC_SIM_DOWNLOAD_ERROR = 0xD5,
+       SMS_FC_UNSPEC_ERROR = 0xFF,
+};
+
+
+enum _SMS_STATUS_E
+{
+       SMS_STATUS_RECEIVE_SUCCESS = 0x00,
+       SMS_STATUS_UNABLE_TO_CONFIRM_DELIVER = 0x01,
+       SMS_STATUS_REPLACED = 0x02,
+       SMS_STATUS_SMSC_SPECIFIC_LAST = 0x1F,
+
+       SMS_STATUS_TRY_CONGESTION = 0x20,
+       SMS_STATUS_TRY_SME_BUSY = 0x21,
+       SMS_STATUS_TRY_NO_RESPONSE = 0x22,
+       SMS_STATUS_TRY_SERVICE_REJECTED = 0x23,
+       SMS_STATUS_TRY_QOS_NOT_AVAILABLE = 0x24,
+
+       SMS_STATUS_PERM_REMOTE_ERROR = 0x40,
+       SMS_STATUS_PERM_IMCOMPATIBLE_DEST = 0x41,
+       SMS_STATUS_PERM_CONNECTION_REJECTED = 0x42,
+       SMS_STATUS_PERM_NOT_OBTAINABLE = 0x43,
+       SMS_STATUS_PERM_QOS_NOT_AVAILABLE = 0x44,
+       SMS_STATUS_PERM_NO_INTERWORK_AVAILABLE = 0x45,
+       SMS_STATUS_PERM_MSG_VAL_PERIOD_EXPIRED = 0x46,
+       SMS_STATUS_PERM_MSG_DEL_BY_ORIGIN_SME = 0x47,
+       SMS_STATUS_PERM_MSG_DEL_BY_SMSC_ADMIN = 0x48,
+       SMS_STATUS_PERM_MSG_NOT_EXIST = 0x49,
+
+       SMS_STATUS_TEMP_CONGESTION = 0x60,
+       SMS_STATUS_TEMP_SME_BUSY = 0x61,
+       SMS_STATUS_TEMP_NO_RESPONSE = 0x62,
+       SMS_STATUS_TEMP_SERVICE_REJECTED = 0x63,
+       SMS_STATUS_TEMP_QOS_NOT_AVAILABLE = 0x64,
+       SMS_STATUS_TEMP_ERROR_IN_SME = 0x65,
+};
+
+
+enum _SMS_REF_NUMBER_E
+{
+       SMS_REF_NUM_8BIT = 0,
+       SMS_REF_NUM_16BIT
+};
+
+
+enum _SMS_REPORT_TYPE_E
+{
+       SMS_REPORT_POSITIVE = 0,
+       SMS_REPORT_NEGATIVE
+};
+
+
+enum _SMS_UDH_TYPE_E
+{
+       SMS_UDH_CONCAT_8BIT = 0x00,
+       SMS_UDH_SPECIAL_SMS = 0x01,
+       // 0x02, 0x03 - Reserved
+       SMS_UDH_APP_PORT_8BIT = 0x04,
+       SMS_UDH_APP_PORT_16BIT = 0x05,
+       SMS_UDH_SC_CONTROL = 0x06,
+       SMS_UDH_SRC_IND = 0x07,
+       SMS_UDH_CONCAT_16BIT = 0x08,
+       SMS_UDH_WCMP = 0x09,
+       SMS_UDH_ALTERNATE_REPLY_ADDRESS = 0x22,
+       SMS_UDH_SINGLE_SHIFT = 0x24,
+       SMS_UDH_LOCKING_SHIFT = 0x25,
+       SMS_UDH_NONE = 0xFF,
+};
+
+
+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,
+};
+
+
+enum _SMS_CB_NETWORK_TYPE_E
+{
+       SMS_CB_NETWORK_TYPE_2G_GSM = 1,
+       SMS_CB_NETWORK_TYPE_3G_UMTS,
+};
+
+
+enum _SMS_CBMSG_TYPE_E
+{
+       SMS_CBMSG_TYPE_CBS = 1,         /**< CBS */
+       SMS_CBMSG_TYPE_SCHEDULE,                /**< Schedule */
+       SMS_CBMSG_TYPE_CBS41,                   /**< CBS41 */
+       SMS_CBMSG_TYPE_JAVACBS,         /**< JAVA-CB Message*/
+       SMS_CBMSG_TYPE_ETWS,
+};
+
+
+enum _SMS_CBMSG_LANG_TYPE_E
+{
+       SMS_CBMSG_LANG_GERMAN                   = 0x00,
+       SMS_CBMSG_LANG_ENGLISH                  = 0x01,
+       SMS_CBMSG_LANG_ITALIAN                  = 0x02,
+       SMS_CBMSG_LANG_FRENCH                   = 0x03,
+       SMS_CBMSG_LANG_SPANISH                  = 0x04,
+       SMS_CBMSG_LANG_DUTCH                    = 0x05,
+       SMS_CBMSG_LANG_SWEDISH          = 0x06,
+       SMS_CBMSG_LANG_DANISH                   = 0x07,
+       SMS_CBMSG_LANG_PORTUGUESE       = 0x08,
+       SMS_CBMSG_LANG_FINNISH                  = 0x09,
+       SMS_CBMSG_LANG_NORWEGIAN        = 0x0a,
+       SMS_CBMSG_LANG_GREEK                    = 0x0b,
+       SMS_CBMSG_LANG_TURKISH                  = 0x0c,
+       SMS_CBMSG_LANG_HUNGARIAN        = 0x0d,
+       SMS_CBMSG_LANG_POLISH                   = 0x0e,
+       SMS_CBMSG_LANG_UNSPECIFIED      = 0x0f,
+
+       SMS_CBMSG_LANG_ISO639           = 0x10,
+
+       SMS_CBMSG_LANG_CZECH                    = 0x20,
+       SMS_CBMSG_LANG_HEBREW           = 0x21,
+       SMS_CBMSG_LANG_ARABIC           = 0x22,
+       SMS_CBMSG_LANG_RUSSIAN          = 0x23,
+       SMS_CBMSG_LANG_ICELANDIC                = 0x24,
+       SMS_CBMSG_LANG_RESERVED_25      = 0x25,
+       SMS_CBMSG_LANG_RESERVED_26      = 0x26,
+       SMS_CBMSG_LANG_RESERVED_27      = 0x27,
+       SMS_CBMSG_LANG_RESERVED_28      = 0x28,
+       SMS_CBMSG_LANG_RESERVED_29      = 0x29,
+       SMS_CBMSG_LANG_RESERVED_2A      = 0x2a,
+       SMS_CBMSG_LANG_RESERVED_2B      = 0x2b,
+       SMS_CBMSG_LANG_RESERVED_2C      = 0x2c,
+       SMS_CBMSG_LANG_RESERVED_2D      = 0x2d,
+       SMS_CBMSG_LANG_RESERVED_2E      = 0x2e,
+       SMS_CBMSG_LANG_RESERVED_2F      = 0x2f,
+
+       SMS_CBMSG_LANG_DUMMY                    = 0xFF
+};
+
+
+enum _SMS_CBMSG_CODING_GROUP_E
+{
+       SMS_CBMSG_CODGRP_GENERAL_DCS,                   /**< Bits 7..4 00xx */
+       SMS_CBMSG_CODGRP_WAP,                                   /**< 1110 Cell Broadcast */
+       SMS_CBMSG_CODGRP_CLASS_CODING,                  /**< 1111 Cell Broadcast */
+};
+
+
+enum _SMS_SAT_CMD_TYPE_E
+{
+       SMS_SAT_CMD_REFRESH,
+       SMS_SAT_CMD_SEND_SMS,
+       SMS_SAT_CMD_SMS_CTRL,
+};
+
+
+enum _SMS_SIM_EFILE_NAME_E
+{
+       SMS_SIM_EFILE_USIM_SMS  = 0x6A3C,               /** < USIM Short Messages file */
+       SMS_SIM_EFILE_USIM_SMSP = 0x6A42,               /** < USIM SMS parameter */
+       SMS_SIM_EFILE_USIM_SMSS = 0x6A43,               /** < USIM SMS status */
+       SMS_SIM_EFILE_USIM_CBMI = 0x6A45,               /** < USIM Cell Broadcast Message Identifier */
+       SMS_SIM_EFILE_USIM_MBDN = 0x6FC7,               /** < USIM Mail Box Dialing Number */
+       SMS_SIM_EFILE_SMS                       = 0x6F3C,               /** < Short Messages file */
+       SMS_SIM_EFILE_SMSP                      = 0x6F42,               /** < SMS Parameter */
+       SMS_SIM_EFILE_SMSS                      = 0x6F43,               /** < SMS Status */
+       SMS_SIM_EFILE_CBMI                      = 0x6F45,               /** < Cell Broadcast Message Identifier */
+       SMS_SIM_EFILE_MBDN              = 0x6FC7,               /** < Mail Box Dialing Number */
+};
+
+
+enum _SMS_SIM_MAILBOX_TYPE_E {
+       MSG_SIM_MAILBOX_VOICE = 0x01,
+       MSG_SIM_MAILBOX_VOICE2 = 0x02,
+       MSG_SIM_MAILBOX_FAX = 0x03,
+       MSG_SIM_MAILBOX_DATA = 0x04,
+       MSG_SIM_MAILBOX_EMAIL = 0x05,
+       MSG_SIM_MAILBOX_OTHER = 0x06,
+};
+
+
+/*==================================================================================================
+                                         STRUCTURES
+==================================================================================================*/
+typedef struct _SMS_ADDRESS_S
+{
+       SMS_TON_T               ton;
+       SMS_NPI_T               npi;
+       char                            address[MAX_ADDRESS_LEN+1];        /* < null terminated string */
+} SMS_ADDRESS_S;
+
+
+typedef struct _SMS_DCS_S
+{
+       bool                                            bCompressed;
+       bool                                            bMWI;
+       bool                                            bIndActive;
+       SMS_MSG_CLASS_T                 msgClass;
+       SMS_CODING_SCHEME_T     codingScheme;
+       SMS_CODING_GROUP_T              codingGroup;
+       SMS_INDICATOR_TYPE_T            indType;
+} SMS_DCS_S;
+
+
+typedef struct _SMS_TIME_REL_S
+{
+       unsigned char time;
+} SMS_TIME_REL_S;
+
+
+typedef struct _SMS_TIME_ABS_S
+{
+       unsigned char year;
+       unsigned char month;
+       unsigned char day;
+       unsigned char hour;
+       unsigned char minute;
+       unsigned char second;
+       unsigned char timeZone;
+} SMS_TIME_ABS_S;
+
+
+typedef struct _SMS_TIMESTAMP_S
+{
+       SMS_TIME_FORMAT_T format;
+
+       union
+       {
+               SMS_TIME_REL_S  relative;
+               SMS_TIME_ABS_S  absolute;
+       } time;
+} SMS_TIMESTAMP_S;
+
+
+typedef struct _SMS_CONCAT_8BIT_S
+{
+       unsigned char           msgRef;
+       unsigned char           totalSeg;
+       unsigned char           seqNum;
+} SMS_CONCAT_8BIT_S;
+
+
+typedef struct _SMS_CONCAT_16BIT_S
+{
+       unsigned short          msgRef;
+       unsigned char           totalSeg;
+       unsigned char           seqNum;
+} SMS_CONCAT_16BIT_S;
+
+
+typedef struct _SMS_APP_PORT_8BIT_S
+{
+       unsigned char           destPort;
+       unsigned char           originPort;
+} SMS_APP_PORT_8BIT_S;
+
+
+typedef struct _SMS_APP_PORT_16BIT_S
+{
+       unsigned short          destPort;
+       unsigned short          originPort;
+} SMS_APP_PORT_16BIT_S;
+
+
+typedef struct _SMS_SPECIAL_INDICATION_S
+{
+       bool                            bStore;
+       unsigned short          msgInd;
+       unsigned short          waitMsgNum;
+} SMS_SPECIAL_INDICATION_S;
+
+
+typedef struct _SMS_UDH_S
+{
+       SMS_UDH_TYPE_T udhType;
+
+       union
+       {
+               SMS_CONCAT_8BIT_S                       concat8bit;
+               SMS_CONCAT_16BIT_S                      concat16bit;
+               SMS_APP_PORT_8BIT_S             appPort8bit;
+               SMS_APP_PORT_16BIT_S            appPort16bit;
+               SMS_SPECIAL_INDICATION_S        specialInd;
+               MSG_SINGLE_SHIFT_S                      singleShift;
+               MSG_LOCKING_SHIFT_S                     lockingShift;
+               SMS_ADDRESS_S                           alternateAddress;
+       } udh;
+} SMS_UDH_S;
+
+
+typedef struct _SMS_USERDATA_S
+{
+       int                     headerCnt;
+       SMS_UDH_S       header[MAX_UD_HEADER_NUM];
+       int                     length;
+       char                    data[MAX_USER_DATA_LEN+1];
+} SMS_USERDATA_S;
+
+
+typedef struct _SMS_TPUD_S
+{
+       int             udl;
+       char            ud[MAX_USER_DATA_LEN+1];
+} SMS_TPUD_S;
+
+
+typedef struct _SMS_SUBMIT_S
+{
+       bool                            bRejectDup;
+       bool                            bStatusReport;
+       bool                            bHeaderInd;
+       bool                            bReplyPath;
+       unsigned char           msgRef;
+       SMS_VPF_T               vpf;
+       SMS_ADDRESS_S   destAddress;
+       SMS_PID_T               pid;
+       SMS_DCS_S               dcs;
+       SMS_TIMESTAMP_S validityPeriod;
+       SMS_USERDATA_S  userData;
+} SMS_SUBMIT_S;
+
+
+typedef struct _SMS_SUBMIT_DATA_S
+{
+       SMS_ADDRESS_S   destAddress;
+       unsigned int            segCount;
+       SMS_USERDATA_S  userData[MAX_SEGMENT_NUM];
+} SMS_SUBMIT_DATA_S;
+
+
+typedef struct _SMS_DELIVER_S
+{
+       bool                            bMoreMsg;
+       bool                            bStatusReport;
+       bool                            bHeaderInd;
+       bool                            bReplyPath;
+       SMS_ADDRESS_S   originAddress;
+       SMS_PID_T               pid;
+       SMS_DCS_S               dcs;
+       SMS_TIMESTAMP_S timeStamp;
+       SMS_USERDATA_S  userData;
+       SMS_TPUD_S              udData;
+} SMS_DELIVER_S;
+
+
+typedef struct _SMS_DELIVER_REPORT_S
+{
+       SMS_REPORT_TYPE_T       reportType;
+       bool                                    bHeaderInd;
+       SMS_FAIL_CAUSE_T                failCause;
+       unsigned char                   paramInd;
+       SMS_PID_T                       pid;
+       SMS_DCS_S                       dcs;
+       SMS_USERDATA_S          userData;
+} SMS_DELIVER_REPORT_S;
+
+
+typedef struct _SMS_STATUS_REPORT_S
+{
+       bool                            bMoreMsg;
+       bool                            bStatusReport;
+       bool                            bHeaderInd;
+       unsigned char           msgRef;
+       SMS_ADDRESS_S   recipAddress;
+       SMS_TIMESTAMP_S timeStamp;
+       SMS_TIMESTAMP_S dischargeTime;
+       SMS_STATUS_T    status;
+       unsigned char           paramInd;
+       SMS_PID_T               pid;
+       SMS_DCS_S               dcs;
+       SMS_USERDATA_S  userData;
+} SMS_STATUS_REPORT_S;
+
+
+typedef struct _SMS_TPDU_S
+{
+       SMS_TPDU_TYPE_T tpduType;
+
+       union
+       {
+               SMS_SUBMIT_S                    submit;
+               SMS_DELIVER_S                   deliver;
+               SMS_DELIVER_REPORT_S    deliverRep;
+               SMS_STATUS_REPORT_S             statusRep;
+       } data;
+} SMS_TPDU_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;
+
+
+typedef struct _SMS_PUSH_APP_INFO_S
+{
+       char*                           pContentType;
+       char*                           pAppId;
+       SMS_WAP_APP_CODE_T      appCode;
+} SMS_PUSH_APP_INFO_S;
+
+
+typedef struct _SMS_CBMSG_SERIAL_NUM_S
+{
+       unsigned char           geoScope;
+       unsigned char           updateNum;
+       unsigned short          msgCode;
+} SMS_CBMSG_SERIAL_NUM_S;
+
+
+typedef struct _SMS_CBMSG_DCS_S
+{
+       SMS_CBMSG_CODING_GROUP_T                codingGroup;            /**< Coding group, GSM 03.38 */
+       SMS_MSG_CLASS_T                                 classType;              /**< The message class */
+       bool                                                            bCompressed;            /**< if text is compressed this is TRUE */
+       SMS_CODING_SCHEME_T                     codingScheme;   /**< How to encode a message. */
+       SMS_CBMSG_LANG_TYPE_T                           langType;
+       unsigned char                                           iso639Lang[3];  /* 2 GSM chars and a CR char */
+       bool                                                            bUDH;
+       unsigned char                                           rawData;
+} SMS_CBMSG_DCS_S;
+
+
+typedef struct _SMS_CBMSG_HEADER_S
+{
+       SMS_CBMSG_SERIAL_NUM_S          serialNum;              /**< Cell Broadcast Serial number */
+       unsigned short                                  msgId;                  /**< Message identifier code */
+       MSG_CB_LANGUAGE_TYPE_T          langType;               /**< Languages in CB Messages */
+       SMS_CBMSG_DCS_S                 dcs;                            /**< Data coding scheme */
+       unsigned char                                   page;                   /**< current page number */
+       unsigned char                                   totalPages;             /**< Total number of pages in this messages */
+       time_t                                          recvTime;               /**< Msg Recv Time */
+} SMS_CBMSG_HEADER_S;
+
+
+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 */
+} SMS_CBMSG_PAGE_S;
+
+
+typedef struct _SMS_CBMSG_S
+{
+       SMS_CBMSG_TYPE_T                        cbMsgType;                                                      /*CBS Msg or SCHEDULE Msg or CBS41 Msg */
+       unsigned short                                  msgId;                                                          /**< Message identifier code */
+       SMS_MSG_CLASS_T                         classType;                                                      /**< The message class */
+       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 */
+} SMS_CBMSG_S;
+
+typedef struct _SMS_ETWS_PRIMARY_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
+{
+       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;
+
+
+/**
+ *     @brief  Represents SIM count information.
+ */
+typedef struct
+{
+       unsigned int    totalCount;                     /**< The total number of SIM */
+       int                     usedCount;                      /**< The used number of SIM */
+       int                     indexList[MAX_SIM_SMS_NUM];     /**< The SIM index list */
+}MSG_SIM_COUNT_S;
+
+
+/**
+ *     @brief  Represents Concat SIM Msg information.
+ */
+typedef struct
+{
+       unsigned int            simIdCnt;                                                                                       /**< The total number of SIM Msg ID*/
+       msg_sim_id_t            simIdList[MAX_SEGMENT_NUM];                                                     /**< The SIM Msg ID List */
+       char                            msgData[(MAX_MSG_DATA_LEN*MAX_SEGMENT_NUM)+1];          /**< user data */
+} SMS_CONCAT_SIM_MSG_S;
+
+
+/**
+ *     @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 */
+} 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 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 */
+} SMS_DATA_INFO_S;
+
+#endif //SMS_PLUGIN_TYPES_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginUAManager.h b/plugin/sms_plugin/include/SmsPluginUAManager.h
new file mode 100755 (executable)
index 0000000..9a86ab2
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_UA_MANAGER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "MsgMutex.h"
+#include "MsgQueue.h"
+#include "MsgThread.h"
+#include "SmsPluginTypes.h"
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginUAManager : public MsgThread
+{
+public:
+       static SmsPluginUAManager* instance();
+
+       //virtual void start();
+
+       void addReqEntity(SMS_REQUEST_INFO_S *request);
+
+private:
+       SmsPluginUAManager();
+       ~SmsPluginUAManager();
+
+       virtual void run();
+
+       static SmsPluginUAManager* pInstance;
+
+       bool bRunning;
+
+       MsgThdSafeQ <SMS_REQUEST_INFO_S> smsTranQ;
+
+       Mutex mx;
+       CndVar cv;
+};
+
+#endif //SMS_PLUGIN_UA_MANAGER_H
+
diff --git a/plugin/sms_plugin/include/SmsPluginUDCodec.h b/plugin/sms_plugin/include/SmsPluginUDCodec.h
new file mode 100755 (executable)
index 0000000..b5d86e9
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_UDCODEC_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include "SmsPluginTypes.h"
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginUDCodec
+{
+public:
+       SmsPluginUDCodec();
+       virtual ~SmsPluginUDCodec();
+
+       static int encodeUserData(const SMS_USERDATA_S *pUserData, SMS_CODING_SCHEME_T CodingScheme, char *pEncodeData);
+       static int decodeUserData(const unsigned char *pTpdu, const int tpduLen, bool bHeaderInd, SMS_CODING_SCHEME_T CodingScheme, SMS_USERDATA_S *pUserData);
+       static int decodeUserData(const unsigned char *pTpdu, const int tpduLen, bool bHeaderInd, SMS_CODING_SCHEME_T CodingScheme, SMS_USERDATA_S *pUserData, SMS_TPUD_S *pTPUD);
+
+       static int pack7bitChar(const unsigned char *pUserData, int dataLen, int fillBits, char *pPackData);
+       static int unpack7bitChar(const unsigned char *pTpdu, unsigned char dataLen, int fillBits, char *pUnpackData);
+
+private:
+       static int encodeGSMData(const SMS_USERDATA_S *pUserData, char *pEncodeData);
+       static int encode8bitData(const SMS_USERDATA_S *pUserData, char *pEncodeData);
+       static int encodeUCS2Data(const SMS_USERDATA_S *pUserData, char *pEncodeData);
+
+       static int decodeGSMData(const unsigned char *pTpdu, const int tpduLen, bool bHeaderInd, SMS_USERDATA_S *pUserData, SMS_TPUD_S *pTPUD);
+       static int decode8bitData(const unsigned char *pTpdu, bool bHeaderInd, SMS_USERDATA_S *pUserData, SMS_TPUD_S *pTPUD);
+       static int decodeUCS2Data(const unsigned char *pTpdu, const int tpduLen, bool bHeaderInd, SMS_USERDATA_S *pUserData, SMS_TPUD_S *pTPUD);
+
+       static int encodeHeader(const SMS_UDH_S header, char *pEncodeHeader);
+       static int decodeHeader(const unsigned char *pTpdu, SMS_UDH_S *pHeader);
+};
+
+#endif
+
diff --git a/plugin/sms_plugin/include/SmsPluginWapPushHandler.h b/plugin/sms_plugin/include/SmsPluginWapPushHandler.h
new file mode 100755 (executable)
index 0000000..de661ff
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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
+#define SMS_PLUGIN_WAPPUSH_HANDLER_H
+
+
+/*==================================================================================================
+                                         INCLUDE FILES
+==================================================================================================*/
+#include <wbxml/wbxml.h>
+#include <libxml/parser.h>
+
+
+#include "SmsPluginTypes.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  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))
+
+
+/*==================================================================================================
+                                     CLASS DEFINITIONS
+==================================================================================================*/
+class SmsPluginWapPushHandler
+{
+public:
+       static SmsPluginWapPushHandler* instance();
+
+       //void registerPushCallback();
+       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);
+
+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_ADDRESS_S   tmpAddress;
+       SMS_TIMESTAMP_S tmpTimeStamp;
+};
+
+#endif //SmsPluginWapPushHandler
+
diff --git a/proxy/CMakeLists.txt b/proxy/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..e0b7c59
--- /dev/null
@@ -0,0 +1,51 @@
+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 Transaction Proxy
+##########################################################
+
+SET(TRANS-PROXY-SRCS
+       ${CMAKE_SOURCE_DIR}/proxy/MsgProxyListener.cpp
+       ${CMAKE_SOURCE_DIR}/proxy/MsgHandleControl.cpp
+       ${CMAKE_SOURCE_DIR}/proxy/MsgHandleSetting.cpp
+       ${CMAKE_SOURCE_DIR}/proxy/MsgHandleStorage.cpp
+       ${CMAKE_SOURCE_DIR}/proxy/MsgHandleTransport.cpp
+       ${CMAKE_SOURCE_DIR}/proxy/MsgHandleFilter.cpp
+)
+
+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)
+
+FOREACH(flag ${trans_proxy_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_LIBRARY(${TRANS-PROXY-LIB} SHARED ${TRANS-PROXY-SRCS})
+TARGET_LINK_LIBRARIES(${TRANS-PROXY-LIB} ${trans_proxy_pkgs_LDFLAGS} ${UTILS-LIB} ${FW-HANDLER-LIB})
+
+INSTALL(TARGETS ${TRANS-PROXY-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
+
diff --git a/proxy/MsgHandleControl.cpp b/proxy/MsgHandleControl.cpp
new file mode 100755 (executable)
index 0000000..58c32d5
--- /dev/null
@@ -0,0 +1,558 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilFile.h"
+#include "MsgGconfWrapper.h"
+#include "MsgProxyListener.h"
+#include "MsgHandle.h"
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgHandle - Control Member Functions
+==================================================================================================*/
+MsgHandle::MsgHandle() : mCounter(0), mClientSock()
+{
+       memset(mConnectionId, 0x00, sizeof(mConnectionId));
+       memset(mCookie, 0x00, sizeof(mCookie));
+}
+
+
+MsgHandle::~MsgHandle()
+{
+
+}
+
+
+void MsgHandle::openHandle()
+{
+//     int ret = 0;
+//     size_t cookieSize;
+
+       bool bReady = false;
+
+       // server is currently booting and service is not available until the end of booting
+       MsgSettingGetBool(VCONFKEY_MSG_SERVER_READY, &bReady);
+
+       if (bReady == false) {
+               THROW(MsgException::SERVER_READY_ERROR, "Msg Server is not ready !!!!!");
+       } else {
+               MSG_DEBUG("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();
+}
+
+
+void MsgHandle::closeHandle(MsgHandle* pHandle)
+{
+       MSG_BEGIN();
+
+       //Remove CB List of closing Handle
+       MsgProxyListener* eventListener = MsgProxyListener::instance();
+
+       eventListener->clearListOfClosedHandle(pHandle);
+       //eventListener->stop();
+
+       // Close Socket IPC
+       disconnectSocket();
+
+       MSG_END();
+}
+
+
+void MsgHandle::connectSocket()
+{
+       mClientSock.connect(MSG_SOCKET_PATH);
+}
+
+
+void MsgHandle::disconnectSocket()
+{
+       mClientSock.close();
+}
+
+
+void MsgHandle::write(const char *pCmdData, int cmdSize, char **ppEvent)
+{
+       if (pCmdData == NULL || ppEvent == NULL) {
+               THROW(MsgException::INVALID_PARAM, "Param is NULL");
+       }
+
+       int ret = 0;
+
+       // Send Command to MSG FW
+       ret = mClientSock.write(pCmdData, cmdSize);
+       if (ret < 0)
+               THROW(MsgException::IPC_ERROR, "IPC write error");
+
+       // Receive Result from MSG FW
+       read(ppEvent);
+
+       if (*ppEvent == NULL) {
+               THROW(MsgException::INVALID_RESULT, "event is NULL");
+       }
+
+}
+
+
+void MsgHandle::read(char **ppEvent)
+{
+       unsigned int dataSize = 0;
+
+       dataSize = mClientSock.read(ppEvent, &dataSize);
+
+       if (dataSize == 0) {
+               THROW(MsgException::IPC_ERROR, "Server closed connection");
+       }
+}
+
+
+void MsgHandle::convertMsgStruct(const MSG_MESSAGE_HIDDEN_S *pSrc, MSG_MESSAGE_INFO_S *pDest)
+{
+       MSG_BEGIN();
+
+       pDest->msgId = pSrc->msgId;
+       pDest->threadId = pSrc->threadId;
+       pDest->folderId = pSrc->folderId;
+       pDest->msgType.mainType = pSrc->mainType;
+       pDest->msgType.subType = pSrc->subType;
+       pDest->msgType.classType= pSrc->classType;
+       pDest->storageId = pSrc->storageId;
+
+       msg_struct_list_s *addr_info_s = pSrc->addr_list;
+
+       if (addr_info_s) {
+               msg_struct_s *addr_info = NULL;
+               MSG_ADDRESS_INFO_S *address = NULL;
+
+               pDest->nAddressCnt = 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);
+                       pDest->addressList[i].displayName[MAX_DISPLAY_NAME_LEN] = '\0';
+               }
+       }
+
+       strncpy(pDest->replyAddress, pSrc->replyAddress, MAX_PHONE_NUMBER_LEN);
+       strncpy(pDest->subject, pSrc->subject, MAX_SUBJECT_LEN);
+
+       pDest->displayTime = pSrc->displayTime;
+       pDest->networkStatus = pSrc->networkStatus;
+       pDest->encodeType = pSrc->encodeType;
+       pDest->bRead = pSrc->bRead;
+       pDest->bProtected = pSrc->bProtected;
+       pDest->bBackup = pSrc->bBackup;
+       pDest->priority = pSrc->priority;
+       pDest->direction = pSrc->direction;
+
+       // Set Port Info.
+       pDest->msgPort.valid = pSrc->bPortValid;
+
+       if (pDest->msgPort.valid == true) {
+               pDest->msgPort.dstPort = pSrc->dstPort;
+               pDest->msgPort.srcPort = pSrc->srcPort;
+       }
+
+       MSG_DEBUG("nSize = %d",  pSrc->dataSize);
+
+       if (pSrc->mainType == MSG_SMS_TYPE){
+               pDest->bTextSms = true;
+               pDest->dataSize = pSrc->dataSize;
+
+               memset(pDest->msgText, 0x00, sizeof(pDest->msgText));
+
+               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");
+
+                       MSG_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");
+
+                       memset(pDest->msgData, 0x00, sizeof(pDest->msgData));
+                       strncpy(pDest->msgData, fileName, MAX_MSG_DATA_LEN);
+
+                       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);
+               MSG_DEBUG("msgText = %s",  pDest->msgText);
+       } else if (pSrc->mainType == MSG_MMS_TYPE) {
+
+               pDest->bTextSms = false;
+               pDest->dataSize = pSrc->dataSize;
+
+               if(pSrc->subType == MSG_READREPLY_MMS) {
+                       memset(pDest->msgData, 0x00, sizeof(pDest->msgData));
+                       memcpy(pDest->msgData, pSrc->pMmsData, pSrc->dataSize);
+               } else {
+                       // 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");
+
+                       // change file extension in case of java MMS msg
+                       if (pSrc->subType == MSG_SENDREQ_JAVA_MMS) {
+                               char* pFileNameExt;
+                               pFileNameExt = strstr(fileName,"DATA");
+                               strncpy(pFileNameExt,"JAVA", MSG_FILENAME_LEN_MAX);
+                       }
+
+                       MSG_DEBUG("Save Message Data into file : size[%d] name[%s]", pDest->dataSize, fileName);
+
+                       if (MsgWriteIpcFile(fileName, (char*)pSrc->pMmsData, pSrc->dataSize) == 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, MAX_MSG_TEXT_LEN);
+                       }
+
+                       if (strlen(pSrc->thumbPath) > 0) {
+                               memset(pDest->thumbPath, 0x00, sizeof(pDest->thumbPath));
+                               memcpy(pDest->thumbPath, pSrc->thumbPath, sizeof(pDest->thumbPath));
+                       }
+               }
+       }
+
+       MSG_END();
+}
+
+
+void MsgHandle::convertMsgStruct(const MSG_MESSAGE_INFO_S *pSrc, MSG_MESSAGE_HIDDEN_S *pDest)
+{
+       MSG_BEGIN();
+
+       pDest->msgId = pSrc->msgId;
+       pDest->threadId = pSrc->threadId;
+       pDest->folderId = pSrc->folderId;
+       pDest->mainType = pSrc->msgType.mainType;
+       pDest->subType = pSrc->msgType.subType;
+       pDest->storageId = pSrc->storageId;
+
+       strncpy(pDest->replyAddress, pSrc->replyAddress, MAX_PHONE_NUMBER_LEN);
+       strncpy(pDest->subject, pSrc->subject, MAX_SUBJECT_LEN);
+
+       pDest->displayTime = pSrc->displayTime;
+       pDest->networkStatus = pSrc->networkStatus;
+       pDest->encodeType = pSrc->encodeType;
+       pDest->bRead = pSrc->bRead;
+       pDest->bProtected = pSrc->bProtected;
+       pDest->bBackup = pSrc->bBackup;
+       pDest->priority = pSrc->priority;
+       pDest->direction = pSrc->direction;
+
+       // Set Port Info.
+       pDest->bPortValid = pSrc->msgPort.valid;
+
+       if (pDest->bPortValid == true) {
+               pDest->dstPort = pSrc->msgPort.dstPort;
+               pDest->srcPort = pSrc->msgPort.srcPort;
+       }
+
+       if(pSrc->thumbPath[0] != '\0')
+               strncpy(pDest->thumbPath, pSrc->thumbPath, MSG_FILEPATH_LEN_MAX);
+
+       pDest->addr_list->nCount = pSrc->nAddressCnt;
+
+       msg_struct_s *addr_info_s = NULL;
+       MSG_ADDRESS_INFO_S *addr_info = NULL;
+
+       for (int i = 0; i < pDest->addr_list->nCount; i++)
+       {
+               addr_info_s = (msg_struct_s *)pDest->addr_list->msg_struct_info[i];
+               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';
+       }
+
+
+       if (pSrc->bTextSms == false) {
+               int fileSize = 0;
+
+               char* pFileData = NULL;
+               AutoPtr<char> buf(&pFileData);
+
+               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);
+                               }
+                       } 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);
+                       }
+               }
+       } else {
+               pDest->dataSize = pSrc->dataSize;
+
+               if (pSrc->msgType.mainType == MSG_SMS_TYPE) {
+                       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);
+                       } else {
+                               pDest->pData = (void*)new char[pDest->dataSize+1];
+                               memset(pDest->pData, 0x00, pDest->dataSize+1);
+                               strncpy((char*)pDest->pData, pSrc->msgText, pDest->dataSize);
+                       }
+               } 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[pDest->dataSize];
+                       memset(pDest->pMmsData, 0x00, pDest->dataSize);
+                       memcpy(pDest->pMmsData, pSrc->msgData, pDest->dataSize);
+               }
+       }
+
+       MSG_END();
+}
+
+
+void MsgHandle::convertSendOptStruct(const MSG_SENDINGOPT_S* pSrc, MSG_SENDINGOPT_INFO_S* pDest, MSG_MESSAGE_TYPE_S msgType)
+{
+       MSG_BEGIN();
+
+       pDest->bSetting = pSrc->bSetting;
+
+       if (pSrc->bSetting == false) {
+               MSG_DEBUG("No Sending Option");
+               return;
+       }
+
+       pDest->bDeliverReq = pSrc->bDeliverReq;
+       pDest->bKeepCopy = pSrc->bKeepCopy;
+
+       MSG_DEBUG("pDest->bSetting = %d", pDest->bSetting);
+       MSG_DEBUG("pDest->bDeliverReq = %d", pDest->bDeliverReq);
+       MSG_DEBUG("pDest->bKeepCopy = %d", pDest->bKeepCopy);
+
+       if (msgType.mainType == MSG_SMS_TYPE) {
+               msg_struct_s *pStruct = (msg_struct_s *)pSrc->smsSendOpt;
+               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;
+               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->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;
+
+                               MSG_DEBUG("pDest->option.mmsSendOpt.expiryTime = %d", pDest->option.mmsSendOptInfo.expiryTime.time);
+                       }
+               }
+       }
+
+       MSG_END();
+}
+
+
+void MsgHandle::convertSendOptStruct(const MSG_SENDINGOPT_INFO_S* pSrc, MSG_SENDINGOPT_S* pDest, MSG_MESSAGE_TYPE_S msgType)
+{
+       MSG_BEGIN();
+
+       pDest->bDeliverReq = pSrc->bDeliverReq;
+       pDest->bKeepCopy = pSrc->bKeepCopy;
+
+       MSG_DEBUG("pDest->bDeliverReq = %d", pDest->bDeliverReq);
+       MSG_DEBUG("pDest->bKeepCopy = %d", pDest->bKeepCopy);
+
+       if (msgType.mainType == MSG_SMS_TYPE) {
+               msg_struct_s *pStruct = (msg_struct_s *)pDest->smsSendOpt;
+               SMS_SENDINGOPT_S *pSms = (SMS_SENDINGOPT_S *)pStruct->data;
+               pSms->bReplyPath = pSrc->option.smsSendOptInfo.bReplyPath;
+       } else if (msgType.mainType == MSG_MMS_TYPE) {
+               msg_struct_s *pStruct = (msg_struct_s *)pDest->mmsSendOpt;
+               MMS_SENDINGOPT_S *pMms = (MMS_SENDINGOPT_S *)pStruct->data;
+               pMms->priority = pSrc->option.mmsSendOptInfo.priority;
+               pMms->bReadReq = pSrc->option.mmsSendOptInfo.bReadReq;
+               pMms->expiryTime = pSrc->option.mmsSendOptInfo.expiryTime.time;
+               pMms->deliveryTime = pSrc->option.mmsSendOptInfo.deliveryTime.time;
+
+               MSG_DEBUG("pDest->option.mmsSendOpt.priority = %d", pMms->priority);
+               MSG_DEBUG("pDest->option.mmsSendOpt.bReadReq = %d", pMms->bReadReq);
+               MSG_DEBUG("pDest->option.mmsSendOpt.expiryTime = %d", pMms->expiryTime);
+       }
+
+       MSG_END();
+}
+
+
+int MsgHandle::getSettingCmdSize(MSG_OPTION_TYPE_T optionType)
+{
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+
+       switch (optionType)
+       {
+               case MSG_GENERAL_OPT :
+                       cmdSize += sizeof(MSG_GENERAL_OPT_S);
+               break;
+               case MSG_SMS_SENDOPT :
+                       cmdSize += sizeof(MSG_SMS_SENDOPT_S);
+               break;
+               case MSG_SMSC_LIST :
+                       cmdSize += sizeof(MSG_SMSC_LIST_S);
+               break;
+               case MSG_MMS_SENDOPT :
+                       cmdSize += sizeof(MSG_MMS_SENDOPT_S);
+               break;
+               case MSG_MMS_RECVOPT :
+                       cmdSize += sizeof(MSG_MMS_RECVOPT_S);
+               break;
+               case MSG_MMS_STYLEOPT :
+                       cmdSize += sizeof(MSG_MMS_STYLEOPT_S);
+               break;
+               case MSG_PUSHMSG_OPT :
+                       cmdSize += sizeof(MSG_PUSHMSG_OPT_S);
+               break;
+               case MSG_CBMSG_OPT :
+                       cmdSize += sizeof(MSG_CBMSG_OPT_S);
+               break;
+               case MSG_VOICEMAIL_OPT :
+                       cmdSize += sizeof(MSG_VOICEMAIL_OPT_S);
+               break;
+               case MSG_MSGSIZE_OPT :
+                       cmdSize += sizeof(MSG_MSGSIZE_OPT_S);
+               break;
+       }
+
+       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_SYNCML_OPERATION :
+       case MSG_EVENT_PLG_STORAGE_CHANGE_IND :
+       case MSG_EVENT_PLG_INCOMING_CB_MSG_IND :
+       case MSG_EVENT_PLG_INCOMING_PUSH_MSG_IND :
+               return false;
+               break;
+       default :
+               return true;
+               break;
+       }
+
+       return true;
+}
diff --git a/proxy/MsgHandleFilter.cpp b/proxy/MsgHandleFilter.cpp
new file mode 100755 (executable)
index 0000000..2e59906
--- /dev/null
@@ -0,0 +1,290 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgHandle.h"
+#include "MsgUtilFunction.h"
+#include "MsgCppTypes.h"
+#include "MsgException.h"
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgHandle - Filter Member Functions
+==================================================================================================*/
+msg_error_t MsgHandle::addFilter(const MSG_FILTER_S *pFilter)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_FILTER_S);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_ADD_FILTER;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pFilter, sizeof(MSG_FILTER_S));
+
+       // 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_ADD_FILTER)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::updateFilter(const MSG_FILTER_S *pFilter)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_FILTER_S);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_UPDATE_FILTER;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pFilter, sizeof(MSG_FILTER_S));
+
+       // 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_UPDATE_FILTER)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::deleteFilter(msg_filter_id_t FilterId)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_filter_id_t);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_DELETE_FILTER;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy(pCmd->cmdData, &FilterId, sizeof(msg_filter_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_DELETE_FILTER)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::getFilterList(msg_struct_list_s *pFilterList)
+{
+       // Allocate Memory to Command Data
+       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_GET_FILTERLIST;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // 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_GET_FILTERLIST)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+
+       // Decode Return Data
+       MsgDecodeFilterList(pEvent->data, pFilterList);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgHandle::setFilterOperation(bool bSetFlag)
+{
+       msg_error_t ret = MSG_SUCCESS;
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + 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_OPERATION;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy(pCmd->cmdData, &bSetFlag, sizeof(bool));
+
+       // 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_SET_FILTER_OPERATION)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       ret = pEvent->result;
+
+       return ret;
+}
+
+
+msg_error_t MsgHandle::getFilterOperation(bool *pSetFlag)
+{
+       msg_error_t ret = MSG_SUCCESS;
+
+       // Allocate Memory to Command Data
+       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_GET_FILTER_OPERATION;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // 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_GET_FILTER_OPERATION)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       ret = pEvent->result;
+
+       // Decode Return Data
+       if (ret == MSG_SUCCESS)
+       {
+               MsgDecodeFilterFlag(pEvent->data, pSetFlag);
+               MSG_DEBUG("Flag : %d", *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;
+       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_SET_FILTER_ACTIVATION)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
diff --git a/proxy/MsgHandleSetting.cpp b/proxy/MsgHandleSetting.cpp
new file mode 100755 (executable)
index 0000000..7da1838
--- /dev/null
@@ -0,0 +1,935 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilFunction.h"
+#include "MsgCppTypes.h"
+#include "MsgException.h"
+#include "MsgHandle.h"
+
+
+#define MSG_TYPE_CHECK(a, b) \
+               ({\
+                       if(a != b) return MSG_ERR_INVALID_PARAMETER; \
+               })\
+
+#define MSG_NULL_CHECK(a) \
+               ({\
+                       if(a == NULL) return MSG_ERR_NULL_POINTER; \
+               })\
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgHandle - Setting Member Functions
+==================================================================================================*/
+
+msg_error_t MsgHandle::getSMSCOption(msg_struct_t msg_struct)
+{
+       msg_struct_s *smsc_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(smsc_opt->type, MSG_STRUCT_SETTING_SMSC_OPT);
+       MSG_NULL_CHECK(smsc_opt->data);
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_SMSC_OPT;
+
+       // Set option type
+       MSG_OPTION_TYPE_T opt_type = MSG_SMSC_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), &opt_type, sizeof(MSG_OPTION_TYPE_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_GET_SMSC_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result == MSG_SUCCESS) {
+               MSG_SMSC_LIST_S smsc_list_tmp = {0,};
+               int dataSize = 0;
+
+               dataSize = sizeof(MSG_SMSC_LIST_S);
+               memcpy(&smsc_list_tmp, pEvent->data, dataSize);
+
+               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;
+
+               msg_struct_s *pStructTmp = NULL;
+
+               for (int i = 0; i < pTmp->smsc_list->nCount; i++) {
+                       pStructTmp = (msg_struct_s *)pTmp->smsc_list->msg_struct_info[i];
+                       memset(pStructTmp->data, 0x00, sizeof(MSG_SMSC_DATA_S));
+                       memcpy(pStructTmp->data, &(smsc_list_tmp.smscData[i]), sizeof(MSG_SMSC_DATA_S));
+               }
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::setSMSCOption(msg_struct_t msg_struct)
+{
+       msg_struct_s *smsc_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(smsc_opt->type, MSG_STRUCT_SETTING_SMSC_OPT);
+       MSG_NULL_CHECK(smsc_opt->data);
+
+       // Allocate Memory to Command Data
+       MSG_OPTION_TYPE_T optionType = MSG_SMSC_LIST;
+       int cmdSize = getSettingCmdSize(optionType);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+       int i = 0;
+
+       msg_struct_s *pTmp = (msg_struct_s *)msg_struct;
+       MSG_SMSC_LIST_HIDDEN_S *pTmpList = (MSG_SMSC_LIST_HIDDEN_S *)pTmp->data;
+
+       MSG_SMSC_LIST_S smsc_list_tmp = {0,};
+
+       smsc_list_tmp.totalCnt = pTmpList->smsc_list->nCount;
+       smsc_list_tmp.selected = pTmpList->selected;
+
+       msg_struct_s *pStructTmp = NULL;
+
+       for (i=0; i < smsc_list_tmp.totalCnt; i++) {
+               pStructTmp = (msg_struct_s *)pTmpList->smsc_list->msg_struct_info[i];
+               MSG_TYPE_CHECK(pStructTmp->type, MSG_STRUCT_SETTING_SMSC_INFO);
+               memcpy(&(smsc_list_tmp.smscData[i]), pStructTmp->data, sizeof(MSG_SMSC_DATA_S));
+       }
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SET_SMSC_OPT;
+
+    // Copy Cookie
+    memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       MSG_SETTING_S pSetting = {0,};
+
+       pSetting.type = optionType;
+       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);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_SET_SMSC_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::getCBOption(msg_struct_t msg_struct)
+{
+       msg_struct_s *cb_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(cb_opt->type, MSG_STRUCT_SETTING_CB_OPT);
+       MSG_NULL_CHECK(cb_opt->data);
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_CB_OPT;
+
+       // Set option type
+       MSG_OPTION_TYPE_T opt_type = MSG_CBMSG_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &opt_type, sizeof(MSG_OPTION_TYPE_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_GET_CB_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result == MSG_SUCCESS) {
+               int i = 0;
+               MSG_CBMSG_OPT_S cb_opt_tmp = {0,};
+               memcpy(&cb_opt_tmp, pEvent->data, sizeof(MSG_CBMSG_OPT_S));
+
+               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;
+
+               for (i = 0; i < CB_LANG_TYPE_MAX; i++)
+                       pTmp->bLanguage[i] = cb_opt_tmp.bLanguage[i];
+
+               pTmp->channelData->nCount = cb_opt_tmp.channelData.channelCnt;
+
+               msg_struct_s *pStructTmp = NULL;
+
+               for (i = 0; i < pTmp->channelData->nCount; i++) {
+                       pStructTmp = (msg_struct_s *)pTmp->channelData->msg_struct_info[i];
+                       memset(pStructTmp->data, 0x00, sizeof(MSG_CB_CHANNEL_INFO_S));
+                       memcpy(pStructTmp->data, &(cb_opt_tmp.channelData.channelInfo[i]), sizeof(MSG_CB_CHANNEL_INFO_S));
+               }
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::setCBOption(msg_struct_t msg_struct)
+{
+       msg_struct_s *cb_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(cb_opt->type, MSG_STRUCT_SETTING_CB_OPT);
+       MSG_NULL_CHECK(cb_opt->data);
+
+       // Allocate Memory to Command Data
+       MSG_OPTION_TYPE_T optionType = MSG_CBMSG_OPT;
+       int cmdSize = getSettingCmdSize(optionType);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+       int i = 0;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SET_CB_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       MSG_CBMSG_OPT_S cb_opt_tmp = {0,};
+       MSG_CBMSG_OPT_HIDDEN_S *cb_msg_opt = (MSG_CBMSG_OPT_HIDDEN_S *)cb_opt->data;
+
+       cb_opt_tmp.bReceive = cb_msg_opt->bReceive;
+       cb_opt_tmp.maxSimCnt = cb_msg_opt->maxSimCnt;
+       for (int i = 0; i < CB_LANG_TYPE_MAX; i++)
+               cb_opt_tmp.bLanguage[i] = cb_msg_opt->bLanguage[i];
+
+       msg_struct_list_s *cb_ch_list = cb_msg_opt->channelData;
+       msg_struct_s *pStructTmp = NULL;
+
+       cb_opt_tmp.channelData.channelCnt = cb_ch_list->nCount;
+
+       for (i = 0; i < cb_opt_tmp.channelData.channelCnt; i++) {
+               pStructTmp = (msg_struct_s *)cb_ch_list->msg_struct_info[i];
+               memcpy(&(cb_opt_tmp.channelData.channelInfo[i]), pStructTmp->data, sizeof(MSG_CB_CHANNEL_INFO_S));
+       }
+
+       MSG_SETTING_S pSetting = {0,};
+       pSetting.type = optionType;
+
+       memcpy(&(pSetting.option.cbMsgOpt), &cb_opt_tmp, sizeof(MSG_CBMSG_OPT_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);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_SET_CB_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::getSmsSendOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *sms_send_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(sms_send_opt->type, MSG_STRUCT_SETTING_SMS_SEND_OPT);
+       MSG_NULL_CHECK(sms_send_opt->data);
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_SMS_SEND_OPT;
+
+       // Set option type
+       MSG_OPTION_TYPE_T opt_type = MSG_SMS_SENDOPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &opt_type, sizeof(MSG_OPTION_TYPE_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_GET_SMS_SEND_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result == MSG_SUCCESS) {
+               memcpy(sms_send_opt->data, pEvent->data, sizeof(MSG_SMS_SENDOPT_S));
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::setSmsSendOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *sms_send_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(sms_send_opt->type, MSG_STRUCT_SETTING_SMS_SEND_OPT);
+       MSG_NULL_CHECK(sms_send_opt->data);
+
+       // Allocate Memory to Command Data
+       MSG_OPTION_TYPE_T optionType = MSG_SMS_SENDOPT;
+       int cmdSize = getSettingCmdSize(optionType);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SET_SMS_SEND_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       MSG_SETTING_S pSetting = {0,};
+       pSetting.type = optionType;
+
+       memcpy(&(pSetting.option.smsSendOpt), sms_send_opt->data, sizeof(MSG_SMS_SENDOPT_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);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_SET_SMS_SEND_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::getMmsSendOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *mms_send_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(mms_send_opt->type, MSG_STRUCT_SETTING_MMS_SEND_OPT);
+       MSG_NULL_CHECK(mms_send_opt->data);
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_MMS_SEND_OPT;
+
+       // Set option type
+       MSG_OPTION_TYPE_T opt_type = MSG_MMS_SENDOPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &opt_type, sizeof(MSG_OPTION_TYPE_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_GET_MMS_SEND_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result == MSG_SUCCESS) {
+               memcpy(mms_send_opt->data, pEvent->data, sizeof(MSG_MMS_SENDOPT_S));
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::setMmsSendOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *mms_send_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(mms_send_opt->type, MSG_STRUCT_SETTING_MMS_SEND_OPT);
+       MSG_NULL_CHECK(mms_send_opt->data);
+
+       // Allocate Memory to Command Data
+       MSG_OPTION_TYPE_T optionType = MSG_MMS_SENDOPT;
+       int cmdSize = getSettingCmdSize(optionType);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SET_MMS_SEND_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       MSG_SETTING_S pSetting = {0,};
+       pSetting.type = optionType;
+
+       memcpy(&(pSetting.option.mmsSendOpt), mms_send_opt->data, sizeof(MSG_MMS_SENDOPT_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);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_SET_MMS_SEND_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::getMmsRecvOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *mms_recv_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(mms_recv_opt->type, MSG_STRUCT_SETTING_MMS_RECV_OPT);
+       MSG_NULL_CHECK(mms_recv_opt->data);
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_MMS_RECV_OPT;
+
+       // Set option type
+       MSG_OPTION_TYPE_T opt_type = MSG_MMS_RECVOPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &opt_type, sizeof(MSG_OPTION_TYPE_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_GET_MMS_RECV_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result == MSG_SUCCESS) {
+               memcpy(mms_recv_opt->data, pEvent->data, sizeof(MSG_MMS_RECVOPT_S));
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::setMmsRecvOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *mms_recv_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(mms_recv_opt->type, MSG_STRUCT_SETTING_MMS_RECV_OPT);
+       MSG_NULL_CHECK(mms_recv_opt->data);
+
+       // Allocate Memory to Command Data
+       MSG_OPTION_TYPE_T optionType = MSG_MMS_RECVOPT;
+       int cmdSize = getSettingCmdSize(optionType);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SET_MMS_RECV_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       MSG_SETTING_S pSetting = {0,};
+       pSetting.type = optionType;
+
+       memcpy(&(pSetting.option.mmsRecvOpt), mms_recv_opt->data, sizeof(MSG_MMS_RECVOPT_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);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_SET_MMS_RECV_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::getPushMsgOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *push_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(push_opt->type, MSG_STRUCT_SETTING_PUSH_MSG_OPT);
+       MSG_NULL_CHECK(push_opt->data);
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_PUSH_MSG_OPT;
+
+       // Set option type
+       MSG_OPTION_TYPE_T opt_type = MSG_PUSHMSG_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &opt_type, sizeof(MSG_OPTION_TYPE_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_GET_PUSH_MSG_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result == MSG_SUCCESS) {
+               memcpy(push_opt->data, pEvent->data, sizeof(MSG_PUSHMSG_OPT_S));
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::setPushMsgOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *push_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(push_opt->type, MSG_STRUCT_SETTING_PUSH_MSG_OPT);
+       MSG_NULL_CHECK(push_opt->data);
+
+       // Allocate Memory to Command Data
+       MSG_OPTION_TYPE_T optionType = MSG_PUSHMSG_OPT;
+       int cmdSize = getSettingCmdSize(optionType);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SET_PUSH_MSG_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       MSG_SETTING_S pSetting = {0,};
+       pSetting.type = optionType;
+
+       memcpy(&(pSetting.option.pushMsgOpt), push_opt->data, sizeof(MSG_PUSHMSG_OPT_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);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_SET_PUSH_MSG_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::getVoiceMsgOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *voice_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(voice_opt->type, MSG_STRUCT_SETTING_VOICE_MSG_OPT);
+       MSG_NULL_CHECK(voice_opt->data);
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_VOICE_MSG_OPT;
+
+       // Set option type
+       MSG_OPTION_TYPE_T opt_type = MSG_VOICEMAIL_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &opt_type, sizeof(MSG_OPTION_TYPE_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_GET_VOICE_MSG_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result == MSG_SUCCESS) {
+               memcpy(voice_opt->data, pEvent->data, sizeof(MSG_VOICEMAIL_OPT_S));
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::setVoiceMsgOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *voice_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(voice_opt->type, MSG_STRUCT_SETTING_VOICE_MSG_OPT);
+       MSG_NULL_CHECK(voice_opt->data);
+
+       // Allocate Memory to Command Data
+       MSG_OPTION_TYPE_T optionType = MSG_VOICEMAIL_OPT;
+       int cmdSize = getSettingCmdSize(optionType);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SET_VOICE_MSG_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       MSG_SETTING_S pSetting = {0,};
+       pSetting.type = optionType;
+
+       memcpy(&(pSetting.option.voiceMailOpt), voice_opt->data, sizeof(MSG_VOICEMAIL_OPT_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);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_SET_VOICE_MSG_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::getGeneralOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *general_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(general_opt->type, MSG_STRUCT_SETTING_GENERAL_OPT);
+       MSG_NULL_CHECK(general_opt->data);
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_GENERAL_MSG_OPT;
+
+       // Set option type
+       MSG_OPTION_TYPE_T opt_type = MSG_GENERAL_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &opt_type, sizeof(MSG_OPTION_TYPE_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_GET_GENERAL_MSG_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result == MSG_SUCCESS) {
+               memcpy(general_opt->data, pEvent->data, sizeof(MSG_GENERAL_OPT_S));
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::setGeneralOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *general_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(general_opt->type, MSG_STRUCT_SETTING_GENERAL_OPT);
+       MSG_NULL_CHECK(general_opt->data);
+
+       // Allocate Memory to Command Data
+       MSG_OPTION_TYPE_T optionType = MSG_GENERAL_OPT;
+       int cmdSize = getSettingCmdSize(optionType);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SET_GENERAL_MSG_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       MSG_SETTING_S pSetting = {0,};
+       pSetting.type = optionType;
+
+       memcpy(&(pSetting.option.generalOpt), general_opt->data, sizeof(MSG_GENERAL_OPT_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);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_SET_GENERAL_MSG_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::getMsgSizeOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *msg_size_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(msg_size_opt->type, MSG_STRUCT_SETTING_MSGSIZE_OPT);
+       MSG_NULL_CHECK(msg_size_opt->data);
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_OPTION_TYPE_T);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_MSG_SIZE_OPT;
+
+       // Set option type
+       MSG_OPTION_TYPE_T opt_type = MSG_MSGSIZE_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &opt_type, sizeof(MSG_OPTION_TYPE_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_GET_MSG_SIZE_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result == MSG_SUCCESS) {
+               memcpy(msg_size_opt->data, pEvent->data, sizeof(MSG_MSGSIZE_OPT_S));
+       }
+
+       return pEvent->result;
+}
+
+msg_error_t MsgHandle::setMsgSizeOpt(msg_struct_t msg_struct)
+{
+       msg_struct_s *msg_size_opt = (msg_struct_s *)msg_struct;
+       MSG_TYPE_CHECK(msg_size_opt->type, MSG_STRUCT_SETTING_MSGSIZE_OPT);
+       MSG_NULL_CHECK(msg_size_opt->data);
+
+       // Allocate Memory to Command Data
+       MSG_OPTION_TYPE_T optionType = MSG_MSGSIZE_OPT;
+       int cmdSize = getSettingCmdSize(optionType);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SET_MSG_SIZE_OPT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       MSG_SETTING_S pSetting = {0,};
+       pSetting.type = optionType;
+
+       memcpy(&(pSetting.option.msgSizeOpt), msg_size_opt->data, sizeof(MSG_MSGSIZE_OPT_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);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_SET_MSG_SIZE_OPT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
diff --git a/proxy/MsgHandleStorage.cpp b/proxy/MsgHandleStorage.cpp
new file mode 100755 (executable)
index 0000000..b530d35
--- /dev/null
@@ -0,0 +1,1644 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgException.h"
+#include "MsgUtilFunction.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 = {0,};
+
+       // Covert MSG_MESSAGE_S to MSG_MESSAGE_INFO_S
+       convertMsgStruct(pMsg, &msgInfo);
+
+       // Covert MSG_SENDINGOPT_S to MSG_SENDINGOPT_INFO_S
+       MSG_MESSAGE_TYPE_S msgType = {0,};
+
+       msgType.mainType = pMsg->mainType;
+       msgType.subType = pMsg->subType;
+       msgType.classType = pMsg->classType;
+
+       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 cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_ADD_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), &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));
+
+       // 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_ADD_MSG)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if (pEvent->result != MSG_SUCCESS) return pEvent->result;
+
+       msg_message_id_t msgId = 0;
+
+       // Decode Return Data
+       MsgDecodeMsgId(pEvent->data, &msgId);
+
+       return (int)msgId;
+}
+
+
+msg_error_t MsgHandle::addSyncMLMessage(const MSG_SYNCML_MESSAGE_S *pSyncMLMsg)
+{
+       MSG_MESSAGE_INFO_S msgInfo = {0, };
+
+       // 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 cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_ADD_SYNCML_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), &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));
+
+       // 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_ADD_SYNCML_MSG)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::updateMessage(const MSG_MESSAGE_HIDDEN_S *pMsg, const MSG_SENDINGOPT_S *pSendOpt)
+{
+       MSG_MESSAGE_INFO_S msgInfo = {0, };
+       MSG_SENDINGOPT_INFO_S sendOptInfo = {0, };
+
+       // Covert MSG_MESSAGE_S to MSG_MESSAGE_INFO_S
+       convertMsgStruct(pMsg, &msgInfo);
+
+       if(pSendOpt != NULL) {
+               MSG_MESSAGE_TYPE_S msgType = {0,};
+
+               msgType.mainType = pMsg->mainType;
+               msgType.subType = pMsg->subType;
+               msgType.classType = pMsg->classType;
+
+               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 cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_UPDATE_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), &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));
+
+       // 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_UPDATE_MSG)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::updateReadStatus(msg_message_id_t MsgId, bool bRead)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_message_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_UPDATE_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), &MsgId, sizeof(msg_message_id_t));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_message_id_t)), &bRead, sizeof(bool));
+
+       // 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_UPDATE_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
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_message_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_UPDATE_PROTECTED;
+
+       // 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));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_message_id_t)), &bProtected, sizeof(bool));
+
+       // 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_UPDATE_PROTECTED)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::deleteMessage(msg_message_id_t MsgId)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_message_id_t);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_DELETE_MSG;
+
+       // Copy Cookie
+       memcpy((void*)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;
+       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_DELETE_MSG)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::deleteAllMessagesInFolder(msg_folder_id_t FolderId, bool bOnlyDB)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_folder_id_t);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_DELALL_MSGINFOLDER;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &FolderId, sizeof(msg_folder_id_t));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_folder_id_t)), &bOnlyDB, sizeof(bool));
+
+       // 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_DELALL_MSGINFOLDER)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+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;
+       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_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
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_message_id_t) + sizeof(msg_folder_id_t);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_MOVE_MSGTOFOLDER;
+
+       // 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));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+sizeof(msg_message_id_t)+MAX_COOKIE_LEN), &DestFolderId, sizeof(msg_folder_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_MOVE_MSGTOFOLDER)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::moveMessageToStorage(msg_message_id_t MsgId, msg_storage_id_t DestStorageId)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_message_id_t) + sizeof(msg_storage_id_t);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_MOVE_MSGTOSTORAGE;
+
+       // 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));
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN+sizeof(msg_message_id_t)), &DestStorageId, sizeof(msg_storage_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_MOVE_MSGTOSTORAGE)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::countMessage(msg_folder_id_t FolderId, MSG_COUNT_INFO_S *pCountInfo)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_folder_id_t);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_COUNT_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), &FolderId, sizeof(msg_folder_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_COUNT_MSG)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+
+       // Decode Return Data
+       MsgDecodeCountInfo(pEvent->data, pCountInfo);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgHandle::countMsgByType(const MSG_MESSAGE_TYPE_S *pMsgType, int *pMsgCount)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_MESSAGE_TYPE_S);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_COUNT_BY_MSGTYPE;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pMsgType, sizeof(MSG_MESSAGE_TYPE_S));
+
+       // 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_COUNT_BY_MSGTYPE)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       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));
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgHandle::countMsgByContact(const MSG_THREAD_LIST_INDEX_INFO_S *pAddrInfo, MSG_THREAD_COUNT_INFO_S *pMsgThreadCountList)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) +  sizeof(MSG_THREAD_LIST_INDEX_S);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_CONTACT_COUNT;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pAddrInfo, sizeof(msg_contact_id_t));
+       msg_struct_s *pAddr = (msg_struct_s *)pAddrInfo->msgAddrInfo;
+
+       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);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_GET_CONTACT_COUNT)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+
+       // Decode Return Data
+       MsgDecodeContactCount(pEvent->data, pMsgThreadCountList);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgHandle::getMessage(msg_message_id_t MsgId, MSG_MESSAGE_HIDDEN_S *pMsg, MSG_SENDINGOPT_S *pSendOpt)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_message_id_t);
+
+       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;
+       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_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;
+       MSG_SENDINGOPT_INFO_S sendOptInfo;
+       MsgDecodeMsgInfo(pEvent->data, &msgInfo, &sendOptInfo);
+
+       // Covert MSG_MESSAGE_INFO_S to MSG_MESSAGE_HIDDEN_S
+       convertMsgStruct(&msgInfo, pMsg);
+
+       if(pSendOpt != NULL) {
+               MSG_MESSAGE_TYPE_S msgType = {0,};
+
+               msgType.mainType = pMsg->mainType;
+               msgType.subType = pMsg->subType;
+               msgType.classType = pMsg->classType;
+
+               convertSendOptStruct(&sendOptInfo, pSendOpt, msgType);
+       }
+
+       // Delete Temp File
+       if (msgInfo.bTextSms == false)
+       {
+               // Delete Temp File
+               MsgDeleteFile(msgInfo.msgData); //ipc
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgHandle::getFolderViewList(msg_folder_id_t FolderId, const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pMsgFolderViewList)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       err = MsgStoConnectDB();
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgStoConnectDB() Error!!");
+               return err;
+       }
+
+       err = MsgStoGetFolderViewList(FolderId, (MSG_SORT_RULE_S *)pSortRule, pMsgFolderViewList);
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgStoGetFolderViewList() Error!!");
+               return err;
+       }
+
+       MsgStoDisconnectDB();
+
+       return err;
+}
+
+
+msg_error_t MsgHandle::addFolder(const MSG_FOLDER_INFO_S *pFolderInfo)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_FOLDER_INFO_S);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_ADD_FOLDER;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pFolderInfo, sizeof(MSG_FOLDER_INFO_S));
+
+       // 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_ADD_FOLDER)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::updateFolder(const MSG_FOLDER_INFO_S *pFolderInfo)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_FOLDER_INFO_S);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_UPDATE_FOLDER;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), pFolderInfo, sizeof(MSG_FOLDER_INFO_S));
+
+       // 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_UPDATE_FOLDER)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;;
+}
+
+
+msg_error_t MsgHandle::deleteFolder(msg_folder_id_t FolderId)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_folder_id_t);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_DELETE_FOLDER;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &FolderId, sizeof(msg_folder_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_DELETE_FOLDER)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::getFolderList(msg_struct_list_s *pFolderList)
+{
+       // Allocate Memory to Command Data
+       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_GET_FOLDERLIST;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // 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_GET_FOLDERLIST)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+
+       // Decode Return Data
+       MsgDecodeFolderList(pEvent->data, pFolderList);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgHandle::getThreadViewList(const MSG_SORT_RULE_S *pSortRule, msg_struct_list_s *pThreadViewList)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       err = MsgStoConnectDB();
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgStoConnectDB() Error!!");
+               return err;
+       }
+
+       err = MsgStoGetThreadViewList(pSortRule, pThreadViewList);
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgStoGetThreadViewList() Error!!");
+               return err;
+       }
+
+       MsgStoDisconnectDB();
+
+       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;
+
+
+// Update Read Status for the Thead ID
+#if 1
+       // 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;
+       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_UPDATE_THREAD_READ)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+#endif
+
+       MSG_END();
+
+       return err;
+}
+
+
+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_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_DELETE_THREADMESSAGELIST;
+
+       // 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));
+       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);
+
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_DELETE_THREADMESSAGELIST)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgHandle::getQuickPanelData(msg_quickpanel_type_t Type, MSG_MESSAGE_HIDDEN_S *pMsg)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_quickpanel_type_t);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_QUICKPANEL_DATA;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &Type, sizeof(msg_quickpanel_type_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_GET_QUICKPANEL_DATA)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       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));
+
+       // Covert MSG_MESSAGE_INFO_S to MSG_MESSAGE_S
+       convertMsgStruct(&msgInfo, pMsg);
+
+       // Delete Temp File
+       if (msgInfo.bTextSms == false)
+       {
+               // Delete Temp File
+               MsgDeleteFile(msgInfo.msgData); //ipc
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgHandle::resetDatabase()
+{
+       // Allocate Memory to Command Data
+       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_RESET_DB;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // 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_RESET_DB)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::getMemSize(unsigned int* memsize)
+{
+       // Allocate Memory to Command Data
+       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_GET_MEMSIZE;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // 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_GET_MEMSIZE)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+
+       // Decode Return Data
+       MsgDecodeMemSize(pEvent->data, memsize);
+
+       return MSG_SUCCESS;
+}
+
+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.
+       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) + sizeof(msg_message_backup_type_t) + sizeof(path);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_BACKUP_MESSAGE;
+
+       // 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);
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_BACKUP_MESSAGE)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+
+       return MSG_SUCCESS;
+}
+
+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) + sizeof(path);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_RESTORE_MESSAGE;
+
+       // 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);
+
+
+       write((char*)pCmd, cmdSize, &pEventData);
+
+       // Get Return Data
+       MSG_EVENT_S* pEvent = (MSG_EVENT_S*)pEventData;
+
+       if (pEvent->eventType != MSG_EVENT_RESTORE_MESSAGE)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgHandle::searchMessage(const char *pSearchString, msg_struct_list_s *pThreadViewList)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       err = MsgStoConnectDB();
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgStoConnectDB() Error!!");
+               return err;
+       }
+
+       err = MsgStoSearchMessage(pSearchString, pThreadViewList);
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgStoSearchMessage() Error!!");
+               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();
+
+       return err;
+}
+
+
+msg_error_t MsgHandle::getRejectMsgList(const char *pNumber, msg_struct_list_s *pRejectMsgList)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       err = MsgStoConnectDB();
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgStoConnectDB() Error!!");
+               return err;
+       }
+
+       err = MsgStoGetRejectMsgList(pNumber, pRejectMsgList);
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgStoGetRejectMsgList() Error!!");
+               return err;
+       }
+
+       MsgStoDisconnectDB();
+
+       return err;
+}
+
+
+msg_error_t MsgHandle::regStorageChangeCallback(msg_storage_change_cb onStorageChange, void *pUserParam)
+{
+       if (!onStorageChange)
+               THROW(MsgException::INVALID_PARAM, "onStorageChange is null");
+
+       MsgProxyListener* eventListener = MsgProxyListener::instance();
+
+       eventListener->start();
+
+       if (eventListener->regStorageChangeEventCB(this, onStorageChange, pUserParam) == false) // callback was already registered, just return SUCCESS
+               return MSG_SUCCESS;
+
+       // 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_STORAGE_CHANGE_CB;
+
+       // 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);
+
+       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);
+
+       // 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_REG_STORAGE_CHANGE_CB)
+       {
+               THROW(MsgException::INVALID_PARAM, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+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);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_GET_REPORT_STATUS;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       // Copy Command Data
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &msg_id, sizeof(msg_message_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_GET_REPORT_STATUS)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       if(pEvent->result != MSG_SUCCESS) return pEvent->result;
+
+       // Decode Return Data
+       MsgDecodeReportStatus(pEvent->data, report_list);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgHandle::getAddressList(const msg_thread_id_t threadId, msg_struct_list_s *pAddrList)
+{
+       msg_error_t err =  MSG_SUCCESS;
+
+       err = MsgStoConnectDB();
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgStoConnectDB() Error!!");
+               return err;
+       }
+
+       err = MsgStoGetAddressList(threadId, (msg_struct_list_s *)pAddrList);
+
+       if (err != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgStoGetThreadViewList() Error!!");
+               return err;
+       }
+
+       MsgStoDisconnectDB();
+
+       return err;
+}
+
+
+msg_error_t MsgHandle::getThreadIdByAddress(msg_struct_list_s *pAddrList, msg_thread_id_t *pThreadId)
+{
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(pAddrList->nCount) + (sizeof(MSG_ADDRESS_INFO_S)*pAddrList->nCount);
+
+       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), &pAddrList->nCount, sizeof(pAddrList->nCount));
+       int addSize = sizeof(MSG_ADDRESS_INFO_S);
+       for(int i=0; i<pAddrList->nCount; i++) {
+               memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+sizeof(pAddrList->nCount)+(addSize*i)+MAX_COOKIE_LEN), ((msg_struct_s *)(pAddrList->msg_struct_info[i]))->data, sizeof(MSG_ADDRESS_INFO_S));
+       }
+
+       // 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_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::getThread(msg_thread_id_t threadId, MSG_THREAD_VIEW_S* pThreadInfo)
+{
+       // 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_GET_THREAD_INFO;
+
+       // 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;
+       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_GET_THREAD_INFO)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       // Decode Return Data
+       MsgDecodeThreadInfo(pEvent->data, pThreadInfo);
+
+       return MSG_SUCCESS;
+}
+
+
+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 err =  MSG_SUCCESS;
+
+       err = MsgStoConnectDB();
+
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("MsgStoConnectDB() Error!!");
+               return err;
+       }
+
+       err = MsgStoGetMessageList(folderId, threadId, msgType, storageId, pMsgList);
+
+       if (err != MSG_SUCCESS) {
+               MSG_DEBUG("MsgStoSearchMessage() 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;
+       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_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;
+       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_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;
+       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_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;
+       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_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,};
+
+       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;
+}
diff --git a/proxy/MsgHandleTransport.cpp b/proxy/MsgHandleTransport.cpp
new file mode 100755 (executable)
index 0000000..daf73f6
--- /dev/null
@@ -0,0 +1,677 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <errno.h>
+
+#include "MsgDebug.h"
+#include "MsgCppTypes.h"
+#include "MsgException.h"
+#include "MsgProxyListener.h"
+#include "MsgHandle.h"
+
+
+#define MAX_ADDRESS_LEN                        21 // including '+'
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgHandle - Transport Member Functions
+==================================================================================================*/
+msg_error_t MsgHandle::submitReq(MSG_REQUEST_S* pReq)
+{
+       MSG_BEGIN();
+
+       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};
+
+       msg_struct_s *msg_s = (msg_struct_s *)pReq->msg;
+
+       MSG_MESSAGE_HIDDEN_S *reqmsg = (MSG_MESSAGE_HIDDEN_S*)msg_s->data;
+
+       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 );
+                               return MSG_ERR_INVALID_MESSAGE;
+                       }
+               }
+
+               /* Begin: Setting default values for submit request */
+       //      pReq->msg.msgId = 0;    // Set Request ID: internal use
+       //      pReq->msg.folderId = MSG_OUTBOX_ID;     // Set Folder ID
+               if (reqmsg->subType == MSG_RETRIEVE_MMS) {
+                       reqmsg->networkStatus = MSG_NETWORK_RETRIEVING;
+               } else {
+                       reqmsg->networkStatus = MSG_NETWORK_SENDING;
+               }
+
+               reqmsg->bRead = false;
+               reqmsg->bProtected = false;
+               reqmsg->priority = MSG_MESSAGE_PRIORITY_NORMAL;
+               reqmsg->direction = MSG_DIRECTION_TYPE_MO;
+               reqmsg->storageId = MSG_STORAGE_PHONE;
+
+               time_t curTime = time(NULL);
+
+               if (curTime < 0)
+                       THROW(MsgException::INVALID_RESULT, "time error : %s", strerror(errno));
+
+               reqmsg->displayTime = curTime;
+               /* End : Setting default values for submit request */
+       } else {
+               //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);
+       }
+
+       // Convert MSG_MESSAGE_S to MSG_MESSAGE_INFO_S
+       convertMsgStruct(reqmsg, &(reqInfo.msgInfo));
+
+       /* Check address validation */
+       if (reqInfo.msgInfo.msgType.mainType == MSG_SMS_TYPE) {
+               for(int i=0; i<reqmsg->addr_list->nCount; i++) {
+                               if (reqInfo.msgInfo.addressList[i].addressVal[0] == '+' && strlen(reqInfo.msgInfo.addressList[i].addressVal)>MAX_ADDRESS_LEN) {
+                                       return MSG_ERR_INVALID_PARAMETER;
+                               } else if (strlen(reqInfo.msgInfo.addressList[i].addressVal)>(MAX_ADDRESS_LEN-1)) {
+                                       return MSG_ERR_INVALID_PARAMETER;
+                               }
+               }
+       }
+
+       MSG_MESSAGE_TYPE_S msgType = {0,};
+
+       msgType.mainType = reqmsg->mainType;
+       msgType.subType = reqmsg->subType;
+       msgType.classType = reqmsg->classType;
+
+       convertSendOptStruct((const MSG_SENDINGOPT_S *)pReq->sendOpt, &(reqInfo.sendOptInfo), msgType);
+
+       reqInfo.reqId = 0;
+
+       /* Register proxy info used for receiving sent status */
+       MSG_PROXY_INFO_S chInfo = {0};
+
+       chInfo.listenerFd = MsgProxyListener::instance()->getRemoteFd();
+
+       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);
+
+       // In case of JAVA MMS msg, add trId
+       if (reqmsg->subType == MSG_SENDREQ_JAVA_MMS)
+               cmdSize += sizeof(trId);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SUBMIT_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), &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));
+
+       // 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));
+
+       // 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;
+
+       int* pReqId = (int*) pEvent->data;
+       pReq->reqId = *pReqId;
+       MSG_DEBUG("SENT_REQ_ID: %d", pReq->reqId);
+
+       if (pEvent->eventType != MSG_EVENT_SUBMIT_REQ)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       MSG_END();
+
+       return pEvent->result;
+}
+
+
+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)
+               THROW(MsgException::INVALID_PARAM, "onStatusChanged is null");
+
+       MsgProxyListener* eventListener = MsgProxyListener::instance();
+
+       eventListener->start();
+
+       if (eventListener->regSentStatusEventCB(this, onStatusChanged, pUserParam) == false) // callback was already registered, just return SUCCESS
+               return MSG_SUCCESS;
+
+       // 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_SENT_STATUS_CB;
+
+       // 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);
+
+       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);
+
+       // 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_REG_SENT_STATUS_CB)
+       {
+               THROW(MsgException::INVALID_PARAM, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::regSmsMessageCallback(msg_sms_incoming_cb onMsgIncoming, unsigned short port, void *pUserParam)
+{
+       if( (!onMsgIncoming) )
+               THROW(MsgException::INVALID_PARAM, "Param %p", onMsgIncoming);
+
+       MsgProxyListener* eventListener = MsgProxyListener::instance();
+
+       eventListener->start();
+
+       if (eventListener->regMessageIncomingEventCB(this, onMsgIncoming, port, pUserParam) == false) // callback was already registered, just return SUCCESS
+               return MSG_SUCCESS;
+
+       // 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
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_REG_INCOMING_MSG_CB;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       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.msgType = MSG_SMS_TYPE;
+       cmdParam.port = port;
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &cmdParam, sizeof(cmdParam));
+
+       MSG_DEBUG("reg new msg [%s], fd %d, port %d", MsgDbgCmdStr(pCmd->cmdType), cmdParam.listenerFd, cmdParam.port);
+
+       // 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_REG_INCOMING_MSG_CB)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::regMmsConfMessageCallback(msg_mms_conf_msg_incoming_cb onMMSConfMsgIncoming, const char *pAppId, void *pUserParam)
+{
+       if( (!onMMSConfMsgIncoming) )
+               THROW(MsgException::INVALID_PARAM, "Param %p", onMMSConfMsgIncoming);
+
+       MsgProxyListener* eventListener = MsgProxyListener::instance();
+
+       eventListener->start();
+
+       if (eventListener->regMMSConfMessageIncomingEventCB(this, onMMSConfMsgIncoming, pAppId, pUserParam) == false) // callback was already registered, just return SUCCESS
+               return MSG_SUCCESS;
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(MSG_CMD_REG_INCOMING_MMS_CONF_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_MMS_CONF_MSG_CB;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       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.msgType = MSG_MMS_TYPE;
+
+       if (pAppId)
+               strncpy(cmdParam.appId, pAppId, MAX_MMS_JAVA_APPID_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;
+       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_REG_INCOMING_MMS_CONF_MSG_CB)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::regSyncMLMessageCallback(msg_syncml_msg_incoming_cb onSyncMLMsgIncoming, void *pUserParam)
+{
+       if( (!onSyncMLMsgIncoming) )
+               THROW(MsgException::INVALID_PARAM, "Param %p", onSyncMLMsgIncoming);
+
+       MsgProxyListener* eventListener = MsgProxyListener::instance();
+
+       eventListener->start();
+
+       if (eventListener->regSyncMLMessageIncomingEventCB(this, onSyncMLMsgIncoming, pUserParam) == false) // callback was already registered, just return SUCCESS
+               return MSG_SUCCESS;
+
+       // 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
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_REG_INCOMING_SYNCML_MSG_CB;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       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.msgType = MSG_SMS_TYPE;
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &cmdParam, sizeof(cmdParam));
+
+       MSG_DEBUG("reg new msg [%s], fd %d", MsgDbgCmdStr(pCmd->cmdType), cmdParam.listenerFd);
+
+       // 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_REG_INCOMING_SYNCML_MSG_CB)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::regLBSMessageCallback(msg_lbs_msg_incoming_cb onLBSMsgIncoming, void *pUserParam)
+{
+       if( (!onLBSMsgIncoming) )
+               THROW(MsgException::INVALID_PARAM, "Param %p", onLBSMsgIncoming);
+
+       MsgProxyListener* eventListener = MsgProxyListener::instance();
+
+       eventListener->start();
+
+       if (eventListener->regLBSMessageIncomingEventCB(this, onLBSMsgIncoming, pUserParam) == false) // callback was already registered, just return SUCCESS
+               return MSG_SUCCESS;
+
+       // 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
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_REG_INCOMING_LBS_MSG_CB;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       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.msgType = MSG_SMS_TYPE;
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &cmdParam, sizeof(cmdParam));
+
+       MSG_DEBUG("reg new msg [%s], fd %d", MsgDbgCmdStr(pCmd->cmdType), cmdParam.listenerFd);
+
+       // 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_REG_INCOMING_LBS_MSG_CB)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::regSyncMLMessageOperationCallback(msg_syncml_msg_operation_cb onSyncMLMsgOperation, void *pUserParam)
+{
+       if( (!onSyncMLMsgOperation) )
+               THROW(MsgException::INVALID_PARAM, "Param %p", onSyncMLMsgOperation);
+
+       MsgProxyListener* eventListener = MsgProxyListener::instance();
+
+       eventListener->start();
+
+       if (eventListener->regSyncMLMessageOperationEventCB(this, onSyncMLMsgOperation, pUserParam) == false) // callback was already registered, just return SUCCESS
+               return MSG_SUCCESS;
+
+       // 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
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+
+       MSG_CMD_S* pCmd = (MSG_CMD_S*) cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_REG_SYNCML_MSG_OPERATION_CB;
+
+       // Copy Cookie
+       memcpy(pCmd->cmdCookie, mCookie, MAX_COOKIE_LEN);
+
+       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.msgType = MSG_SMS_TYPE;
+
+       memcpy((void*)((char*)pCmd+sizeof(MSG_CMD_TYPE_T)+MAX_COOKIE_LEN), &cmdParam, sizeof(cmdParam));
+
+       MSG_DEBUG("register syncML msg operation callback [%s], fd %d", MsgDbgCmdStr(pCmd->cmdType), cmdParam.listenerFd);
+
+       // 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_REG_SYNCML_MSG_OPERATION_CB)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       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();
+
+       if (eventListener->regPushMessageIncomingEventCB(this, onPushMsgIncoming, pAppId, pUserParam) == false) // callback was already registered, just return SUCCESS
+               return MSG_SUCCESS;
+
+       // 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 = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+       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;
+       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_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();
+
+       if (eventListener->regCBMessageIncomingEventCB(this, onCBIncoming, bSave, pUserParam) == false) // callback was already registered, just return SUCCESS
+               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 = eventListener->getRemoteFd(); // fd that is reserved to the "listener thread" by msgfw daemon
+       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", MsgDbgCmdStr(pCmd->cmdType), cmdParam.listenerFd);
+
+       // 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_REG_INCOMING_CB_MSG_CB)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
+
+msg_error_t MsgHandle::operateSyncMLMessage(msg_message_id_t msgId)
+{
+       if( msgId < 1)
+               THROW(MsgException::INVALID_PARAM, "Param msgId %d", msgId);
+
+       // Allocate Memory to Command Data
+       int cmdSize = sizeof(MSG_CMD_S) + sizeof(msg_message_id_t);
+
+       char cmdBuf[cmdSize];
+       bzero(cmdBuf, cmdSize);
+       MSG_CMD_S* pCmd = (MSG_CMD_S*)cmdBuf;
+
+       // Set Command Parameters
+       pCmd->cmdType = MSG_CMD_SYNCML_OPERATION;
+
+       // 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;
+       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_SYNCML_OPERATION)
+       {
+               THROW(MsgException::INVALID_RESULT, "Event Data Error");
+       }
+
+       return pEvent->result;
+}
+
diff --git a/proxy/MsgProxyListener.cpp b/proxy/MsgProxyListener.cpp
new file mode 100755 (executable)
index 0000000..931034e
--- /dev/null
@@ -0,0 +1,1009 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilFile.h"
+#include "MsgProxyListener.h"
+#include "MsgGconfWrapper.h"
+
+
+gboolean readSocket(GIOChannel *source, GIOCondition condition, gpointer data)
+{
+       MSG_BEGIN();
+
+       if (G_IO_ERR & condition)
+       {
+               MSG_DEBUG("IO Error!!! [%d]", condition);
+
+               MsgProxyListener::instance()->stop();
+               return FALSE;
+       }
+
+       if (G_IO_HUP & condition)
+       {
+               MSG_DEBUG("socket fd Error!!! [%d]", condition);
+
+               MsgProxyListener::instance()->stop();
+               return FALSE;
+       }
+
+       if (G_IO_NVAL & condition)
+       {
+               MSG_DEBUG("Invaild socket Error!!! [%d]", condition);
+
+               MsgProxyListener::instance()->stop();
+               return FALSE;
+       }
+
+       char* buf = NULL;
+       unsigned int len;
+
+       int n = MsgProxyListener::instance()->readFromSocket(&buf, &len);
+
+       if (n > 0)
+       {
+               MSG_DEBUG(">>Receiving %d bytes", n);
+               MsgProxyListener::instance()->handleEvent((MSG_EVENT_S*)buf);
+       }
+       else if (n == 0)
+       {
+               MSG_DEBUG("Server closed connection");
+               MsgProxyListener::instance()->stop();
+               if (buf)
+               {
+                       delete [] buf;
+                       buf = NULL;
+               }
+               return FALSE;
+       }
+       else // dataSize < 0
+       {
+               MSG_DEBUG("Data is not for Listener");
+       }
+
+       if (buf)
+       {
+               delete [] buf;
+               buf = NULL;
+       }
+
+       MSG_END();
+
+       return TRUE;
+}
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgListenerThread - Member Functions
+==================================================================================================*/
+MsgProxyListener* MsgProxyListener::pInstance = NULL;
+
+
+MsgProxyListener::MsgProxyListener() : running(0)
+{
+       sentStatusCBList.clear();
+       newMessageCBList.clear();
+       newMMSConfMessageCBList.clear();
+       newSyncMLMessageCBList.clear();
+       newLBSMessageCBList.clear();
+}
+
+
+MsgProxyListener::~MsgProxyListener()
+{
+       sentStatusCBList.clear();
+       newMessageCBList.clear();
+       newMMSConfMessageCBList.clear();
+       newSyncMLMessageCBList.clear();
+       newLBSMessageCBList.clear();
+}
+
+
+MsgProxyListener* MsgProxyListener::instance()
+{
+       static Mutex mm;
+       MutexLocker lock(mm);
+
+       if (!pInstance)
+               pInstance = new MsgProxyListener();
+
+       return pInstance;
+}
+
+
+void MsgProxyListener::start()
+{
+       if (running == 0)
+       {
+               mx.lock();
+               cliSock.connect(MSG_SOCKET_PATH);
+               cv.signal(); // wake up the waiting thread
+               mx.unlock();
+
+               int fd = cliSock.fd();
+
+               MSG_DEBUG("Socket Fd : %d", fd);
+
+               channel = g_io_channel_unix_new(fd); // initializes ref_count = 1
+
+               eventSourceId = g_io_add_watch(channel, (GIOCondition)(G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL), &readSocket, NULL); // increments ref_count =2
+
+               MSG_DEBUG("Call g_io_add_watch() : %d", eventSourceId);
+       }
+
+       running++;
+       MSG_DEBUG("add Listener and [%d] are running.", running);
+}
+
+
+void MsgProxyListener::stop()
+{
+       MSG_BEGIN();
+
+       if (running > 1)
+       {
+               running--;
+               MSG_DEBUG("There are still running Listener. [%d] left.", running);
+       }
+       else if (running == 1)
+       {
+               MutexLocker lock(mx);
+
+               running--;
+
+               g_io_channel_unref(channel); // decrements ref_count = 1
+
+               g_source_remove(eventSourceId);
+
+               cliSock.close();
+
+               MSG_DEBUG("client Listener is terminated.");
+       }
+
+       MSG_END();
+}
+
+
+bool MsgProxyListener::regSentStatusEventCB(MsgHandle* pMsgHandle, msg_sent_status_cb pfSentStatus, void *pUserParam)
+{
+       MutexLocker lock(mx);
+
+       std::list<MSG_SENT_STATUS_CB_ITEM_S>::iterator it = sentStatusCBList.begin();
+
+       for (; it != sentStatusCBList.end(); it++)
+       {
+               if (it->hAddr == pMsgHandle && it->pfSentStatusCB == pfSentStatus)
+               {
+                       MSG_DEBUG("msg_sent_status_cb() callback : [%p] is already registered!!!", pfSentStatus);
+
+                       it->userParam = pUserParam;
+
+                       return false;
+               }
+       }
+
+       MSG_SENT_STATUS_CB_ITEM_S sentStatusCB = {pMsgHandle, pfSentStatus, pUserParam};
+
+       sentStatusCBList.push_back(sentStatusCB);
+
+       return true;
+}
+
+
+bool MsgProxyListener::regMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_sms_incoming_cb pfNewMessage, int port, void *pUserParam)
+{
+       MutexLocker lock(mx);
+
+       std::list<MSG_INCOMING_CB_ITEM_S>::iterator it = newMessageCBList.begin();
+
+       for (; it != newMessageCBList.end(); it++)
+       {
+               if (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;
+               }
+       }
+
+       MSG_INCOMING_CB_ITEM_S incomingCB = {pMsgHandle, pfNewMessage, port, pUserParam};
+
+       newMessageCBList.push_back(incomingCB);
+
+       return true;
+}
+
+
+bool MsgProxyListener::regMMSConfMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_mms_conf_msg_incoming_cb pfNewMMSConfMessage, const char *pAppId, void *pUserParam)
+{
+       MutexLocker lock(mx);
+
+       std::list<MSG_MMS_CONF_INCOMING_CB_ITEM_S>::iterator it = newMMSConfMessageCBList.begin();
+
+       for (; it != newMMSConfMessageCBList.end(); it++)
+       {
+               if (it->pfMMSConfIncomingCB == pfNewMMSConfMessage)
+               {
+
+                       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))
+                       {
+                               MSG_DEBUG("msg_mms_conf_msg_incoming_cb() callback : AppId [%s] is already registered!!!", pAppId);
+
+                               it->userParam = pUserParam;
+
+                               return false;
+                       }
+               }
+       }
+
+       MSG_MMS_CONF_INCOMING_CB_ITEM_S incomingConfCB = {pMsgHandle, pfNewMMSConfMessage, {0}, pUserParam};
+
+       if (pAppId != NULL)
+               strncpy(incomingConfCB.appId, pAppId, MAX_MMS_JAVA_APPID_LEN);
+
+       newMMSConfMessageCBList.push_back(incomingConfCB);
+
+       return true;
+}
+
+
+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->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);
+
+                               it->userParam = pUserParam;
+
+                               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->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::regSyncMLMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_syncml_msg_incoming_cb pfNewSyncMLMessage, void *pUserParam)
+{
+       MutexLocker lock(mx);
+
+       std::list<MSG_SYNCML_INCOMING_CB_ITEM_S>::iterator it = newSyncMLMessageCBList.begin();
+
+       for (; it != newSyncMLMessageCBList.end(); it++)
+       {
+               if (it->pfSyncMLIncomingCB == pfNewSyncMLMessage)
+               {
+                       MSG_DEBUG("msg_syncml_msg_incoming_cb() callback : [%p] is already registered!!!", pfNewSyncMLMessage);
+
+                       it->userParam = pUserParam;
+
+                       return false;
+               }
+       }
+
+       MSG_SYNCML_INCOMING_CB_ITEM_S incomingCB = {pMsgHandle, pfNewSyncMLMessage, pUserParam};
+
+       newSyncMLMessageCBList.push_back(incomingCB);
+
+       return true;
+}
+
+
+bool MsgProxyListener::regLBSMessageIncomingEventCB(MsgHandle* pMsgHandle, msg_lbs_msg_incoming_cb pfNewLBSMsgIncoming, void *pUserParam)
+{
+       MutexLocker lock(mx);
+
+       std::list<MSG_LBS_INCOMING_CB_ITEM_S>::iterator it = newLBSMessageCBList.begin();
+
+       for (; it != newLBSMessageCBList.end(); it++)
+       {
+               if (it->pfLBSMsgIncoming == pfNewLBSMsgIncoming)
+               {
+                       MSG_DEBUG("msg_lbs_msg_incoming_cb() callback : [%p] is already registered!!!", pfNewLBSMsgIncoming);
+
+                       it->userParam = pUserParam;
+
+                       return false;
+               }
+       }
+
+       MSG_LBS_INCOMING_CB_ITEM_S incomingCB = {pMsgHandle, pfNewLBSMsgIncoming, pUserParam};
+
+       newLBSMessageCBList.push_back(incomingCB);
+
+       return true;
+}
+
+
+bool MsgProxyListener::regSyncMLMessageOperationEventCB(MsgHandle* pMsgHandle, msg_syncml_msg_operation_cb pfSyncMLMessageOperation, void *pUserParam)
+{
+       MutexLocker lock(mx);
+
+       std::list<MSG_SYNCML_OPERATION_CB_ITEM_S>::iterator it = operationSyncMLMessageCBList.begin();
+
+       for (; it != operationSyncMLMessageCBList.end(); it++)
+       {
+               if (it->pfSyncMLOperationCB == pfSyncMLMessageOperation)
+               {
+                       MSG_DEBUG("msg_syncml_msg_incoming_cb() callback : [%p] is already registered!!!", pfSyncMLMessageOperation);
+
+                       it->userParam = pUserParam;
+
+                       return false;
+               }
+       }
+
+       MSG_SYNCML_OPERATION_CB_ITEM_S incomingCB = {pMsgHandle, pfSyncMLMessageOperation, pUserParam};
+
+       operationSyncMLMessageCBList.push_back(incomingCB);
+
+       return true;
+}
+
+
+bool MsgProxyListener::regStorageChangeEventCB(MsgHandle* pMsgHandle, msg_storage_change_cb pfStorageChangeOperation, void *pUserParam)
+{
+       MutexLocker lock(mx);
+
+       std::list<MSG_STORAGE_CHANGE_CB_ITEM_S>::iterator it = storageChangeCBList.begin();
+
+       for (; it != storageChangeCBList.end(); it++)
+       {
+               if (it->pfStorageChangeCB == pfStorageChangeOperation)
+               {
+                       MSG_DEBUG("msg_storage_change_cb() callback : [%p] is already registered!!!", pfStorageChangeOperation);
+
+                       it->userParam = pUserParam;
+
+                       return false;
+               }
+       }
+
+       MSG_STORAGE_CHANGE_CB_ITEM_S changeCB = {pMsgHandle, pfStorageChangeOperation, pUserParam};
+
+       storageChangeCBList.push_back(changeCB);
+
+       return true;
+}
+
+
+void MsgProxyListener::clearListOfClosedHandle(MsgHandle* pMsgHandle)
+{
+       MSG_BEGIN();
+
+       // sent status CB list
+       std::list<MSG_SENT_STATUS_CB_ITEM_S>::iterator it = sentStatusCBList.begin();
+
+       for (; it != sentStatusCBList.end(); it++)
+       {
+               if (it->hAddr == pMsgHandle)
+               {
+                       sentStatusCBList.erase(it);
+                       it = sentStatusCBList.begin();
+
+                       //Stop client Listener
+                       stop();
+               }
+       }
+
+       // new message CB list
+       std::list<MSG_INCOMING_CB_ITEM_S>::iterator it2 = newMessageCBList.begin();
+
+       for (; it2 != newMessageCBList.end(); it2++)
+       {
+               if (it2->hAddr == pMsgHandle)
+               {
+                       newMessageCBList.erase(it2);
+                       it2 = newMessageCBList.begin();
+
+                       //Stop client Listener
+                       stop();
+               }
+       }
+
+       // MMS conf Message CB list
+       std::list<MSG_MMS_CONF_INCOMING_CB_ITEM_S>::iterator it3 = newMMSConfMessageCBList.begin();
+
+       for (; it3 != newMMSConfMessageCBList.end(); it3++)
+       {
+               if (it3->hAddr == pMsgHandle)
+               {
+                       newMMSConfMessageCBList.erase(it3);
+                       it3 = newMMSConfMessageCBList.begin();
+
+                       //Stop client Listener
+                       stop();
+               }
+       }
+
+       // SyncML Message CB list
+       std::list<MSG_SYNCML_INCOMING_CB_ITEM_S>::iterator it4 = newSyncMLMessageCBList.begin();
+
+       for (; it4 != newSyncMLMessageCBList.end(); it4++)
+       {
+               if (it4->hAddr == pMsgHandle)
+               {
+                       newSyncMLMessageCBList.erase(it4);
+                       it4 = newSyncMLMessageCBList.begin();
+
+                       //Stop client Listener
+                       stop();
+               }
+       }
+
+       // LBS Message CB list
+       std::list<MSG_LBS_INCOMING_CB_ITEM_S>::iterator it5 = newLBSMessageCBList.begin();
+
+       for (; it5 != newLBSMessageCBList.end(); it5++)
+       {
+               if (it5->hAddr == pMsgHandle)
+               {
+                       newLBSMessageCBList.erase(it5);
+                       it5 = newLBSMessageCBList.begin();
+
+                       //Stop client Listener
+                       stop();
+               }
+       }
+
+       // Push Message CB list
+       std::list<MSG_PUSH_INCOMING_CB_ITEM_S>::iterator it6 = newPushMessageCBList.begin();
+
+       for (; it6 != newPushMessageCBList.end(); it6++)
+       {
+               if (it6->hAddr == pMsgHandle)
+               {
+                       newPushMessageCBList.erase(it6);
+                       it6 = newPushMessageCBList.begin();
+
+                       //Stop client Listener
+                       stop();
+               }
+
+       }
+
+       // CB Message CB list
+       std::list<MSG_CB_INCOMING_CB_ITEM_S>::iterator it7 = newCBMessageCBList.begin();
+
+       bool bSave = false;
+       for (; it7 != newCBMessageCBList.end(); it7++)
+       {
+
+               if (it7->hAddr == pMsgHandle)
+               {
+
+                       newCBMessageCBList.erase(it7);
+                       it7 = newCBMessageCBList.begin();
+
+                       //Stop client Listener
+                       stop();
+               }
+               else
+               {
+                       if(it7->bsave == true)
+                               bSave = true;
+               }
+       }
+
+       if(!bSave)
+               if(MsgSettingSetBool(CB_SAVE, bSave) != MSG_SUCCESS)
+                       MSG_DEBUG("MsgSettingSetBool FAIL: CB_SAVE");
+
+       // Storage change Message CB list
+       std::list<MSG_STORAGE_CHANGE_CB_ITEM_S>::iterator it8 = storageChangeCBList.begin();
+
+       for (; it8 != storageChangeCBList.end(); it8++)
+       {
+               if (it8->hAddr == pMsgHandle)
+               {
+                       storageChangeCBList.erase(it8);
+                       it8 = storageChangeCBList.begin();
+
+                       //Stop client Listener
+                       stop();
+               }
+       }
+
+       MSG_END();
+}
+
+void MsgProxyListener::handleEvent(const MSG_EVENT_S* pMsgEvent)
+{
+       MSG_BEGIN();
+
+       if (!pMsgEvent)
+               THROW(MsgException::INVALID_PARAM, "pMsgEvent is NULL");
+
+       if (pMsgEvent->eventType == MSG_EVENT_PLG_SENT_STATUS_CNF)
+       {
+               unsigned int chInfo[3] = {0}; //3// reqid, status, object
+
+               memcpy(&chInfo, (void*)((char*)pMsgEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)), sizeof(chInfo));
+
+               msg_struct_s status = {0,};
+               MSG_SENT_STATUS_S statusData = {(msg_request_id_t)chInfo[0], (msg_network_status_t)chInfo[1]};
+
+               status.type = MSG_STRUCT_SENT_STATUS_INFO;
+               status.data = (void *)&statusData;
+
+               mx.lock();
+
+               MsgSentStatusCBList::iterator it = sentStatusCBList.begin();
+
+               for( ; it != sentStatusCBList.end() ; it++)
+               {
+                       MsgHandle* pHandle = it->hAddr;
+
+                       msg_sent_status_cb pfunc = it->pfSentStatusCB;
+
+                       void* param = it->userParam;
+
+                       pfunc((msg_handle_t)pHandle, (msg_struct_t)&status, param);
+               }
+
+               mx.unlock();
+       }
+       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;
+
+               mx.lock();
+
+               MsgNewMessageCBList::iterator it = newMessageCBList.begin();
+               MsgNewMessageCBList matchList;
+
+               for( ; it != newMessageCBList.end() ; it++)
+               {
+                       if( portKey == it->port)
+                       {
+                               matchList.push_back(*it);
+                       }
+               }
+
+               mx.unlock();
+
+               it = matchList.begin();
+
+               for( ; it != matchList.end(); it++ )
+               {
+                       MsgHandle* pHandle = it->hAddr;
+
+                       MSG_MESSAGE_INFO_S *pMsgInfo = (MSG_MESSAGE_INFO_S *)pMsgEvent->data;
+                       MSG_MESSAGE_HIDDEN_S msgHidden = {0,};
+
+                       msgHidden.pData = NULL;
+                       msgHidden.pMmsData = NULL;
+
+                       /* 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;
+                       }
+
+                       msgHidden.addr_list = addr_list;
+
+                       pHandle->convertMsgStruct(pMsgInfo, &msgHidden);
+
+                       msg_struct_s msg = {0,};
+                       msg.type = MSG_STRUCT_MESSAGE_INFO;
+                       msg.data = &msgHidden;
+
+                       msg_sms_incoming_cb pfunc = it->pfIncomingCB;
+
+                       void* param = it->userParam;
+
+                       pfunc((msg_handle_t)pHandle, (msg_struct_t) &msg, param);
+
+                       delete [] (char*)msgHidden.pData;
+                       if (msgHidden.pMmsData != NULL)
+                               delete [] (char*)msgHidden.pMmsData;
+
+                       // address Memory Free
+                       if (msgHidden.addr_list!= NULL)
+                       {
+                               for(int i=0; i<MAX_TO_ADDRESS_CNT; i++) {
+                                       msg_struct_s * addrInfo = (msg_struct_s *)msgHidden.addr_list->msg_struct_info[i];
+                                       delete (MSG_ADDRESS_INFO_S *)addrInfo->data;
+                                       addrInfo->data = NULL;
+                                       delete (msg_struct_s *)msgHidden.addr_list->msg_struct_info[i];
+                                       msgHidden.addr_list->msg_struct_info[i] = NULL;
+                               }
+
+                               delete [] msgHidden.addr_list->msg_struct_info;
+
+                               delete msgHidden.addr_list;
+                               msgHidden.addr_list = NULL;
+                       }
+
+               }
+
+       }
+       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;
+
+               char* appIdKey = (pMmsRecvData->msgAppId.valid)? pMmsRecvData->msgAppId.appId: NULL;
+
+               mx.lock();
+
+               MsgNewMMSConfMessageCBList::iterator it = newMMSConfMessageCBList.begin();
+               MsgNewMMSConfMessageCBList matchList;
+
+               for( ; it != newMMSConfMessageCBList.end() ; it++)
+               {
+                       if(appIdKey)
+                       {
+                               if(!strcmp(appIdKey, it->appId))
+                                       matchList.push_back(*it);
+                       }
+                       else//(appIdKey == NULL && it->appId[0] == 0)
+                       {
+                               if(it->appId[0] == 0)
+                                       matchList.push_back(*it);
+                       }
+               }
+
+               mx.unlock();
+
+               // Contents of msgData removed and replaced to retrievedFilePath for convertMsgStruct
+               // it is moved from UpdateMessage in MmsPluginStorage.cpp
+               char tempFileName[MSG_FILENAME_LEN_MAX+1] = {0};  // check MSG_FILENAME_LEN_MAX
+
+               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), MAX_MSG_DATA_LEN);
+
+               it = matchList.begin();
+
+               for( ; it != matchList.end() ; it++)
+               {
+                       MsgHandle* pHandle = it->hAddr;
+
+                       MSG_MESSAGE_INFO_S *pMsgInfo = (MSG_MESSAGE_INFO_S *)pMsgEvent->data;
+                       MSG_MESSAGE_HIDDEN_S msgHidden = {0,};
+
+                       msgHidden.pData = NULL;
+                       msgHidden.pMmsData = NULL;
+
+                       /* 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;
+                       }
+
+                       msgHidden.addr_list = addr_list;
+
+                       pHandle->convertMsgStruct(pMsgInfo, &msgHidden);
+
+                       msg_struct_s msg = {0,};
+                       msg.type = MSG_STRUCT_MESSAGE_INFO;
+                       msg.data = &msgHidden;
+
+                       msg_mms_conf_msg_incoming_cb pfunc = it->pfMMSConfIncomingCB;
+
+                       void* param = it->userParam;
+                       pfunc((msg_handle_t)pHandle, (msg_struct_t) &msg, param);
+
+                       delete [] (char*)msgHidden.pData;
+                       if (msgHidden.pMmsData != NULL)
+                               delete [] (char*)msgHidden.pMmsData;
+
+                       // address Memory Free
+                       if (msgHidden.addr_list!= NULL)
+                       {
+                               for(int i=0; i<MAX_TO_ADDRESS_CNT; i++) {
+                                       msg_struct_s * addrInfo = (msg_struct_s *)msgHidden.addr_list->msg_struct_info[i];
+                                       delete (MSG_ADDRESS_INFO_S *)addrInfo->data;
+                                       addrInfo->data = NULL;
+                                       delete (msg_struct_s *)msgHidden.addr_list->msg_struct_info[i];
+                                       msgHidden.addr_list->msg_struct_info[i] = NULL;
+                               }
+
+                               delete [] msgHidden.addr_list->msg_struct_info;
+
+                               delete msgHidden.addr_list;
+                               msgHidden.addr_list = NULL;
+                       }
+
+                       // Here the retrieved message will be deleted from native storage.
+                       // as of now, msg which have appId is considered as JAVA MMS message and it will be sent and handled in JAVA app.
+                       if(appIdKey)
+                       {
+                               MSG_DEBUG("delete received JAVA MMS message:%s from native storage",tempFileName);
+                               pHandle->deleteMessage(pMsgInfo->msgId);
+                       }
+               }
+       }
+       else if ( pMsgEvent->eventType == MSG_EVENT_PLG_INCOMING_SYNCML_MSG_IND )
+       {
+               MSG_SYNCML_MESSAGE_DATA_S* pSyncMLData = (MSG_SYNCML_MESSAGE_DATA_S *)pMsgEvent->data;
+
+               MSG_DEBUG("msgType [%d]", pSyncMLData->syncmlType);
+
+               mx.lock();
+
+               MsgNewSyncMLMessageCBList::iterator it = newSyncMLMessageCBList.begin();
+
+               for( ; it != newSyncMLMessageCBList.end() ; it++)
+               {
+                       MsgHandle* pHandle = it->hAddr;
+
+                       msg_syncml_msg_incoming_cb pfunc = it->pfSyncMLIncomingCB;
+
+                       void* param = it->userParam;
+
+                       pfunc((msg_handle_t)pHandle, pSyncMLData->syncmlType, pSyncMLData->pushBody, pSyncMLData->pushBodyLen, pSyncMLData->wspHeader, pSyncMLData->wspHeaderLen, param);
+               }
+
+               mx.unlock();
+       }
+       else if ( pMsgEvent->eventType == MSG_EVENT_PLG_INCOMING_LBS_MSG_IND )
+       {
+               MSG_LBS_MESSAGE_DATA_S* pLBSData = (MSG_LBS_MESSAGE_DATA_S *)pMsgEvent->data;
+
+               mx.lock();
+
+               MsgNewLBSMessageCBList::iterator it = newLBSMessageCBList.begin();
+
+               for( ; it != newLBSMessageCBList.end() ; it++)
+               {
+                       MsgHandle* pHandle = it->hAddr;
+
+                       msg_lbs_msg_incoming_cb pfunc = it->pfLBSMsgIncoming;
+
+                       void* param = it->userParam;
+
+                       pfunc((msg_handle_t)pHandle, pLBSData->pushHeader, pLBSData->pushBody, pLBSData->pushBodyLen, param);
+               }
+
+               mx.unlock();
+       }
+       else if ( pMsgEvent->eventType == MSG_EVENT_SYNCML_OPERATION )
+       {
+               int msgId;
+               int extId;
+
+               memcpy(&msgId, (void*)((char*)pMsgEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)), sizeof(int));
+               memcpy(&extId, (void*)((char*)pMsgEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)+sizeof(int)), sizeof(int));
+
+               MSG_DEBUG("msgId [%d]", msgId);
+               MSG_DEBUG("extId [%d]", extId);
+
+               mx.lock();
+
+               MsgOperationSyncMLMessageCBList::iterator it = operationSyncMLMessageCBList.begin();
+
+               for( ; it != operationSyncMLMessageCBList.end() ; it++)
+               {
+                       MsgHandle* pHandle = it->hAddr;
+
+                       msg_syncml_msg_operation_cb pfunc = it->pfSyncMLOperationCB;
+
+                       void* param = it->userParam;
+
+                       pfunc((msg_handle_t)pHandle, msgId, extId, param);
+               }
+
+               mx.unlock();
+       }
+       else if (pMsgEvent->eventType == MSG_EVENT_PLG_STORAGE_CHANGE_IND)
+       {
+               msg_storage_change_type_t storageChangeType;
+               msg_id_list_s msgIdList;
+               memset(&msgIdList, 0x00, sizeof(msg_id_list_s));
+
+               // Decode event data
+               memcpy(&storageChangeType, (void*)((char*)pMsgEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)), sizeof(msg_storage_change_type_t));
+               memcpy(&msgIdList.nCount, (void*)((char*)pMsgEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)+sizeof(msg_storage_change_type_t)), sizeof(int));
+
+               if(msgIdList.nCount > 0)
+                       msgIdList.msgIdList = (msg_message_id_t*)((char*)pMsgEvent+sizeof(MSG_EVENT_TYPE_T)+sizeof(msg_error_t)+sizeof(msg_storage_change_type_t)+sizeof(int));
+               else
+                       msgIdList.msgIdList = NULL;
+
+               MSG_DEBUG("storageChangeType [%d], msgIdList.nCount [%d]", storageChangeType, msgIdList.nCount);
+
+               mx.lock();
+
+               MsgStorageChangeCBList::iterator it = storageChangeCBList.begin();
+
+               for( ; it != storageChangeCBList.end() ; it++)
+               {
+                       MsgHandle* pHandle = it->hAddr;
+
+                       msg_storage_change_cb pfunc = it->pfStorageChangeCB;
+
+                       void* param = it->userParam;
+
+                       pfunc((msg_handle_t)pHandle, storageChangeType, (msg_id_list_s*)&msgIdList, param);
+               }
+
+               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;
+
+                       pfunc((msg_handle_t)pHandle, pPushData->pushHeader, pPushData->pushBody, pPushData->pushBodyLen, param);
+               }
+
+               mx.unlock();
+       }
+
+       MSG_END();
+}
+
+
+int  MsgProxyListener::getRemoteFd()
+{
+       MutexLocker lock(mx);
+
+       int tmpFd = cliSock.getRemoteFd();
+
+       MSG_DEBUG("listener fd [%d]", tmpFd);
+
+       if( tmpFd == -1 )
+       {
+               cv.wait(mx.pMutex());
+       }
+
+       return cliSock.getRemoteFd();
+}
+
+
+int MsgProxyListener::readFromSocket(char** buf, unsigned int* len)
+{
+       return cliSock.read(buf, len);
+}
+
+#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>
diff --git a/utils/CMakeLists.txt b/utils/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..cb0cd43
--- /dev/null
@@ -0,0 +1,65 @@
+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 Framework Utils
+##########################################################
+
+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
+)
+
+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
+       ${CMAKE_SOURCE_DIR}/vobject-engine/include
+)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(utils_pkgs REQUIRED glib-2.0 vconf db-util contacts-service2 dlog pmapi mm-session alarm-service notification drm-client)
+
+FOREACH(flag ${utils_pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+ADD_DEFINITIONS("-DPREFIX=\"${CMAKE_INSTALL_PREFIX}\"")
+ADD_DEFINITIONS("-DFEATURE_JAVA_MMS")
+ADD_DEFINITIONS("-D__SUPPORT_DRM__")
+
+SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed")
+
+ADD_LIBRARY(${UTILS-LIB} SHARED ${UTILS-SRCS})
+TARGET_LINK_LIBRARIES(${UTILS-LIB} ${utils_pkgs_LDFLAGS} rt ${VOBJECT-LIB})
+
+INSTALL(TARGETS ${UTILS-LIB} DESTINATION lib COMPONENT RuntimeLibraries)
+
diff --git a/utils/MsgContact.cpp b/utils/MsgContact.cpp
new file mode 100755 (executable)
index 0000000..ae4ada3
--- /dev/null
@@ -0,0 +1,731 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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.h>
+}
+
+#include "MsgDebug.h"
+#include "MsgUtilStorage.h"
+#include "MsgGconfWrapper.h"
+#include "MsgContact.h"
+
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+__thread bool isContactSvcConnected = false;
+
+MsgDbHandler ContactDbHandle;
+
+MsgContactChangeCB cbFunction = NULL;
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+static void MsgContactSvcCallback(const char *view_uri, void *user_data)
+{
+       MSG_DEBUG("Contact Data is Changed!!!");
+
+       MsgSyncContact();
+
+       if (ContactDbHandle.disconnect() != MSG_SUCCESS)
+               MSG_DEBUG("DB Disconnect Fail");
+}
+
+
+msg_error_t MsgOpenContactSvc()
+{
+       int errCode = CONTACTS_ERROR_NONE;
+
+       if (!isContactSvcConnected) {
+               errCode = contacts_connect2();
+
+               if (errCode == CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("Connect to Contact Service Success");
+                       isContactSvcConnected = true;
+               } else {
+                       MSG_DEBUG("Connect to Contact Service Fail [%d]", errCode);
+                       isContactSvcConnected = false;
+                       return MSG_ERR_DB_CONNECT;
+               }
+       } else {
+               MSG_DEBUG("Already connected to Contact Service.");
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgCloseContactSvc()
+{
+       int errCode = CONTACTS_ERROR_NONE;
+
+       if (isContactSvcConnected) {
+               errCode = contacts_disconnect2();
+
+               if (errCode == CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("Disconnect to Contact Service Success");
+               } else {
+                       MSG_DEBUG("Disconnect to Contact Service Fail [%d]", errCode);
+                       return MSG_ERR_DB_DISCONNECT;
+               }
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgInitContactSvc(MsgContactChangeCB cb)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if ((err = MsgOpenContactSvc()) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgOpenContactSvc fail.");
+               return err;
+       }
+
+       int errCode = CONTACTS_ERROR_NONE;
+
+       if (!isContactSvcConnected) {
+               MSG_DEBUG("Contact Service Not Opened.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       if (cb != NULL)
+               cbFunction = cb;
+
+       // Register callback function
+       errCode = contacts_db_add_changed_cb(_contacts_contact._uri, MsgContactSvcCallback, NULL);
+
+       if (errCode == CONTACTS_ERROR_NONE)
+               MSG_DEBUG("Register Contact Service Callback");
+       else
+               MSG_DEBUG("Fail to Register Contact Service Callback [%d]", errCode);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgGetContactInfo(const MSG_ADDRESS_INFO_S *pAddrInfo, MSG_CONTACT_INFO_S *pContactInfo)
+{
+       MSG_BEGIN();
+
+       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_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_SUCCESS;
+       }
+
+       int ret = 0;
+       int index = 0;
+       unsigned int count = 0;
+       contacts_query_h query = NULL;
+       contacts_filter_h filter = NULL;
+       contacts_list_h contacts = 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);
+
+               ret = contacts_filter_add_str(filter, _contacts_contact_number.number_filter, CONTACTS_MATCH_EXACTLY, pAddrInfo->addressVal);
+
+       } 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);
+
+               ret = contacts_filter_add_str(filter, _contacts_contact_email.email, CONTACTS_MATCH_EXACTLY, pAddrInfo->addressVal);
+
+       } else {
+               MSG_DEBUG("Invalid pAddrInfo->addressType.");
+               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_SUCCESS;
+       }
+
+       ret = contacts_list_get_count(contacts, &count);
+
+       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;
+       }
+
+       contacts_record_h contact = NULL;
+
+       if (pAddrInfo->addressType == MSG_ADDRESS_TYPE_PLMN || pAddrInfo->addressType == MSG_ADDRESS_TYPE_UNKNOWN) {
+               contacts_record_h number = NULL;
+
+               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_SUCCESS;
+               }
+
+               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);
+                       contacts_record_destroy(number, true);
+                       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);
+                       contacts_record_destroy(contact, true);
+                       contacts_record_destroy(number, true);
+                       return MSG_SUCCESS;
+               }
+       } 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_SUCCESS;
+               }
+
+               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);
+                       contacts_record_destroy(email, true);
+                       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);
+                       contacts_record_destroy(contact, true);
+                       contacts_record_destroy(email, true);
+                       return MSG_SUCCESS;
+               }
+       }
+
+       contacts_list_destroy(contacts, true);
+
+       // 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);
+               contacts_record_destroy(contact, true);
+               return MSG_SUCCESS;
+       }
+
+       char* strFirstName = NULL;
+       ret = contacts_record_get_str_p(name, _contacts_name.first, &strFirstName);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               contacts_record_destroy(contact, true);
+               return MSG_SUCCESS;
+       }
+
+       char* strLastName = NULL;
+       ret = contacts_record_get_str_p(name, _contacts_name.last, &strLastName);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               contacts_record_destroy(contact, true);
+               return MSG_SUCCESS;
+       }
+
+       MSG_DEBUG("First Name : [%s], Last Name : [%s]", strFirstName, strLastName);
+
+       if (strFirstName != NULL)
+               strncpy(pContactInfo->firstName, strFirstName, MAX_DISPLAY_NAME_LEN);
+
+       if (strLastName != NULL)
+               strncpy(pContactInfo->lastName, strLastName, MAX_DISPLAY_NAME_LEN);
+
+       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_SUCCESS;
+       }
+
+       MSG_DEBUG("Contact ID [%d]", pContactInfo->contactId);
+
+       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);
+               contacts_record_destroy(contact, true);
+               return MSG_SUCCESS;
+       }
+
+       if (strImagePath != NULL)
+               strncpy(pContactInfo->imagePath , strImagePath, MAX_IMAGE_PATH_LEN);
+
+       MSG_DEBUG("Image Path [%s]", pContactInfo->imagePath);
+
+       contacts_record_destroy(contact, true);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+void MsgSyncContact()
+{
+       int ret = -1;
+       unsigned int changed_count = 0;
+       int lastSyncTime = 0;
+       int finalSyncTime = 0;
+
+       /* get contact sync time */
+       lastSyncTime = MsgSettingGetInt(CONTACT_SYNC_TIME);
+
+       if (lastSyncTime < 0) {
+               MSG_DEBUG("Fail to get CONTACT_SYNC_TIME.");
+               lastSyncTime = 0;
+       }
+
+       contacts_list_h contactsList = NULL;
+
+       ret = contacts_db_get_changes_by_version(_contacts_contact_updated_info._uri, -1, lastSyncTime, &contactsList, &finalSyncTime);
+
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_db_get_changes_by_version() Error [%d]", ret);
+               return;
+       }
+
+       ret = contacts_list_get_count(contactsList, &changed_count);
+
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_list_get_count() Error [%d]", ret);
+               contacts_list_destroy(contactsList, true);
+               return;
+       }
+
+       for (unsigned 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;
+               }
+
+               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);
+
+               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 == CONTACTS_CHANGE_UPDATED || type == CONTACTS_CHANGE_INSERTED) {
+                       MsgUpdateContact(index_num, type);
+               } else {// Delete
+                       MSG_DEBUG("Delete Contact");
+                       MsgDeleteContact(index_num);
+               }
+
+               ret = contacts_list_next(contactsList);
+               if (ret != CONTACTS_ERROR_NONE) {
+                       MSG_DEBUG("contacts_list_next() Error [%d]", ret);
+               }
+       }
+
+       if(MsgSettingSetInt(CONTACT_SYNC_TIME, finalSyncTime) != MSG_SUCCESS)
+               MSG_DEBUG("MsgSettingSetInt fail : CONTACT_SYNC_TIME");
+       MSG_DEBUG("lastSyncTime : %d", finalSyncTime);
+
+       contacts_list_destroy(contactsList, true);
+
+       if(changed_count > 0)
+               cbFunction();
+}
+
+
+bool MsgInsertContact(MSG_CONTACT_INFO_S *pContactInfo, const char *pNumber)
+{
+       if (!pNumber || strlen(pNumber) <= 0)
+               return false;
+
+       if (MsgStoAddContactInfo(&ContactDbHandle, pContactInfo, pNumber) != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to add contact info.");
+               return false;
+       }
+
+       return true;
+}
+
+
+bool MsgUpdateContact(int index, int type)
+{
+       int ret = CONTACTS_ERROR_NONE;
+
+       contacts_record_h contact = 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_record_destroy(contact, true);
+               return false;
+       }
+
+       MSG_CONTACT_INFO_S contactInfo;
+       memset(&contactInfo, 0x00, sizeof(MSG_CONTACT_INFO_S));
+
+       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_DEBUG("Contact ID [%d]", contactInfo.contactId);
+
+       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);
+               contacts_record_destroy(contact, true);
+               return false;
+       }
+
+       if (strImagePath != NULL)
+               strncpy(contactInfo.imagePath , strImagePath, MAX_IMAGE_PATH_LEN);
+
+       MSG_DEBUG("Image Path [%s]", contactInfo.imagePath);
+
+       // 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);
+               contacts_record_destroy(contact, true);
+               return false;
+       }
+
+       char* strFirstName = NULL;
+       ret = contacts_record_get_str_p(name, _contacts_name.first, &strFirstName);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               contacts_record_destroy(contact, true);
+               return false;
+       }
+
+       char* strLastName = NULL;
+       ret = contacts_record_get_str_p(name, _contacts_name.last, &strLastName);
+       if (ret != CONTACTS_ERROR_NONE) {
+               MSG_DEBUG("contacts_record_get_str_p() Error [%d]", ret);
+               contacts_record_destroy(contact, true);
+               return false;
+       }
+
+       MSG_DEBUG("First Name : [%s], Last Name : [%s]", strFirstName, strLastName);
+
+       if (strFirstName != NULL)
+               strncpy(contactInfo.firstName, strFirstName, MAX_DISPLAY_NAME_LEN);
+
+       if (strLastName != NULL)
+               strncpy(contactInfo.lastName, strLastName, MAX_DISPLAY_NAME_LEN);
+
+       MsgStoClearContactInfo(&ContactDbHandle, index);
+
+       unsigned 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;
+       }
+
+       if (count > 0) {
+               for(unsigned 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);
+                               if (!MsgInsertContact(&contactInfo, strNumber)) {
+                                       MSG_DEBUG("MsgInsertContact fail.");
+                               }
+                       }
+               }
+       } else {// No phone number in contact
+               contacts_record_destroy(contact, true);
+               return true;
+       }
+
+       MsgStoSetConversationDisplayName(&ContactDbHandle, index);
+
+       contacts_record_destroy(contact, true);
+
+       return true;
+}
+
+
+bool MsgDeleteContact(int index)
+{
+       if (MsgStoClearContactInfo(&ContactDbHandle, index) != MSG_SUCCESS)
+               return false;
+
+       return true;
+}
+
+
+int MsgGetContactNameOrder()
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if ((err = MsgOpenContactSvc()) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgOpenContactSvc fail.");
+               return 0;
+       }
+
+       if (!isContactSvcConnected) {
+               MSG_DEBUG("Contact Service Not Opened.");
+               return 0; // return default value : FIRSTLAST
+       }
+
+       int ret = CONTACTS_ERROR_NONE;
+
+       contacts_name_display_order_e order = CONTACTS_NAME_DISPLAY_ORDER_FIRSTLAST;
+
+       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 0;
+       }
+
+       if (order == CONTACTS_NAME_DISPLAY_ORDER_FIRSTLAST)
+               return 0;
+       else
+               return 1;
+}
+
+
+void MsgAddPhoneLog(const MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       if ((err = MsgOpenContactSvc()) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgOpenContactSvc fail.");
+               return;
+       }
+
+       if (!isContactSvcConnected) {
+               MSG_DEBUG("Contact Service Not Opened.");
+               return;
+       }
+
+       if(pMsgInfo->nAddressCnt < 1) {
+               MSG_DEBUG("address count is [%d]", pMsgInfo->nAddressCnt);
+               return;
+       }
+
+       for (int i = 0; pMsgInfo->nAddressCnt > i; i++) {
+               int ret = 0;
+               contacts_record_h plog = NULL;
+
+               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;
+               }
+
+               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);
+               } 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 {
+                               strncpy(strText, pMsgInfo->msgText, 100);
+                               MSG_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;
+       }
+
+       MSG_DEBUG("MsgDeletePhoneLog [%d]", msgId);
+
+       if (!isContactSvcConnected) {
+               MSG_DEBUG("Contact Service Not Opened.");
+               return;
+       }
+
+       int ret = CONTACTS_ERROR_NONE;
+       int index = 0;
+       unsigned 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);
+
+
+       ret = contacts_query_set_filter(query, filter);
+       ret = contacts_db_get_records_with_query(query, 0, 1, &plogs);
+
+       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);
+               }
+
+               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);
+
+}
+
+
+int MsgContactSVCBeginTrans()
+{
+       //return contacts_svc_begin_trans();
+       return 0;
+}
+
+
+int MsgContactSVCEndTrans(bool bSuccess)
+{
+       //return contacts_svc_end_trans(bSuccess);
+       return 0;
+}
diff --git a/utils/MsgDebug.cpp b/utils/MsgDebug.cpp
new file mode 100755 (executable)
index 0000000..06a71ea
--- /dev/null
@@ -0,0 +1,443 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <sys/syscall.h>
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+const char * MsgDbgCmdStr(MSG_CMD_TYPE_T cmdType)
+{
+       switch ( cmdType )
+       {
+// 0
+               case MSG_CMD_OPEN_HANDLE:
+                       return "MSG_CMD_OPEN_HANDLE";
+               case MSG_CMD_CLOSE_HANDLE:
+                       return "MSG_CMD_CLOSE_HANDLE";
+               case MSG_CMD_GET_STORAGELIST:
+                       return "MSG_CMD_GET_STORAGELIST";
+               case MSG_CMD_ADD_MSG:
+                       return "MSG_CMD_ADD_MSG";
+               case MSG_CMD_ADD_SYNCML_MSG:
+                       return "MSG_CMD_ADD_SYNCML_MSG";
+
+// 5
+               case MSG_CMD_UPDATE_MSG:
+                       return "MSG_CMD_UPDATE_MSG";
+               case MSG_CMD_UPDATE_READ:
+                       return "MSG_CMD_UPDATE_READ";
+               case MSG_CMD_UPDATE_PROTECTED:
+                       return "MSG_CMD_UPDATE_PROTECTED";
+               case MSG_CMD_DELETE_MSG:
+                       return "MSG_CMD_DELETE_MSG";
+               case MSG_CMD_DELALL_MSGINFOLDER:
+                       return "MSG_CMD_DELALL_MSGINFOLDER";
+
+// 10
+               case MSG_CMD_MOVE_MSGTOFOLDER:
+                       return "MSG_CMD_MOVE_MSGTOFOLDER";
+               case MSG_CMD_MOVE_MSGTOSTORAGE:
+                       return "MSG_CMD_MOVE_MSGTOSTORAGE";
+               case MSG_CMD_COUNT_MSG:
+                       return "MSG_CMD_COUNT_MSG";
+               case MSG_CMD_GET_MSG:
+                       return "MSG_CMD_GET_MSG";
+               case MSG_CMD_GET_FOLDERVIEWLIST:
+                       return "MSG_CMD_GET_FOLDERVIEWLIST";
+
+// 15
+               case MSG_CMD_ADD_FOLDER:
+                       return "MSG_CMD_ADD_FOLDER";
+               case MSG_CMD_UPDATE_FOLDER:
+                       return "MSG_CMD_UPDATE_FOLDER";
+               case MSG_CMD_DELETE_FOLDER:
+                       return "MSG_CMD_DELETE_FOLDER";
+               case MSG_CMD_GET_FOLDERLIST:
+                       return "MSG_CMD_GET_FOLDERLIST";
+               case MSG_CMD_ADD_FILTER:
+                       return "MSG_CMD_ADD_FILTER";
+
+// 20
+               case MSG_CMD_UPDATE_FILTER:
+                       return "MSG_CMD_UPDATE_FILTER";
+               case MSG_CMD_DELETE_FILTER:
+                       return "MSG_CMD_DELETE_FILTER";
+               case MSG_CMD_GET_FILTERLIST:
+                       return "MSG_CMD_GET_FILTERLIST";
+               case MSG_CMD_SET_FILTER_OPERATION:
+                       return "MSG_CMD_SET_FILTER_OPERATION";
+               case MSG_CMD_GET_FILTER_OPERATION:
+                       return "MSG_CMD_GET_FILTER_OPERATION";
+
+// 25
+               case MSG_CMD_GET_MSG_TYPE:
+                       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:
+                       return "MSG_CMD_REG_STORAGE_CHANGE_CB";
+
+// 30
+               case MSG_CMD_REG_INCOMING_MSG_CB:
+                       return "MSG_CMD_REG_INCOMING_MSG_CB";
+               case MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB:
+                       return "MSG_CMD_REG_INCOMING_MMS_CONF_MSG_CB";
+               case MSG_CMD_REG_INCOMING_SYNCML_MSG_CB:
+                       return "MSG_CMD_REG_INCOMING_SYNCML_MSG_CB";
+               case MSG_CMD_REG_INCOMING_LBS_MSG_CB:
+                       return "MSG_CMD_REG_INCOMING_LBS_MSG_CB";
+               case MSG_CMD_PLG_SENT_STATUS_CNF:
+                       return "MSG_CMD_PLG_SENT_STATUS_CNF";
+
+// 35
+               case MSG_CMD_PLG_STORAGE_CHANGE_IND:
+                       return "MSG_CMD_PLG_STORAGE_CHANGE_IND";
+               case MSG_CMD_PLG_INCOMING_MSG_IND:
+                       return "MSG_CMD_PLG_INCOMING_MSG_IND";
+               case MSG_CMD_PLG_INCOMING_MMS_CONF:
+                       return "MSG_CMD_PLG_INCOMING_MMS_CONF";
+               case MSG_CMD_PLG_INCOMING_SYNCML_IND:
+                       return "MSG_CMD_PLG_INCOMING_SYNCML_IND";
+               case MSG_CMD_PLG_INCOMING_LBS_IND:
+                       return "MSG_CMD_PLG_INCOMING_LBS_IND";
+
+// 40
+               case MSG_CMD_PLG_INIT_SIM_BY_SAT:
+                       return "MSG_CMD_PLG_INIT_SIM_BY_SAT";
+               case MSG_CMD_GET_THREADVIEWLIST:
+                       return "MSG_CMD_GET_THREADVIEWLIST";
+               case MSG_CMD_GET_CONVERSATIONVIEWLIST:
+                       return "MSG_CMD_GET_CONVERSATIONVIEWLIST";
+               case MSG_CMD_DELETE_THREADMESSAGELIST:
+                       return "MSG_CMD_DELETE_THREADMESSAGELIST";
+               case MSG_CMD_GET_CONTACT_COUNT:
+                       return "MSG_CMD_GET_CONTACT_COUNT";
+
+// 45
+               case MSG_CMD_GET_QUICKPANEL_DATA:
+                       return "MSG_CMD_GET_QUICKPANEL_DATA";
+               case MSG_CMD_COUNT_BY_MSGTYPE:
+                       return "MSG_CMD_COUNT_BY_MSGTYPE";
+               case MSG_CMD_RESET_DB:
+                       return "MSG_CMD_RESET_DB";
+               case MSG_CMD_GET_MEMSIZE:
+                       return "MSG_CMD_GET_MEMSIZE";
+               case MSG_CMD_BACKUP_MESSAGE:
+                       return "MSG_CMD_BACKUP_MESSAGE";
+
+// 50
+               case MSG_CMD_RESTORE_MESSAGE:
+                       return "MSG_CMD_RESTORE_MESSAGE";
+               case MSG_CMD_UPDATE_THREAD_READ:
+                       return "MSG_CMD_UPDATE_THREAD_READ";
+               case MSG_CMD_REG_SYNCML_MSG_OPERATION_CB:
+                       return "MSG_CMD_REG_SYNCML_MSG_OPERATION_CB";
+               case MSG_CMD_SYNCML_OPERATION:
+                       return "MSG_CMD_SYNCML_OPERATION";
+               case MSG_CMD_GET_REPORT_STATUS:
+                       return "MSG_CMD_GET_REPORT_STATUS";
+
+// 55
+               case MSG_CMD_GET_THREAD_ID_BY_ADDRESS:
+                       return "MSG_CMD_GET_THREAD_ID_BY_ADDRESS";
+               case MSG_CMD_GET_THREAD_INFO:
+                       return "MSG_CMD_GET_THREAD_INFO";
+               case MSG_CMD_GET_SMSC_OPT:
+                       return "MSG_CMD_GET_SMSC_OPT";
+               case MSG_CMD_GET_CB_OPT:
+                       return "MSG_CMD_GET_CB_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:
+                       return "MSG_CMD_GET_MMS_RECV_OPT";
+               case MSG_CMD_GET_PUSH_MSG_OPT:
+                       return "MSG_CMD_GET_PUSH_MSG_OPT";
+               case MSG_CMD_GET_VOICE_MSG_OPT:
+                       return "MSG_CMD_GET_VOICE_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:
+                       return "MSG_CMD_SET_SMS_SEND_OPT";
+               case MSG_CMD_SET_MMS_SEND_OPT:
+                       return "MSG_CMD_SET_MMS_SEND_OPT";
+               case MSG_CMD_SET_MMS_RECV_OPT:
+                       return "MSG_CMD_SET_MMS_RECV_OPT";
+               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";
+
+               default:
+                       return "Unknown Command Type!!!";
+       }
+
+       return NULL;
+}
+
+const char * MsgDbgEvtStr(MSG_EVENT_TYPE_T evtType)
+{
+       switch ( evtType )
+       {
+// 0
+               case MSG_EVENT_OPEN_HANDLE:
+                       return "MSG_EVENT_OPEN_HANDLE";
+               case MSG_EVENT_CLOSE_HANDLE:
+                       return "MSG_EVENT_CLOSE_HANDLE";
+               case MSG_EVENT_GET_STORAGELIST:
+                       return "MSG_EVENT_GET_STORAGELIST";
+               case MSG_EVENT_ADD_MSG:
+                       return "MSG_EVENT_ADD_MSG";
+               case MSG_EVENT_ADD_SYNCML_MSG:
+                       return "MSG_EVENT_ADD_SYNCML_MSG";
+// 5
+               case MSG_EVENT_UPDATE_MSG:
+                       return "MSG_EVENT_UPDATE_MSG";
+               case MSG_EVENT_UPDATE_READ:
+                       return "MSG_EVENT_UPDATE_READ";
+               case MSG_EVENT_UPDATE_PROTECTED:
+                       return "MSG_EVENT_UPDATE_PROTECTED";
+               case MSG_EVENT_DELETE_MSG:
+                       return "MSG_EVENT_DELETE_MSG";
+               case MSG_EVENT_DELALL_MSGINFOLDER:
+                       return "MSG_EVENT_DELALL_MSGINFOLDER";
+// 10
+               case MSG_EVENT_MOVE_MSGTOFOLDER:
+                       return "MSG_EVENT_MOVE_MSGTOFOLDER";
+               case MSG_EVENT_MOVE_MSGTOSTORAGE:
+                       return "MSG_EVENT_MOVE_MSGTOSTORAGE";
+               case MSG_EVENT_COUNT_MSG:
+                       return "MSG_EVENT_COUNT_MSG";
+               case MSG_EVENT_GET_MSG:
+                       return "MSG_EVENT_GET_MSG";
+               case MSG_EVENT_GET_FOLDERVIEWLIST:
+                       return "MSG_EVENT_GET_FOLDERVIEWLIST";
+// 15
+               case MSG_EVENT_ADD_FOLDER:
+                       return "MSG_EVENT_ADD_FOLDER";
+               case MSG_EVENT_UPDATE_FOLDER:
+                       return "MSG_EVENT_UPDATE_FOLDER";
+               case MSG_EVENT_DELETE_FOLDER:
+                       return "MSG_EVENT_DELETE_FOLDER";
+               case MSG_EVENT_GET_FOLDERLIST:
+                       return "MSG_EVENT_GET_FOLDERLIST";
+               case MSG_EVENT_ADD_FILTER:
+                       return "MSG_EVENT_ADD_FILTER";
+//20
+               case MSG_EVENT_UPDATE_FILTER:
+                       return "MSG_EVENT_UPDATE_FILTER";
+               case MSG_EVENT_DELETE_FILTER:
+                       return "MSG_EVENT_DELETE_FILTER";
+               case MSG_EVENT_GET_FILTERLIST:
+                       return "MSG_EVENT_GET_FILTERLIST";
+               case MSG_EVENT_SET_FILTER_OPERATION:
+                       return "MSG_EVENT_SET_FILTER_OPERATION";
+               case MSG_EVENT_GET_FILTER_OPERATION:
+                       return "MSG_EVENT_GET_FILTER_OPERATION";
+//25
+               case MSG_EVENT_GET_MSG_TYPE:
+                       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:
+                       return "MSG_EVENT_REG_STORAGE_CHANGE_CB";
+
+// 30
+               case MSG_EVENT_REG_INCOMING_MSG_CB:
+                       return "MSG_EVENT_REG_INCOMING_MSG_CB";
+               case MSG_EVENT_REG_INCOMING_MMS_CONF_MSG_CB:
+                       return "MSG_EVENT_REG_INCOMING_MMS_CONF_MSG_CB";
+               case MSG_EVENT_REG_INCOMING_SYNCML_MSG_CB:
+                       return "MSG_EVENT_REG_INCOMING_SYNCML_MSG_CB";
+               case MSG_EVENT_REG_INCOMING_LBS_MSG_CB:
+                       return "MSG_EVENT_REG_INCOMING_LBS_MSG_CB";
+               case MSG_EVENT_PLG_SENT_STATUS_CNF:
+                       return "MSG_EVENT_PLG_SENT_STATUS_CNF";
+
+// 35
+               case MSG_EVENT_PLG_STORAGE_CHANGE_IND:
+                       return "MSG_EVENT_STORAGE_CHANGE_CB";
+               case MSG_EVENT_PLG_INCOMING_MSG_IND:
+                       return "MSG_EVENT_PLG_INCOMING_MSG_IND";
+               case MSG_EVENT_PLG_INCOMING_MMS_CONF:
+                       return "MSG_EVENT_PLG_INCOMING_MMS_CONF";
+               case MSG_EVENT_PLG_INCOMING_SYNCML_MSG_IND:
+                       return "MSG_EVENT_PLG_INCOMING_SYNCML_MSG_IND";
+               case MSG_EVENT_PLG_INCOMING_LBS_MSG_IND:
+                       return "MSG_EVENT_PLG_INCOMING_LBS_MSG_IND";
+
+// 40
+               case MSG_EVENT_PLG_INIT_SIM_BY_SAT:
+                       return "MSG_EVENT_PLG_INIT_SIM_BY_SAT";
+               case MSG_EVENT_GET_THREADVIEWLIST:
+                       return "MSG_EVENT_GET_THREADVIEWLIST";
+               case MSG_EVENT_GET_CONVERSATIONVIEWLIST:
+                       return "MSG_EVENT_GET_CONVERSATIONVIEWLIST";
+               case MSG_EVENT_DELETE_THREADMESSAGELIST:
+                       return "MSG_EVENT_DELETE_THREADMESSAGELIST";
+               case MSG_EVENT_GET_CONTACT_COUNT:
+                       return "MSG_EVENT_GET_CONTACT_COUNT";
+
+// 45
+               case MSG_EVENT_GET_QUICKPANEL_DATA:
+                       return "MSG_EVENT_GET_QUICKPANEL_DATA";
+               case MSG_EVENT_COUNT_BY_MSGTYPE:
+                       return "MSG_EVENT_COUNT_BY_MSGTYPE";
+               case MSG_EVENT_RESET_DB:
+                       return "MSG_EVENT_RESET_DB";
+               case MSG_EVENT_GET_MEMSIZE:
+                       return "MSG_EVENT_GET_MEMSIZE";
+               case MSG_EVENT_BACKUP_MESSAGE:
+                       return "MSG_EVENT_BACKUP_MESSAGE";
+
+// 50
+               case MSG_EVENT_RESTORE_MESSAGE:
+                       return "MSG_EVENT_RESTORE_MESSAGE";
+               case MSG_EVENT_UPDATE_THREAD_READ:
+                       return "MSG_EVENT_UPDATE_THREAD_READ";
+               case MSG_EVENT_REG_SYNCML_MSG_OPERATION_CB:
+                       return "MSG_EVENT_REG_SYNCML_MSG_OPERATION_CB";
+               case MSG_EVENT_SYNCML_OPERATION:
+                       return "MSG_EVENT_SYNCML_OPERATION";
+               case MSG_EVENT_GET_REPORT_STATUS:
+                       return "MSG_EVENT_GET_REPORT_STATUS";
+
+// 55
+               case MSG_CMD_GET_THREAD_ID_BY_ADDRESS:
+                       return "MSG_CMD_GET_THREAD_ID_BY_ADDRESS";
+               case MSG_CMD_GET_THREAD_INFO:
+                       return "MSG_CMD_GET_THREAD_INFO";
+               case MSG_EVENT_GET_SMSC_OPT:
+                       return "MSG_EVENT_GET_SMSC_OPT";
+               case MSG_EVENT_GET_CB_OPT:
+                       return "MSG_EVENT_GET_CB_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:
+                       return "MSG_EVENT_GET_MMS_RECV_OPT";
+               case MSG_EVENT_GET_PUSH_MSG_OPT:
+                       return "MSG_EVENT_GET_PUSH_MSG_OPT";
+               case MSG_EVENT_GET_VOICE_MSG_OPT:
+                       return "MSG_EVENT_GET_VOICE_MSG_OPT";
+
+// 65
+               case MSG_EVENT_GET_GENERAL_MSG_OPT:
+                       return "MSG_EVENT_GET_GENERAL_MSG_OPT";
+
+// 65
+               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";
+               case MSG_EVENT_SET_CB_OPT:
+                       return "MSG_EVENT_SET_CB_OPT";
+               case MSG_EVENT_SET_SMS_SEND_OPT:
+                       return "MSG_EVENT_SET_SMS_SEND_OPT";
+               case MSG_EVENT_SET_MMS_SEND_OPT:
+                       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";
+               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";
+               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";
+
+               case MSG_EVENT_DELETE_PUSH_EVENT:
+                       return "MSG_EVENT_DELETE_PUSH_EVENT";
+               case MSG_EVENT_UPDATE_PUSH_EVENT:
+                       return "MSG_EVENT_UPDATE_PUSH_EVENT";
+
+               default:
+                       return "Unknown Event Type!!!";
+       }
+
+       return NULL;
+}
+
+
+int get_tid()
+{
+    return syscall(__NR_gettid);
+}
+
diff --git a/utils/MsgDrmWrapper.cpp b/utils/MsgDrmWrapper.cpp
new file mode 100755 (executable)
index 0000000..a8ac429
--- /dev/null
@@ -0,0 +1,208 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgDrmWrapper.h"
+#include "MsgUtilFile.h"
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <dirent.h>
+#include <string.h>
+#include <sys/vfs.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <drm_client_types.h>
+#include <drm_client.h>
+
+#define MSG_MAX_DRM_FILE_PATH MSG_FILEPATH_LEN_MAX
+
+bool MsgDrmRegisterFile(MSG_DRM_OPENMODE eMode, char *pBuffer, int nSize)
+{
+       if (eMode == MSG_MODE_STREAM) {
+               MSG_DEBUG("Fail(eMode == MSG_MODE_STREAM)");
+               return false;
+       }
+
+       if (pBuffer == NULL) {
+               MSG_DEBUG("[Error] pBuffer is NULL");
+               return false;
+       }
+
+       MSG_DEBUG("buffer = %s, nSize = %d", pBuffer, nSize);
+
+       drm_bool_type_e isDrm;
+       int eDRMResult = drm_is_drm_file(pBuffer, &isDrm);
+
+       if (eDRMResult != DRM_RETURN_SUCCESS || isDrm != DRM_TRUE) {
+               MSG_DEBUG("file is not drm file");
+               return false;
+       }
+
+       drm_request_type_e request_type = DRM_REQUEST_TYPE_REGISTER_FILE;
+
+       eDRMResult = drm_process_request(request_type, pBuffer, NULL);
+       if (DRM_RETURN_SUCCESS != eDRMResult) {
+               MSG_DEBUG("drm_process_request is failed : %d", eDRMResult);
+               return false;
+       }
+       MSG_END();
+       return true;
+}
+
+bool MsgDrmUnregisterFile(char *szFilename)
+{
+       if (szFilename == NULL) {
+               MSG_DEBUG("[Error] szFilename is NULL");
+               return false;
+       }
+
+       MSG_DEBUG("szFilename = %s", szFilename);
+
+       drm_request_type_e request_type = DRM_REQUEST_TYPE_UNREGISTER_FILE;
+
+       int eDRMResult = drm_process_request(request_type, szFilename, NULL); // Unregister a DCF file
+       if (DRM_RETURN_SUCCESS != eDRMResult) {
+               MSG_DEBUG("drm_process_request : %d", eDRMResult);
+               return false;
+       }
+
+       return true;
+}
+
+bool MsgDrmIsDrmFile(const char *szFilePath)
+{
+       drm_bool_type_e isDrm;
+       int eDRMResult = drm_is_drm_file(szFilePath, &isDrm);
+
+       if (eDRMResult != DRM_RETURN_SUCCESS || isDrm != DRM_TRUE) {
+               MSG_DEBUG("file is not drm file");
+               return false;
+       }
+
+       return true;
+}
+
+/*Added to convert the .dm files in to .dcf files since our platform supports only .dcf :: Start*/
+bool MsgDrmConvertDmtoDcfType(char *inputFile, char *outputFile)
+{
+       return true;
+}
+
+bool MsgDrmGetDrmType(const char *szFileName, MSG_DRM_TYPE *eDRMType)
+{
+       if (szFileName == NULL || eDRMType == NULL) {
+               MSG_DEBUG("Param is NULL");
+               return false;
+       }
+
+       drm_file_type_e file_type;
+       int result = drm_get_file_type(szFileName, &file_type);
+       if (result != DRM_RETURN_SUCCESS) {
+               MSG_DEBUG("drm_get_file_type is failed %d", result);
+               return false;
+       }
+
+       if (file_type == DRM_TYPE_OMA_V1) {
+               drm_file_info_s drmInfo;
+               bzero(&drmInfo, sizeof(drm_file_info_s));
+               int eDRMResult = drm_get_file_info(szFileName, &drmInfo);
+               if (DRM_RETURN_SUCCESS != eDRMResult) {
+                       MSG_DEBUG("drm_get_file_info is Fail eDRMResult = %d", eDRMResult);
+                       return false;
+               }
+
+               // Convert DRM_METHOD into MSG_DRM_TYPE
+               switch (drmInfo.oma_info.method) {
+               case DRM_METHOD_TYPE_FORWARD_LOCK:
+                       *eDRMType = MSG_DRM_FORWARD_LOCK;
+                       break;
+               case DRM_METHOD_TYPE_COMBINED_DELIVERY:
+                       *eDRMType = MSG_DRM_COMBINED_DELIVERY;
+                       break;
+               case DRM_METHOD_TYPE_SEPARATE_DELIVERY:
+                       *eDRMType = MSG_DRM_SEPARATE_DELIVERY;
+                       break;
+               default:
+                       *eDRMType = MSG_DRM_NONE;
+                       break;
+               }
+               MSG_DEBUG("eDRMType : %d", *eDRMType);
+       } else {
+               MSG_DEBUG("This is not a DRM_TYPE_OMA_V1 type");
+               return false;
+       }
+
+       return true;
+}
+
+bool MsgDrmGetMimeTypeEx(const char *szFileName, char *szMimeType, int nMimeTypeLen)
+{
+       if (!szFileName || !szMimeType || !nMimeTypeLen) {
+               MSG_DEBUG("param is NULL");
+               return false;
+       }
+
+       char strTemp[MSG_MAX_DRM_FILE_PATH + 1] = {0,};
+
+       strncpy(strTemp, szFileName, strlen(szFileName));
+
+       drm_content_info_s tdcfContentinfo;
+       memset(&tdcfContentinfo, 0x00, sizeof(drm_content_info_s));
+       int eDRMResult = drm_get_content_info(strTemp, &tdcfContentinfo); // Get attribute of DRM File
+       if (DRM_RETURN_SUCCESS == eDRMResult) {
+               MSG_DEBUG("contentType = %s", tdcfContentinfo.mime_type);
+               snprintf(szMimeType, nMimeTypeLen, "%s", tdcfContentinfo.mime_type);
+
+       } else {
+               MSG_DEBUG("drm_get_content_info is failed %d", eDRMResult);
+               return false;
+       }
+
+       return true;
+}
+
+bool MsgDrmGetContentID(const char *szFileName, char *szContentID, int nContentIDLen)
+{
+       if (!szFileName || !szContentID || !nContentIDLen) {
+               MSG_DEBUG("param is NULL");
+               return false;
+       }
+
+       char strTemp[MSG_MAX_DRM_FILE_PATH + 1] = {0,};
+
+       strncpy(strTemp, szFileName, sizeof(strTemp));
+
+       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);
+        snprintf(szContentID, nContentIDLen, "%s", content_info.content_id);
+       } else {
+               MSG_DEBUG("drm_get_content_info is failed %d", result);
+               return false;
+       }
+
+       return true;
+}
+
diff --git a/utils/MsgException.cpp b/utils/MsgException.cpp
new file mode 100755 (executable)
index 0000000..51980dc
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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"
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+string MsgException::errorStrings[NUM_ERRORS] =
+{
+       "SUCCESS",
+
+       "INVALID_PARAM",
+       "INVALID_RESULT",
+       "SELECT_ERROR",
+       "IPC_ERROR",
+       "OUT_OF_RANGE" , //5
+
+       "SMS_PLG_ERROR",
+       "MMS_PLG_ERROR",
+       "PLUGIN_ERROR",
+       "SENT_STATUS_ERROR",
+       "INCOMING_MSG_ERROR", //10
+
+       "FILE_OPERATION_ERROR",
+       "SECURITY_ERROR"
+       "SERVER_READY_ERROR"
+};
+
diff --git a/utils/MsgGconfWrapper.cpp b/utils/MsgGconfWrapper.cpp
new file mode 100755 (executable)
index 0000000..cac8937
--- /dev/null
@@ -0,0 +1,294 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgNotificationWrapper.h"
+#include "MsgGconfWrapper.h"
+
+#ifdef USE_GCONF
+
+#define GCONF_SUCCESS 1
+
+MSG_GOBJECT_CLIENT_S* pClient = NULL;
+
+#endif
+
+bool bAutoReject = false;
+bool bUnknownAutoReject = false;
+
+
+/*==================================================================================================
+                                     DEFINES
+==================================================================================================*/
+#define MSG_UNREAD_CNT         "db/badge/org.tizen.message"
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+static void MsgVconfCB(keynode_t *key, void* data)
+{
+       char *keyStr = NULL;
+       keyStr = vconf_keynode_get_name(key);
+
+       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)) {
+               bUnknownAutoReject = vconf_keynode_get_bool(key);
+               MSG_DEBUG("[%s] key CB called. set to [%d].", VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL, bUnknownAutoReject);
+       } else {
+               MSG_DEBUG("key did not match.");
+       }
+}
+
+msg_error_t MsgSettingSetString(const char *pKey, const char *pSetValue)
+{
+       if (pKey == NULL || pSetValue == NULL)
+       {
+               MSG_DEBUG("IN Parameter is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+#ifdef USE_GCONF
+       if (gconf_client_set_string((GConfClient*)pClient, pKey, pSetValue, NULL) !=  GCONF_SUCCESS)
+               return MSG_ERR_SET_SETTING;
+#else
+       if (vconf_set_str(pKey, pSetValue) != 0)
+               return MSG_ERR_SET_SETTING;
+#endif
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgSettingSetInt(const char *pKey, int nSetValue)
+{
+       if (pKey == NULL)
+       {
+               MSG_DEBUG("IN Parameter is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+#ifdef USE_GCONF
+       if (gconf_client_set_int((GConfClient*)pClient, pKey, nSetValue, NULL) !=  GCONF_SUCCESS)
+               return MSG_ERR_SET_SETTING;
+#else
+       if (vconf_set_int(pKey, nSetValue) != 0)
+               return MSG_ERR_SET_SETTING;
+#endif
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgSettingSetBool(const char *pKey, bool bSetValue)
+{
+       if (pKey == NULL)
+       {
+               MSG_DEBUG("IN Parameter is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+#ifdef USE_GCONF
+       if (gconf_client_set_bool((GConfClient*)pClient, pKey, bSetValue, NULL) !=  GCONF_SUCCESS)
+               return MSG_ERR_SET_SETTING;
+#else
+       if (vconf_set_bool(pKey, bSetValue) != 0)
+               return MSG_ERR_SET_SETTING;
+#endif
+
+       return MSG_SUCCESS;
+}
+
+
+char* MsgSettingGetString(const char *pKey)
+{
+       if (pKey == NULL)
+       {
+               MSG_DEBUG("IN Parameter is NULL");
+               return NULL;
+       }
+
+#ifdef USE_GCONF
+       return gconf_client_get_string((GConfClient*)pClient, pKey, NULL);
+#else
+       return vconf_get_str(pKey);
+#endif
+}
+
+
+int MsgSettingGetInt(const char *pKey)
+{
+       if (pKey == NULL)
+       {
+               MSG_DEBUG("IN Parameter is NULL");
+               return -1;
+       }
+
+       int retVal = 0;
+
+#ifdef USE_GCONF
+       retVal = gconf_client_get_int((GConfClient*)pClient, pKey, NULL);
+#else
+       if (vconf_get_int(pKey, &retVal) < 0)
+               return -1;
+#endif
+
+       return retVal;
+}
+
+
+int MsgSettingGetBool(const char *pKey, bool *pVal)
+{
+       if (pKey == NULL)
+       {
+               MSG_DEBUG("IN Parameter is NULL");
+               return -1;
+       }
+
+       int retVal = 0, param = 0;
+
+#ifdef USE_GCONF
+       *pVal = gconf_client_get_bool((GConfClient*)pClient, pKey, NULL);
+#else
+       if (vconf_get_bool(pKey, &param) < 0)
+               return -1;
+#endif
+
+       *pVal = (bool)param;
+
+       return retVal;
+}
+
+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 activated. Turn on the lcd.");
+               pm_change_state(LCD_NORMAL);
+       }
+
+       MSG_END();
+}
+
+msg_error_t MsgSettingHandleNewMsg(int SmsCnt, int MmsCnt)
+{
+       MSG_BEGIN();
+
+       MSG_DEBUG("smsCnt = %d, mmsCnt = %d ##", SmsCnt, MmsCnt);
+
+       // Set Msg Count into VConf
+       if (MsgSettingSetIndicator(SmsCnt, MmsCnt) != MSG_SUCCESS)
+       {
+               MSG_DEBUG("MsgSettingSetIndicator() FAILED");
+               return MSG_ERR_SET_SETTING;
+       }
+
+       if (SmsCnt == 0 && MmsCnt == 0)
+       {
+               MSG_DEBUG("No New Message.");
+       }
+       else
+       {
+               MSG_DEBUG("New Message.");
+               MsgChangePmState();
+       }
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgSettingSetIndicator(int SmsCnt, int MmsCnt)
+{
+
+       if (MsgSettingSetInt(VCONFKEY_MESSAGE_RECV_SMS_STATE, SmsCnt) != 0)
+               return MSG_ERR_SET_SETTING;
+       if (MsgSettingSetInt(VCONFKEY_MESSAGE_RECV_MMS_STATE, MmsCnt) != 0)
+               return MSG_ERR_SET_SETTING;
+
+       int sumCnt = SmsCnt + MmsCnt;
+
+//     if (MsgSettingSetInt(MSG_UNREAD_CNT, sumCnt) != 0)
+       if (MsgInsertBadge(sumCnt) != MSG_SUCCESS)
+               return MSG_ERR_SET_SETTING;
+
+       return MSG_SUCCESS;
+}
+
+
+bool MsgSettingGetAutoReject()
+{
+       return bAutoReject;
+}
+
+bool MsgSettingGetUnknownAutoReject()
+{
+       return bUnknownAutoReject;
+}
+
+void MsgSettingRegVconfCBCommon(const char *pKey, _vconf_change_cb pCb)
+{
+       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);
+       }
+}
+
+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 MsgSettingRegVconfCB()
+{
+       // Set default values.
+       MsgSettingGetBool(VCONFKEY_CISSAPPL_AUTO_REJECT_BOOL, &bAutoReject);
+       MsgSettingGetBool(VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL, &bUnknownAutoReject);
+
+       MsgSettingRegVconfCBCommon(VCONFKEY_CISSAPPL_AUTO_REJECT_BOOL, MsgVconfCB);
+       MsgSettingRegVconfCBCommon(VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL, MsgVconfCB);
+}
+
+void MsgSettingRemoveVconfCB()
+{
+       MsgSettingRemoveVconfCBCommon(VCONFKEY_CISSAPPL_AUTO_REJECT_BOOL, MsgVconfCB);
+       MsgSettingRemoveVconfCBCommon(VCONFKEY_CISSAPPL_AUTO_REJECT_UNKNOWN_BOOL, MsgVconfCB);
+
+}
diff --git a/utils/MsgIpcSocket.cpp b/utils/MsgIpcSocket.cpp
new file mode 100755 (executable)
index 0000000..733e531
--- /dev/null
@@ -0,0 +1,506 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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/un.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <errno.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include "MsgDebug.h"
+#include "MsgException.h"
+#include "MsgIpcSocket.h"
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgIpcClientSocket - Member Functions
+==================================================================================================*/
+MsgIpcClientSocket::MsgIpcClientSocket() : sockfd(-1), remotefd(-1), maxfd(-1)
+{
+       FD_ZERO(&fds);
+}
+
+
+msg_error_t MsgIpcClientSocket::connect(const char* path)
+{
+       MSG_BEGIN();
+
+       if (!path || strlen(path) > strlen(MSG_SOCKET_PATH)) {
+               THROW(MsgException::IPC_ERROR, "path is null");
+       }
+
+       sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
+
+       if (sockfd < 0) {
+               THROW(MsgException::IPC_ERROR,"socket not opened %s",strerror(errno));
+       }
+
+       struct sockaddr_un serverSA = {0, };
+       serverSA.sun_family = AF_UNIX;
+
+       memset(serverSA.sun_path, 0x00, sizeof(serverSA.sun_path));
+       strncpy(serverSA.sun_path, path, sizeof(serverSA.sun_path)-1);  /* // "./socket" */
+
+       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));
+       }
+
+       /* add fd for select() */
+       addfd(sockfd);
+
+       /* read remote fd for reg func */
+       char *rfd = NULL;
+       AutoPtr<char> wrap(&rfd);
+       unsigned int rlen;
+
+       read(&rfd, &rlen);
+
+       if (rfd == NULL) {
+               THROW(MsgException::IPC_ERROR,"rfd is NULL %s", strerror(errno));
+       }
+
+       memcpy(&remotefd, rfd, sizeof(rlen));
+
+       MSG_DEBUG("Connected: client fd [%d] <----> remote fd [%d]", sockfd, remotefd);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgIpcClientSocket::close()
+{
+       if (sockfd < 0) {
+               MSG_FATAL("Client socket is not opened (check if you call close twice by accident) [%d]", sockfd);
+               return MSG_ERR_UNKNOWN;
+       }
+
+       /* it means that client is going to close the connection.*/
+       int cmd = CLOSE_CONNECTION_BY_USER;
+       int len = sizeof(cmd);
+
+       char cmdbuf[len];
+       bzero(cmdbuf, len);
+       memcpy(cmdbuf, &cmd, len);
+
+       ::close(sockfd);
+       sockfd = CUSTOM_SOCKET_ERROR;
+
+       return MSG_SUCCESS;
+}
+
+void MsgIpcClientSocket::addfd(int fd)
+{
+       MSG_DEBUG("%d added", fd);
+       FD_SET(fd, &fds);
+       if (fd > maxfd)
+               maxfd = fd;
+}
+
+int MsgIpcClientSocket::writen (const char *buf, unsigned int len)
+{
+       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));
+                       return nwrite;
+               } else if (nwrite == 0) {
+                       break;
+               }
+
+               nleft -= nwrite;
+               buf += nwrite;
+       }
+       return (len-nleft);
+}
+
+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) {
+               MSG_FATAL("buf[%p]      and len[%d] MUST NOT NULL", buf, len);
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       /* send the data size first */
+       int n = writen((const char*)&len, sizeof(len));
+       if (n != sizeof(len)) {
+               MSG_FATAL("WARNING: write header_size[%d] not matched [%d]", n, sizeof(len));
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       /* send the data in subsequence */
+       n = writen(buf, len);
+       if ((unsigned int)n != len) {
+               MSG_FATAL("WARNING: write data_size[%d] not matched [%d]", n, len);
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       return len;
+}
+
+int MsgIpcClientSocket::readn( char *buf, unsigned int len )
+{
+       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));
+                       return nread;
+               } else if( nread == 0 ) {
+                       break;
+               }
+
+               nleft -= nread;
+               buf += nread;
+       }
+
+       return (len-nleft);
+}
+
+
+/* what if the buf is shorter than data? */
+int MsgIpcClientSocket::read(char** buf, unsigned int* len)
+{
+       if (sockfd < 0) {
+               MSG_FATAL("socket is not opened [%d]", sockfd);
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       if (!buf || !len) {
+               MSG_FATAL("rbuf and rlen MUST NOT NULL");
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       /* read the data size first */
+       int n = readn((char*) len, 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 */
+       unsigned int ulen = (unsigned int)*len;
+       *buf = new char[ulen];
+       bzero(*buf, ulen);
+       n = readn(*buf, ulen);
+
+       if ((unsigned int)n !=  ulen) {
+               MSG_FATAL("WARNING: read data_size [%d] not matched [%d]", n, ulen);
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       return n;
+}
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgIpcServerSocket - Member Functions
+==================================================================================================*/
+MsgIpcServerSocket::MsgIpcServerSocket() : sockfd(-1), maxfd(-1)
+{
+       FD_ZERO(&fds);
+}
+
+void MsgIpcServerSocket::addfd(int fd)
+{
+       MSG_DEBUG("%d added", fd);
+       FD_SET(fd, &fds);
+
+       std::map<int, int>::iterator it = mapFds.find(fd);
+       if (it != mapFds.end())
+               MSG_FATAL("Duplicate FD %d", fd);
+       else
+               mapFds[fd] = fd;
+
+       if (fd > maxfd)
+               maxfd = fd;
+}
+
+msg_error_t MsgIpcServerSocket::open(const char* path)
+{
+       MSG_BEGIN();
+
+       if (!path || strlen(path) > strlen(MSG_SOCKET_PATH)) {
+               MSG_FATAL("path is null");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (sockfd != CUSTOM_SOCKET_ERROR) {
+               MSG_FATAL("WARNING: server_socket already opened %d at %p", sockfd,  &sockfd);
+               return MSG_ERR_UNKNOWN;
+       }
+
+       sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
+
+       if (sockfd == CUSTOM_SOCKET_ERROR) {
+               MSG_FATAL("socket failed: %s", strerror(errno));
+               return MSG_ERR_UNKNOWN;
+       }
+
+       MSG_DEBUG("server_socket(%p) opened : %d", &sockfd, sockfd);
+
+       struct sockaddr_un local = {0, };
+
+       local.sun_family = AF_UNIX;
+       memset(local.sun_path, 0x00, sizeof(local.sun_path));
+       strncpy(local.sun_path, path, sizeof(local.sun_path)-1);
+
+       unlink(local.sun_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));
+               return MSG_ERR_UNKNOWN;
+       }
+
+       /**
+        * determine permission of socket file
+        *
+        *  - S_IRWXU : for user, allow read and write and execute
+        *  - S_IRWXG : for group, allow read and write and execute
+        *  - S_IRWXO : for other, allow read and write and execute
+        *
+        *  - S_IRUSR, S_IWUSR, S_IXUSR : for user, allow only read, write, execute respectively
+        *  - S_IRGRP, S_IWGRP, S_IXGRP : for group, allow only read, write, execute respectively
+        *  - S_IROTH, S_IWOTH, S_IXOTH : for other, allow only read, write, execute respectively
+        */
+       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));
+               return MSG_ERR_UNKNOWN;
+       }
+
+       if (listen(sockfd, CUSTOM_SOCKET_BACKLOG) == CUSTOM_SOCKET_ERROR) {
+               MSG_FATAL("listen: %s", strerror(errno));
+               return MSG_ERR_UNKNOWN;
+       }
+
+       addfd(sockfd);
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t MsgIpcServerSocket::accept()
+{
+       MSG_BEGIN();
+
+       if (sockfd == CUSTOM_SOCKET_ERROR) {
+               MSG_FATAL("server_socket not init");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       struct sockaddr_un remote;
+
+       int t = sizeof(remote);
+       int fd = ::accept(sockfd, (struct sockaddr *)&remote, (socklen_t*) &t);
+       if (fd < 0) {
+               MSG_FATAL("accept: %s", strerror(errno));
+               return MSG_ERR_UNKNOWN;
+       }
+
+       addfd(fd);
+       MSG_DEBUG("%d is added", fd);
+
+       /* write the registerd fd */
+       write(fd, (const char*) &fd, sizeof(fd));
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+void MsgIpcServerSocket::close(int fd)
+{
+       MSG_BEGIN();
+
+       if (sockfd == CUSTOM_SOCKET_ERROR) {
+               MSG_FATAL("server_socket not init");
+               return;
+       }
+
+       MSG_DEBUG("%d to be removed", fd);
+       FD_CLR(fd, &fds);
+
+       std::map<int, int>::iterator it = mapFds.find(fd);
+       if (it == mapFds.end())
+               MSG_FATAL("No FD %d", fd);
+       else
+               mapFds.erase(it);
+
+       if (fd == maxfd) {
+               int newmax = 0;
+               for (it = mapFds.begin() ; it != mapFds.end() ; it++)
+                       newmax = (it->second > newmax )? it->second : newmax;
+               maxfd = newmax;
+       }
+       MSG_DEBUG("fd %d removal done", fd);
+       ::close(fd);
+
+       MSG_END();
+}
+
+int MsgIpcServerSocket::readn( int fd, char *buf, unsigned int len )
+{
+       size_t nleft;
+       int nread;
+
+       nleft = (size_t)len;
+       while (nleft > 0) {
+               nread = ::read(fd, (void*)buf, nleft);
+               if (nread < 0) {
+                       MSG_FATAL("read: %s", strerror(errno));
+                       return nread;
+               }
+               else if (nread == 0)
+                       break;
+
+               nleft -= nread;
+               buf += nread;
+       }
+       return (len-nleft);
+}
+
+int MsgIpcServerSocket::read(int fd, char** buf, int* len )
+{
+       if (sockfd == CUSTOM_SOCKET_ERROR) {
+               MSG_FATAL("server_socket(%p) is not initd %d", &sockfd, sockfd);
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       if (!buf || !len) {
+               MSG_FATAL("buf[%p] and len[%p] MUST NOT NULL", buf, len);
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       /* read the data size first */
+       int n = readn(fd, (char*) len, sizeof(int));
+
+       if (n == CLOSE_CONNECTION_BY_SIGNAL) {
+               MSG_FATAL("fd %d CLOSE_CONNECTION_BY_SIGNAL", fd);
+               return n;
+       }
+
+       else if (n != sizeof(int)) {
+               MSG_FATAL("readn %d(%d)", n, sizeof(int));
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       MSG_DEBUG("MsgLen %d", *len);
+       if (*len == CLOSE_CONNECTION_BY_USER)
+               return *len;
+
+       /* 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 ((unsigned int)n != ulen) {
+                       MSG_FATAL("WARNING: read data_size [%d] not matched [%d]", n, ulen);
+                       return CUSTOM_SOCKET_ERROR;
+               }
+       }
+
+       return n;
+}
+
+int MsgIpcServerSocket::writen(int fd, const char *buf, unsigned int len)
+{
+       unsigned int nleft;
+       int nwrite;
+
+       nleft = len;
+
+       while (nleft > 0) {
+               /*  MSG_NOSIGNAL to prevent SIGPIPE Error */
+               /*  MSG_DONTWAIT to avoid socket block */
+               nwrite = ::send(fd, (const void*) buf, nleft, MSG_NOSIGNAL|MSG_DONTWAIT);
+
+               if (nwrite < 0) {
+                       MSG_FATAL("write: %s", strerror(errno));
+                       return nwrite;
+               } else if (nwrite == 0) { /* Nothing is send. */
+                       break;
+               } else {
+                       nleft -= nwrite;
+                       buf += nwrite;
+               }
+       }
+
+       return (len-nleft);
+}
+
+
+int MsgIpcServerSocket::write(int fd, const char* buf, unsigned int len)
+{
+       MSG_BEGIN();
+
+       if (!buf || len <= 0) {
+               MSG_FATAL("buf [%p] and len [%d] MUST NOT NULL", buf, len);
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       MSG_DEBUG("for debug - fd : [%d], buf : [%p], len : [%d]", fd, buf, len);
+
+       /* send the data size first */
+       int n = writen(fd, (const char*)&len, sizeof(len));
+
+       if (n != sizeof(len)) {
+               MSG_FATAL("WARNING: write header_size[%d] not matched [%d]", n, sizeof(len));
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       /*  send the data in subsequence */
+       n = writen(fd, buf, len);
+
+       MSG_DEBUG("Writing %d bytes", n);
+
+       if ((unsigned int)n != len) {
+               MSG_FATAL("Written byte (%d) is not matched to input byte (%d)", n, len);
+               return CUSTOM_SOCKET_ERROR;
+       }
+
+       MSG_END();
+
+       return len;
+}
diff --git a/utils/MsgMemory.cpp b/utils/MsgMemory.cpp
new file mode 100755 (executable)
index 0000000..3023871
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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>
+
+#include "MsgDebug.h"
+#include "MsgSqliteWrapper.h"
+#include "MsgMemory.h"
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+void MsgReleaseMemory()
+{
+       MSG_BEGIN();
+
+       // Release Malloc Memory
+       malloc_trim(0);
+
+       // Release Stack Memory
+//     stack_trim();
+
+       // Release Memory using in sqlite
+       MsgReleaseMemoryDB();
+
+       MSG_END();
+}
+
diff --git a/utils/MsgMmsMessage.cpp b/utils/MsgMmsMessage.cpp
new file mode 100755 (executable)
index 0000000..f4ff2b7
--- /dev/null
@@ -0,0 +1,1158 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <time.h>
+#include <stdlib.h>
+
+#include "MsgTypes.h"
+#include "MsgMmsTypes.h"
+#include "MsgMmsMessage.h"
+#include "MsgDebug.h"
+#include "MsgUtilFile.h"
+#include "MsgStorageTypes.h"
+#include "MsgInternalTypes.h"
+
+
+MMS_SMIL_ROOTLAYOUT    rootlayout;
+
+static void __release_glist_element(gpointer data, gpointer user_data);
+static void __release_page_element(gpointer data, gpointer user_data);
+
+static void __release_glist_element(gpointer data, gpointer user_data)
+{
+       if(data != NULL) {
+               free(data);
+       }
+}
+
+static void __release_page_element(gpointer data, gpointer user_data)
+{
+       if(data != NULL) {
+               MMS_PAGE_S *page = (MMS_PAGE_S *)data;
+
+               if (page->medialist) {
+                       MMS_MEDIA_S *media = NULL;
+                       int mediaCnt = g_list_length(page->medialist);
+
+                       for (int i = 0; i < mediaCnt; i++) {
+                               media = (MMS_MEDIA_S *)g_list_nth_data(page->medialist, i);
+                               if (media)
+                                       free(media);
+                       }
+
+                       g_list_free(page->medialist);
+                       page->medialist = NULL;
+                       page->mediaCnt = 0;
+               }
+
+               free(page);
+       }
+}
+
+msg_error_t _MsgMmsReleasePageList(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (pMsgData->pagelist) {
+               g_list_foreach(pMsgData->pagelist, __release_page_element, NULL);
+               g_list_free(pMsgData->pagelist);
+               pMsgData->pagelist = NULL;
+       }
+
+       pMsgData->pageCnt = 0;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t _MsgMmsReleaseRegionList(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (pMsgData->regionlist) {
+               g_list_foreach(pMsgData->regionlist, __release_glist_element, NULL);
+               g_list_free(pMsgData->regionlist);
+               pMsgData->regionlist = NULL;
+       }
+
+       pMsgData->regionCnt = 0;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t _MsgMmsReleaseAttachList(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (pMsgData->attachlist) {
+               g_list_foreach(pMsgData->attachlist, __release_glist_element, NULL);
+               g_list_free(pMsgData->attachlist);
+               pMsgData->attachlist = NULL;
+       }
+
+       pMsgData->attachCnt = 0;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t _MsgMmsReleaseTransitionList(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (pMsgData->transitionlist) {
+               g_list_foreach(pMsgData->transitionlist, __release_glist_element, NULL);
+               g_list_free(pMsgData->transitionlist);
+               pMsgData->transitionlist = NULL;
+       }
+
+       pMsgData->transitionCnt = 0;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t _MsgMmsReleaseMetaList(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (pMsgData->metalist) {
+               g_list_foreach(pMsgData->metalist, __release_glist_element, NULL);
+               g_list_free(pMsgData->metalist);
+               pMsgData->metalist = NULL;
+       }
+
+       pMsgData->metaCnt = 0;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t _MsgMmsAddRegion(MMS_MESSAGE_DATA_S *pMsgData, MMS_SMIL_REGION* pRegion)
+{
+       if(pMsgData == NULL || pRegion == NULL)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       pMsgData->regionlist = g_list_append(pMsgData->regionlist, pRegion);
+       pMsgData->regionCnt++;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t _MsgMmsAddPage(MMS_MESSAGE_DATA_S *pMsgData, MMS_PAGE_S *pPage)
+{
+       if(pMsgData == NULL || pPage == NULL)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       pMsgData->pagelist = g_list_append(pMsgData->pagelist, pPage);
+       pMsgData->pageCnt++;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t _MsgMmsAddMedia(MMS_PAGE_S* pPage, MMS_MEDIA_S *pMedia)
+{
+       if(pPage == NULL || pMedia == NULL)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       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);
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t _MsgMmsAddTransition(MMS_MESSAGE_DATA_S *pMsgData, MMS_SMIL_TRANSITION* pTransition)
+{
+       if(pMsgData == NULL || pTransition == NULL)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       pMsgData->transitionlist = g_list_append(pMsgData->transitionlist, pTransition);
+       pMsgData->transitionCnt++;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t _MsgMmsAddMeta(MMS_MESSAGE_DATA_S *pMsgData, MMS_SMIL_META* pMeta)
+{
+       if(pMsgData == NULL || pMeta == NULL)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       pMsgData->metalist = g_list_append(pMsgData->metalist, pMeta);
+       pMsgData->metaCnt++;
+
+       return MSG_SUCCESS;
+}
+
+msg_error_t _MsgMmsAddAttachment(MMS_MESSAGE_DATA_S *pMsgData, MMS_ATTACH_S *pAttach)
+{
+       if(pMsgData == NULL || pAttach == NULL)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       pMsgData->attachlist = g_list_append(pMsgData->attachlist, pAttach);
+       pMsgData->attachCnt++;
+
+       return MSG_SUCCESS;
+}
+
+bool _MsgMmsFindMatchedMedia(MMS_MESSAGE_DATA_S *pMsgData, char *pszFilePath)
+{
+       if (pMsgData == NULL || pszFilePath == NULL)
+               return false;
+
+       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);
+
+                       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;
+                                       }
+                               }
+                       }
+               }
+       }
+
+       return false;
+}
+
+msg_error_t _MsgMmsAddSmilDoc(char* pSmil, MMS_MESSAGE_DATA_S* pMsgData)
+{
+       MSG_DEBUG("MsgMmsAddSmilDoc");
+
+       if(pSmil == NULL || pMsgData == NULL)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       char    fullpath[MSG_FILEPATH_LEN_MAX] = {0,};
+       char smilFileName[MSG_FILENAME_LEN_MAX+1] = {0,};
+       time_t  RawTime = 0;
+
+       //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);
+
+       if (MsgWriteSmilFile(fullpath, pSmil, strlen(pSmil)) == false) {
+               MSG_DEBUG("MsgWriteSmilFile error");
+               return MSG_ERR_MMS_ERROR;
+       }
+       strncpy(pMsgData->szSmilFilePath, smilFileName, MSG_FILEPATH_LEN_MAX-1);
+
+       return MSG_SUCCESS;
+}
+
+
+char* _MsgMmsSerializeMessageData(const MMS_MESSAGE_DATA_S* pMsgData, unsigned int *pSize)
+{
+       MSG_DEBUG("MsgMmsSerializeMessageData");
+
+       if (pMsgData == NULL)
+               return NULL;
+
+       int bufsize = 0;
+       int offset = 0;
+       int pageCnt = 0;
+       char *buf = NULL;
+
+       pageCnt = pMsgData->pageCnt;
+
+       int mediaCnt = 0;
+
+       if (pMsgData->pagelist) {
+               for (int pageIdx = 0; pageIdx < pageCnt; pageIdx++) {
+                       bufsize += sizeof(int); // Media cnt
+
+                       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);
+
+                                       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)
+#ifdef MMS_SMIL_ANIMATE
+                                                       + MAX_SMIL_ANIMATE_ATTRIBUTE_NAME + MAX_SMIL_ANIMATE_ATTRIBUTE_TYPE + MAX_SMIL_ANIMATE_TARGET_ELEMENT
+                                                       + MAX_SMIL_ANIMATE_CALC_MODE + 5 * sizeof(int)
+#endif
+                                                       );
+                                       }
+                               }
+                       }
+
+                       bufsize += sizeof(int) * 6;
+               }
+       }
+
+       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 += 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 += 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 += 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 += sizeof(MMS_SMIL_ROOTLAYOUT);
+
+#ifdef FEATURE_JAVA_MMS
+       bufsize += sizeof(MMS_APPID_INFO_S);
+#endif
+
+       int filePathLen = strlen(pMsgData->szSmilFilePath);
+
+       bufsize += sizeof(int) + filePathLen + sizeof(int);
+
+       MSG_DEBUG("MsgMmsSerializeMessageData: bufsize = %d", bufsize);
+
+       buf = (char *)calloc(bufsize, 1);
+
+       // copy file path length
+       MSG_DEBUG("MsgMmsSerializeMessageData: smilFilePath Length = %d",  filePathLen);
+
+       memcpy(buf, &filePathLen, sizeof(int));
+
+       offset += sizeof(int);
+
+       // copy file path
+       MSG_DEBUG("MsgMmsSerializeMessageData: smilFilePath = %s",  pMsgData->szSmilFilePath);
+
+       if (filePathLen > 0) {
+               memcpy(buf + offset, pMsgData->szSmilFilePath, filePathLen);
+
+               offset += filePathLen;
+       }
+
+       // copy page count
+       MSG_DEBUG("MsgMmsSerializeMessageData: pageCnt = %d",  pMsgData->pageCnt);
+
+       memcpy(buf + offset, &(pMsgData->pageCnt), sizeof(int));
+
+       offset += sizeof(int);
+
+       if (pMsgData->pagelist) {
+               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));
+                       offset += sizeof(int);
+
+                       MSG_DEBUG("MsgMmsSerializeMessageData: mediaCnt = %d",  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);
+
+                                       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);
+
+#ifdef MMS_SMIL_ANIMATE
+                                               memcpy(buf + offset, media->sMedia.sAVI.nAttributeName, MAX_SMIL_ANIMATE_ATTRIBUTE_NAME);
+                                               offset +=  MAX_SMIL_ANIMATE_ATTRIBUTE_NAME;
+
+                                               memcpy(buf + offset, media->sMedia.sAVI.nAttributeType, MAX_SMIL_ANIMATE_ATTRIBUTE_TYPE);
+                                               offset +=  MAX_SMIL_ANIMATE_ATTRIBUTE_TYPE;
+
+                                               memcpy(buf + offset, media->sMedia.sAVI.nTargetElement, MAX_SMIL_ANIMATE_TARGET_ELEMENT);
+                                               offset +=  MAX_SMIL_ANIMATE_TARGET_ELEMENT;
+
+                                               memcpy(buf + offset, &(media->sMedia.sAVI.nFrom), sizeof(int));
+                                               offset += sizeof(int);
+
+                                               memcpy(buf + offset, &(media->sMedia.sAVI.nTo), sizeof(int));
+                                               offset += sizeof(int);
+
+                                               memcpy(buf + offset, &(media->sMedia.sAVI.nBy), sizeof(int));
+                                               offset += sizeof(int);
+
+                                               memcpy(buf + offset, &(media->sMedia.sAVI.nValues), sizeof(int));
+                                               offset += sizeof(int);
+
+                                               memcpy(buf + offset, &(media->sMedia.sAVI.nDur), sizeof(int));
+                                               offset += sizeof(int);
+
+                                               memcpy(buf + offset, media->sMedia.sAVI.nCalcMode, MAX_SMIL_ANIMATE_CALC_MODE);
+                                               offset +=  MAX_SMIL_ANIMATE_CALC_MODE;
+#endif
+                                       }
+                               }
+                       }
+
+                       memcpy(buf + offset, &page->nDur, sizeof(int));
+                       offset += sizeof(int);
+                       memcpy(buf + offset, &page->nBegin, sizeof(int));
+                       offset += sizeof(int);
+                       memcpy(buf + offset, &page->nEnd, sizeof(int));
+                       offset += sizeof(int);
+                       memcpy(buf + offset, &page->nMin, sizeof(int));
+                       offset += sizeof(int);
+                       memcpy(buf + offset, &page->nMax, sizeof(int));
+                       offset += sizeof(int);
+                       memcpy(buf + offset, &page->nRepeat, sizeof(int));
+                       offset += sizeof(int);
+               }
+       }
+
+       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, &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, &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, &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, &pMsgData->rootlayout, sizeof(MMS_SMIL_ROOTLAYOUT));
+       offset += sizeof(MMS_SMIL_ROOTLAYOUT);
+
+#ifdef FEATURE_JAVA_MMS
+       memcpy(buf + offset, &pMsgData->msgAppId, sizeof(MMS_APPID_INFO_S));
+       offset += sizeof(MMS_APPID_INFO_S);
+#endif
+
+       *pSize = offset;
+
+       return buf;
+}
+
+int _MsgMmsGetPageCount(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return 0;
+       }
+
+       int count = 0;
+
+       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;
+       }
+
+       MMS_PAGE_S *page = NULL;
+
+       if (pMsgData->pagelist)
+               page = (MMS_PAGE_S *)g_list_nth_data(pMsgData->pagelist, pageIdx);
+
+       return page;
+}
+
+int _MsgMmsGetAttachCount(MMS_MESSAGE_DATA_S *pMsgData)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return 0;
+       }
+
+       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;
+       }
+
+       MMS_ATTACH_S *attach = NULL;
+       if (pMsgData->attachlist)
+               attach = (MMS_ATTACH_S *)g_list_nth_data(pMsgData->attachlist, attachIdx);
+
+       return attach;
+}
+
+MMS_SMIL_REGION *_MsgMmsGetSmilRegion(MMS_MESSAGE_DATA_S *pMsgData, int regionIdx)
+{
+       if (pMsgData == NULL) {
+               MSG_DEBUG("pMsgData is NULL");
+               return NULL;
+       }
+
+       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           _MsgMmsDeserializeMessageData(MMS_MESSAGE_DATA_S* pBody, char* pData)
+{
+       MSG_DEBUG("MmsGetMsgBodyfromFile");
+
+       if (pBody == NULL || pData == NULL) {
+               MSG_DEBUG("param is NULL. pBody = %x, pData = %x", pBody, pData);
+               return false;
+       }
+
+       int offset = 0;
+       int pageCnt = 0;
+       int filePathLen = 0;
+
+       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;
+
+       memcpy(&filePathLen, pData, sizeof(int));
+
+       offset += sizeof(int);
+
+       MSG_DEBUG("Smil File Path Length : %d", filePathLen);
+
+       if (filePathLen > MSG_FILEPATH_LEN_MAX) {
+               MSG_DEBUG("Smil File Path Length is abnormal.");
+               return false;
+       }
+
+       memset(pBody->szSmilFilePath, 0x00, MSG_FILEPATH_LEN_MAX);
+
+       if (filePathLen > 0) {
+               memcpy(pBody->szSmilFilePath, pData + offset, filePathLen);
+
+               offset += filePathLen;
+       }
+
+       memcpy(&(pBody->pageCnt), pData + offset, sizeof(int));
+
+       offset += sizeof(int);
+
+       pageCnt = pBody->pageCnt;
+
+       MSG_DEBUG("MMS PAGE COUNT: %d", pageCnt);
+
+       for (int j = 0; j < pageCnt; ++j) {
+               pPage = (MMS_PAGE_S *)calloc(sizeof(MMS_PAGE_S), 1);
+
+               memcpy(&pPage->mediaCnt, pData + offset, sizeof(int));
+               offset += sizeof(int);
+               MSG_DEBUG("MMS MEDIA COUNT: %d", pPage->mediaCnt);
+
+               for (int i = 0; i < pPage->mediaCnt; ++i) {
+                       pMedia = (MMS_MEDIA_S *)calloc(sizeof(MMS_MEDIA_S), 1);
+
+                       memcpy(&pMedia->mediatype, pData + offset, sizeof(int));
+                       offset += sizeof(int);
+
+                       memcpy(pMedia->szSrc, pData + offset, MSG_FILEPATH_LEN_MAX);
+                       offset += MSG_FILEPATH_LEN_MAX;
+
+                       memcpy(pMedia->szFileName, pData + offset, MSG_FILENAME_LEN_MAX);
+                       offset += MSG_FILENAME_LEN_MAX;
+
+                       memcpy(pMedia->szFilePath, pData + offset, MSG_FILEPATH_LEN_MAX);
+                       offset += MSG_FILEPATH_LEN_MAX;
+
+                       memcpy(pMedia->szContentID, pData + offset, MSG_MSG_ID_LEN+1);
+                       offset += MSG_MSG_ID_LEN + 1;
+
+                       memcpy(pMedia->regionId, pData + offset, MAX_SMIL_REGION_ID);
+                       offset += MAX_SMIL_REGION_ID;
+
+                       memcpy(pMedia->szAlt, pData + offset, MAX_SMIL_ALT_LEN);
+                       offset += MAX_SMIL_ALT_LEN;
+
+#ifdef __SUPPORT_DRM__
+                       memcpy(&pMedia->drmType, pData + offset, sizeof(MsgDrmType));
+                       offset += sizeof(MsgDrmType);
+
+                       memcpy(pMedia->szDrm2FullPath, pData + offset, MSG_FILEPATH_LEN_MAX);
+                       offset += MSG_FILEPATH_LEN_MAX;
+#endif
+
+                       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;
+
+                               memcpy(pMedia->sMedia.sText.szTransOutId, pData + offset, MAX_SMIL_TRANSOUT_ID);
+                               offset += MAX_SMIL_TRANSOUT_ID;
+
+                               memcpy(&pMedia->sMedia.sText.nRepeat, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sText.nBegin, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sText.nEnd, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sText.nDurTime, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sText.nBgColor, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sText.bBold, pData + offset, sizeof(bool));
+                               offset += sizeof(bool);
+
+                               memcpy(&pMedia->sMedia.sText.bUnderLine, pData + offset, sizeof(bool));
+                               offset += sizeof(bool);
+
+                               memcpy(&pMedia->sMedia.sText.bItalic, pData + offset, sizeof(bool));
+                               offset += sizeof(bool);
+
+                               memcpy(&pMedia->sMedia.sText.bReverse, pData + offset, sizeof(bool));
+                               offset += sizeof(bool);
+
+                               memcpy(&pMedia->sMedia.sText.nDirection, pData + offset, sizeof(MmsTextDirection));
+                               offset += sizeof(MmsTextDirection);
+
+                               //memcpy(&pMedia->sMedia.sText.nFont, pData + offset, sizeof(MmsSmilFontType));
+                               //offset += sizeof(MmsSmilFontType);
+
+                               memcpy(&pMedia->sMedia.sText.nSize, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               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;
+
+                               memcpy(pMedia->sMedia.sAVI.szTransOutId, pData + offset, MAX_SMIL_TRANSOUT_ID);
+                               offset += MAX_SMIL_TRANSOUT_ID;
+
+                               memcpy(&pMedia->sMedia.sAVI.nRepeat, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sAVI.nBegin, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sAVI.nEnd, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sAVI.nDurTime, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sAVI.nBgColor, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+#ifdef MMS_SMIL_ANIMATE
+                               memcpy(pMedia->sMedia.sAVI.nAttributeName, pData + offset, MAX_SMIL_ANIMATE_ATTRIBUTE_NAME);
+                               offset += MAX_SMIL_ANIMATE_ATTRIBUTE_NAME;
+
+                               memcpy(pMedia->sMedia.sAVI.nAttributeType, pData + offset, MAX_SMIL_ANIMATE_ATTRIBUTE_TYPE);
+                               offset += MAX_SMIL_ANIMATE_ATTRIBUTE_TYPE;
+
+                               memcpy(pMedia->sMedia.sAVI.nTargetElement, pData + offset, MAX_SMIL_ANIMATE_TARGET_ELEMENT);
+                               offset += MAX_SMIL_ANIMATE_TARGET_ELEMENT;
+
+                               memcpy(&pMedia->sMedia.sAVI.nFrom, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sAVI.nTo, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sAVI.nBy, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sAVI.nValues, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(&pMedia->sMedia.sAVI.nDur, pData + offset, sizeof(int));
+                               offset += sizeof(int);
+
+                               memcpy(pMedia->sMedia.sAVI.nCalcMode, pData + offset, MAX_SMIL_ANIMATE_CALC_MODE);
+                               offset += MAX_SMIL_ANIMATE_CALC_MODE;
+#endif
+                       }
+                       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);
+
+               pBody->pagelist = g_list_append(pBody->pagelist, pPage);
+       }
+
+       //Processing Region List
+       memcpy(&pBody->regionCnt, pData + offset, sizeof(int));
+       offset += sizeof(int);
+
+       MSG_DEBUG(" pBody->regionCnt: %d", pBody->regionCnt);
+
+       for (int i = 0; i < pBody->regionCnt; ++i) {
+               pRegion = (MMS_SMIL_REGION *)calloc(sizeof(MMS_SMIL_REGION), 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);
+
+               pBody->regionlist = g_list_append(pBody->regionlist, pRegion);
+       }
+
+       //Processing Attachment List
+       memcpy(&pBody->attachCnt, pData + offset, sizeof(int));
+       offset += sizeof(int);
+
+       MSG_DEBUG(" pBody->attachCnt: %d", pBody->attachCnt);
+
+       for (int i = 0; i < pBody->attachCnt; ++i) {
+               pAttach = (MMS_ATTACH_S *)calloc(sizeof(MMS_ATTACH_S), 1);
+
+               memcpy(&pAttach->mediatype, pData + offset, sizeof(MimeType));
+               offset += sizeof(MimeType);
+
+               memcpy(pAttach->szFileName, pData + offset, MSG_FILENAME_LEN_MAX);
+               offset += MSG_FILENAME_LEN_MAX;
+
+               memcpy(pAttach->szFilePath, pData + offset, MSG_FILEPATH_LEN_MAX);
+               offset += MSG_FILEPATH_LEN_MAX;
+
+               memcpy(&pAttach->fileSize, pData + offset, sizeof(int));
+               offset += sizeof(int);
+
+#ifdef __SUPPORT_DRM__
+               memcpy(&pAttach->drmType, pData + offset, sizeof(MsgDrmType));
+               offset += sizeof(MsgDrmType);
+
+               memcpy(pAttach->szDrm2FullPath, pData + offset, MSG_FILEPATH_LEN_MAX);
+               offset += MSG_FILEPATH_LEN_MAX;
+#endif
+
+               pBody->attachlist = g_list_append(pBody->attachlist, pAttach);
+       }
+
+       //Processing Transition List
+       memcpy(&pBody->transitionCnt, pData + offset, sizeof(int));
+       offset += sizeof(int);
+
+       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);
+
+               memcpy(pTransition->szID, pData + offset, MAX_SMIL_TRANSITION_ID);
+               offset += MAX_SMIL_TRANSITION_ID;
+
+               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);
+
+               pBody->transitionlist = g_list_append(pBody->transitionlist, pTransition);
+       }
+
+       //Processing Meta List
+       memcpy(&pBody->metaCnt, pData + offset, sizeof(int));
+       offset += sizeof(int);
+
+       MSG_DEBUG(" pBody->metaCnt: %d", pBody->metaCnt);
+
+       for (int i = 0; i < pBody->metaCnt; ++i) {
+               pMeta = (MMS_SMIL_META *)calloc(sizeof(MMS_SMIL_META), 1);
+
+               memcpy(pMeta->szID, pData + offset, MAX_SMIL_META_ID);
+               offset += MAX_SMIL_META_ID;
+
+               memcpy(pMeta->szName, pData + offset, MAX_SMIL_META_NAME);
+               offset += MAX_SMIL_META_NAME;
+
+               memcpy(pMeta->szContent, pData + offset, MAX_SMIL_META_CONTENT);
+               offset += MAX_SMIL_META_CONTENT;
+
+               pBody->metalist = g_list_append(pBody->metalist, pMeta);
+       }
+
+       memcpy(&pBody->rootlayout, pData + offset, sizeof(MMS_SMIL_ROOTLAYOUT));
+       offset += sizeof(MMS_SMIL_ROOTLAYOUT);
+
+#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);
+
+       return true;
+}
+
+bool   _MsgMmsSetRootLayout(MMS_MESSAGE_DATA_S* pMmsMsg, MMS_SMIL_ROOTLAYOUT* pRootlayout)
+{
+       memcpy(&pMmsMsg->rootlayout, pRootlayout, sizeof(MMS_SMIL_ROOTLAYOUT));
+       return true;
+}
+
diff --git a/utils/MsgMutex.cpp b/utils/MsgMutex.cpp
new file mode 100755 (executable)
index 0000000..cad97a4
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 */
+#include <sys/mman.h>
+#include <errno.h>
+
+#include "MsgDebug.h"
+#include "MsgMutex.h"
+
+#define MSG_SHM_NAME "/msg_fw_shm"
+
+typedef struct {
+       pthread_mutex_t mutex;
+       pthread_cond_t  condvar;
+       int ready;
+} MSG_MUTEX_S;
+
diff --git a/utils/MsgNotificationWrapper.cpp b/utils/MsgNotificationWrapper.cpp
new file mode 100755 (executable)
index 0000000..a8fc3e2
--- /dev/null
@@ -0,0 +1,935 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilStorage.h"
+#include "MsgGconfWrapper.h"
+#include "MsgNotificationWrapper.h"
+
+extern "C"
+{
+       #include <notification.h>
+}
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+void MsgSmsClass0Noti(MSG_MESSAGE_INFO_S* pMsg, notification_h noti, bundle* args)
+{
+       MSG_BEGIN();
+       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
+       char tempId[6];
+
+       memset(tempId, 0x00, sizeof(tempId));
+
+       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);
+       }
+
+       noti_err = notification_set_layout(noti, NOTIFICATION_LY_NOTI_EVENT_SINGLE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_layout : %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);
+       }
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "CLASS 0 Message", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, "New CLASS 0 Message", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       if (pMsg->addressList[0].displayName[0] == '\0')
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, pMsg->addressList[0].addressVal, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       else
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, pMsg->addressList[0].displayName, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2, pMsg->msgText, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       // set time.
+       notification_set_time_to_text(noti, NOTIFICATION_TEXT_TYPE_INFO_SUB_1, pMsg->displayTime);
+
+       bundle_add(args, "type", "msg_id");
+
+       snprintf(tempId, 5, "%d", pMsg->msgId);
+       bundle_add(args, "msgId", tempId);
+
+       MSG_END();
+}
+
+void MsgSmsCBNoti(MSG_MESSAGE_INFO_S* pMsg, notification_h noti, bundle* args)
+{
+       MSG_BEGIN();
+
+       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
+       char tempId[6];
+
+       memset(tempId, 0x00, sizeof(tempId));
+
+       noti_err = notification_set_application(noti, "8r4r5ddzzn.Messages");
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_application : %d", noti_err);
+       }
+
+       noti_err = notification_set_layout(noti, NOTIFICATION_LY_NOTI_EVENT_SINGLE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_layout : %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);
+       }
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "CB Message", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, "New CB Message", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       if (pMsg->addressList[0].displayName[0] == '\0')
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, pMsg->addressList[0].addressVal, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       else
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, pMsg->addressList[0].displayName, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2, pMsg->msgText, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       // set time.
+       notification_set_time_to_text(noti, NOTIFICATION_TEXT_TYPE_INFO_SUB_1, pMsg->displayTime);
+
+       memset(&tempId, 0x00, sizeof(tempId));
+
+       bundle_add(args, "type", "msg_id");
+
+       snprintf(tempId, 5, "%d", pMsg->msgId);
+       bundle_add(args, "msgId", tempId);
+
+       MSG_END();
+}
+
+void MsgSmsVoiceNoti(MSG_MESSAGE_INFO_S* pMsg, notification_h noti, bundle* args)
+{
+       MSG_BEGIN();
+
+       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
+
+       noti_err = notification_set_application(noti, "org.tizen.call");
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_application : %d", noti_err);
+       }
+
+       noti_err = notification_set_layout(noti, NOTIFICATION_LY_NOTI_EVENT_SINGLE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_layout : %d", noti_err);
+       }
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "Voice Message", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, "New Voice Message", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       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);
+       }
+
+       if (pMsg->addressList[0].displayName[0] == '\0')
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, pMsg->addressList[0].addressVal, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       else
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, pMsg->addressList[0].displayName, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2, pMsg->msgText, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       // set time.
+       notification_set_time_to_text(noti, NOTIFICATION_TEXT_TYPE_INFO_SUB_1, pMsg->displayTime);
+
+       //FIXME :: Temp code for voice number, 2012.08.16 sangkoo.kim
+       bundle_add(args, "launch-type", "MO");
+       bundle_add(args, "number", pMsg->addressList[0].addressVal);
+
+       MSG_END();
+}
+
+
+void MsgSmsReportNoti(MSG_MESSAGE_INFO_S* pMsg, notification_h noti, bundle* args)
+{
+       MSG_BEGIN();
+
+       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
+       char tempId[6];
+
+       memset(tempId, 0x00, sizeof(tempId));
+
+       noti_err = notification_set_application(noti, "8r4r5ddzzn.Messages");
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_application : %d", noti_err);
+       }
+       noti_err = notification_set_layout(noti, NOTIFICATION_LY_NOTI_EVENT_SINGLE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_layout : %d", noti_err);
+       }
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "Delivery Message", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, "New Delivery Message", NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       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 (pMsg->addressList[0].displayName[0] == '\0')
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, pMsg->addressList[0].addressVal, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       else
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, pMsg->addressList[0].displayName, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2, pMsg->msgText, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       // set time.
+       notification_set_time_to_text(noti, NOTIFICATION_TEXT_TYPE_INFO_SUB_1, pMsg->displayTime);
+
+       // get msg id
+       MsgDbHandler dbhandler;
+       char sqlQuery[MAX_QUERY_LEN+1];
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery),
+                       "SELECT MSG_ID "
+                       "FROM %s "
+                       "WHERE CONV_ID IN (SELECT CONV_ID FROM %s WHERE ADDRESS_VAL LIKE '%%%s') AND FOLDER_ID=%d "
+                       "ORDER BY DISPLAY_TIME DESC;"
+                       , MSGFW_MESSAGE_TABLE_NAME, MSGFW_ADDRESS_TABLE_NAME, pMsg->addressList[0].addressVal, MSG_SENTBOX_ID);
+
+       MSG_DEBUG("sqlQuery - %s", sqlQuery);
+
+       if (dbhandler.prepareQuery(sqlQuery) == MSG_SUCCESS) {
+
+               if (dbhandler.stepQuery() == MSG_ERR_DB_ROW) {
+                       memset(&tempId, 0x00, sizeof(tempId));
+
+                       bundle_add(args, "type", "report");
+
+                       snprintf(tempId, 5, "%d", dbhandler.columnInt(0));
+                       bundle_add(args, "msgId", tempId);
+
+                       MSG_DEBUG("msgId [%s] add.", tempId);
+               }
+
+               dbhandler.finalizeQuery();
+       }
+
+       MSG_END();
+}
+
+
+msg_error_t MsgInsertNoti(MSG_MESSAGE_INFO_S* pMsg)
+{
+       MSG_DEBUG("Start to Insert Notification.");
+       notification_h noti = NULL;
+       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
+       bundle* args = NULL;
+
+       noti = notification_create(NOTIFICATION_TYPE_NOTI);
+       if (noti == NULL) {
+               MSG_DEBUG("notification_create is failed.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       if (pMsg->msgType.mainType == MSG_SMS_TYPE) {
+               switch(pMsg->msgType.subType)
+               {
+               case MSG_CB_SMS :
+                       args = bundle_create();
+                       MsgSmsCBNoti(pMsg, noti, args);
+                       break;
+               case MSG_MWI_VOICE_SMS :
+               case MSG_MWI_FAX_SMS :
+               case MSG_MWI_EMAIL_SMS :
+               case MSG_MWI_OTHER_SMS :
+                       args = bundle_create();
+                       MsgSmsVoiceNoti(pMsg, noti, args);
+                       break;
+               case MSG_STATUS_REPORT_SMS :
+                       args = bundle_create();
+                       MsgSmsReportNoti(pMsg, noti, args);
+                       break;
+               default :
+                       MsgRefreshNoti(true);
+                       noti_err = notification_free(noti);
+                       if (noti_err != NOTIFICATION_ERROR_NONE) {
+                               MSG_DEBUG("Fail to notification_free");
+                       }
+                       return MSG_SUCCESS;
+                       break;
+               }
+       } else if (pMsg->msgType.mainType == MSG_MMS_TYPE) {
+               switch(pMsg->msgType.subType)
+               {
+               default :
+                       MsgRefreshNoti(true);
+                       noti_err = notification_free(noti);
+                       if (noti_err != NOTIFICATION_ERROR_NONE) {
+                               MSG_DEBUG("Fail to notification_free");
+                       }
+                       return MSG_SUCCESS;
+                       break;
+               }
+       } else {
+               MSG_DEBUG("Message type does not match.");
+
+               noti_err = notification_free(noti);
+               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                       MSG_DEBUG("Fail to notification_free");
+               }
+
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       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_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");
+       }
+
+       if (args != NULL) {
+               bundle_free(args);
+       }
+
+       MsgChangePmState();
+
+       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;
+
+       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));
+
+       int report_status_type;
+       int report_status_value;
+
+       if (pMsg->msgType.subType == MSG_DELIVERYIND_MMS) {
+               report_status_type = MSG_REPORT_TYPE_DELIVERY;
+               MSG_DEBUG("mms subtype is Delivery Report type");
+       } else if (pMsg->msgType.subType == MSG_READORGIND_MMS) {
+               report_status_type = MSG_REPORT_TYPE_READ;
+               MSG_DEBUG("mms subtype is Read Report type");
+       } else {
+               MSG_DEBUG("No matching subtype. subtype [%d]", pMsg->msgType.subType);
+               return MSG_SUCCESS;
+       }
+
+       MSG_ADDRESS_INFO_S *address_info_s = &pMsg->addressList[0];
+       MSG_DEBUG("address info : %s, type : %d", address_info_s->addressVal, address_info_s->addressType);
+
+       if (address_info_s->addressType == MSG_ADDRESS_TYPE_PLMN) {
+
+               if (strlen(address_info_s->addressVal) > MAX_PRECONFIG_NUM) {
+                       char newPhoneNum[MAX_PRECONFIG_NUM+1];
+
+                       memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
+
+                       MsgConvertNumber(address_info_s->addressVal, newPhoneNum);
+
+                       snprintf(sqlQuery, sizeof(sqlQuery),
+                                               "SELECT A.ADDRESS_VAL, A.DISPLAY_NAME, A.FIRST_NAME, A.LAST_NAME, B.STATUS "
+                                               "FROM %s A, %s B "
+                                               "WHERE B.MSG_ID=%d AND B.STATUS_TYPE=%d AND A.ADDRESS_VAL LIKE '%%%s' AND B.ADDRESS_VAL LIKE \'%%%s\';"
+                                               , MSGFW_ADDRESS_TABLE_NAME, MSGFW_REPORT_TABLE_NAME, pMsg->msgId, report_status_type, newPhoneNum, newPhoneNum);
+               } else {
+
+                       snprintf(sqlQuery, sizeof(sqlQuery),
+                               "SELECT A.ADDRESS_VAL, A.DISPLAY_NAME, A.FIRST_NAME, A.LAST_NAME, B.STATUS "
+                               "FROM %s A, %s B "
+                               "WHERE B.MSG_ID=%d AND B.STATUS_TYPE=%d AND A.ADDRESS_VAL LIKE '%s' AND B.ADDRESS_VAL LIKE '%s';"
+                               , MSGFW_ADDRESS_TABLE_NAME, MSGFW_REPORT_TABLE_NAME, pMsg->msgId, report_status_type, address_info_s->addressVal, address_info_s->addressVal);
+               }
+
+       } else if (address_info_s->addressType == MSG_ADDRESS_TYPE_EMAIL) {//check full
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                       "SELECT A.ADDRESS_VAL, A.DISPLAY_NAME, A.FIRST_NAME, A.LAST_NAME, B.STATUS "
+                       "FROM %s A, %s B "
+                       "WHERE B.MSG_ID=%d AND B.STATUS_TYPE=%d AND A.ADDRESS_VAL=\'%s\' AND B.ADDRESS_VAL LIKE \'%s\';"
+                       , MSGFW_ADDRESS_TABLE_NAME, MSGFW_REPORT_TABLE_NAME, pMsg->msgId, report_status_type, address_info_s->addressVal, address_info_s->addressVal);
+       } else {
+               snprintf(sqlQuery, sizeof(sqlQuery),
+                       "SELECT A.ADDRESS_VAL, A.DISPLAY_NAME, A.FIRST_NAME, A.LAST_NAME, B.STATUS "
+                       "FROM %s A, %s B "
+                       "WHERE B.MSG_ID=%d B.STATUS_TYPE=%d;"
+                       , MSGFW_ADDRESS_TABLE_NAME, MSGFW_REPORT_TABLE_NAME, pMsg->msgId, report_status_type);
+       }
+
+       MSG_DEBUG("sqlQuery = [%s]", sqlQuery);
+
+       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);
+                       MSG_DEBUG("addressVal is [%s]",addressVal);
+               } else {
+                       MSG_DEBUG("address Val is Null");
+               }
+
+               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));
+                               }
+                       }
+               }
+
+               report_status_value = pDbHandle->columnInt(4);
+               MSG_DEBUG("report status [type = %d, value = %d]", report_status_type, report_status_value);
+       } else {
+               MSG_DEBUG("DB Query Result Fail");
+               pDbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       pDbHandle->finalizeQuery();
+
+       noti = notification_create(NOTIFICATION_TYPE_NOTI);
+       if (noti == NULL) {
+               MSG_DEBUG("notification_create is failed.");
+               return MSG_ERR_UNKNOWN;
+       }
+
+       noti_err = notification_set_application(noti, "8r4r5ddzzn.Messages");
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_application : %d", noti_err);
+       }
+       noti_err = notification_set_layout(noti, NOTIFICATION_LY_NOTI_EVENT_SINGLE);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_set_layout : %d", noti_err);
+       }
+
+       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_INFO_1, addressVal, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+       else
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, displayName, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+       // set time.
+//     notification_set_time_to_text(noti, NOTIFICATION_TEXT_TYPE_INFO_SUB_1, msgTime);
+
+
+       if (pMsg->msgType.subType == MSG_DELIVERYIND_MMS) {
+
+               switch(report_status_value) {
+               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.");
+                       break;
+               }
+
+               MSG_DEBUG("content text : %s", contents);
+
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2, 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(report_status_value) {
+               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.");
+                       break;
+               }
+
+               MSG_DEBUG("content text : %s", contents);
+
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2, 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 MsgRefreshNoti(bool bWithTicker)
+{
+
+       MsgDbHandler dbhandler;
+       MSG_MESSAGE_INFO_S msg = {0,};
+
+       int notiPrivId = MsgSettingGetInt(NOTIFICATION_PRIV_ID);
+
+       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 thumbPath[MAX_IMAGE_PATH_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(thumbPath, 0x00, sizeof(thumbPath));
+       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, A.IMAGE_PATH, B.MSG_ID, B.MSG_TEXT, B.SUBJECT, B.MAIN_TYPE \
+                       FROM %s A, %s B WHERE A.CONV_ID=B.CONV_ID AND B.READ_STATUS=0 AND B.FOLDER_ID=%d ORDER BY B.DISPLAY_TIME DESC;",
+                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME, MSG_INBOX_ID);
+
+       if (dbhandler.prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (dbhandler.stepQuery() == MSG_ERR_DB_ROW) {
+               threadId = dbhandler.columnInt(0);
+
+               if (dbhandler.columnText(1) != NULL)
+                       strncpy(addressVal, (char*)dbhandler.columnText(1), MAX_ADDRESS_VAL_LEN);
+
+
+               char *pTempDisplayName = (char *)dbhandler.columnText(2);
+               if (pTempDisplayName != NULL && pTempDisplayName[0] != '\0') {
+                       strncpy(displayName, pTempDisplayName, MAX_DISPLAY_NAME_LEN);
+               } else {
+                       if (dbhandler.columnText(3) != NULL)
+                               strncpy(firstName, (char*)dbhandler.columnText(3), MAX_DISPLAY_NAME_LEN);
+
+                       if (dbhandler.columnText(4) != NULL)
+                               strncpy(lastName, (char*)dbhandler.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)dbhandler.columnInt(5);
+
+               contactId = dbhandler.columnInt(6);
+
+               strncpy(thumbPath, (char*)dbhandler.columnText(7), MAX_IMAGE_PATH_LEN);
+
+               msg.msgId = dbhandler.columnInt(8);
+
+               strncpy(msg.msgText, (char*)dbhandler.columnText(9), MAX_MSG_TEXT_LEN);
+
+               strncpy(msg.subject, (char*)dbhandler.columnText(10), MAX_SUBJECT_LEN);
+
+               msg.msgType.mainType = dbhandler.columnInt(11);
+
+               MSG_DEBUG("unread message [%d].", msg.msgId);
+       } else {
+
+               MSG_DEBUG("No unread message.");
+               MSG_DEBUG("notiPrivId [%d]", notiPrivId);
+
+               dbhandler.finalizeQuery();
+
+               // No unread message.
+               if (notiPrivId > 0) {
+                       noti_err = notification_delete_by_priv_id(NULL, NOTIFICATION_TYPE_NOTI, notiPrivId);
+                       if (noti_err != NOTIFICATION_ERROR_NONE) {
+                               MSG_DEBUG("Fail to notification_delete_by_priv_id : %d", noti_err);
+                       }
+               }
+
+               notiPrivId = 0;
+
+               if(MsgSettingSetInt(NOTIFICATION_PRIV_ID, notiPrivId) != MSG_SUCCESS)
+                       MSG_DEBUG("MsgSettingSetInt fail : NOTIFICATION_PRIV_ID");
+
+               return MSG_ERR_DB_STEP;
+       }
+
+       dbhandler.finalizeQuery();
+
+
+       args = bundle_create();
+
+       int unreadMsgCnt = MsgStoGetUnreadCnt(&dbhandler, MSG_SMS_TYPE);
+       unreadMsgCnt += MsgStoGetUnreadCnt(&dbhandler, MSG_MMS_TYPE);
+
+       MSG_DEBUG("notiPrivId [%d], unreadMsgCnt [%d]", notiPrivId, unreadMsgCnt);
+
+       if (notiPrivId > 0) {
+               noti = notification_load(NULL, notiPrivId);
+               if (noti == NULL)
+                       MSG_DEBUG("notification_load is failed.");
+       }
+
+       if (noti == NULL) {
+               noti = notification_create(NOTIFICATION_TYPE_NOTI);
+               if (noti == NULL) {
+                       MSG_DEBUG("notification_new is failed.");
+                       bundle_free(args);
+                       return MSG_ERR_UNKNOWN;
+               }
+
+               notiPrivId = 0;
+       }
+       noti_err = notification_set_application(noti, "8r4r5ddzzn.Messages");
+       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);
+       }
+
+
+       if (unreadMsgCnt > 1) {
+
+               noti_err = notification_set_layout(noti, NOTIFICATION_LY_NOTI_EVENT_MULTIPLE);
+               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                       MSG_DEBUG("Fail to notification_set_layout : %d", noti_err);
+               }
+
+               noti_err = notification_set_text_domain(noti, MSG_SYS_PACKAGE_NAME, MSG_SYS_LOCALEDIR);
+               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                       MSG_DEBUG("Fail to notification_set_text_domain.");
+               }
+
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "Message", MESSAGE, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+               char unreadMsgCntStr[5] = {0,};
+               snprintf(unreadMsgCntStr, 5, "%d", unreadMsgCnt);
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_EVENT_COUNT, unreadMsgCntStr, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, "New Messages", NEW_MESSAGES, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+               if (displayName[0] == '\0')
+                       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, addressVal, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+               else
+                       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, displayName, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+               if (msg.msgType.mainType == MSG_SMS_TYPE)
+                       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2,msg.msgText, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+               else
+                       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2, msg.subject, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+               // set time.
+               notification_set_time_to_text(noti, NOTIFICATION_TEXT_TYPE_INFO_SUB_1, msgTime);
+
+       } else {
+
+               noti_err = notification_set_layout(noti, NOTIFICATION_LY_NOTI_EVENT_SINGLE);
+               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                       MSG_DEBUG("Fail to notification_set_layout : %d", noti_err);
+               }
+
+               noti_err = notification_set_text_domain(noti, MSG_SYS_PACKAGE_NAME, MSG_SYS_LOCALEDIR);
+               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                       MSG_DEBUG("Fail to notification_set_text_domain.");
+               }
+
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_TITLE, "Message", MESSAGE, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+               notification_set_text(noti, NOTIFICATION_TEXT_TYPE_CONTENT, "New Message", NEW_MESSAGE, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+               if (displayName[0] == '\0')
+                       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, addressVal, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+               else
+                       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_1, displayName, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+               if (msg.msgType.mainType == MSG_SMS_TYPE)
+                       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2,msg.msgText, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+               else
+                       notification_set_text(noti, NOTIFICATION_TEXT_TYPE_INFO_2, msg.subject, NULL, NOTIFICATION_VARIABLE_TYPE_NONE);
+
+               // set time.
+               notification_set_time_to_text(noti, NOTIFICATION_TEXT_TYPE_INFO_SUB_1, msgTime);
+
+       }
+       {
+               if (bWithTicker)
+                       noti_err = notification_set_display_applist(noti, NOTIFICATION_DISPLAY_APP_ALL);
+               else
+                       noti_err = notification_set_display_applist(noti, NOTIFICATION_DISPLAY_APP_ALL^NOTIFICATION_DISPLAY_APP_TICKER);
+
+               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                       MSG_DEBUG("Fail to notification_set_display_applist : %d", noti_err);
+               }
+       }
+
+       memset(&tempId, 0x00, sizeof(tempId));
+
+       bundle_add(args, "type", "msg_id");
+
+       snprintf(tempId, 5, "%d", msg.msgId);
+       bundle_add(args, "msgId", tempId);
+
+       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);
+               }
+       }
+
+       if (notiPrivId > 0) {
+               noti_err = notification_update(noti);
+               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                       MSG_DEBUG("Fail to notification_update");
+               }
+       } else {
+               noti_err = notification_insert(noti, &notiPrivId);
+               if (noti_err != NOTIFICATION_ERROR_NONE) {
+                       MSG_DEBUG("Fail to notification_insert");
+               }
+
+               if (MsgSettingSetInt(NOTIFICATION_PRIV_ID, notiPrivId) != MSG_SUCCESS)
+                       MSG_DEBUG("MsgSettingSetInt fail: NOTIFICATION_PRIV_ID");
+               MSG_DEBUG("Insert notiPrivId [%d]", notiPrivId);
+       }
+
+       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 MsgCleanAndResetNoti()
+{
+       msg_error_t err = MSG_SUCCESS;
+       notification_error_e noti_err = NOTIFICATION_ERROR_NONE;
+
+       noti_err = notification_delete_all_by_type("/usr/bin/msg-server", NOTIFICATION_TYPE_NOTI);
+       if (noti_err != NOTIFICATION_ERROR_NONE) {
+               MSG_DEBUG("Fail to notification_delete_all_by_type noti_err [%d]", noti_err);
+               return MSG_ERR_UNKNOWN;
+       }
+
+       err = MsgRefreshNoti(false);
+       if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("Fail to MsgRefreshNoti");
+       }
+
+       return err;
+}
+
+
+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, "8r4r5ddzzn.Messages");
+       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;
+}
+msg_error_t MsgInsertBadge(unsigned int unreadMsgCnt)
+{
+       return MSG_SUCCESS;
+}
diff --git a/utils/MsgSoundPlayer.cpp b/utils/MsgSoundPlayer.cpp
new file mode 100755 (executable)
index 0000000..2655b16
--- /dev/null
@@ -0,0 +1,308 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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(bool isEmergency)
+{
+       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");
+
+               if (isEmergency)
+                       execl("/usr/bin/msg-helper", MSG_EMERGENCY_SOUND_START, NULL);
+               else
+                       execl("/usr/bin/msg-helper", MSG_NORMAL_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, (void *)alarm_info);
+
+       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();
+
+       alarm_info_t *alarm_info = (alarm_info_t *)pUserParam;
+
+       g_bRepeat = false;
+
+       if (MsgSoundGetUnreadMsgCnt() <= 0) {
+               MSG_DEBUG("no unread msg");
+       } else {
+               MsgSoundPlayStart(false);
+       }
+
+       if (alarmmgr_free_alarm(alarm_info) != ALARMMGR_RESULT_SUCCESS)
+               MSG_DEBUG("alarmmgr_free_alarm is failed");
+
+       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(false);
+
+       MSG_END();
+}
diff --git a/utils/MsgSpamFilter.cpp b/utils/MsgSpamFilter.cpp
new file mode 100755 (executable)
index 0000000..c694d11
--- /dev/null
@@ -0,0 +1,214 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 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' 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;",
+                       MSGFW_FILTER_TABLE_NAME, MSG_FILTER_BY_ADDRESS_SAME, pMsgInfo->addressList[0].addressVal, MAX_PRECONFIG_NUM, MAX_PRECONFIG_NUM,
+                       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 (err == MSG_ERR_DB_GETTABLE) {
+               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+       }
+
+       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);
+               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_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_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.");
+                       }
+               }
+       }
+
+       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;
+}
diff --git a/utils/MsgSqliteWrapper.cpp b/utils/MsgSqliteWrapper.cpp
new file mode 100755 (executable)
index 0000000..c916108
--- /dev/null
@@ -0,0 +1,474 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <stddef.h>
+#include <unistd.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "MsgDebug.h"
+#include "MsgSqliteWrapper.h"
+
+extern "C"
+{
+       #include <db-util.h>
+}
+
+
+/*==================================================================================================
+                                     VARIABLES
+==================================================================================================*/
+__thread sqlite3 *handle = NULL;
+__thread sqlite3_stmt *stmt = NULL;
+//__thread char **result = NULL;
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgDbHandler - Member Functions
+==================================================================================================*/
+MsgDbHandler::MsgDbHandler()
+{
+       handle = NULL;
+       stmt = NULL;
+       result = NULL;
+}
+
+
+MsgDbHandler::~MsgDbHandler()
+{
+       if(handle != NULL) {
+               if (disconnect() != MSG_SUCCESS)
+                       MSG_DEBUG("disconnect is failed!!");
+       }
+
+       if(stmt != NULL)
+               finalizeQuery();
+
+       if(result != NULL)
+               freeTable();
+}
+
+
+msg_error_t MsgDbHandler::connect()
+{
+       int ret = 0;
+
+       if (handle == NULL)
+       {
+               char strDBName[64];
+
+               memset(strDBName, 0x00, sizeof(strDBName));
+               snprintf(strDBName, 64, "%s", MSGFW_DB_NAME);
+
+               ret = db_util_open(strDBName, &handle, DB_UTIL_REGISTER_HOOK_METHOD);
+
+               if (ret == SQLITE_OK)
+               {
+                       MSG_DEBUG("DB Connect Success : [%p]", handle);
+                       return MSG_SUCCESS;
+               }
+               else
+               {
+                       MSG_DEBUG("DB Connect Fail [%d]", ret);
+                       return MSG_ERR_DB_CONNECT;
+               }
+       }
+       else
+       {
+               MSG_DEBUG("DB Connect exist : [%p]", handle);
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgDbHandler::disconnect()
+{
+       int ret = 0;
+
+       if (handle != NULL)
+       {
+               ret = db_util_close(handle);
+
+               if (ret == SQLITE_OK)
+               {
+                       handle = NULL;
+                       MSG_DEBUG("DB Disconnect Success");
+                       return MSG_SUCCESS;
+               }
+               else
+               {
+                       MSG_DEBUG("DB Disconnect Fail [%d]", ret);
+                       return MSG_ERR_DB_DISCONNECT;
+               }
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+bool MsgDbHandler::checkTableExist(const char *pTableName)
+{
+       char strQuery[256];
+       int nRowCnt = 0, nResult = 0;
+
+       /* Formulate the Query */
+       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)
+       {
+               freeTable();
+               return false;
+       }
+
+       nResult = getColumnToInt(1);
+       MSG_DEBUG("Result [%d]", nResult);
+
+       freeTable();
+
+       if (nResult > 0)
+               return true;
+       else
+               return false;
+}
+
+
+msg_error_t MsgDbHandler::execQuery(const char *pQuery)
+{
+       int ret = 0;
+
+       if (!pQuery)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       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;
+       }
+       else
+       {
+               MSG_DEBUG("Execute Query Fail [%d]", ret);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgDbHandler::getTable(const char *pQuery, int *pRowCnt)
+{
+       int ret = 0;
+
+       *pRowCnt = 0;
+
+       if(connect() != MSG_SUCCESS)
+               return MSG_ERR_DB_DISCONNECT;
+
+       freeTable();
+       ret = sqlite3_get_table(handle, pQuery, &result, pRowCnt, 0, NULL);
+
+       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
+       {
+               MSG_DEBUG("Get Table Fail [%d]", ret);
+               return MSG_ERR_DB_GETTABLE;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+void MsgDbHandler::freeTable()
+{
+       if (result)
+       {
+               sqlite3_free_table(result);
+               result = NULL;
+       }
+}
+
+
+msg_error_t MsgDbHandler::bindText(const char *pBindStr, int index)
+{
+       int ret = 0;
+
+       if (pBindStr != NULL)
+               ret = sqlite3_bind_text(stmt, index, pBindStr, (strlen(pBindStr) + sizeof(unsigned char)), SQLITE_STATIC);
+
+       return ret;
+}
+
+
+msg_error_t MsgDbHandler::bindBlob(const void * pBindBlob, int size, int index)
+{
+       int ret = 0;
+
+       ret = sqlite3_bind_blob(stmt, index, pBindBlob, size, SQLITE_STATIC);
+
+       return ret;
+}
+
+
+msg_error_t MsgDbHandler::prepareQuery(const char *pQuery)
+{
+       int ret = 0;
+
+       stmt = NULL;
+
+       if(connect() != MSG_SUCCESS)
+               return MSG_ERR_DB_DISCONNECT;
+
+
+       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);
+               return MSG_ERR_DB_PREPARE;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgDbHandler::stepQuery()
+{
+       int ret = 0;
+
+       ret = sqlite3_step(stmt);
+
+       if (ret == SQLITE_ROW)
+       {
+               MSG_DEBUG("MsgStepQuery() SQLITE_ROW");
+               return MSG_ERR_DB_ROW;
+       }
+       else if (ret == SQLITE_DONE)
+       {
+               MSG_DEBUG("MsgStepQuery() SQLITE_DONE");
+               return MSG_ERR_DB_DONE;
+       }
+       else
+       {
+               MSG_DEBUG("MsgStepQuery() Fail [%d]", ret);
+               return MSG_ERR_DB_STEP;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+void MsgDbHandler::finalizeQuery()
+{
+       if(stmt != NULL)
+               sqlite3_finalize(stmt);
+       stmt = NULL;
+}
+
+
+int MsgDbHandler::columnInt(int ColumnIndex)
+{
+       return sqlite3_column_int(stmt, ColumnIndex);
+}
+
+
+const unsigned char* MsgDbHandler::columnText(int ColumnIndex)
+{
+       return sqlite3_column_text(stmt, ColumnIndex);
+}
+
+
+const void* MsgDbHandler::columnBlob(int ColumnIndex)
+{
+       return sqlite3_column_blob(stmt, ColumnIndex);
+}
+
+
+msg_error_t MsgDbHandler::beginTrans()
+{
+       int ret = 0;
+
+       if(connect() != MSG_SUCCESS)
+               return MSG_ERR_DB_DISCONNECT;
+
+
+       ret = sqlite3_exec(handle, "BEGIN deferred;", 0, 0, NULL);
+
+       if (ret == SQLITE_OK)
+       {
+               MSG_DEBUG("Begin Transaction Success");
+               return MSG_SUCCESS;
+       }
+       else
+       {
+               MSG_DEBUG("Begin Transaction Fail [%d]", ret);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgDbHandler::endTrans(bool Success)
+{
+       int ret = 0;
+
+       if(connect() != MSG_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 (ret == SQLITE_OK)
+       {
+               MSG_DEBUG("End Transaction Success");
+               return MSG_SUCCESS;
+       }
+       else
+       {
+               MSG_DEBUG("End Transaction Fail [%d]", ret);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+int MsgDbHandler::getColumnToInt(int RowIndex)
+{
+       char* pTemp = result[RowIndex];
+
+       int nTemp = 0;
+
+       if (pTemp == NULL)
+       {
+               MSG_DEBUG("NULL");
+               return nTemp;
+       }
+
+       nTemp = (int)strtol(pTemp, (char**)NULL, 10);
+
+       return nTemp;
+}
+
+
+char MsgDbHandler::getColumnToChar(int RowIndex)
+{
+       char* pTemp = result[RowIndex];
+
+       if (pTemp == NULL)
+       {
+               MSG_DEBUG("NULL");
+               return '\0';
+       }
+
+       return *pTemp;
+}
+
+
+void MsgDbHandler::getColumnToString(int RowIndex, int Length, char *pString)
+{
+       char* pTemp = result[RowIndex];
+
+       if (pTemp == NULL)
+       {
+               MSG_DEBUG("NULL");
+               return;
+       }
+
+       strncpy(pString, pTemp, Length);
+}
+
+
+msg_error_t MsgDbHandler::getRowId(const char *pTableName, unsigned int *pRowId)
+{
+       int ret = 0, nRowId = 0, nRowCnt = 0;
+       char strQuery[256];
+
+       if (pTableName == NULL || pRowId == NULL)
+               return MSG_ERR_INVALID_PARAMETER;
+
+       MSG_DEBUG("Table Name [%s]", pTableName);
+
+       memset(strQuery, 0x00, sizeof(strQuery));
+       snprintf(strQuery, sizeof(strQuery), "select max(rowid) from %s", pTableName);
+
+       ret = getTable(strQuery, &nRowCnt);
+
+       if (ret == SQLITE_OK)
+       {
+               nRowId = getColumnToInt(1);
+
+               if ((nRowCnt <= 1) && (nRowId == 0))
+                       *pRowId = 1;
+               else
+                       *pRowId = nRowId + 1;
+       }
+       else
+       {
+               MSG_DEBUG("MsgGetRowId failed");
+               *pRowId = 0;
+               freeTable();
+               return MSG_ERR_DB_GETTABLE;
+       }
+
+       freeTable();
+
+       MSG_DEBUG("Row ID [%d]", *pRowId);
+
+       return MSG_SUCCESS;
+}
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+void MsgReleaseMemoryDB()
+{
+       int freeSize = 0;
+
+       freeSize = sqlite3_release_memory(-1);
+
+       MSG_DEBUG("freed memory size (bytes) : [%d]", freeSize);
+}
+
diff --git a/utils/MsgTextConvert.cpp b/utils/MsgTextConvert.cpp
new file mode 100755 (executable)
index 0000000..d76e7ee
--- /dev/null
@@ -0,0 +1,939 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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"
+
+
+/*==================================================================================================
+                                     IMPLEMENTATION OF MsgConvertText - Member Functions
+==================================================================================================*/
+
+MsgTextConvert::MsgTextConvert()
+{
+       extCharList.clear();
+       ucs2toGSM7DefList.clear();
+       ucs2toGSM7ExtList.clear();
+       ucs2toTurkishList.clear();
+       ucs2toSpanishList.clear();
+       ucs2toPortuList.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
+       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; // ï¿½ï¿½
+}
+
+
+MsgTextConvert::~MsgTextConvert()
+{
+       extCharList.clear();
+       ucs2toGSM7DefList.clear();
+       ucs2toGSM7ExtList.clear();
+       ucs2toTurkishList.clear();
+       ucs2toSpanishList.clear();
+       ucs2toPortuList.clear();
+}
+
+
+
+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)
+       {
+               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, 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 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 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;
+
+               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 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_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 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);
+       }
+
+       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 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("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;
+
+       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;
+
+//MSG_DEBUG("inText : [%04x]", inText);
+
+               itExt = extCharList.find(inText);
+
+               if (itExt != extCharList.end())
+               {
+                       newType = (MSG_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 == 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
+                               {
+                                       pDestText[outTextLen++] = 0x20;
+                                       *bIncludeAbnormalChar = true;
+                               }
+                       }
+                       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
+                               {
+                                       pDestText[outTextLen++] = 0x20;
+                                       *bIncludeAbnormalChar = true;
+                               }
+                       }
+                       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
+                               {
+                                       pDestText[outTextLen++] = 0x20;
+                                       *bIncludeAbnormalChar = true;
+                               }
+                       }
+                       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;
+                                       }
+
+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;
+                                       *bIncludeAbnormalChar = true;
+                               }
+                       }
+                       else
+                       {
+                               pDestText[outTextLen++] = 0x20;
+                               *bIncludeAbnormalChar = true;
+                       }
+               }
+
+               // 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 MsgTextConvert::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 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_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 == 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)
+{
+       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");
+}
diff --git a/utils/MsgUtilFile.cpp b/utils/MsgUtilFile.cpp
new file mode 100755 (executable)
index 0000000..5e533da
--- /dev/null
@@ -0,0 +1,935 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <stddef.h>
+#include <time.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <sys/stat.h>
+#include <string.h>
+#include <dirent.h>
+#include <unistd.h>    //sync()
+
+#include "MsgStorageTypes.h"
+#include "MsgDebug.h"
+#include "MsgException.h"
+#include "MsgUtilFile.h"
+#include "MsgMmsTypes.h"
+#include "MsgInternalTypes.h"
+#include "MsgDrmWrapper.h"
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+// File operation wrappers
+FILE *MsgOpenFile(const char *filepath, const char *opt)
+{
+       if (!filepath || !opt) {
+               MSG_FATAL("Null parameter");
+               return NULL;
+       }
+
+       MSG_DEBUG("[FILE] filepath : [%s], opt [%s]", filepath, opt);
+
+       FILE *pFile = NULL;
+
+       try {
+               pFile = fopen(filepath, opt);
+               MSG_DEBUG("[FILE] pFile [%p]", pFile);
+       } catch (exception &e) {
+               MSG_FATAL("%s", e.what());
+               return NULL;
+       }
+
+       return pFile;
+}
+
+void MsgCloseFile(FILE *pFile)
+{
+       if (!pFile) {
+               MSG_FATAL("NULL parameter");
+               return;
+       }
+
+       MSG_DEBUG("[FILE] pFile [%p]", pFile);
+
+       try {
+               fclose(pFile);
+       } catch (exception &e) {
+               MSG_FATAL("%s", e.what());
+       }
+}
+
+int MsgFseek(FILE *pFile, long int offset, int origin)
+{
+       if (!pFile) {
+               MSG_FATAL("pFile NULL");
+               return -1;
+       }
+
+       int ret = -1;
+
+       MSG_DEBUG("[FILE] pFile [%p], offset [%d], origin [%d]", pFile, offset, origin);
+
+       try {
+               ret = fseek(pFile, offset, origin);             // return 0, if success.
+       } catch (exception &e) {
+               MSG_FATAL("%s", e.what());
+               return -1;
+       }
+
+       return ret;
+}
+
+size_t MsgWriteFile(const char *pData, size_t size, size_t count, FILE *pFile)
+{
+       if (!pData || !pFile) {
+               MSG_FATAL("pData or pFile NULL");
+               return 0;
+       }
+
+       size_t nWrite = 0;
+
+       MSG_DEBUG("[FILE] pData [%p], size [%d], count [%d], pFile [%p]", pData, size, count, pFile);
+
+       try {
+               nWrite = fwrite(pData, size, count, pFile);
+       } catch (exception &e) {
+               MSG_FATAL("%s", e.what());
+       }
+
+       return nWrite;
+}
+
+size_t MsgReadFile(void *pData, size_t size, size_t count, FILE *pFile)
+{
+       if (!pData || !pFile) {
+               MSG_FATAL("pData or pFile NULL");
+               return 0;
+       }
+
+       size_t nRead = 0;
+
+       try {
+               nRead = fread(pData, size, count, pFile);
+       } catch (exception &e) {
+               MSG_FATAL("%s", e.what());
+       }
+
+       return nRead;
+}
+
+long int MsgFtell(FILE *pFile)
+{
+       if (!pFile) {
+               MSG_FATAL("pFile NULL");
+               return -1L;
+       }
+
+       long int ret = -1L; // -1L return if error occured.
+
+       try {
+               ret = ftell(pFile);
+       } catch (exception &e) {
+               MSG_FATAL("%s", e.what());
+       }
+
+       return ret;
+}
+
+int MsgFflush(FILE *pFile)
+{
+       if(!pFile) {
+               MSG_FATAL("pFile NULL");
+               return -1;
+       }
+
+       int ret = -1;
+
+       try {
+               ret = fflush(pFile);            // return 0 if success
+       } catch (exception &e) {
+               MSG_FATAL("%s", e.what());
+       }
+
+       return ret;
+}
+
+int MsgFsync(FILE *pFile)
+{
+       if(!pFile) {
+               MSG_FATAL("pFile NULL");
+               return -1;
+       }
+
+       int ret = -1;
+
+       try {
+               ret = fdatasync(pFile->_fileno);        // return 0 if success
+       } catch (exception &e) {
+               MSG_FATAL("%s", e.what());
+       }
+
+       return ret;
+}
+
+bool MsgCreateFileName(char *pFileName)
+{
+       if (pFileName == NULL) {
+               MSG_DEBUG("[ERROR] pFileName is NULL");
+               return false;
+       }
+
+       struct timespec ts;
+
+       try {
+               if (clock_gettime(CLOCK_REALTIME, &ts) < 0) {
+                       MSG_DEBUG("clock_gettime() error: %s", strerror(errno));
+                       return false;
+               }
+
+               // Create Random Number
+               srandom((unsigned int)ts.tv_nsec);
+
+               MSG_DEBUG("ts.tv_nsec : %d", ts.tv_nsec);
+
+               // between 1 - 1000000000
+               snprintf(pFileName, MSG_FILENAME_LEN_MAX, "MSG_%lu.DATA", random()%1000000000+1);
+       } catch (exception& e) {
+               MSG_FATAL("%s", e.what());
+               return false;
+       }
+
+       return true;
+}
+
+
+bool MsgOpenAndReadFile(const char *pFileName, char **ppData, int *pDataSize)
+{
+       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);
+
+
+       pFile = MsgOpenFile(fullPath, "rb");
+
+       if (pFile == NULL) {
+               MSG_DEBUG("File Open Error: %s", strerror(errno));
+               return false;
+       }
+
+       if (MsgFseek(pFile, 0L, SEEK_END) < 0) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Read Error: %s", strerror(errno));
+               return false;
+       }
+
+       int FileSize = MsgFtell(pFile);
+
+       if (FileSize <= 0) {
+               MSG_DEBUG("Filesize is error : %d", FileSize);
+               *pDataSize = 0;
+               MsgCloseFile(pFile);
+               return false;
+       }
+
+       *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));
+               return false;
+       }
+
+       if (MsgReadFile(*ppData, sizeof(char), FileSize, pFile) != (size_t)FileSize) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Read Error: %s", strerror(errno));
+               return false;
+       }
+
+       *pDataSize = FileSize;
+
+       MsgCloseFile(pFile);
+
+       return true;
+}
+
+
+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));
+               MsgCloseFile(pFile);
+               return false;
+       }
+
+       *nSize = MsgReadFile(pBuf, sizeof(char), length, pFile);
+
+       MSG_END();
+       return true;
+}
+
+
+bool MsgWriteIpcFile(const char *pFileName, const char *pData, int DataSize)
+{
+       if (!pFileName) {
+               MSG_DEBUG("NULL parameter, pFileName [%p], pData [%p]", pFileName, pData);
+               return false;
+       }
+
+       char fullPath[MAX_FULL_PATH_SIZE] = {0};
+
+       snprintf(fullPath, MAX_FULL_PATH_SIZE, MSG_IPC_DATA_PATH"%s", pFileName);
+
+       FILE *pFile = MsgOpenFile(fullPath, "wb+");
+
+       if (pFile == NULL) {
+               MSG_DEBUG("File Open Error: %s", strerror(errno));
+               return false;
+       }
+
+       if (MsgFseek(pFile, 0L, SEEK_SET) < 0) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Seek Error: %s", strerror(errno));
+               return false;
+       }
+
+       if (MsgWriteFile(pData, sizeof(char), DataSize, pFile) != (size_t)DataSize) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Write Error: %s", 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 (chown(fullPath, 0, 6502 ) != 0) {
+               MSG_DEBUG("File chown Error: %s", strerror(errno));
+       }
+
+       return true;
+}
+
+int MsgReadSmilFile(const char *pFileName, char **ppData)
+{
+       if (!pFileName) {
+               MSG_DEBUG("pFileName is NULL");
+               return -1;
+       }
+
+       int     nSize = 0;
+       char fullPath[MAX_FULL_PATH_SIZE] = {0};
+
+       snprintf(fullPath, MAX_FULL_PATH_SIZE, MSG_SMIL_FILE_PATH"%s", pFileName);
+
+       MSG_DEBUG("open file name: %s", fullPath);
+
+       FILE *pFile = MsgOpenFile(fullPath, "rb");
+
+       if (pFile == NULL) {
+               MSG_DEBUG("File Open Error: %s", strerror(errno));
+               return -1;
+       }
+
+       if (MsgFseek(pFile, 0L, SEEK_END) < 0) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Seek Error: %s", strerror(errno));
+               return -1;
+       }
+
+       int FileSize = MsgFtell(pFile);
+
+       if (FileSize <= 0) {
+               MSG_DEBUG("Filesize is error : %d", FileSize);
+               MsgCloseFile(pFile);
+               return FileSize;
+       }
+
+       *ppData = new char[FileSize + 1];
+
+       if (MsgFseek(pFile, 0L, SEEK_SET) < 0) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Sead Error: %s", strerror(errno));
+               return -1;
+       }
+
+       if (MsgReadFile(*ppData, sizeof(char), FileSize, pFile) != (size_t)FileSize) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Read Error: %s", strerror(errno));
+               return -1;
+       }
+
+       ppData[FileSize] = '\0';
+
+       nSize = FileSize;
+
+       MsgCloseFile(pFile);
+
+       return nSize;
+}
+
+
+bool MsgWriteSmilFile(const char *pFilePath,char *pData, int DataSize)
+{
+       if(!pFilePath) {
+               MSG_DEBUG("pFilePath is NULL");
+               return false;
+       }
+
+       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);
+               } else {
+                       MSG_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));
+               return false;
+       }
+
+       if (MsgFseek(pFile, 0L, SEEK_SET) < 0) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Seek Error: %s", strerror(errno));
+               return false;
+       }
+
+       if (MsgWriteFile(pData, sizeof(char), DataSize, pFile) != (size_t)DataSize) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Write Error: %s", strerror(errno));
+               return false;
+       }
+
+       MsgFflush(pFile);
+       MsgCloseFile(pFile);
+
+       return true;
+}
+
+
+void MsgDeleteFile(const char *pFileName)
+{
+       if (!pFileName) {
+               MSG_FATAL("pFileName is NULL");
+               return;
+       }
+
+       if (strlen(pFileName) == 0) {
+               MSG_FATAL("pFileName has zero length");
+               return;
+       }
+
+       char fullPath[MAX_FULL_PATH_SIZE] = {0};
+
+       try {
+               snprintf(fullPath, MAX_FULL_PATH_SIZE, MSG_IPC_DATA_PATH"%s", pFileName);
+
+               MSG_DEBUG("%s", fullPath);
+
+               if (remove(fullPath) != 0)
+                       MSG_FATAL("File Delete Error [%s]: %s", fullPath, strerror(errno));
+       } catch (exception &e) {
+               MSG_FATAL ("%s", e.what());
+       }
+
+}
+
+
+void MsgDeleteSmilFile(const char *pFileName)
+{
+       if (!pFileName ) {
+               MSG_FATAL("pFileName NULL");
+               return;
+       }
+
+       try {
+               char fullPath[MAX_FULL_PATH_SIZE] = {0};
+
+               snprintf(fullPath, MAX_FULL_PATH_SIZE, MSG_SMIL_FILE_PATH"%s", pFileName);
+
+               if (remove(fullPath) != 0)
+                       MSG_FATAL("File Delete Error [%s]: %s", fullPath, strerror(errno));
+       } catch (exception &e) {
+               MSG_FATAL("%s", e.what());
+       }
+}
+
+
+bool MsgGetFileSize(const char *pFilePath, int *nSize)
+{
+       if (!pFilePath) {
+               MSG_FATAL("pFileName NULL");
+               return false;
+       }
+
+       FILE *pFile = NULL;
+
+       pFile = MsgOpenFile(pFilePath, "rb");
+
+       if (!pFile) {
+               MSG_DEBUG("File Open error: %s", strerror(errno));
+               return false;
+       }
+
+       if (MsgFseek(pFile, 0L, SEEK_END) < 0) {
+               MsgCloseFile(pFile);
+               MSG_FATAL("File Read Error: %s", strerror(errno));
+               return false;
+       }
+
+       *nSize = MsgFtell(pFile);
+
+       MsgCloseFile(pFile);
+
+       return true;
+}
+
+
+FILE *MsgOpenMMSFile(char *pFileName)
+{
+       int len;
+
+       if (!pFileName) {
+               MSG_DEBUG("pFileName NULL: %s", strerror(errno));
+               return NULL;
+       }
+
+       len = strlen(pFileName);
+
+       for (int i = 0; i < len; i++) {
+               switch (pFileName[i]) {
+               case '*':
+                       pFileName[i] = '-';
+                       break;
+               }
+       }
+
+       MSG_DEBUG("pFileName = %s", pFileName);
+
+       char fullPath[MAX_FULL_PATH_SIZE+1] = {0};
+
+       snprintf(fullPath, MAX_FULL_PATH_SIZE+1, "%s.mms", pFileName);
+
+       FILE *pFile = MsgOpenFile(fullPath, "wb+");
+
+       if (pFile == NULL) {
+               MSG_FATAL("File Open Error: %s", strerror(errno));
+               return NULL;
+       }
+
+       if (MsgFseek(pFile, 0L, SEEK_CUR) < 0) {
+               MsgCloseFile(pFile);
+               MSG_DEBUG("File Read Error: %s", strerror(errno));
+               return NULL;
+       }
+
+       return pFile;
+}
+
+
+bool MsgWriteDataFromEncodeBuffer(FILE *pFile, char *pInBuffer, int *pPtr, int maxLen, int *pOffset )
+{
+       if (!pFile || !pPtr || !pInBuffer || !pOffset) {
+               MSG_FATAL(" NULL parameter passed");
+               return false;
+       }
+
+       MSG_DEBUG("MsgWriteDataFromEncodeBuffer:");
+       MSG_DEBUG("pInBuffer %x", pInBuffer);
+       MSG_DEBUG("pPtr %d",  (*pPtr));
+       MSG_DEBUG("before to fwite %x", pFile);
+
+       if (MsgWriteFile(pInBuffer, sizeof(char), (*pPtr), pFile) != (size_t)(*pPtr)) {
+               MSG_FATAL("MsgWriteFile failed");
+               return false;
+       }
+
+       MSG_DEBUG("after to fwite \n");
+
+       MsgFflush(pFile);
+
+       memset( pInBuffer, 0, maxLen );
+
+       *pPtr = 0;
+
+       if (MsgFseek(pFile, 0L, SEEK_END) < 0) {
+               MSG_FATAL("MsgFseek failed");
+               return false;
+       }
+
+       *pOffset = MsgFtell(pFile);
+
+       if (*pOffset == -1L) {
+               MSG_FATAL("MsgFtell failed");
+               return false;
+       }
+
+       return true;
+}
+
+
+bool MsgOpenCreateAndOverwriteFile(char *pFullPath, char *pBuff, int TotalLength)
+{
+       FILE *pFile = NULL ;
+       mode_t file_mode;
+
+       file_mode = (S_IRUSR | S_IWUSR);
+
+       if ((pFile = MsgOpenFile(pFullPath, "wb+")) == NULL) {
+               MSG_FATAL("MsgOpenFile errer");
+               return false;
+       }
+
+       if (MsgWriteFile(pBuff, sizeof(char), TotalLength, pFile) != (size_t)TotalLength) {
+               MsgCloseFile( pFile );
+               return false;
+       }
+
+       MsgFsync(pFile);        //file is written to device immediately, it prevents missing file data from unexpected power off
+       MsgFflush(pFile);
+       MsgCloseFile(pFile);
+
+       if (chmod(pFullPath, file_mode) < 0)
+               MSG_FATAL("File chmod Error: %s", strerror(errno));
+
+       return true;
+}
+
+
+char *MsgOpenAndReadMmsFile( const char *szFilePath, int offset, int size, int *npSize )
+{
+       FILE *pFile = NULL;
+       char *pData = NULL;
+       int     readSize = 0;
+
+       if (szFilePath == NULL) {
+               MSG_DEBUG("MsgOpenAndReadMmsFile: [ERROR] szFilePath id NULL");
+               goto __CATCH;
+       }
+
+       *npSize = 0;
+
+       pFile = MsgOpenFile( szFilePath, "rb" );
+
+       if (pFile == NULL) {
+               MSG_DEBUG("MsgOpenAndReadMmsFile: [ERROR] Can't open filepath", strerror(errno));
+               goto __CATCH;
+       }
+
+       if( size == -1 ) {
+               if (MsgGetFileSize(szFilePath, & readSize) == false) {
+                       MSG_DEBUG("MsgGetFileSize: failed");
+                       goto __CATCH;
+               }
+       } else {
+               readSize = size;
+       }
+
+       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) );
+               goto __CATCH;
+       }
+       memset( pData, 0, readSize + 1 );
+
+       if (MsgFseek( pFile, offset, SEEK_SET) < 0) {
+               MSG_DEBUG( "MsgOpenAndReadMmsFile: [ERROR] FmSeekFile failed", strerror(errno) );
+               goto __CATCH;
+       }
+
+       *npSize = MsgReadFile(pData, sizeof(char), readSize, pFile);
+
+       MsgCloseFile(pFile);
+
+       pFile = NULL;
+
+       *(pData + (*npSize)) = '\0';
+
+       return pData;
+
+__CATCH:
+
+       if (pData) {
+               free( pData );
+               pData = NULL;
+       }
+
+       *npSize = 0;
+
+       if (pFile != NULL) {
+               MsgCloseFile( pFile );
+               pFile = NULL;
+       }
+
+       return NULL;
+}
+
+// it is equivalent to "rm -rf pDirPath"
+int MsgRmRf(char *pDirPath)
+{
+       struct dirent *d;
+       DIR *dir;
+
+       dir = opendir(pDirPath);
+
+       if (dir == NULL) {
+               MSG_FATAL("error opendir: %s", strerror(errno));
+               return -1;
+       }
+
+       int size = strlen(pDirPath) + 256;
+
+       char *path = (char*)malloc(size);
+
+       if (path == NULL) {
+               MSG_DEBUG("path is NULL");
+               closedir(dir);
+               return -1;
+       }
+
+       bzero(path, size);
+
+       while ((d = readdir(dir)) != NULL) {
+               if (d->d_type == DT_DIR) {
+                       snprintf(path, size, "%s/%s", pDirPath, d->d_name);
+
+                       if ((strcmp(".", d->d_name) == 0) || (strcmp("..", d->d_name) == 0))
+                               continue;
+
+                       MsgRmRf(path);
+
+                       if (rmdir(path) != 0) {
+
+                               if (path != NULL)
+                                       free(path);
+
+                               closedir(dir);
+
+                               MSG_FATAL("error rmdir: %s", strerror(errno));
+
+                               return -1;
+                       }
+               } else {
+                       snprintf(path, size, "%s/%s", pDirPath, d->d_name);
+
+                       if (MsgDrmIsDrmFile(path))
+                               MsgDrmUnregisterFile(path);
+
+                       if (remove(path) != 0) {
+
+                               if (path != NULL)
+                                       free(path);
+
+                               closedir(dir);
+
+                               MSG_FATAL("error remove: %s", strerror(errno));
+
+                               return -1;
+                       }
+               }
+       }
+
+       closedir(dir);
+
+       if (path != NULL)
+               free(path);
+
+       return 0;
+}
+
+
+int MsgGetFileSize(const char *pFileName)
+{
+       struct stat file_stat;
+
+       if (lstat(pFileName, &file_stat)) {
+               MSG_FATAL("error lstat: %s", strerror(errno));
+               return -1;
+       }
+
+       return file_stat.st_size;
+}
+
+
+// it is equivalent to "du dir_path"
+unsigned int MsgDu(const char *pDirPath)
+{
+       struct dirent *d;
+       DIR *dir;
+
+       dir = opendir(pDirPath);
+
+       if (dir == NULL) {
+               MSG_FATAL("error opendir: %s", strerror(errno));
+               return -1;
+       }
+
+       int size = strlen(pDirPath) + 256;
+       char *path = (char*)malloc(size);
+       bzero(path, size);
+
+       unsigned int totalFileSize = 0;
+
+       while ((d = readdir(dir)) != NULL) {
+               if( d->d_type == DT_DIR) {
+                       snprintf(path, size, "%s/%s", pDirPath, d->d_name);
+
+                       if ((strcmp(".", d->d_name) == 0) || (strcmp("..", d->d_name) == 0))
+                               continue;
+
+                       unsigned int dirSize = MsgDu(path);
+
+                       if (dirSize == 0) {
+                               MSG_FATAL("error MsgDu");
+                               closedir(dir);
+                               free(path);
+                               return dirSize;
+                       }
+
+                       totalFileSize += dirSize;
+               } else {
+                       snprintf(path, size, "%s/%s", pDirPath, d->d_name);
+                       int fileSize = MsgGetFileSize(path);
+
+                       if (fileSize < 0) {
+                               MSG_FATAL("error MsgGetFileSize");
+                               closedir(dir);
+                               free(path);
+                               return fileSize;
+                       }
+
+                       totalFileSize += fileSize;
+               }
+       }
+
+       closedir(dir);
+
+       free(path);
+
+       return totalFileSize;
+}
+
+
+bool MsgAppendFile(const char *pFilePath, const char *pData, int DataSize)
+{
+       if (!pFilePath) {
+               MSG_FATAL("NULL check error, pFileName %p, pData %p", pFilePath, pData);
+               return false;
+       }
+
+       char fullPath[MAX_FULL_PATH_SIZE] = {0};
+
+       snprintf(fullPath, MAX_FULL_PATH_SIZE, "%s", pFilePath);
+
+       FILE *pFile = MsgOpenFile(fullPath, "a+");
+
+       if (pFile == NULL) {
+               MSG_FATAL("File Open Error: %s", strerror(errno));
+               return false;
+       }
+
+       if (MsgFseek(pFile, 0L, SEEK_CUR) < 0) {
+               MsgCloseFile(pFile);
+               MSG_FATAL("File Sead Error: %s", strerror(errno));
+               return false;
+       }
+
+       if (MsgWriteFile(pData, sizeof(char), DataSize, pFile) != (size_t)DataSize) {
+               MsgCloseFile(pFile);
+               MSG_FATAL("File Write Error: %s", strerror(errno));
+               return false;
+       }
+
+       MsgFsync(pFile);        //file is written to device immediately, it prevents missing file data from unexpected power off
+       MsgFflush(pFile);
+       MsgCloseFile(pFile);
+       return true;
+}
+
+void MsgMmsInitDir()
+{
+       struct dirent *d = NULL;
+       DIR* dir = NULL;
+
+       dir = opendir(MSG_DATA_PATH);
+
+       if (dir == NULL) {
+               MSG_FATAL("error opendir: %s", strerror(errno));
+               return;
+       }
+
+       // Remove temporal Mms folder (/opt/usr/data/msg-service/msgdata/*.dir)
+       while ((d = readdir(dir)) != NULL) {
+               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);
+
+                               MsgRmRf(filePath);
+                               rmdir(filePath);
+                       }
+               }
+       }
+
+       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_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;
+}
diff --git a/utils/MsgUtilFunction.cpp b/utils/MsgUtilFunction.cpp
new file mode 100755 (executable)
index 0000000..de54bb3
--- /dev/null
@@ -0,0 +1,705 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgUtilFunction.h"
+
+ /*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+
+// Encoders
+int MsgEncodeCountInfo(MSG_COUNT_INFO_S *pCountInfo, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = sizeof(MSG_COUNT_INFO_S);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, pCountInfo, dataSize);
+
+       return dataSize;
+}
+
+
+int MsgEncodeRecipientList(MSG_RECIPIENTS_LIST_S *pRecipientList, char **ppDest)
+{
+       int count = 0, dataSize = 0;
+
+       count = pRecipientList->recipientCnt;
+       dataSize = sizeof(int) + (sizeof(MSG_ADDRESS_INFO_S)*count);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, &count, sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       for (int i = 0; i < count; i++)
+       {
+               memcpy(p, &(pRecipientList->recipientAddr[i]), sizeof(MSG_ADDRESS_INFO_S));
+               p = (void*)((char*)p + sizeof(MSG_ADDRESS_INFO_S));
+       }
+
+       return dataSize;
+}
+
+
+int MsgEncodeCountByMsgType(int MsgCount, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = sizeof(int);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, &MsgCount, dataSize);
+
+       return dataSize;
+}
+
+
+int MsgEncodeMsgId(msg_message_id_t *pMsgId, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = (sizeof(msg_message_id_t));
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, pMsgId, dataSize);
+
+       return dataSize;
+}
+
+
+int MsgEncodeMsgInfo(MSG_MESSAGE_INFO_S *pMsgInfo, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = sizeof(MSG_MESSAGE_INFO_S);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+
+       p = (void*)((char*)p + sizeof(MSG_MESSAGE_INFO_S));
+
+       return dataSize;
+}
+
+
+int MsgEncodeMsgInfo(MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S* pSendOptInfo, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = (sizeof(MSG_MESSAGE_INFO_S) + sizeof(MSG_SENDINGOPT_INFO_S));
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, pMsgInfo, sizeof(MSG_MESSAGE_INFO_S));
+
+       p = (void*)((char*)p + sizeof(MSG_MESSAGE_INFO_S));
+
+       memcpy(p, pSendOptInfo, sizeof(MSG_SENDINGOPT_INFO_S));
+
+       return dataSize;
+}
+
+int MsgEncodeFolderList(msg_struct_list_s *pFolderList, char **ppDest)
+{
+       int count = 0, dataSize = 0;
+
+       count = pFolderList->nCount;
+       dataSize = sizeof(int) + (sizeof(MSG_FOLDER_INFO_S)*count);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, &count, sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       msg_struct_s *folder_info = NULL;
+
+       for (int i = 0; i < count; i++)
+       {
+               folder_info = (msg_struct_s *)pFolderList->msg_struct_info[i];
+               memcpy(p, folder_info->data, sizeof(MSG_FOLDER_INFO_S));
+               p = (void*)((char*)p + sizeof(MSG_FOLDER_INFO_S));
+       }
+
+       return dataSize;
+}
+
+int MsgEncodeFilterList(msg_struct_list_s *pFilterList, char **ppDest)
+{
+       int count = 0, dataSize = 0;
+
+       count = pFilterList->nCount;
+       dataSize = sizeof(int) + (sizeof(MSG_FILTER_S)*count);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, &count, sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       msg_struct_s *filter_info = NULL;
+
+       for (int i = 0; i < count; i++)
+       {
+               filter_info = (msg_struct_s *)pFilterList->msg_struct_info[i];
+               memcpy(p, filter_info->data, sizeof(MSG_FILTER_S));
+               p = (void*)((char*)p + sizeof(MSG_FILTER_S));
+       }
+
+       return dataSize;
+}
+
+
+int MsgEncodeFilterFlag(bool *pSetFlag, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = (sizeof(bool));
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, pSetFlag, dataSize);
+
+       return dataSize;
+}
+
+
+int MsgEncodeMsgType(MSG_MESSAGE_TYPE_S *pMsgType, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = (sizeof(MSG_MESSAGE_TYPE_S));
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, pMsgType, dataSize);
+
+       return dataSize;
+}
+
+
+int MsgEncodeThreadViewList(msg_struct_list_s *pThreadViewList, char **ppDest)
+{
+       int count = 0, dataSize = 0;
+
+       count = pThreadViewList->nCount;
+
+       dataSize = sizeof(int) + (sizeof(MSG_THREAD_VIEW_S)*count);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, &count, sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       msg_struct_s *thread_info = NULL;
+
+       for (int i = 0; i < count; i++)
+       {
+               thread_info = (msg_struct_s *)pThreadViewList->msg_struct_info[i];
+               memcpy(p, thread_info->data, sizeof(MSG_THREAD_VIEW_S));
+               p = (void*)((char*)p + sizeof(MSG_THREAD_VIEW_S));
+       }
+
+       return dataSize;
+}
+
+
+int MsgEncodeConversationViewList(msg_struct_list_s *pConvViewList, char **ppDest)
+{
+       int count = 0, dataSize = 0;
+
+       count = pConvViewList->nCount;
+
+       dataSize = sizeof(int) + (sizeof(msg_struct_list_s)*count);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, &count, sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       for (int i = 0; i < count; i++)
+       {
+               memcpy(p, &(pConvViewList->msg_struct_info[i]), sizeof(msg_struct_list_s));
+               p = (void*)((char*)p + sizeof(msg_struct_list_s));
+       }
+
+       return dataSize;
+}
+
+
+int MsgEncodeMsgGetContactCount(MSG_THREAD_COUNT_INFO_S *threadCountInfo, char **ppDest)
+{
+       int dataSize = sizeof(int) + sizeof(int) + sizeof(int) + sizeof(int);
+
+       MSG_DEBUG("datasize = [%d] \n", dataSize);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, &(threadCountInfo->totalCount), sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       memcpy(p, &(threadCountInfo->unReadCount), sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       memcpy(p, &(threadCountInfo->mmsMsgCount), sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       memcpy(p, &(threadCountInfo->smsMsgCount), sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       return dataSize;
+}
+
+int MsgEncodeMemSize(unsigned int *memsize, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = sizeof(unsigned int);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, memsize, dataSize);
+
+       return dataSize;
+}
+
+
+int MsgEncodeSyncMLOperationData(int msgId, int extId, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = sizeof(int) + sizeof(int);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, &msgId, sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       memcpy(p, &extId, sizeof(int));
+
+       return dataSize;
+}
+
+
+int MsgEncodeStorageChangeData(const msg_storage_change_type_t storageChangeType, const msg_id_list_s *pMsgIdList, char **ppDest)
+{
+       int dataSize = 0;
+       int count = 0;
+
+       count = pMsgIdList->nCount;
+
+       dataSize = sizeof(msg_storage_change_type_t) + sizeof(int) + (sizeof(msg_message_id_t)*count);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, &storageChangeType, sizeof(msg_storage_change_type_t));
+       p = (void*)((char*)p + sizeof(msg_storage_change_type_t));
+
+       memcpy(p, &count, sizeof(int));
+       p = (void*)((char*)p + sizeof(int));
+
+       for (int i = 0; i < count; i++) {
+               memcpy(p, &(pMsgIdList->msgIdList[i]), sizeof(msg_message_id_t));
+               p = (void*)((char*)p + sizeof(msg_message_id_t));
+       }
+
+       return dataSize;
+}
+
+
+int MsgEncodeReportStatus(MSG_REPORT_STATUS_INFO_S* pReportStatus, int count, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = (sizeof(MSG_REPORT_STATUS_INFO_S)*count + sizeof(int));
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, &count, sizeof(int));
+
+       p = (void*)((int)p + sizeof(int));
+
+       memcpy(p, pReportStatus, sizeof(MSG_REPORT_STATUS_INFO_S)*count);
+
+       return dataSize;
+}
+
+
+int MsgEncodeThreadId(msg_thread_id_t *pThreadId, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = (sizeof(msg_thread_id_t));
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, pThreadId, dataSize);
+
+       return dataSize;
+}
+
+
+int MsgEncodeThreadInfo(MSG_THREAD_VIEW_S *pThreadInfo, char **ppDest)
+{
+       int dataSize = 0;
+
+       dataSize = sizeof(MSG_THREAD_VIEW_S);
+
+       *ppDest = (char*)new char[dataSize];
+
+       void* p = (void*)*ppDest;
+
+       memcpy(p, pThreadInfo, sizeof(MSG_THREAD_VIEW_S));
+
+       p = (void*)((char*)p + sizeof(MSG_THREAD_VIEW_S));
+
+       return dataSize;
+}
+
+
+
+// Decoders
+void MsgDecodeMsgId(char *pSrc, msg_message_id_t *pMsgId)
+{
+       memcpy(pMsgId, pSrc, sizeof(msg_message_id_t));
+}
+
+
+void MsgDecodeCountInfo(char *pSrc, MSG_COUNT_INFO_S *pCountInfo)
+{
+       memcpy(pCountInfo, pSrc, sizeof(MSG_COUNT_INFO_S));
+}
+
+
+void MsgDecodeMemSize(char *pSrc, unsigned int *memsize)
+{
+       memcpy(memsize, pSrc, sizeof(unsigned int));
+}
+
+
+void MsgDecodeMsgInfo(char *pSrc, MSG_MESSAGE_INFO_S *pMsgInfo, MSG_SENDINGOPT_INFO_S* pSendOptInfo)
+{
+       memcpy(pMsgInfo, pSrc, sizeof(MSG_MESSAGE_INFO_S));
+
+       pSrc = pSrc + sizeof(MSG_MESSAGE_INFO_S);
+
+       memcpy(pSendOptInfo, pSrc, sizeof(MSG_SENDINGOPT_INFO_S));
+}
+
+void MsgDecodeRecipientList(char *pSrc, MSG_RECIPIENTS_LIST_S *pRecipientList)
+{
+       int count = 0;
+
+       memcpy(&count, pSrc, sizeof(int));
+       pSrc = pSrc + sizeof(int);
+
+       pRecipientList->recipientCnt= count;
+       pRecipientList->recipientAddr = (MSG_ADDRESS_INFO_S*)new char[sizeof(MSG_ADDRESS_INFO_S)*count];
+
+       MSG_ADDRESS_INFO_S* pInfoTmp = pRecipientList->recipientAddr;
+
+       for (int i = 0; i < count; i++)
+       {
+               memcpy(pInfoTmp, pSrc, sizeof(MSG_ADDRESS_INFO_S));
+               pSrc = pSrc + sizeof(MSG_ADDRESS_INFO_S);
+               pInfoTmp++;
+       }
+}
+
+
+void MsgDecodeFolderList(char *pSrc, msg_struct_list_s *pFolderList)
+{
+       int count = 0;
+
+       memcpy(&count, pSrc, sizeof(int));
+       pSrc = pSrc + sizeof(int);
+
+       if( count > 0 )
+       {
+               pFolderList->nCount = count;
+               pFolderList->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_FOLDER_INFO_S *)*count];
+
+               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)];
+                       pInfoTmp = (msg_struct_s *)pFolderList->msg_struct_info[i];
+                       pInfoTmp->type = MSG_STRUCT_FOLDER_INFO;
+                       pInfoTmp->data = new char[sizeof(MSG_FOLDER_INFO_S)];
+                       memcpy(pInfoTmp->data, pSrc, sizeof(MSG_FOLDER_INFO_S));
+                       pSrc = pSrc + sizeof(MSG_FOLDER_INFO_S);
+               }
+       }
+       else if ( count == 0 )
+       {
+               pFolderList->nCount = count;
+               pFolderList->msg_struct_info = NULL;
+       }
+}
+
+void MsgDecodeFilterList(char *pSrc, msg_struct_list_s *pFilterList)
+{
+       int count = 0;
+
+       memcpy(&count, pSrc, sizeof(int));
+       pSrc = pSrc + sizeof(int);
+
+       if( count > 0 )
+       {
+               pFilterList->nCount = count;
+               pFilterList->msg_struct_info = (msg_struct_t *)new char[sizeof(MSG_FILTER_S *)*count];
+
+               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)];
+                       pStructTmp = (msg_struct_s *)pFilterList->msg_struct_info[i];
+                       pStructTmp->type = MSG_STRUCT_FILTER;
+                       pStructTmp->data = new char[sizeof(MSG_FILTER_S)];
+                       memcpy(pStructTmp->data, pSrc, sizeof(MSG_FILTER_S));
+                       pSrc = pSrc + sizeof(MSG_FILTER_S);
+               }
+       }
+       else if ( count == 0 )
+       {
+               pFilterList->nCount = count;
+               pFilterList->msg_struct_info = NULL;
+       }
+
+}
+
+
+void MsgDecodeFilterFlag(char *pSrc, bool *pSetFlag)
+{
+       memcpy(pSetFlag, pSrc, sizeof(bool));
+}
+
+
+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;
+
+       if(pSrc == NULL)
+               return;
+
+       memcpy(&count, pSrc, sizeof(int));
+       pSrc = pSrc + sizeof(int);
+       pMsgThreadCountList->totalCount = count;
+
+
+       memcpy(&count, pSrc, sizeof(int));
+       pSrc = pSrc + sizeof(int);
+       pMsgThreadCountList->unReadCount        = count;
+
+
+       memcpy(&count, pSrc, sizeof(int));
+       pSrc = pSrc + sizeof(int);
+       pMsgThreadCountList->mmsMsgCount        = count;
+
+
+       memcpy(&count, pSrc, sizeof(int));
+       pSrc = pSrc + sizeof(int);
+       pMsgThreadCountList->smsMsgCount        = count;
+
+
+       return;
+}
+
+
+void MsgDecodeReportStatus(char *pSrc,  msg_struct_list_s *report_list)
+{
+       int count = 0;
+
+       if(pSrc == NULL)
+               return;
+
+       memcpy(&count, pSrc, sizeof(int));
+       pSrc = pSrc + sizeof(int);
+
+       report_list->nCount = 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));
+
+               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);
+
+               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;
+}
+
+void MsgDecodeThreadId(char *pSrc, msg_thread_id_t *pThreadId)
+{
+       memcpy(pThreadId, pSrc, sizeof(msg_thread_id_t));
+}
+
+void MsgDecodeThreadInfo(char *pSrc, MSG_THREAD_VIEW_S *pThreadInfo)
+{
+       memcpy(pThreadInfo, pSrc, sizeof(MSG_THREAD_VIEW_S));
+}
+
+// Event Encoder
+int MsgMakeEvent(const void *pData, int DataSize, MSG_EVENT_TYPE_T MsgEvent, msg_error_t MsgError, void **ppEvent)
+{
+       MSG_EVENT_S* pMsgEvent = NULL;
+
+       *ppEvent = (MSG_EVENT_S*)new char[sizeof(MSG_EVENT_S) + DataSize];
+
+       pMsgEvent = (MSG_EVENT_S*)*ppEvent;
+
+       pMsgEvent->eventType = MsgEvent;
+       pMsgEvent->result = MsgError;
+
+       MSG_DEBUG("eventType [%d : %s]", pMsgEvent->eventType, MsgDbgEvtStr(pMsgEvent->eventType));
+       MSG_DEBUG("result [%d]", pMsgEvent->result);
+
+       if (DataSize > 0)
+               memcpy((void*)pMsgEvent->data, pData, DataSize);
+
+       return (sizeof(MSG_EVENT_S) + DataSize);
+}
+
+int msg_verify_number(const char *raw, char *trimmed)
+{
+       if (!(raw && trimmed)) {
+               MSG_DEBUG("Phone Number is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       for (int i=0, j=0 ; raw[i] ; i++) {
+               if ((raw[i] >= '0' && raw[i] <= '9') || raw[i] == '+' || raw[i] == ',' || raw[i] == ' ' \
+                               || raw[i] == '*' ||  raw[i] == '#') {
+                       trimmed[j++] = raw[i];
+               } else if (raw[i] == '-') {
+                       continue;
+               } else {
+                       MSG_DEBUG("Unacceptable character in telephone number: [%c]", raw[i]);
+                       return MSG_ERR_INVALID_PARAMETER;
+               }
+       }
+
+       MSG_DEBUG("Trimming [%s]->[%s]", raw, trimmed);
+       return MSG_SUCCESS;
+}
+
+int msg_verify_email(const char *raw)
+{
+       bool onlyNum = true;
+       bool atExist = false;
+
+       if (!raw) {
+               MSG_DEBUG("Email is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       for (int i = 0; raw[i]; i++) {
+
+               if (raw[i] == '@') {
+                       onlyNum = false;
+
+                       if (atExist == false) {
+                               atExist = true;
+                               continue;
+                       } else {
+                               MSG_DEBUG("Character [@] is included more than twice in email address.");
+                               return MSG_ERR_INVALID_PARAMETER;
+                       }
+               }
+
+               if ((raw[i] >= '0' && raw[i] <= '9') || raw[i] == '+' || raw[i] == '*' ||  raw[i] == '#') {
+                       continue;
+               } else if ((raw[i] >= 'a' && raw[i] <= 'z') ||(raw[i] >= 'A' && raw[i] <= 'Z') ||(raw[i] == '.') || raw[i] == '_' || raw[i] == '-') {
+                       onlyNum = false;
+                       continue;
+               } else if (raw[i] == ',') {
+                       if (onlyNum == false && atExist == false) {
+                               MSG_DEBUG("Unacceptable type in address.");
+                               return MSG_ERR_INVALID_PARAMETER;
+                       }
+                       atExist = false;
+                       onlyNum = true;
+                       continue;
+               } else {
+                       MSG_DEBUG("Unacceptable character in address : [%c]", raw[i]);
+                       return MSG_ERR_INVALID_PARAMETER;
+               }
+       }
+
+       return MSG_SUCCESS;
+}
diff --git a/utils/MsgUtilStorage.cpp b/utils/MsgUtilStorage.cpp
new file mode 100755 (executable)
index 0000000..33f5fa9
--- /dev/null
@@ -0,0 +1,1461 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 "MsgNotificationWrapper.h"
+#include "MsgUtilStorage.h"
+
+#include <sys/stat.h>
+#include <sys/vfs.h>
+
+
+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}};
+
+
+/*==================================================================================================
+                                     FUNCTION IMPLEMENTATION
+==================================================================================================*/
+unsigned int MsgStoAddMessageTable(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsgInfo)
+{
+       MSG_BEGIN();
+
+       msg_error_t err = MSG_SUCCESS;
+
+       msg_message_id_t msgId = 0;
+
+       err = pDbHandle->getRowId(MSGFW_MESSAGE_TABLE_NAME, &msgId);
+
+       if (err != MSG_SUCCESS)
+               return 0;
+
+       int fileSize = 0;
+
+       char* pFileData = NULL;
+       AutoPtr<char> buf(&pFileData);
+
+       // Get File Data
+       if (pMsgInfo->bTextSms == false) {
+               if (MsgOpenAndReadFile(pMsgInfo->msgData, &pFileData, &fileSize) == false)
+                       return 0;
+
+               MSG_DEBUG("file size [%d]", fileSize);
+       }
+
+       // 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, ?, ?, ?, ?, 0);",
+                       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_DEBUG("QUERY : %s", sqlQuery);
+
+       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->bTextSms == false)
+               pDbHandle->bindText(pFileData, 4);
+       else
+               pDbHandle->bindText(pMsgInfo->msgText, 4);
+
+       if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+               pDbHandle->finalizeQuery();
+               return 0;
+       }
+
+       pDbHandle->finalizeQuery();
+
+       return msgId;
+}
+
+
+msg_error_t MsgStoSetReadStatus(MsgDbHandler *pDbHandle, msg_message_id_t msgId, bool bRead)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET READ_STATUS = %d WHERE MSG_ID = %d;",
+                       MSGFW_MESSAGE_TABLE_NAME, (int)bRead, msgId);
+
+       if (pDbHandle->execQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_EXEC;
+
+       // Get MAIN_TYPE, SUB_TYPE, STORAGE_ID
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.MAIN_TYPE, A.SUB_TYPE, 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);
+
+       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       MSG_MESSAGE_TYPE_S msgType;
+       msg_thread_id_t convId;
+
+       if (pDbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               msgType.mainType = pDbHandle->columnInt(0);
+               msgType.subType = pDbHandle->columnInt(1);
+               convId = pDbHandle->columnInt(2);
+       } else {
+               pDbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       pDbHandle->finalizeQuery();
+
+       MSG_DEBUG("Main Type:[%d] SubType:[%d] ConvId:[%d]", msgType.mainType, msgType.subType, convId);
+
+       if (MsgStoUpdateConversation(pDbHandle, convId) != MSG_SUCCESS) {
+               MSG_DEBUG("MsgStoUpdateConversation() Error");
+               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);
+
+       MsgRefreshNoti(false);
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetOldestMessage(MsgDbHandler *pDbHandle, const MSG_MESSAGE_INFO_S *pMsgInfo, msg_message_id_t *pMsgId)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT MSG_ID FROM %s \
+                       WHERE SUB_TYPE = %d AND FOLDER_ID = %d AND STORAGE_ID = %d AND PROTECTED = 0 \
+                       ORDER BY DISPLAY_TIME ASC",
+                       MSGFW_MESSAGE_TABLE_NAME, pMsgInfo->msgType.subType, pMsgInfo->folderId, MSG_STORAGE_PHONE);
+
+       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (pDbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               *pMsgId = pDbHandle->columnInt(0);
+       } else {
+               pDbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       pDbHandle->finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoCheckMsgCntFull(MsgDbHandler *pDbHandle, const MSG_MESSAGE_TYPE_S* pMsgType, msg_folder_id_t folderId)
+{
+       MSG_BEGIN();
+
+       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);
+                       return MSG_ERR_STORAGE_ERROR;
+               }
+
+               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;
+}
+
+
+msg_error_t MsgStoCountMsgByLimitCategory(MsgDbHandler *pDbHandle, const MSG_MESSAGE_TYPE_S *pMsgType, int *pMsgCount, msg_folder_id_t folderId)
+{
+       if (pMsgType == NULL) {
+               MSG_DEBUG("pMsgType is NULL");
+               return MSG_ERR_NULL_POINTER;
+       }
+
+       *pMsgCount = 0;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       if ((pMsgType->mainType == MSG_SMS_TYPE) && (pMsgType->subType == MSG_WAP_SI_SMS ||pMsgType->subType == MSG_WAP_SL_SMS)) { // PUSH
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE MAIN_TYPE = %d AND SUB_TYPE IN (%d, %d) AND FOLDER_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsgType->mainType, MSG_WAP_SI_SMS, MSG_WAP_SL_SMS, MSG_INBOX_ID);
+       } else if ((pMsgType->mainType == MSG_SMS_TYPE) && (pMsgType->subType == MSG_CB_SMS)) { // CB
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE MAIN_TYPE = %d AND SUB_TYPE IN (%d) AND FOLDER_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsgType->mainType, MSG_CB_SMS, MSG_CBMSGBOX_ID);
+       } else if ((pMsgType->mainType == MSG_SMS_TYPE) && (pMsgType->subType == MSG_SYNCML_CP)) { // Provision
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE MAIN_TYPE = %d AND SUB_TYPE IN (%d) AND FOLDER_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsgType->mainType, MSG_SYNCML_CP, MSG_INBOX_ID);
+       } else if ((pMsgType->mainType == MSG_SMS_TYPE)) { // SMS
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE MAIN_TYPE = %d AND SUB_TYPE NOT IN (%d, %d, %d, %d) AND FOLDER_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsgType->mainType, MSG_WAP_SI_SMS, MSG_WAP_SL_SMS, MSG_CB_SMS, MSG_SYNCML_CP, MSG_INBOX_ID); // etc SMS
+       } else if ((pMsgType->mainType == MSG_MMS_TYPE) &&
+                       (pMsgType->subType == MSG_SENDREQ_MMS || pMsgType->subType == MSG_SENDCONF_MMS || pMsgType->subType == MSG_RETRIEVE_AUTOCONF_MMS ||
+                                       pMsgType->subType == MSG_RETRIEVE_MANUALCONF_MMS || pMsgType->subType == MSG_NOTIFICATIONIND_MMS)) { // MMS
+               snprintf(sqlQuery, sizeof(sqlQuery), "SELECT COUNT(MSG_ID) FROM %s WHERE MAIN_TYPE = %d AND SUB_TYPE IN (%d, %d, %d, %d, %d) AND FOLDER_ID = %d;",
+                               MSGFW_MESSAGE_TABLE_NAME, pMsgType->mainType, MSG_SENDREQ_MMS, MSG_SENDCONF_MMS, MSG_RETRIEVE_AUTOCONF_MMS, MSG_RETRIEVE_MANUALCONF_MMS, MSG_NOTIFICATIONIND_MMS, folderId);
+       } else {
+               return MSG_ERR_INVALID_PARAMETER;
+       }
+
+       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return MSG_ERR_DB_PREPARE;
+
+       if (pDbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               *pMsgCount = pDbHandle->columnInt(0);
+       } else {
+               pDbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       pDbHandle->finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+int MsgStoCheckMsgCntLimit(const MSG_MESSAGE_TYPE_S* pMsgType, msg_folder_id_t folderId)
+{
+       int msgboxType = -1;
+       int msgType= -1;
+
+       switch (folderId)
+       {
+               case MSG_INBOX_ID :
+                       msgboxType = MSG_COUNT_LIMIT_INBOX_TYPE;
+               break;
+
+               case MSG_OUTBOX_ID :
+                       msgboxType = MSG_COUNT_LIMIT_OUTBOX_TYPE;
+               break;
+
+               case MSG_SENTBOX_ID :
+                       msgboxType = MSG_COUNT_LIMIT_SENTBOX_TYPE;
+               break;
+
+               case MSG_DRAFT_ID :
+                       msgboxType = MSG_COUNT_LIMIT_DRAFTBOX_TYPE;
+               break;
+
+               case MSG_CBMSGBOX_ID :
+                       msgboxType = MSG_COUNT_LIMIT_CBMSGBOX_TYPE;
+               break;
+
+               default:
+                       MSG_DEBUG("Unknown mailbox Type [%d]", folderId);
+               return -1;
+       }
+
+       switch (pMsgType->subType)
+       {
+               case MSG_NORMAL_SMS:
+               case MSG_REPLACE_TYPE1_SMS:
+               case MSG_REPLACE_TYPE2_SMS:
+               case MSG_REPLACE_TYPE3_SMS:
+               case MSG_REPLACE_TYPE4_SMS:
+               case MSG_REPLACE_TYPE5_SMS:
+               case MSG_REPLACE_TYPE6_SMS:
+               case MSG_REPLACE_TYPE7_SMS:
+               case MSG_MWI_VOICE_SMS:
+               case MSG_MWI_FAX_SMS:
+               case MSG_MWI_EMAIL_SMS:
+               case MSG_MWI_OTHER_SMS:
+               case MSG_STATUS_REPORT_SMS:
+                       msgType = MSG_COUNT_LIMIT_SMS_TYPE;
+               break;
+
+               case MSG_CB_SMS:
+                       msgType = MSG_COUNT_LIMIT_CB_TYPE;
+               break;
+
+               case MSG_WAP_SI_SMS:
+               case MSG_WAP_SL_SMS:
+                       msgType = MSG_COUNT_LIMIT_WAPPUSH_TYPE;
+               break;
+
+               case MSG_SYNCML_CP:
+                       msgType = MSG_COUNT_LIMIT_PROVISION_TYPE;
+               break;
+
+               case MSG_SENDREQ_MMS:
+               case MSG_SENDCONF_MMS:
+               case MSG_NOTIFICATIONIND_MMS:
+               case MSG_RETRIEVE_AUTOCONF_MMS:
+               case MSG_RETRIEVE_MANUALCONF_MMS:
+                       msgType = MSG_COUNT_LIMIT_MMS_TYPE;
+               break;
+
+               default:
+                       MSG_DEBUG("Unknown Message Type [%d]", pMsgType->subType);
+               return -1;
+       }
+
+       return msgCntLimit[msgboxType][msgType];
+}
+
+
+msg_error_t MsgStoAddAddress(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];
+
+       // 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++) {
+
+               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 = pDbHandle->getRowId(MSGFW_ADDRESS_TABLE_NAME, &addrId);
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("pDbHandle->getRowId fail. [%d]", err);
+                       return err;
+               }
+
+               // 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);
+
+               MSG_DEBUG("Add Address Info. [%s]", sqlQuery);
+
+               if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+                       return MSG_ERR_DB_PREPARE;
+
+               pDbHandle->bindText(contactInfo.firstName, 1);
+               pDbHandle->bindText(contactInfo.lastName, 2);
+
+               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)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+       char firstName[MAX_DISPLAY_NAME_LEN+1];
+       char lastName[MAX_DISPLAY_NAME_LEN+1];
+
+       *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);
+
+       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Query Failed [%s]", sqlQuery);
+               return MSG_ERR_DB_PREPARE;
+       }
+
+       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);
+
+                       if (pDbHandle->columnText(6) != NULL)
+                                       strncpy(lastName, (char *)pDbHandle->columnText(6), MAX_DISPLAY_NAME_LEN);
+
+                       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));
+                               }
+
+                               if (strlen(firstName) > 0) {
+                                       strncat(pAddress[*nAddressCnt].displayName, firstName, MAX_DISPLAY_NAME_LEN-strlen(pAddress[*nAddressCnt].displayName));
+                               }
+                       }
+               }
+
+               (*nAddressCnt)++;
+       }
+
+       pDbHandle->finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+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->msg_struct_info = 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);
+
+       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Query Failed [%s]", sqlQuery);
+               return MSG_ERR_DB_PREPARE;
+       }
+
+       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];
+
+       for (int i = 0; i < MAX_TO_ADDRESS_CNT; i++) {
+               pAddress->msg_struct_info[i] = (msg_struct_t)new char[sizeof(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)];
+               memset(pTmp->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+       }
+
+
+       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 (pDbHandle->columnText(6) != NULL)
+                               strncpy(lastName, (char *)pDbHandle->columnText(6), MAX_DISPLAY_NAME_LEN);
+
+                       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));
+                               }
+                       }
+               }
+
+               pAddress->nCount++;
+       }
+
+       pDbHandle->finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+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;
+
+       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;",
+                       MSGFW_ADDRESS_TABLE_NAME, convId);
+
+       msg_error_t  err = pDbHandle->getTable(sqlQuery, &rowCnt);
+
+       if (err == MSG_ERR_DB_NORECORD) {
+               pDbHandle->freeTable();
+               return MSG_SUCCESS;
+       } else if (err != MSG_SUCCESS) {
+               MSG_DEBUG("sqlQuery is - %s", sqlQuery);
+               pDbHandle->freeTable();
+               return err;
+       }
+
+       pAddrlist->nCount = rowCnt;
+
+       MSG_DEBUG("pAddrlist->nCount [%d]", pAddrlist->nCount);
+
+       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];
+
+       for (int i = 0; i < MAX_TO_ADDRESS_CNT; i++) {
+               pAddrlist->msg_struct_info[i] = (msg_struct_t)new char[sizeof(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)];
+               memset(pTmp->data, 0x00, sizeof(MSG_ADDRESS_INFO_S));
+       }
+
+       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));
+                               }
+                       }
+               }
+
+       }
+       pDbHandle->freeTable();
+
+       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];
+
+       memset(msgText, 0x00, sizeof(msgText));
+
+       // 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 STORAGE_ID = %d AND READ_STATUS = 0;",
+                       MSGFW_MESSAGE_TABLE_NAME, convId, MSG_INBOX_ID, MSG_STORAGE_PHONE);
+
+       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 > %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);
+
+       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 > %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);
+
+       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;
+       }
+
+       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 > %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);
+
+       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;
+       }
+
+       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) {
+               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;
+       }
+
+       pDbHandle->finalizeQuery();
+
+       MSG_END();
+
+       return MSG_SUCCESS;
+}
+
+
+/* consider to replcae this function to trigger. */
+msg_error_t MsgStoClearConversationTable(MsgDbHandler *pDbHandle)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s \
+                       WHERE CONV_ID NOT IN (SELECT CONV_ID FROM %s) AND CONV_ID <> 0;",
+                       MSGFW_CONVERSATION_TABLE_NAME, MSGFW_MESSAGE_TABLE_NAME);
+
+       err = pDbHandle->execQuery(sqlQuery);
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "DELETE FROM %s WHERE CONV_ID NOT IN (SELECT CONV_ID FROM %s);",
+                       MSGFW_ADDRESS_TABLE_NAME, MSGFW_CONVERSATION_TABLE_NAME);
+
+       err = pDbHandle->execQuery(sqlQuery);
+
+       return err;
+}
+
+
+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];
+
+       *pConvId = 0;
+
+       if(pMsg->nAddressCnt == 1) {
+               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);
+
+                       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));
+
+                       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);
+               }
+
+               int rowCnt = 0;
+               msg_thread_id_t convId = 0;
+               err = pDbHandle->getTable(sqlQuery, &rowCnt);
+
+               /* No record or other error */
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed [%s]", sqlQuery);
+                       pDbHandle->freeTable();
+                       return false;
+               }
+
+               if(rowCnt > 0) {
+                       convId = pDbHandle->getColumnToInt(1);
+
+                       MSG_DEBUG("CONV_ID : [%d]", convId);
+
+                       if (convId > 0) {
+                               *pConvId = convId;
+                               pDbHandle->freeTable();
+                               return true;
+                       } else {
+                               pDbHandle->freeTable();
+                               return false;
+                       }
+               }
+
+       } 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);
+
+                       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));
+
+                       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;
+
+               MSG_DEBUG("Query [%s]", sqlQuery);
+
+               err = pDbHandle->getTable(sqlQuery, &rowCnt);
+
+               /* No record or other error */
+               if (err != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed [%s]", sqlQuery);
+                       pDbHandle->freeTable();
+                       return false;
+               }
+
+               for (int i = 1; i <= rowCnt; i++) {
+                       convId = pDbHandle->getColumnToInt(i);
+
+                       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+                       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++ ) {
+
+                               if (j!=0)
+                                       strncat(sqlQuery, "OR ", MAX_QUERY_LEN-strlen(sqlQuery));
+
+                               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));
+
+       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);
+       } 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);
+       }
+
+       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS)
+               return 0;
+
+       if (pDbHandle->stepQuery() == MSG_ERR_DB_ROW) {
+               msgCnt = pDbHandle->columnInt(0);
+       } else {
+               pDbHandle->finalizeQuery();
+               return 0;
+       }
+
+       pDbHandle->finalizeQuery();
+
+       return msgCnt;
+}
+
+
+msg_error_t MsgStoAddContactInfo(MsgDbHandler *pDbHandle, MSG_CONTACT_INFO_S *pContactInfo, const char *pNumber)
+{
+       char newPhoneNum[MAX_PRECONFIG_NUM+1];
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       if (strlen(pNumber) > MAX_PRECONFIG_NUM) {
+               memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
+               MsgConvertNumber(pNumber, newPhoneNum);
+
+               MSG_DEBUG("Phone Number to Compare : [%s]", newPhoneNum);
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET \
+                               CONTACT_ID = %d, FIRST_NAME = ?, LAST_NAME = ?, IMAGE_PATH = '%s' \
+                               WHERE ADDRESS_VAL LIKE '%%%%%s';",
+                               MSGFW_ADDRESS_TABLE_NAME, pContactInfo->contactId, pContactInfo->imagePath, newPhoneNum);
+       } else {
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET \
+                               CONTACT_ID = %d, FIRST_NAME = ?, LAST_NAME = ?, IMAGE_PATH = '%s' \
+                               WHERE ADDRESS_VAL = '%s';",
+                               MSGFW_ADDRESS_TABLE_NAME, pContactInfo->contactId, pContactInfo->imagePath, pNumber);
+       }
+
+       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("sqlQuery [%s]", sqlQuery);
+               return MSG_ERR_DB_PREPARE;
+       }
+
+       pDbHandle->bindText(pContactInfo->firstName, 1);
+
+       pDbHandle->bindText(pContactInfo->lastName, 2);
+
+       if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+               pDbHandle->finalizeQuery();
+               MSG_DEBUG("Update contact Info. Fail [%s]", sqlQuery);
+               return MSG_ERR_DB_STEP;
+       }
+
+       pDbHandle->finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoClearContactInfo(MsgDbHandler *pDbHandle, int contactId)
+{
+       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(CONV_ID) FROM %s WHERE CONTACT_ID = %d;",
+                       MSGFW_ADDRESS_TABLE_NAME, contactId);
+
+       err = pDbHandle->getTable(sqlQuery, &rowCnt);
+
+       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, DISPLAY_NAME = '', FIRST_NAME = '', LAST_NAME = '', IMAGE_PATH = '' \
+                       WHERE CONTACT_ID = %d;",
+                       MSGFW_ADDRESS_TABLE_NAME, contactId);
+
+       if (pDbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to execute query");
+               return MSG_ERR_DB_EXEC;
+       }
+
+       MsgDbHandler tmpDbHandle;
+       for (int i=1; i<=rowCnt; i++)
+               MsgStoSetConversationDisplayName(&tmpDbHandle, (msg_thread_id_t)pDbHandle->getColumnToInt(i));
+
+       pDbHandle->freeTable();
+
+       return err;
+}
+
+
+msg_error_t MsgStoClearContactInfo(MsgDbHandler *pDbHandle, int contactId, const char *pNumber)
+{
+       char newPhoneNum[MAX_PRECONFIG_NUM+1];
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(newPhoneNum, 0x00, sizeof(newPhoneNum));
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       if (strlen(pNumber) > MAX_PRECONFIG_NUM) {
+               MsgConvertNumber(pNumber, newPhoneNum);
+
+               MSG_DEBUG("Phone Number to Compare : [%s]", newPhoneNum);
+
+               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 (pDbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Fail to execute query");
+               return MSG_ERR_DB_EXEC;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoGetMmsRawFilePath(MsgDbHandler *pDbHandle, msg_message_id_t msgId, char *pFilePath)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.FILE_PATH FROM %s A, %s B \
+                       WHERE A.MSG_ID = B.MSG_ID AND B.MSG_ID = %d;",
+                       MMS_PLUGIN_MESSAGE_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(pFilePath, (char*)pDbHandle->columnText(0), MSG_FILEPATH_LEN_MAX);
+       } else {
+               pDbHandle->finalizeQuery();
+               return MSG_ERR_DB_STEP;
+       }
+
+       pDbHandle->finalizeQuery();
+
+       return MSG_SUCCESS;
+}
+
+
+bool MsgStoCheckReadReportRequested(MsgDbHandler *pDbHandle, msg_message_id_t msgId)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+       int rowCnt = 0;
+       bool bReadReportRequested = false;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.ASK_READ_REPLY FROM %s A, %s B \
+                       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);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               pDbHandle->freeTable();
+               MSG_DEBUG("[Error]Failed to Get Table");
+               return bReadReportRequested;
+       }
+
+       if (rowCnt != 1) {
+               pDbHandle->freeTable();
+               MSG_DEBUG("[Error]MSG_ERR_DB_NORECORD");
+               return bReadReportRequested;
+       }
+
+       bReadReportRequested = pDbHandle->getColumnToInt(1);
+
+       pDbHandle->freeTable();
+
+       return bReadReportRequested;
+}
+
+
+bool MsgStoCheckReadReportIsSent(MsgDbHandler *pDbHandle, msg_message_id_t msgId)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       int rowCnt = 0;
+       bool bReadReportIsSent = true;
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT A.READ_REPORT_SENT FROM %s A, %s B \
+                       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);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               pDbHandle->freeTable();
+               MSG_DEBUG("[Error]Failed to Get Table");
+               return bReadReportIsSent;
+       }
+
+       if (rowCnt != 1) {
+               pDbHandle->freeTable();
+               MSG_DEBUG("[Error]MSG_ERR_DB_NORECORD");
+               return bReadReportIsSent;
+       }
+
+       bReadReportIsSent = (bool)pDbHandle->getColumnToInt(1);
+
+       pDbHandle->freeTable();
+
+       return bReadReportIsSent;
+}
+
+
+msg_error_t MsgStoAddConversation(MsgDbHandler *pDbHandle, msg_thread_id_t *pConvId)
+{
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       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, '', '');",
+                       MSGFW_CONVERSATION_TABLE_NAME, *pConvId);
+
+       if (pDbHandle->execQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Query Failed. [%s]", sqlQuery);
+               return MSG_ERR_DB_EXEC;
+       }
+
+       return MSG_SUCCESS;
+}
+
+
+msg_error_t MsgStoSetConversationDisplayName(MsgDbHandler *pDbHandle, int contactId)
+{
+       msg_error_t err = MSG_SUCCESS;
+       int rowCnt = 0;
+       char displayName[MAX_DISPLAY_NAME_LEN+1];
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       MSG_DEBUG("contactId [%d]", contactId);
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "SELECT DISTINCT(CONV_ID) FROM %s WHERE CONTACT_ID = %d;",
+                       MSGFW_ADDRESS_TABLE_NAME, contactId);
+
+       err = pDbHandle->getTable(sqlQuery, &rowCnt);
+
+       if (err != MSG_SUCCESS && err != MSG_ERR_DB_NORECORD) {
+               pDbHandle->freeTable();
+               MSG_DEBUG("Query Failed [%s]", sqlQuery);
+               return err;
+       }
+
+       int order = MsgGetContactNameOrder();
+       msg_struct_s *pAddrInfo = NULL;
+       MSG_ADDRESS_INFO_S *address = NULL;
+
+       for (int i = 1; i <= rowCnt; i++)
+       {
+               memset(displayName, 0x00, sizeof(displayName));
+               MsgDbHandler tmpDbHandle;
+               msg_struct_list_s addressList = {0,};
+               MsgStoGetAddressByConvId(&tmpDbHandle, (msg_thread_id_t)pDbHandle->getColumnToInt(i), order, &addressList);
+
+               for (int j = 0; j < addressList.nCount; j++)
+               {
+                       if (j >0)
+                               strncat(displayName, ", ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
+
+                       pAddrInfo = (msg_struct_s *)addressList.msg_struct_info[j];
+                       address = (MSG_ADDRESS_INFO_S *)pAddrInfo->data;
+
+                       if (address->displayName[0] == '\0')
+                               strncat(displayName, address->addressVal, MAX_DISPLAY_NAME_LEN-strlen(displayName));
+                       else
+                               strncat(displayName, address->displayName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
+               }
+
+               memset(sqlQuery, 0x00, sizeof(sqlQuery));
+               snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET DISPLAY_NAME = ? WHERE CONV_ID = %d;",
+                               MSGFW_CONVERSATION_TABLE_NAME, pDbHandle->getColumnToInt(i));
+
+               if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+                       MSG_DEBUG("Query Failed [%s]", sqlQuery);
+                       return MSG_ERR_DB_PREPARE;
+               }
+
+               pDbHandle->bindText(displayName, 1);
+
+               if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+                       pDbHandle->finalizeQuery();
+                       MSG_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++){
+                       msg_struct_s *pStruct = (msg_struct_s *)addressList.msg_struct_info[j];
+                       delete [] (MSG_ADDRESS_INFO_S *)pStruct->data;
+                       delete [] (msg_struct_s *)pStruct;
+               }
+       }
+
+       pDbHandle->freeTable();
+
+       return err;
+}
+
+
+msg_error_t MsgStoSetConversationDisplayName(MsgDbHandler *pDbHandle, msg_thread_id_t convId)
+{
+       msg_error_t err = MSG_SUCCESS;
+
+       char displayName[MAX_DISPLAY_NAME_LEN+1];
+       char sqlQuery[MAX_QUERY_LEN+1];
+
+       msg_struct_list_s addressList = {0,};
+
+       int order = MsgGetContactNameOrder();
+       msg_struct_s *pAddrInfo = NULL;
+       MSG_ADDRESS_INFO_S *address = NULL;
+
+       memset(displayName, 0x00, sizeof(displayName));
+
+       MsgStoGetAddressByConvId(pDbHandle, convId, order, &addressList);
+
+       for (int j = 0; j < addressList.nCount; j++)
+       {
+               if (j >0)
+                       strncat(displayName, ", ", MAX_DISPLAY_NAME_LEN-strlen(displayName));
+
+               pAddrInfo = (msg_struct_s *)addressList.msg_struct_info[j];
+               address = (MSG_ADDRESS_INFO_S *)pAddrInfo->data;
+
+               if (address->displayName[0] == '\0')
+                       strncat(displayName, address->addressVal, MAX_DISPLAY_NAME_LEN-strlen(displayName));
+               else
+                       strncat(displayName, address->displayName, MAX_DISPLAY_NAME_LEN-strlen(displayName));
+       }
+
+       memset(sqlQuery, 0x00, sizeof(sqlQuery));
+       snprintf(sqlQuery, sizeof(sqlQuery), "UPDATE %s SET DISPLAY_NAME = ? WHERE CONV_ID = %d;",
+                       MSGFW_CONVERSATION_TABLE_NAME, convId);
+
+       if (pDbHandle->prepareQuery(sqlQuery) != MSG_SUCCESS) {
+               MSG_DEBUG("Query Failed [%s]", sqlQuery);
+               return MSG_ERR_DB_PREPARE;
+       }
+
+       pDbHandle->bindText(displayName, 1);
+
+       if (pDbHandle->stepQuery() != MSG_ERR_DB_DONE) {
+               pDbHandle->finalizeQuery();
+               MSG_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++){
+               msg_struct_s *pStruct = (msg_struct_s *)addressList.msg_struct_info[j];
+               delete [] (MSG_ADDRESS_INFO_S *)pStruct->data;
+               delete [] (msg_struct_s *)pStruct;
+       }
+
+       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;
+
+       return err;
+}
+
+char *MsgStoReplaceString(const char *origStr, const char *oldStr, const char *newStr)
+{
+       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++;
+                       }
+               }
+       } else {
+               return g_strdup(origStr);
+       }
+
+       replaceStr = (char *)calloc(1, i + sizeof(char) * (matchedCnt * (newStrLen - oldStrLen) + 1));
+       if (replaceStr == NULL)
+               return NULL;
+
+       pTemp = replaceStr;
+
+       while (*origStr) {
+               if (memcmp(origStr, oldStr, oldStrLen) == 0) {
+                       memcpy(pTemp, newStr, newStrLen);
+                       pTemp += newStrLen;
+                       origStr += oldStrLen;
+               } else {
+                       *pTemp++ = *origStr++;
+               }
+       }
+
+       return replaceStr;
+}
diff --git a/utils/MsgVMessage.cpp b/utils/MsgVMessage.cpp
new file mode 100755 (executable)
index 0000000..862502d
--- /dev/null
@@ -0,0 +1,620 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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"
+
+
+/*==================================================================================================
+                                     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;
+       int                     err = MSG_SUCCESS;
+
+       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;
+       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;
+                               AutoPtr<char> buf(&pFileData);
+
+                               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;
+
+               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(pDbHandle, 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)
+                       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;
+       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;
+                               AutoPtr<char> buf(&pFileData);
+
+                               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;
+
+               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)
+                       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..114a14b
--- /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_C_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)
+
+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_C_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..f7af58a
--- /dev/null
@@ -0,0 +1,1538 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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* ) malloc ( 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;
+       }
+
+       pBuf = (char *)malloc(len);
+       if(len < 1 || (pBuf  == NULL)) {
+               if (pBuf) {
+                       free(pBuf);
+                       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 *)malloc(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 *)malloc(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 *)malloc(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 *)malloc(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);
+
+       pCardRaw = _VUnfoldingNoSpecNew(pCardRaw);
+       pCardRawTmp = pCardRaw;
+       len = _VManySpace2Space( pCardRaw );
+
+       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(start_status == 1) {
+                                                       goto CATCH;
+                                               }
+                                               if ( ( pVCard = ( VTree* )malloc( 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* )malloc( 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* )malloc( 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* )malloc( 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;
+               }
+       }
+
+       if ( ( pVCardRes = ( char * )malloc( sizeof( char ) * ( total += 14 + 14 ) ) ) == NULL )
+       {
+               VDATA_TRACE(  "vcard_encode:malloc failed\n" );
+               VDATA_TRACE_END
+               return NULL;
+       }
+
+       memcpy( pVCardRes, "BEGIN:VCARD\r\n", 14 );
+       strcat( pVCardRes, "VERSION:2.1\r\n" );
+
+       pTmpObj = pVCardRaw->pTop;
+
+       while ( true )
+       {
+               if(pTmpObj == NULL)
+                       break;
+
+               if ( ( pTemp = __VCardTypeEncode( pTmpObj, pszCardTypeList[pTmpObj->property] ) ) != NULL )
+               {
+                       len = strlen( pTemp );
+
+                       if ( ( pVCardRes = ( char* )realloc( pVCardRes, ( total += len+10 ) ) ) == NULL )
+                       {
+                               VDATA_TRACE(  "vcard_encode():realloc failed\n");
+                               VFREE( pTemp );
+                               pTemp = NULL;
+                               VDATA_TRACE_END
+                               return NULL;
+                       }
+
+                       if( strncmp(pTemp,"VERSION", strlen("VERSION")) != 0)
+                               strncat(pVCardRes, pTemp, strlen(pTemp));
+
+                       VDATA_TRACE("pTemp : %s", pTemp);
+
+                       VFREE( pTemp );
+                       pTemp = NULL;
+               }
+
+               if ( pTmpObj->pSibling != NULL )
+                       pTmpObj = pTmpObj->pSibling;
+               else
+                       break;
+       }
+
+       if ( ( pVCardRes = ( char * )realloc( pVCardRes, ( total += 12 ) ) ) == NULL )
+       {
+               VDATA_TRACE(  "vcard_encode:realloc failed\n");
+               VDATA_TRACE_END
+               return NULL;
+       }
+       strcat( pVCardRes, "END:VCARD\r\n" );
+       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 * )malloc( total += ( len+1 ) ) ) == NULL )
+       {
+               VDATA_TRACE(  "__VCardTypeEncode():malloc failed\n");
+               VDATA_TRACE_END
+               return NULL;
+       }
+       memset( szTypeValue, '\0', ( len+1 ) );
+#ifdef VDATA_GROUPNAME_SUPPORTED
+       if ( pTypeObj->pszGroupName != NULL )
+       {
+               strcat( szTypeValue, pTypeObj->pszGroupName );
+               strcat( szTypeValue, "." );
+       }
+#endif // VDATA_GROUPNAME_SUPPORTED
+       strcat( szTypeValue, pType );
+
+       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;
+               }
+               strcat( szTypeValue, pTemp );
+               VFREE( pTemp );
+               pTemp = NULL;
+       }
+
+       if ( ( szTypeValue = ( char * )realloc( szTypeValue, ( total += 2 ) ) ) == NULL )
+       {
+               VDATA_TRACE_END
+               return NULL;
+       }
+
+       strcat( 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 * )malloc( len+20 ) ) == NULL ) {
+                               VFREE(szTypeValue);
+                               VDATA_TRACE_END
+                               return NULL;
+                       }
+
+                       memset( pEncode, '\0', len+20 );
+
+                       if(strcmp(pType, pszCardTypeList[19]) != 0)     {
+                               strcat( pEncode, pTypeObj->pszValue[i] );
+                               _VEscape(pEncode);
+                       }
+                       else
+                               memcpy(pEncode, pTypeObj->pszValue[i], biLen);
+                       }
+               else {
+                       char    buf[1000];
+                       strncpy( buf, pTypeObj->pszValue[i], 999 );
+                       _VEscape( buf );
+                       strcat( pEncode, ";" );
+                       strcat( pEncode, buf );
+               }
+       }
+
+       if(strcmp(pType, pszCardTypeList[19]) != 0)     {
+               if (pEncode) {
+                       strcat( pEncode, "\0\0" );
+                       len = strlen( pEncode );
+               }
+       }
+       else {
+               len = biLen;
+       }
+
+       if ( enc & pEncList[2].flag ) {
+               if((pRes = (char *)malloc(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 *)malloc((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 *)malloc(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;
+       }
+       strncat( 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;
+       }
+
+       strncat(szTypeValue, pRes, total - 1);
+
+       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*)malloc(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. */
+               strcat( szParam, ";" );
+               if(pTemp->parameter != VCARD_PARAM_TYPE) {
+                       strcat( szParam, pszCardParamList[pTemp->parameter] );
+                       strcat( 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;
+                               }
+                               strcat( szParam, "NONE" );
+               }
+
+               /** 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;
+                                       }
+
+                                       strcat( szParam, pList[i].szName );
+                                       strcat( 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..5938e61
--- /dev/null
@@ -0,0 +1,1233 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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);
+
+    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 );
+
+       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*) malloc(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..8aaba5c
--- /dev/null
@@ -0,0 +1,1634 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 *)malloc(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 *)malloc(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 *)malloc(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 *)malloc(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 *)malloc(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);
+       len = _VUnfoldingNoSpec(pMsgRaw, VMESSAGE);
+       pMsgRawTmp = pMsgRaw;
+       len = _VManySpace2Space( pMsgRaw );
+
+       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* )malloc( 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* )malloc( 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* )malloc( 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* )malloc( 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* )malloc( 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(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 * )malloc( sizeof( char ) * ( total += 13 ) ) ) == NULL )
+                               {
+                                       VDATA_TRACE(  "vmsg_encode:malloc 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;
+                               strncat( 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;
+                                       strncat(pVMsgRes, encoded, len+10);
+                                       VDATA_TRACE("pTemp : %s", encoded);
+                                       VFREE( pTemp );
+                                       VFREE( encoded );
+                                       VFREE(pVMsgRes);
+                                       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;
+                                       strncat(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;
+                               strncat( 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;
+       strncat( 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 * )malloc( total += ( len+1 ) ) ) == NULL )
+       {
+               VDATA_TRACE(  "__VMsgTypeEncode():malloc failed\n");
+               VDATA_TRACE_END
+               return NULL;
+       }
+       memset( szTypeValue, '\0', ( len+1 ) );
+       strncat( 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;
+               }
+               strncat( szTypeValue, pTemp, len);
+               VFREE( pTemp );
+               pTemp = NULL;
+       }
+
+       if ( ( szTypeValue = ( char * )realloc( szTypeValue, ( total += 2 ) ) ) == NULL )
+       {
+               VDATA_TRACE_END
+               return NULL;
+       }
+
+       strncat( 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 * )malloc( len+20 ) ) == NULL )
+                       {
+                               VFREE(szTypeValue);
+                               VDATA_TRACE_END
+                               return NULL;
+                       }
+
+                       memset( pEncode, '\0', len+20 );
+
+                       if(strcmp(pType, pszMsgTypeList[6]) != 0)
+                       {
+                               strncat( 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 );
+                       strcat( pEncode, ";" );
+                       strcat( pEncode, buf );
+               }
+       }
+
+       if(strcmp(pType, pszMsgTypeList[6]) != 0)       {
+               if (pEncode) {
+                       strcat( pEncode, "\0\0" );
+                       len = strlen( pEncode );
+               }
+       }
+       else {
+               len = biLen;
+       }
+
+       if ( enc & pMsgEncList[2].flag ) {
+               if((pRes = (char *)malloc(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 *)malloc((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 *)malloc(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;
+       }
+       strncat( 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;
+       }
+
+       strncat(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*)malloc(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. */
+               strcat( szParam, ";" );
+               if(pTemp->parameter != VMSG_PARAM_TYPE) {
+                       strcat( szParam, pszMsgParamList[pTemp->parameter] );
+                       strcat( szParam, "=" );
+               }
+
+               /** 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;
+                               }
+                               strcat( szParam, "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;
+                                       }
+
+                                       strcat( szParam, pList[i].szName );
+                                       strcat( 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
+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..0bd7285
--- /dev/null
@@ -0,0 +1,231 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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..15466a0
--- /dev/null
@@ -0,0 +1,209 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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..2d2249a
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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..c0a5acf
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <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 VDATA_TRACE(fmt, arg...)
+#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
diff --git a/vobject-engine/test_code/CQ_VCARD.c b/vobject-engine/test_code/CQ_VCARD.c
new file mode 100755 (executable)
index 0000000..3348275
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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>
+
+extern void utc_vdata_vcard_decode_1();
+extern void utc_vdata_vcard_decode_2();
+extern void utc_vdata_vcard_decode_3();
+extern void utc_vdata_vcard_decode_4();
+extern void utc_vdata_vcard_decode_5();
+extern void utc_vdata_vcard_decode_6();
+extern void utc_vdata_vcard_decode_7();
+extern void utc_vdata_vcard_encode_1();
+extern void utc_vdata_vcard_encode_0();
+extern void utc_vdata_vcard_encode_2();
+extern void utc_vdata_vcard_encode_3();
+extern void utc_vdata_vcard_encode_4();
+extern void utc_vdata_vcard_encode_5();
+extern void utc_vdata_vcard_encode_6();
+extern void utc_vdata_vcard_encode_7();
+extern void utc_vdata_vcard_encode_8();
+
+int CQ_TEST() {
+#if 0
+       printf("\n################################### VCard CQ Test  ##################################\n");
+       printf("[TEST CASE] utc_vdata_vcard_decode_1 : decode a raw buffer to a tree.\n");
+       utc_vdata_vcard_decode_1();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_decode_2 :  decode a raw buffer without begin token to a tree.\n");
+       utc_vdata_vcard_decode_2();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_decode_3 : decode a raw buffer without end token to a tree.\n");
+       utc_vdata_vcard_decode_3();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_decode_4 : decode a raw buffer having invalid version tag to a tree.\n");
+       utc_vdata_vcard_decode_4();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_decode_5 : decode a raw buffer without having crlf in between two tokens to a tree.\n");
+       utc_vdata_vcard_decode_5();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_decode_6 : decode a raw buffer having some invalid token to a tree.\n");
+       utc_vdata_vcard_decode_6();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_decode_7 : decode a NULL raw buffer to a tree.\n");
+       utc_vdata_vcard_decode_7();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_encode_0 : \n");
+       utc_vdata_vcard_encode_0();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_encode_1 : encode a tree to a buffer.\n");
+       utc_vdata_vcard_encode_1();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_encode_2 : encode a tree with tree type as vcalendar to a buffer.\n");
+       utc_vdata_vcard_encode_2();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_encode_3 : encode a tree with all the vobjects as NULL to a buffer.\n");
+       utc_vdata_vcard_encode_3();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_encode_4 : encode a tree with an object having property as very high value to a buffer.\n");
+       utc_vdata_vcard_encode_4();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_encode_5 : encode a NULL tree to a buffer.\n");
+       utc_vdata_vcard_encode_5();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_encode_6 : encode a tree with an object having property but no other value to a buffer.\n");
+       utc_vdata_vcard_encode_6();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_encode_7 : encode a tree with an object having value count greater than actual vales to a buffer.\n");
+       utc_vdata_vcard_encode_7();
+       printf("\n\n[TEST CASE] utc_vdata_vcard_encode_8 : encode a tree with tree type as a high value to a buffer.\n");
+       utc_vdata_vcard_encode_8();
+       printf("\n################################### VCard CQ Test  ##################################\n\n");
+#endif
+
+       return 0;
+}
+
+int main(int argc, char** argv) {
+
+       CQ_TEST();
+}
diff --git a/vobject-engine/test_code/uts_vdata_vcard_decode.c b/vobject-engine/test_code/uts_vdata_vcard_decode.c
new file mode 100755 (executable)
index 0000000..f33d501
--- /dev/null
@@ -0,0 +1,230 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <VCard.h>
+#include <VTypes.h>
+#include <glib.h>
+
+#define MT_CHECK_EQUAL(arg1, arg2) arg1 != arg2 ? \
+       fprintf(stderr,"[VOBJECT-TEST-CASE] %s %s:%d NOT EQUAL\n",__FILE__,__FUNCTION__,__LINE__) :\
+       fprintf(stderr,"[VOBJECT-TEST-CASE] %s %s:%d EQUAL\n",__FILE__,__FUNCTION__,__LINE__);
+
+#define VDATA_TEST_TRACE(fmt, arg...) \
+       do { {fprintf(stderr, "[VOBJECT-TEST-CASE] %s %s:%d: " fmt,__FILE__,__FUNCTION__, __LINE__, ##arg);}}while (false);
+
+
+/** decode a raw buffer to a tree */
+void utc_vdata_vcard_decode_1()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = g_strdup("BEGIN:VCARD\r\nVERSION:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531\r\nEND:VCARD");
+
+       tree = VCardDecode(buffer);
+       VDATA_TEST_TRACE("call executed \n");
+
+       if(!(tree != NULL)) return;
+
+       VDATA_TEST_TRACE("treetype is %d \n", tree->treeType);
+
+       if (!(tree->pTop)){
+               VDATA_TEST_TRACE("decodeing faili - utc_vdata_vcard_decode_%d",1);
+               return;
+       }
+       VDATA_TEST_TRACE ("top property is %d \n", tree->pTop->property);
+       VDATA_TEST_TRACE ("top property value is %s \n", *(tree->pTop->pszValue));
+
+       if (tree->pTop->pParam){
+               VDATA_TEST_TRACE ("top param is %d \n", tree->pTop->pParam->parameter);
+               VDATA_TEST_TRACE ("top param val is %d \n", tree->pTop->pParam->paramValue);
+       }
+
+       if (tree->pCur){
+               VDATA_TEST_TRACE ("cur property is %d \n", tree->pCur->property);
+               VDATA_TEST_TRACE ("top property value is %s \n", *(tree->pCur->pszValue));
+       }
+
+       if (!(tree->pTop->pSibling)){
+               VDATA_TEST_TRACE("decodeing faili - utc_vdata_vcard_decode_%d",1);
+               return;
+       }
+
+       VDATA_TEST_TRACE ("sibling not NULL \n");
+       VDATA_TEST_TRACE ("sibling property is %d \n", tree->pTop->pSibling->property);
+       VDATA_TEST_TRACE ("sibling property value is %s \n", *(tree->pTop->pSibling->pszValue));
+
+       if (tree->pTop->pSibling->pParam){
+               VDATA_TEST_TRACE ("sibling param is %d \n", tree->pTop->pSibling->pParam->parameter);
+               VDATA_TEST_TRACE ("sibling param val is %d \n", tree->pTop->pSibling->pParam->paramValue);
+       }
+
+       VDATA_TEST_TRACE("decodeing success - utc_vdata_vcard_decode_%d\n",1);
+
+       VObject* pSibling2 = tree->pTop->pSibling->pSibling;
+       if (!pSibling2)
+               return;
+
+       VDATA_TEST_TRACE ("sibling2 not NULL \n");
+       VDATA_TEST_TRACE ("sibling2 property is %d \n", pSibling2->property);
+       VDATA_TEST_TRACE ("sibling2 property value is %s \n", *(pSibling2->pszValue));
+
+       if (pSibling2->pParam){
+               VDATA_TEST_TRACE ("sibling param is %d \n", pSibling2->pParam->parameter);
+               VDATA_TEST_TRACE ("sibling param val is %d \n", pSibling2->pParam->paramValue);
+       }
+
+       if (tree->pTop->pParent)
+               VDATA_TEST_TRACE ("parent not NULL \n");
+       if (tree->pTop->pChild)
+               VDATA_TEST_TRACE ("child not NULL \n");
+
+
+       if(buffer != NULL)
+               g_free(buffer);
+}
+
+/** decode a raw buffer without begin token to a tree */
+void utc_vdata_vcard_decode_2()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = g_strdup("VERSION:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531\r\nEND:VCARD");
+
+       tree = VCardDecode(buffer);
+       VDATA_TEST_TRACE("call executed \n");
+
+       if(!(tree != NULL)) VDATA_TEST_TRACE("tree is null");
+
+       if(buffer != NULL)
+               g_free(buffer);
+}
+
+/*decode a raw buffer without end token to a tree*/
+void utc_vdata_vcard_decode_3()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = g_strdup("BEGIN:VCARD\r\nVERSION:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531");
+
+       VDATA_TEST_TRACE("%s\n", buffer);
+       tree = VCardDecode(buffer);
+       VDATA_TEST_TRACE("call executed \n");
+
+       if(!tree) return;
+
+       VDATA_TEST_TRACE ("treetype is %d \n", tree->treeType);
+
+
+       if(buffer != NULL)
+               g_free(buffer);
+}
+/*decode a raw buffer having invalid version tag to a tree*/
+void utc_vdata_vcard_decode_4()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = g_strdup("BEGIN:VCARD\r\nVE:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531\r\nEND:VCARD");
+
+       tree = VCardDecode(buffer);
+
+       VDATA_TEST_TRACE ("call executed \n");
+       VDATA_TEST_TRACE ("treetype is %d \n", tree->treeType);
+
+       if (!(tree->pTop)){
+               VDATA_TEST_TRACE ("tree->pTop null. \n");
+               return;
+       }
+
+       VDATA_TEST_TRACE ("top property is %d \n", tree->pTop->property);
+       VDATA_TEST_TRACE ("top property value is %s \n", *(tree->pTop->pszValue));
+
+       MT_CHECK_EQUAL(tree->pTop->property, (int)VCARD_TYPE_N);
+
+
+       if(buffer != NULL)
+               g_free(buffer);
+}
+
+/** decode a raw buffer without having crlf in between two tokens to a tree */
+void utc_vdata_vcard_decode_5()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = g_strdup("BEGIN:VCARDVERSION:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531\r\nEND:VCARD");
+
+       tree = VCardDecode(buffer);
+       VDATA_TEST_TRACE ("call executed \n");
+       VDATA_TEST_TRACE ("treetype is %d \n", tree->treeType);
+
+       if (!(tree->pTop)){
+               VDATA_TEST_TRACE ("tree->pTop null. \n");
+               return;
+       }
+
+       VDATA_TEST_TRACE ("top property is %d \n", tree->pTop->property);
+       VDATA_TEST_TRACE ("top property value is %s \n", *(tree->pTop->pszValue));
+
+       MT_CHECK_EQUAL(tree->pTop->property, (int)VCARD_TYPE_N);
+
+       if(buffer != NULL)
+               g_free(buffer);
+}
+
+/*decode a raw buffer having some invalid token to a tree*/
+void utc_vdata_vcard_decode_6()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = g_strdup("BEGIN:VCARD\r\nVERSIOOOONNNN:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531\r\nEND:VCARD");
+
+       tree = VCardDecode(buffer);
+       VDATA_TEST_TRACE ("call executed \n");
+       VDATA_TEST_TRACE ("treetype is %d \n", tree->treeType);
+
+       if (!(tree->pTop)){
+               VDATA_TEST_TRACE ("tree->pTop null. \n");
+               return;
+       }
+
+       VDATA_TEST_TRACE ("top property is %d \n", tree->pTop->property);
+       VDATA_TEST_TRACE ("top property value is %s \n", *(tree->pTop->pszValue));
+
+       MT_CHECK_EQUAL(tree->pTop->property, (int)VCARD_TYPE_N);
+
+       if(buffer != NULL)
+               g_free(buffer);
+}
+
+/*decode a NULL raw buffer to a tree*/
+void utc_vdata_vcard_decode_7()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       tree = VCardDecode(buffer);
+       VDATA_TEST_TRACE ("call executed \n");
+
+       MT_CHECK_EQUAL((VTree*)NULL, tree);
+
+       if(buffer != NULL)
+               g_free(buffer);
+}
diff --git a/vobject-engine/test_code/uts_vdata_vcard_encode.c b/vobject-engine/test_code/uts_vdata_vcard_encode.c
new file mode 100755 (executable)
index 0000000..e2b8aa8
--- /dev/null
@@ -0,0 +1,320 @@
+/*
+* Copyright 2012-2013  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://floralicense.org
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT 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 <VCalendar.h>
+#include <VCard.h>
+#include <VTypes.h>
+#include <glib.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#define MT_CHECK_EQUAL(arg1, arg2) arg1 != arg2 ? \
+  fprintf(stderr,"[VOBJECT-TEST-CASE] %s %s:%d NOT EQUAL",__FILE__,__FUNCTION__,__LINE__) :\
+  fprintf(stderr,"[VOBJECT-TEST-CASE] %s %s:%d EQUAL",__FILE__,__FUNCTION__,__LINE__);
+
+#define MT_CHECK_NOT_EQUAL(arg1, arg2) arg1 != arg2 ? \
+  fprintf(stderr,"[VOBJECT-TEST-CASE] %s %s:%d NOT EQUAL",__FILE__,__FUNCTION__,__LINE__) :\
+  fprintf(stderr,"[VOBJECT-TEST-CASE] %s %s:%d EQUAL",__FILE__,__FUNCTION__,__LINE__);
+
+#define VDATA_TEST_TRACE(fmt, arg...) \
+  do { {fprintf(stderr, "[VOBJECT-TEST-CASE] %s %s:%d: " fmt "\n" ,__FILE__,__FUNCTION__, __LINE__, ##arg);}}while (false);
+
+#define null NULL
+
+/* */
+void
+utc_vdata_vcard_encode_0() {
+
+       FILE* fp;
+       char* buffer;
+       char* temp;
+       VTree *tree = NULL;
+       VObject*        pTemp = NULL;
+       VParam*         pTmpParam = NULL;
+
+       struct stat stat_object;
+       VDATA_TEST_TRACE("START");
+
+       if(lstat("sample.vcf", &stat_object) != 0) {
+               VDATA_TEST_TRACE("error get file status..");
+               return ;
+       }
+
+       if( (buffer = (char*) malloc(stat_object.st_size)) == NULL )
+               return ;
+
+       VDATA_TEST_TRACE("sample.vcf file size : %d", stat_object.st_size);
+
+       if( (fp = fopen("sample.vcf",  "r")) == NULL )
+               return ;
+       fread(buffer, stat_object.st_size, sizeof(char), fp);
+       fclose(fp);
+
+       VDATA_TEST_TRACE("~~~~~");
+
+       tree = VCardDecode(buffer);
+
+       pTemp = tree->pTop;
+       pTmpParam = pTemp->pParam;
+
+       while(1) {
+               //VDATA_TEST_TRACE("%d %d",pTemp->property, VCARD_TYPE_PHOTO);
+               temp = pTemp->pszValue[0];
+               VDATA_TEST_TRACE("%s",temp);
+
+               if (pTemp->pSibling != NULL) {
+                       pTemp = pTemp->pSibling;
+                       pTmpParam = pTemp->pParam;
+               }
+               else {
+                       break;
+               }
+       }
+
+       VDATA_TEST_TRACE("END");
+
+
+       return ;
+
+}
+
+
+/*encode a tree to a buffer*/
+void utc_vdata_vcard_encode_1()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = g_strdup("BEGIN:VCARD\r\nVERSION:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531\r\nEND:VCARD");
+
+       tree = VCardDecode(buffer);
+       tree->pTop->property = 32;
+
+       char *temp = g_strdup("2.2");;
+       tree->pTop->pszValue[0] = temp;
+
+       if(buffer != NULL) {
+       g_free(buffer);
+       buffer = NULL;
+       }
+
+       VDATA_TEST_TRACE ("top property value is %s \n", *(tree->pTop->pszValue));
+       buffer = VCardEncode(tree);
+
+       VCalFreeVTreeMemory(tree);
+       tree = VCardDecode(buffer);
+
+       VDATA_TEST_TRACE ("call executed buffer is %s\n", buffer);
+       MT_CHECK_NOT_EQUAL((gchar *)NULL, buffer);
+
+       if(buffer != NULL)
+               g_free(buffer);
+
+       if(temp != NULL)
+               g_free(temp);
+
+       buffer = NULL;
+       temp = NULL;
+}
+/*encode a tree with tree type as vcalendar to a buffer*/
+void utc_vdata_vcard_encode_2()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = g_strdup("BEGIN:VCARD\r\nVERSION:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531\r\nEND:VCARD");
+       tree = VCardDecode(buffer);
+
+       tree->treeType = VCALENDAR;
+
+       if(buffer != NULL)
+       g_free(buffer);
+       buffer = NULL;
+
+       buffer = VCardEncode(tree);
+       VDATA_TEST_TRACE ("call executed buffer is %s\n", buffer);
+       MT_CHECK_EQUAL((gchar *)NULL, buffer);
+       VCalFreeVTreeMemory(tree);
+
+       if(buffer != NULL)
+               g_free(buffer);
+
+       buffer = NULL;
+}
+
+/*encode a tree with all the vobjects as NULL to a buffer*/
+void utc_vdata_vcard_encode_3()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       tree = g_new0(VTree, 1);
+       tree->treeType = VCARD;
+       tree->pTop = NULL;
+       tree->pCur = NULL;
+
+       buffer = VCardEncode(tree);
+       VDATA_TEST_TRACE ("call executed buffer is %s\n", buffer);
+       MT_CHECK_NOT_EQUAL((gchar *)NULL, buffer);
+       VCalFreeVTreeMemory(tree);
+
+       if(buffer != NULL)
+               g_free(buffer);
+
+       buffer = NULL;
+}
+
+/*encode a tree with an object having property as very high value to a buffer*/
+void utc_vdata_vcard_encode_4()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = g_strdup("BEGIN:VCARD\r\nVERSION:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531\r\nEND:VCARD");
+       tree = VCardDecode(buffer);
+
+       tree->pTop->property = 65;
+
+       if(buffer != NULL)
+       g_free(buffer);
+
+       buffer = NULL;
+
+       buffer = VCardEncode(tree);
+
+       VDATA_TEST_TRACE ("call executed buffer is %s\n", buffer);
+       MT_CHECK_NOT_EQUAL((gchar*)NULL, buffer);
+
+       VCalFreeVTreeMemory(tree);
+
+       if(buffer != NULL)
+               g_free(buffer);
+
+       buffer = NULL;
+}
+
+/*encode a NULL tree to a buffer*/
+void utc_vdata_vcard_encode_5()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = VCardEncode(tree);
+       VDATA_TEST_TRACE ("call executed buffer is %s\n", buffer);
+       MT_CHECK_EQUAL((gchar *)NULL, buffer);
+
+       if(buffer != NULL)
+               g_free(buffer);
+
+       buffer = NULL;
+}
+
+/*encode a tree with an object having property but no other value to a buffer*/
+void utc_vdata_vcard_encode_6()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = g_strdup("BEGIN:VCARD\r\nVERSION:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531\r\nEND:VCARD");
+       tree = VCardDecode(buffer);
+
+       tree->pTop->property = 14;
+       tree->pTop->pszValue[0] = NULL;
+
+       if(buffer != NULL)
+       g_free(buffer);
+
+       buffer = NULL;
+
+       buffer = VCardEncode(tree);
+       VDATA_TEST_TRACE ("call executed buffer is %s\n", buffer);
+       MT_CHECK_NOT_EQUAL((gchar *)NULL, buffer);
+       VCalFreeVTreeMemory(tree);
+
+       if(buffer != NULL)
+               g_free(buffer);
+
+       buffer = NULL;
+}
+
+/*encode a tree with an object having value count greater than actual vales to a buffer*/
+void utc_vdata_vcard_encode_7()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+       gchar *temp;
+
+       buffer = g_strdup("BEGIN:VCARD\r\nVERSION:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531\r\nEND:VCARD");
+       tree = VCardDecode(buffer);
+
+       tree->pTop->property = VCARD_TYPE_N;
+       tree->pTop->valueCount = 5;
+       temp = g_strdup( "amit");
+       tree->pTop->pszValue[0] = temp;
+
+
+       if(buffer != NULL)
+       g_free(buffer);
+
+       buffer = NULL;
+
+       VDATA_TEST_TRACE ("top property value is %s \n", *(tree->pTop->pszValue));
+       buffer = VCardEncode(tree);
+
+       VDATA_TEST_TRACE ("call executed buffer is %s\n", buffer);
+       MT_CHECK_NOT_EQUAL((gchar *)NULL, buffer);
+       VCalFreeVTreeMemory(tree);
+
+
+       if(buffer != NULL)
+               g_free(buffer);
+
+       if(temp != NULL)
+               g_free(temp);
+
+       buffer = NULL;
+       temp = NULL;
+}
+
+/*encode a tree with tree type as a high value to a buffer*/
+void utc_vdata_vcard_encode_8()
+{
+       gchar *buffer = NULL;
+       VTree *tree = NULL;
+
+       buffer = g_strdup("BEGIN:VCARD\r\nVERSION:2.1\r\nN:Martin;Stephen\r\nTEL;HOME;VOICE:+1 (210) 555-1357\r\nTEL;HOME;FAX:+1 (210) 555-0864\r\nADR;WORK;PARCEL;POSTAL;DOM:123 Cliff Ave.;Big Town;CA;97531\r\nEND:VCARD");
+
+       tree = VCardDecode(buffer);
+
+       tree->treeType = 15;
+
+       if(buffer != NULL)
+       g_free(buffer);
+
+       buffer = NULL;
+
+       buffer = VCardEncode(tree);
+       VDATA_TEST_TRACE ("call executed buffer is %s\n", buffer);
+       MT_CHECK_EQUAL((gchar*)NULL, buffer);
+       VCalFreeVTreeMemory(tree);
+
+       if(buffer != NULL)
+               g_free(buffer);
+
+       buffer = NULL;
+}
+